void gen_SSCA2_graph_MPI(graph_t* g) { uint32_t local_TotVertices, TotVertices; uint32_t* clusterSizes; uint32_t* firstVsInCluster; uint32_t estTotClusters, local_totClusters; uint32_t *startVertex, *endVertex; uint32_t local_numEdges; weight_t* weights; weight_t MinWeight,MaxWeight; vertex_id_t u, v; edge_id_t offset; uint32_t MaxCliqueSize; uint32_t MaxParallelEdges = 1; double ProbUnidirectional = 1.0; double ProbIntercliqueEdges = 0.1; uint32_t i_cluster, currCluster; uint32_t *startV, *endV, *d; uint32_t estNumEdges, edgeNum; uint32_t i, j, k, t, t1, t2, dsize; double p; int seed; uint32_t* permV; int size, rank, lgsize; g->directed = false; g->min_weight = 0; g->max_weight = 1; g->filename[0] = '\0'; g->n = (vertex_id_t)1 << g->scale; if (strlen(g->filename) == 0) sprintf(g->filename, "ssca2-%d", g->scale); /*----------------------------------------------*/ /* initialize RNG */ /*----------------------------------------------*/ seed = 2387; srand48(seed); MinWeight = g->min_weight; MaxWeight = g->max_weight; TotVertices = g->n; size = g->nproc; g->local_n = g->n/size; local_TotVertices = g->local_n; rank = g->rank; for (lgsize = 0; lgsize < size; ++lgsize) { if ((1 << lgsize) == size) break; } MPI_Datatype MPI_VERTEX_ID_T; MPI_Type_contiguous(sizeof(vertex_id_t), MPI_BYTE, &MPI_VERTEX_ID_T); MPI_Type_commit(&MPI_VERTEX_ID_T); /*----------------------------------------------*/ /* generate local clusters */ /*----------------------------------------------*/ MaxCliqueSize = 49; /* Estimate number of clusters required to make up * TotVertices and pad by 25% */ estTotClusters = 1.25 * TotVertices / (size * MaxCliqueSize/2); /* Allocate a block of memory for this cluster-size array */ clusterSizes = (uint32_t *) malloc(estTotClusters*sizeof(uint32_t)); /* Generate random cluster sizes. */ for(i = 0; i < estTotClusters; i++) { clusterSizes[i] = 1 + ( drand48() * MaxCliqueSize); } local_totClusters = 0; /* Allocate memory for storing the first vertex in each cluster */ firstVsInCluster = (uint32_t *) malloc(estTotClusters*sizeof(uint32_t)); /* Compute the first vertex in each cluster */ firstVsInCluster[0] = 0; for (i=1; i<estTotClusters; i++) { firstVsInCluster[i] = firstVsInCluster[i-1] + clusterSizes[i-1]; if (firstVsInCluster[i] > local_TotVertices-1) break; } local_totClusters = i; /* Fix the size of the last cluster */ clusterSizes[local_totClusters-1] = local_TotVertices -\ firstVsInCluster[local_totClusters-1]; /*------------------------------------------------------*/ /* generate intra-cluster edges */ /*------------------------------------------------------*/ /* Roughly estimate the total number of edges */ estNumEdges = (uint32_t) ((local_TotVertices * (double) MaxCliqueSize * (2-ProbUnidirectional)/2) +\ (local_TotVertices * (double) ProbIntercliqueEdges/(1-ProbIntercliqueEdges))) * \ (1+MaxParallelEdges/2); /* Check if no. of edges is within bounds for 32-bit code */ if ((estNumEdges > ((1<<30) - 1)) && (sizeof(uint32_t*) < 8)) { fprintf(stderr, "ERROR: long* should be 8 bytes \ for this problem size\n"); fprintf(stderr, "\tPlease recompile the code \ in 64-bit mode\n"); exit(-1); }
int main(int argc, char* argv[]) { if (argc != 4 ) { fprintf( stderr, "need csr-filename N reps!\n" ); exit(-1); } char* l_csr_file; REALTYPE* l_a_sp; unsigned int* l_rowptr; unsigned int* l_colidx; unsigned int l_rowcount, l_colcount, l_elements; REALTYPE* l_a_dense; REALTYPE* l_b; REALTYPE* l_c; REALTYPE* l_c_gold; REALTYPE* l_c_dense; REALTYPE l_max_error = 0.0; unsigned int l_m; unsigned int l_n; unsigned int l_k; unsigned int l_i; unsigned int l_j; unsigned int l_z; unsigned int l_elems; unsigned int l_reps; struct timeval l_start, l_end; double l_total; /* read sparse A */ l_csr_file = argv[1]; l_n = atoi(argv[2]); l_reps = atoi(argv[3]); if (my_csr_reader( l_csr_file, &l_rowptr, &l_colidx, &l_a_sp, &l_rowcount, &l_colcount, &l_elements ) != 0 ) { exit(-1); } l_m = l_rowcount; l_k = l_colcount; printf("CSR matrix data structure we just read:\n"); printf("rows: %u, columns: %u, elements: %u\n", l_rowcount, l_colcount, l_elements); /* allocate dense matrices */ l_a_dense = (REALTYPE*)_mm_malloc(l_k * l_m * sizeof(REALTYPE), 64); l_b = (REALTYPE*)_mm_malloc(l_k * l_n * sizeof(REALTYPE), 64); l_c = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_gold = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); l_c_dense = (REALTYPE*)_mm_malloc(l_m * l_n * sizeof(REALTYPE), 64); /* touch B */ for ( l_i = 0; l_i < l_k*l_n; l_i++) { l_b[l_i] = (REALTYPE)drand48(); } /* touch dense A */ for ( l_i = 0; l_i < l_k*l_m; l_i++) { l_a_dense[l_i] = (REALTYPE)0.0; } /* init dense A using sparse A */ for ( l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for ( l_z = 0; l_z < l_elems; l_z++ ) { l_a_dense[(l_i*l_k)+l_colidx[l_rowptr[l_i]+l_z]] = l_a_sp[l_rowptr[l_i]+l_z]; } } /* touch C */ for ( l_i = 0; l_i < l_m*l_n; l_i++) { l_c[l_i] = (REALTYPE)0.0; l_c_gold[l_i] = (REALTYPE)0.0; l_c_dense[l_i] = (REALTYPE)0.0; } /* compute golden results */ printf("computing golden solution...\n"); for ( l_j = 0; l_j < l_n; l_j++ ) { for (l_i = 0; l_i < l_m; l_i++ ) { l_elems = l_rowptr[l_i+1] - l_rowptr[l_i]; for (l_z = 0; l_z < l_elems; l_z++) { l_c_gold[(l_n*l_i) + l_j] += l_a_sp[l_rowptr[l_i]+l_z] * l_b[(l_n*l_colidx[l_rowptr[l_i]+l_z])+l_j]; } } } printf("...done!\n"); /* libxsmm generated code */ printf("computing libxsmm (A sparse) solution...\n"); libxsmm_code(l_b, l_c); printf("...done!\n"); /* BLAS code */ printf("computing BLAS (A dense) solution...\n"); double alpha = 1.0; double beta = 1.0; char trans = 'N'; dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense, &l_n ); printf("...done!\n"); /* check for errors */ l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c[l_i]-l_c_gold[l_i]) > l_max_error ) { l_max_error = fabs(l_c[l_i]-l_c_gold[l_i]); } } printf("max error (libxmm vs. gold): %f\n", l_max_error); l_max_error = (REALTYPE)0.0; for ( l_i = 0; l_i < l_m*l_n; l_i++) { if (fabs(l_c_dense[l_i]-l_c_gold[l_i]) > l_max_error ) { l_max_error = fabs(l_c_dense[l_i]-l_c_gold[l_i]); } } printf("max error (dense vs. gold): %f\n", l_max_error); /* Let's measure performance */ gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { libxsmm_code(l_b, l_c); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] LIBXSMM (RM, M=%i, N=%i, K=%i): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i): %f (sparse)\n", l_m, l_n, l_k, (2.0 * (double)l_elements * (double)l_n * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GFLOPS LIBXSMM (RM, M=%i, N=%i, K=%i): %f (dense)\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s LIBXSMM (RM, M=%i, N=%i, K=%i): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); gettimeofday(&l_start, NULL); for ( l_j = 0; l_j < l_reps; l_j++ ) { dgemm(&trans, &trans, &l_n, &l_m, &l_k, &alpha, l_b, &l_n, l_a_dense, &l_k, &beta, l_c_dense, &l_n ); } gettimeofday(&l_end, NULL); l_total = sec(l_start, l_end); fprintf(stdout, "time[s] MKL (RM, M=%i, N=%i, K=%i): %f\n", l_m, l_n, l_k, l_total/(double)l_reps ); fprintf(stdout, "GFLOPS MKL (RM, M=%i, N=%i, K=%i): %f\n", l_m, l_n, l_k, (2.0 * (double)l_m * (double)l_n * (double)l_k * (double)l_reps * 1.0e-9) / l_total ); fprintf(stdout, "GB/s MKL (RM, M=%i, N=%i, K=%i): %f\n", l_m, l_n, l_k, ((double)sizeof(double) * ((2.0*(double)l_m * (double)l_n) + ((double)l_k * (double)l_n)) * (double)l_reps * 1.0e-9) / l_total ); /* free */ /* @TODO */ }
/*determines if star with prob p should be separrated into stream*/ int prob_ok(int n, double* p) { int ok; double r; double step1, step2, step3; r = drand48(); switch (n) { case 1: if ( r > p[0] ) { ok = 0; } else { ok = 1; } break; case 2: step1 = p[0] + p[1]; if ( r > step1 ) { ok = 0; } else if ( (r < p[0]) ) { ok = 1; } else if ( (r > p[0]) && (r <= step1) ) { ok = 2; } break; case 3: step1 = p[0] + p[1]; step2 = p[0] + p[1] + p[2]; if ( r > step2 ) { ok = 0; } else if ( (r < p[0]) ) { ok = 1; } else if ( (r > p[0]) && (r <= step1) ) { ok = 2; } else if ( (r > step1) && (r <= step2) ) { ok = 3; } break; case 4: step1 = p[0] + p[1]; step2 = p[0] + p[1] + p[2]; step3 = p[0] + p[1] + p[2] + p[3]; if ( r > step3 ) { ok = 0; } else if ( (r <= p[0]) ) { ok = 1; } else if ( (r > p[0]) && (r <= step1) ) { ok = 2; } else if ( (r > step1) && (r <= step2) ) { ok = 3; } else if ( (r > step2) && (r <= step3) ) { ok = 4; } break; default: fprintf(stderr, "ERROR: Too many streams to separate using current code; " "please update the switch statement in probability.c->prob_ok to handle %d streams", n); exit(EXIT_SUCCESS); } return ok; }
void * fail_prone_malloc(size_t size) { return drand48() < ALLOC_ERR_PROB ? NULL : __libc_malloc(size); }
void * fail_prone_calloc(size_t nitems, size_t size) { return drand48() < ALLOC_ERR_PROB ? NULL : __libc_calloc(nitems, size); }
int main() { int i, j, k, d = 10,d2=5; float * a = fvec_new (d * d); float * b = fvec_new (d * d); float * b0 = fvec_new (d * d); #define B0(i,j) b0[(i)+(j)*d] #define A(i,j) a[(i)+(j)*d] #define B(i,j) b[(i)+(j)*d] float * lambda = fvec_new (d); float * v = fvec_new (d * d); float *v_part=fvec_new (d * d2); for (i = 0 ; i < d ; i++) for (j = 0 ; j <= i ; j++) { A(i,j) = A(j,i) = drand48(); B0(i,j)=drand48(); B0(j,i)=drand48(); /* B(i,j) = B(j,i) = drand48(); */ } /* make a positive definite b (with b=b0*b0') */ for (i = 0 ; i < d ; i++) for (j = 0 ; j < d ; j++) { double accu=0; for(k=0;k<d;k++) accu+=B0(i,k)*B0(j,k); B(i,j)=accu; } printf ("a = "); fmat_print(a,d,d); printf ("\nb = "); fmat_print(b,d,d); printf ("Solution of the eigenproblem Av=lambda v\n"); printf ("\n"); int ret=eigs_sym (d, a, lambda, v); assert(ret==0); printf ("\n"); printf("Eigenvectors:\n"); fmat_print(v,d,d); fprintf(stdout, "lambda = "); fvec_print (lambda, d); printf ("\n"); printf("Partial eigenvalues/vectors:\n"); printf ("\n"); ret=eigs_sym_part (d, a, d2, lambda, v_part); assert(ret>0); if(ret<d2) printf("!!! only %d / %d eigenvalues converged\n",ret,d2); printf ("\n"); printf("Eigenvectors:\n"); fmat_print(v_part,d,d2); fprintf(stdout, "lambda = "); fvec_print (lambda, d2); printf ("\n"); printf ("Solution of the generalized eigenproblem Av=lambda B v\n"); printf ("\n"); ret=geigs_sym (d, a, b, lambda, v); assert(ret==0); printf ("\n"); fmat_print(v,d,d); fprintf(stdout, "lambda = "); fvec_print (lambda, d); printf ("\n"); free (a); free (lambda); free (v); return 0; }
int doAllFeatures() { /* Initial biases */ { int u,m,f; for(u=0;u<NUSERS;u++) { for(f=0;f<NFEATURES;f++) bU[u][f]=drand48()*0.01-0.005; } for(m=0;m<NMOVIES;m++) { for(f=0;f<NFEATURES;f++) bV[m][f]=drand48()*0.01-0.005; } } /* Initial estimation for current feature */ { int u,m,f; for(u=0;u<NUSERS;u++) { for(f=0;f<NFEATURES;f++) sU[u][f]=drand48()*0.1-0.04; } for(m=0;m<NMOVIES;m++) { for(f=0;f<NFEATURES;f++) { sV[m][f]=drand48()*0.05-0.025; sY[m][f]=drand48()*0.02-0.01; } } } /* Optimize current feature */ double nrmse=2., last_rmse=10.; double thr=sqrt(1.-E); int loopcount=0; //thr=sqrt(1.-E2); double Gamma2 = G2; double Gamma0 = G0; while( ( nrmse < (last_rmse-E) ) || loopcount++ < 20) { last_rmse=nrmse; clock_t t0=clock(); int u,m, f; for(u=0;u<NUSERS;u++) { // Calculate sumY and NuSY for each factor double sumY[NFEATURES]; ZERO(sumY); double lNuSY[NFEATURES]; ZERO(lNuSY); int base0=useridx[u][0]; int d0=UNTRAIN(u); int j; int f; int dall=UNALL(u); double NuS = 1.0/sqrt(dall); for(j=0;j<d0;j++) { int mm=userent[base0+j]&USER_MOVIEMASK; for(f=0;f<NFEATURES;f++) sumY[f]+=sY[mm][f]; } //if ( loopcount > 1 ) { //printf("sumY: %f\n", sumY); //fflush(stdout); //} for(j=0;j<d0;j++) { int mm=userent[base0+j]&USER_MOVIEMASK; for(f=0;f<NFEATURES;f++) { lNuSY[f] = NuS * sumY[f]; //if ( loopcount > 1 ) { //printf("lNuSY: %f\n", lNuSY[f]); //fflush(stdout); //} } } double ycontrib[NFEATURES]; ZERO(ycontrib); // For all rated movies double bdampen = d0/1.1; for(j=0;j<d0;j++) { int m=userent[base0+j]&USER_MOVIEMASK; // Figure out the current error double ee=err[base0+j]; double e2 = ee; for (f=0; f<NFEATURES; f++) { e2 -= (bU[u][f] + bV[m][f]); e2 -= ((sU[u][f]+lNuSY[f])*sV[m][f]); } // update U V and slope component of Y //double yfactor = NuS/sqrt(moviecount[m]); //double yfactor = NuS; double yfactor = NuS/d0; for (f=0; f<NFEATURES; f++) { // Train the biases double bUu = bU[u][f]; double bVm = bV[m][f]; bU[u][f] += Gamma0 * (e2 - bUu * L4) / bdampen; bV[m][f] += Gamma0 * (e2 - bVm * L4) / bdampen; double sUu = sU[u][f]; double sVm = sV[m][f]; sU[u][f] += (Gamma2 * ((e2 * sVm) - L8 * sUu)); sV[m][f] += (Gamma2 * ((e2 * (sUu + lNuSY[f])) - L8 * sVm)); //printf("sU: %f\n", sU[u][f]); //printf("sV: %f\n", sV[m][f]); //fflush(stdout); ycontrib[f] += e2 * sVm * yfactor; //printf("ycont: %f\n", ycontrib[f]); //fflush(stdout); } } // Train Ys over all known movies for user for(j=0;j<dall;j++) { int m=userent[base0+j]&USER_MOVIEMASK; for (f=0; f<NFEATURES; f++) { double sYm = sY[m][f]; sY[m][f] += Gamma2 * (ycontrib[f] - L7 * sYm); //printf("before sY: %f\tycon: %f\tG2*ycon: %f\treg: %f\n", sY[m][f], ycontrib[f], (G2_Y*ycontrib[f]), G2_Y*L7_Y*sYm); //printf("after sY: %f\tycon: %f\tG2*ycon: %f\treg: %f\n", sY[m][f], ycontrib[f], (G2_Y*ycontrib[f]), G2_Y*L7_Y*sYm); //printf("sY: %f\tycon: %f\tG2*ycon: %f\n", sY[m][f], ycontrib[f], (G2*ycontrib[f])); //fflush(stdout); } } } // Report rmse for main loop nrmse=0.; int ntrain=0; int elcnt=0; for(u=0;u<NUSERS;u++) { int base0=useridx[u][0]; int d0=UNTRAIN(u); int j; // Setup the Ys again double sumY[NFEATURES]; ZERO(sumY); double lNuSY[NFEATURES]; ZERO(lNuSY); int dall=UNALL(u); double NuS = 1.0/sqrt(dall); for(j=0;j<d0;j++) { int mm=userent[base0+j]&USER_MOVIEMASK; for(f=0;f<NFEATURES;f++) sumY[f]+=sY[mm][f]; } for(j=0;j<d0;j++) { int mm=userent[base0+j]&USER_MOVIEMASK; for(f=0;f<NFEATURES;f++) lNuSY[f] = NuS * sumY[f]; } for(j=0;j<d0;j++) { int m=userent[base0+j]&USER_MOVIEMASK; double ee = err[base0+j]; double e2 = ee; for (f=0; f<NFEATURES; f++) { e2 -= (bU[u][f] + bV[m][f]); e2 -= ( (sU[u][f] + lNuSY[f]) * sV[m][f]); } if( elcnt++ == 5000 ) { printf("0 E: %f \t NE: %f\tNuSY: %f\tsV: %f\tsU: %f\tbU: %f\tbV: %f\tsY: %f\tU: %d\tM: %d\n", ee, e2, lNuSY[0], sV[m][0], sU[u][0], bU[u][0], bV[m][0], sY[m][0],u, m); printf("1 E: %f \t NE: %f\tNuSY: %f\tsV: %f\tsU: %f\tbU: %f\tbV: %f\tsY: %f\tU: %d\tM: %d\n", ee, e2, lNuSY[1], sV[m][1], sU[u][1], bU[u][1], bV[m][1], sY[m][1],u, m); printf("2 E: %f \t NE: %f\tNuSY: %f\tsV: %f\tsU: %f\tbU: %f\tbV: %f\tsY: %f\tU: %d\tM: %d\n", ee, e2, lNuSY[2], sV[m][2], sU[u][2], bU[u][2], bV[m][2], sY[m][2],u, m); printf("3 E: %f \t NE: %f\tNuSY: %f\tsV: %f\tsU: %f\tbU: %f\tbV: %f\tsY: %f\tU: %d\tM: %d\n", ee, e2, lNuSY[3], sV[m][3], sU[u][3], bU[u][3], bV[m][3], sY[m][3],u, m); fflush(stdout); } /* if( e > 5.0 || e < -5.0 ) { printf("bad EE: %f\tU: %d\tM: %d\tNuSY: %f\te: %f\t sV: %f\tsU: %f\tbU: %f\tbV: %f\n", ee, u, m, NuSY, e, new_sV[m], new_sU[u], bUu, bVm); fflush(stdout); } */ nrmse+=e2*e2; } ntrain+=d0; } nrmse=sqrt(nrmse/ntrain); double prmse = rmseprobe(); lg("%f\t%f\t%f\n",nrmse,prmse,(clock()-t0)/(double)CLOCKS_PER_SEC); //rmse_print(0); if ( loopcount < 6 ) { Gamma2 *= 0.95; Gamma0 *= 0.95; } else if ( loopcount < 14 ) { Gamma2 *= 0.92; Gamma0 *= 0.92; } else { Gamma2 *= 0.90; Gamma0 *= 0.90; } } /* Perform a final iteration in which the errors are clipped and stored */ removeUV(); //if(save_model) { //dappend_bin(fnameV,sV,NMOVIES); //dappend_bin(fnameU,sU,NUSERS); //} return 1; }
void *elCamino(float *x_obs, float *x_aComparar,float *y_ayudaAx, float *xDelMomento,float *xCandidato, float *a, float *b, float *c, float *d,float *l,float paso, int t, int iteraciones, int burn) { int i; float aPrima; float bPrima; float cPrima; float dPrima; float lPresente; float lCandidato; float gamma; float beta; float alpha; float x_0 = 15 ; float y_0 = 13; const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for(i=0; i < (iteraciones-1) ; i++) { aPrima = gsl_ran_gaussian(r, 0.1)+a[i]; //bPrima = gsl_ran_gaussian(r, 0.1)+b[i]; //cPrima = gsl_ran_gaussian(r, 0.1)+c[i]; //dPrima = gsl_ran_gaussian(r, 0.1)+d[i]; xDelMomento = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], b[i], c[i], d[i], t, paso); xCandidato = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, aPrima, b[i], c[i], d[i], t, paso); lPresente = likelyhood(x_obs, xDelMomento, t); lCandidato = likelyhood(x_obs, xCandidato , t); gamma = (lCandidato - lPresente); if(gamma>=0.00) { a[i+1]=aPrima; } else { beta = drand48(); alpha = exp(gamma); if(beta<=alpha) { a[i+1]=aPrima; } else { a[i+1]=a[i]; } } //aPrima = gsl_ran_gaussian(r, 0.1)+a[i]; bPrima = gsl_ran_gaussian(r, 0.1)+b[i]; //cPrima = gsl_ran_gaussian(r, 0.1)+c[i]; //dPrima = gsl_ran_gaussian(r, 0.1)+d[i]; xDelMomento = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], b[i], c[i], d[i], t, paso); xCandidato = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], bPrima, c[i], d[i], t, paso); lPresente = likelyhood(x_obs, xDelMomento, t); lCandidato = likelyhood(x_obs, xCandidato , t); gamma = (lCandidato - lPresente); if(gamma>=0.00) { b[i+1]=bPrima; } else { beta = drand48(); alpha = exp(gamma); if(beta<=alpha) { b[i+1]=bPrima; } else { b[i+1]=b[i]; } } //aPrima = gsl_ran_gaussian(r, 0.1)+a[i]; //bPrima = gsl_ran_gaussian(r, 0.1)+b[i]; cPrima = gsl_ran_gaussian(r, 0.1)+c[i]; //dPrima = gsl_ran_gaussian(r, 0.1)+d[i]; xDelMomento = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], b[i], c[i], d[i], t, paso); xCandidato = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], b[i], cPrima, d[i], t, paso); lPresente = likelyhood(x_obs, xDelMomento, t); lCandidato = likelyhood(x_obs, xCandidato , t); gamma = (lCandidato - lPresente); if(gamma>=0.00) { c[i+1]=cPrima; } else { beta = drand48(); alpha = exp(gamma); if(beta<=alpha) { c[i+1]=cPrima; } else { c[i+1]=c[i]; } } //aPrima = gsl_ran_gaussian(r, 0.1)+a[i]; //bPrima = gsl_ran_gaussian(r, 0.1)+b[i]; //cPrima = gsl_ran_gaussian(r, 0.1)+c[i]; dPrima = gsl_ran_gaussian(r, 0.1)+d[i]; xDelMomento = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], b[i], c[i], d[i], t, paso); xCandidato = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i], b[i], c[i], dPrima, t, paso); lPresente = likelyhood(x_obs, xDelMomento, t); lCandidato = likelyhood(x_obs, xCandidato , t); gamma = (lCandidato - lPresente); if(gamma>=0.00) { d[i+1]=dPrima; } else { beta = drand48(); alpha = exp(gamma); if(beta<=alpha) { d[i+1]=dPrima; } else { d[i+1]=d[i]; } } xCandidato = RungeKutta(x_aComparar, y_ayudaAx, x_0, y_0, a[i+1], b[i+1], c[i+1], d[i+1], t, paso); l[i+1] = likelyhood(x_obs,xCandidato,t); if(i+1>burn) { printf("%f %f %f %f %f\n", a[i+1],b[i+1],c[i+1],d[i+1],l[i+1]); } } }
int main(int argc,char *argv[]) { signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); int *g; int *new_g; int gsize; long count; long count_1; long count_2; long count_3; int i; int j; int k; long best_count; long prev_best_count; int best_i; int best_j; int best_k; int best_l; void *taboo_list; int* taboo_array; int val,iter,jter; int multi = 0; /* * start with graph of size 8 */ if (argc < 2) { gsize = 8; g = (int *)malloc(gsize*gsize*sizeof(int)); if(g == NULL) { exit(1); } /* * start out with all zeros */ memset(g,0,gsize*gsize*sizeof(int)); val = 0, iter = 0, jter=0; for( iter=0; iter<gsize; iter++){ for( jter = 0; jter< gsize; jter++){ g[iter*gsize + jter] = val; val = 1 - val; } } PrintGraph(g, gsize); } else if (argc == 2) { gsize = atoi(argv[1]); g = (int *)malloc(gsize*gsize*sizeof(int)); if(g == NULL) { exit(1); } g = PaleyGraph(gsize); int* row = (int *)malloc(gsize*sizeof(int)); memcpy(row, g, gsize*sizeof(int)); create_sgraph(&g, gsize, row); taboo_array = (int*)malloc(sizeof(int)*gsize); memset(taboo_array, 0, gsize*sizeof(int)); printf("Starting from Paley graph of size %d\n.", gsize); fflush(stdout); free(row); } else { gsize = atoi(argv[1]); g = (int *)malloc(gsize*gsize*sizeof(int)); ReadGraph(argv[2], &g, &gsize); count = CliqueCount(g,gsize); if (count == 0) { printf("Eureka! Sym Counter-example found!\n"); PrintGraph(g,gsize); fflush(stdout); new_g = (int *)malloc((gsize+1)*(gsize+1)*sizeof(int)); if(new_g == NULL) exit(1); int* row = (int *)malloc((gsize+1)*sizeof(int)); memcpy(row, g, gsize*sizeof(int)); free(g); gsize = gsize+1; create_sgraph(&new_g, gsize, row); free(row); //CopyGraph(g,gsize,new_g,gsize+1); set_sedge(&new_g, gsize, gsize-1, 0); long count0 = CliqueCount(new_g, gsize); set_sedge(&new_g, gsize, gsize-1, 1); long count1 = CliqueCount(new_g, gsize); if(count0 < count1) set_sedge(&new_g, gsize, gsize-1, 0); taboo_array = (int*) malloc(sizeof(int)*gsize); memset(taboo_array, 0, sizeof(int)*gsize); g = new_g; } else { int* row = (int *)malloc(gsize*sizeof(int)); memcpy(row, g, gsize*sizeof(int)); create_sgraph(&g, gsize, row); taboo_array = (int*)malloc(sizeof(int)*gsize); memset(taboo_array, 0, gsize*sizeof(int)); printf("Starting from given graph of size %d\n.", gsize); fflush(stdout); free(row); } } /* *make a fifo to use as the taboo list */ taboo_list = FIFOInitEdge(TABOOSIZE); if(taboo_list == NULL) { exit(1); } /* * while we do not have a publishable result */ while(gsize<206) { best_count = BIGCOUNT; while(gsize < 206) { best_j = -1; count = CliqueCount(g,gsize); if(count == 0) { printf("Eureka! Sym Counter-example found!\n"); PrintGraph(g,gsize); fflush(stdout); /* * make a new graph one size bigger */ new_g = (int *)malloc((gsize+1)*(gsize+1)*sizeof(int)); if(new_g == NULL) exit(1); int* row = (int *)malloc((gsize+1)*sizeof(int)); memcpy(row, g, gsize*sizeof(int)); free(g); gsize = gsize+1; create_sgraph(&new_g, gsize, row); free(row); //CopyGraph(g,gsize,new_g,gsize+1); set_sedge(&new_g, gsize, gsize-1, 0); long count0 = CliqueCount(new_g, gsize); set_sedge(&new_g, gsize, gsize-1, 1); long count1 = CliqueCount(new_g, gsize); if(count0 < count1) set_sedge(&new_g, gsize, gsize-1, 0); taboo_array = (int*) malloc(sizeof(int)*gsize); memset(taboo_array, 0, sizeof(int)*gsize); g = new_g; best_count = BIGCOUNT; /* * reset the taboo list for the new graph */ //taboo_list = FIFOResetEdge(taboo_list); free(taboo_array); taboo_array = (int*) malloc(sizeof(int)*gsize); memset(taboo_array, 0, sizeof(int)*gsize); continue; } //best_count = BIGCOUNT; prev_best_count = best_count; if(multi<5){ for(i=0; i < gsize; i++) { flip_sedge(&g, gsize, i); count = CliqueCount(g,gsize); if(count<best_count && !taboo_array[i]){ //if(count<best_count ){ best_count = count; best_i = i; } flip_sedge(&g, gsize, i); } } else{ for(i=0; i<gsize; i++){ for(j=i+1; j<gsize; j++){ flip_sedge(&g, gsize, i); flip_sedge(&g, gsize, j); count = CliqueCount(g,gsize); if(count<best_count){ best_count = count; best_i = i; best_j = j; } flip_sedge(&g, gsize, i); flip_sedge(&g, gsize, j); } } } if(best_count == BIGCOUNT || best_count==prev_best_count) { if(multi>=5) { printf("no best edge found, continuing with taboo\n"); fflush(stdout); break; } else { printf("single flip exhausted. starting singleflip again.", multi); fflush(stdout); memset(taboo_array, 0, sizeof(int)*gsize); multi ++; continue; } //flip_sedge(g, gsize, i); } flip_sedge(&g, gsize, best_i); count = best_count; if(multi) flip_sedge(&g, gsize, best_j); taboo_array[best_i] = 1; printf("sym ce size: %d, best_count: %ld, best edge(s): (%d), (%d)\n", gsize, best_count, best_i, best_j); g_latest = g; g_size_latest = gsize; g_count_latest = count; fflush(stdout); } while(gsize < 206) { /* * if we have a counter example */ if(count == 0) { printf("Eureka! Counter-example found!\n"); PrintGraph(g,gsize); fflush(stdout); /* * make a new graph one size bigger */ new_g = (int *)malloc((gsize+1)*(gsize+1)*sizeof(int)); if(new_g == NULL) exit(1); /* * copy the old graph into the new graph leaving the * last row and last column alone */ CopyGraph(g,gsize,new_g,gsize+1); /* * zero out the last column and last row */ for(i=0; i < (gsize+1); i++) { if(drand48() > 0.5) { new_g[i*(gsize+1) + gsize] = 0; // last column new_g[gsize*(gsize+1) + i] = 0; // last row } else { new_g[i*(gsize+1) + gsize] = 1; // last column new_g[gsize*(gsize+1) + i] = 1; // last row } } /* * throw away the old graph and make new one the * graph */ free(g); g = new_g; gsize = gsize+1; /* * reset the taboo list for the new graph */ taboo_list = FIFOResetEdge(taboo_list); /* * keep going */ //continue; break; //Go to first while loop } /* * otherwise, we need to consider flipping an edge * * let's speculative flip each edge, record the new count, * and unflip the edge. We'll then remember the best flip and * keep it next time around * * only need to work with upper triangle of matrix => * notice the indices */ best_count = BIGCOUNT; for(i=0; i < gsize; i++) { for(j=i+1; j < gsize; j++) { /* * flip two edges (i,j), (i,random(j) + 1) */ int k = getRandomJ(gsize); int l = getRandomJ(gsize); g[i*gsize+j] = 1 - g[i*gsize+j]; count_1 = CliqueCount(g,gsize); if (k == j) k = j + 1; g[i*gsize + k] = 1 - g[i*gsize + k]; count_2 = CliqueCount(g,gsize); if (l == j) l = j + 1; if (l == k) l = (k + 1) % gsize; g[i*gsize + l] = 1 - g[i*gsize + l]; count_3 = CliqueCount(g,gsize); count = (count_1 < count_2) ? count_1 : count_2 ; count = (count_3 < count) ? count_3 : count ; /* * is it better and the i,j,count not taboo? */ if(count < best_count){ if(count == count_1 //#ifdef USE_TABOO && !FIFOFindEdgeCount(taboo_list,i,j,count) //#endif ) { best_count = count; best_i = i; best_j = j; best_k = best_l = -1; } else if(count == count_2 //#ifdef USE_TABOO && (!FIFOFindEdgeCount(taboo_list,i,j,count) || !FIFOFindEdgeCount(taboo_list,i,k, count)) //#endif ) { best_count = count; best_i = i; best_j = j; best_k = k; best_l = -1; } else if(count == count_3 //#ifdef USE_TABOO && (!FIFOFindEdgeCount(taboo_list,i,j,count) || !FIFOFindEdgeCount(taboo_list,i,k, count) || !FIFOFindEdgeCount(taboo_list,i,l, count)) //#endif ) { best_count = count; best_i = i; best_j = j; best_k = k; best_l = l; } } /* * flip it back */ g[i*gsize+j] = 1 - g[i*gsize+j]; g[i*gsize+k] = 1 - g[i*gsize+k]; g[i*gsize+l] = 1 - g[i*gsize+l]; } } if(best_count == BIGCOUNT) { printf("no best edge found, terminating\n"); exit(1); } /* * keep the best flip we saw */ g[best_i*gsize + best_j] = 1 - g[best_i*gsize + best_j]; if (best_k != -1) g[best_i*gsize + best_k] = 1 - g[best_i*gsize + best_k]; if (best_l != -1) g[best_i*gsize + best_l] = 1 - g[best_i*gsize + best_l]; /* * taboo this graph configuration so that we don't visit * it again */ //count = CliqueCount(g,gsize); count = best_count; //#ifdef USE_TABOO // FIFOInsertEdge(taboo_list,best_i,best_j); FIFOInsertEdgeCount(taboo_list,best_i,best_j,count); if (best_k != -1) FIFOInsertEdgeCount(taboo_list,best_i,best_k,count); if (best_l != -1) FIFOInsertEdgeCount(taboo_list,best_i,best_l,count); //#endif printf("ce size: %d, best_count: %ld, best edges: (%d,%d) (%d,%d) (%d,%d), new colors: %d %d\n", gsize, best_count, best_i, best_j, best_i, best_k, best_i, best_l, g[best_i*gsize+best_j], g[best_i*gsize+best_k]); fflush(stdout); g_latest = g; g_size_latest = gsize; g_count_latest = count; /* * rinse and repeat */ } } FIFODeleteGraph(taboo_list); return(0); }
// Test node data sorting void SortNodeData() { int NNodes = 10000; int NEdges = 100000; TPt <TNodeEDatNet<TInt, TInt> > Net; TPt <TNodeEDatNet<TInt, TInt> > Net1; TPt <TNodeEDatNet<TInt, TInt> > Net2; int i; int n; int NCount; int x,y; bool t; int NodeId; int NodeDat; bool ok; bool Sorted; int Min; int Value; Net = TNodeEDatNet<TInt, TInt>::New(); t = Net->Empty(); // create the nodes for (i = 0; i < NNodes; i++) { Net->AddNode((i*13) % NNodes); } t = Net->Empty(); n = Net->GetNodes(); // create random edges NCount = NEdges; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); // Net->GetEdges() is not correct for the loops (x == y), // skip the loops in this test if (x != y && !Net->IsEdge(x,y)) { n = Net->AddEdge(x, y); NCount--; } } PrintNStats("SortNodeData:Net", Net); // add data to nodes, square of node ID % NNodes for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { NodeId = NI.GetId(); NodeDat = (NI.GetId()*NI.GetId()) % NNodes; Net->SetNDat(NodeId, NodeDat); } // test node data ok = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { NodeDat = Net->GetNDat(NI.GetId()); Value = (NI.GetId()*NI.GetId()) % NNodes; if (NodeDat != Value) { ok = false; } } printf("network SortNodeData:Net, status1 %s\n", (ok == true) ? "ok" : "ERROR"); // test sorting of node IDs (unsorted) Min = -1; Sorted = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { Value = NI.GetId(); if (Min > Value) { Sorted = false; } Min = Value; } printf("network SortNodeData:Net, status2 %s\n", (Sorted == false) ? "ok" : "ERROR"); // sort the nodes by node IDs (sorted) Net->SortNIdById(); // test sorting of node IDs Min = -1; Sorted = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { Value = NI.GetId(); if (Min > Value) { Sorted = false; } Min = Value; } printf("network SortNodeData:Net, status3 %s\n", (Sorted == true) ? "ok" : "ERROR"); // test sorting of node data (unsorted) Min = -1; Sorted = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { Value = Net->GetNDat(NI.GetId()); if (Min > Value) { Sorted = false; } Min = Value; } printf("network SortNodeData:Net, status4 %s\n", (Sorted == false) ? "ok" : "ERROR"); // sort the nodes by node data Net->SortNIdByDat(); // test sorting of node data (sorted) Min = -1; Sorted = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { Value = Net->GetNDat(NI.GetId()); if (Min > Value) { Sorted = false; } Min = Value; } printf("network SortNodeData:Net, status5 %s\n", (Sorted == true) ? "ok" : "ERROR"); // test sorting of node IDs (unsorted) Min = -1; Sorted = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { Value = NI.GetId(); if (Min > Value) { Sorted = false; } Min = Value; } printf("network SortNodeData:Net, status6 %s\n", (Sorted == false) ? "ok" : "ERROR"); // test node data ok = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { NodeDat = Net->GetNDat(NI.GetId()); Value = (NI.GetId()*NI.GetId()) % NNodes; if (NodeDat != Value) { ok = false; } } printf("network SortNodeData:Net, status7 %s\n", (ok == true) ? "ok" : "ERROR"); }
int main(void) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; // velocity of ball // TODO use drand for velocityX double velocityX = drand48() * 3.0; double velocityY = 3.0; // keep playing until game over waitForClick(); while (lives > 0 && bricks > 0) { // check for mouse event GEvent event = getNextEvent(MOUSE_EVENT); updateScoreboard(window, label, points); // set velocity of ball move(ball, velocityX, velocityY); // detect collision GObject collision = detectCollision(window, ball); if (getX(ball) + getWidth(ball) >= getWidth(window)) { velocityX = -velocityX; } // bounce off left edge of window else if (getX(ball) <= 0) { velocityX = -velocityX; } else if (getY(ball) + getHeight(ball) >= getHeight(window)) { lives -= 1; waitForClick(); setLocation(ball, 190, 290); move(ball, velocityX, -velocityY); } else if (getY(ball) <= 0) { velocityY = -velocityY; } else if (collision != NULL) { if (collision == paddle) { velocityY = -velocityY; } else if (strcmp(getType(collision), "GRect") == 0) { // TODO velocityY = -velocityY; removeGWindow(window, collision); points += 1; bricks -= 1; } } pause(10); if (event != NULL) { if (getEventType(event) == MOUSE_MOVED) { // ensure circle follows top cursor double x = getX(event) - getWidth(paddle) / 2; double y = 525; setLocation(paddle, x, y); } } } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
// Test update edge data void UpdateEdgeData() { int NNodes = 10000; int NEdges = 100000; TPt <TNodeEDatNet<TInt, TInt> > Net; TPt <TNodeEDatNet<TInt, TInt> > Net1; TPt <TNodeEDatNet<TInt, TInt> > Net2; int i; int n; int NCount; int x,y; bool t; int SrcNId; int DstNId; int EdgeDat; int Value; bool ok; Net = TNodeEDatNet<TInt, TInt>::New(); t = Net->Empty(); // create the nodes for (i = 0; i < NNodes; i++) { Net->AddNode(i); } t = Net->Empty(); n = Net->GetNodes(); // create random edges and edge data x+y+10 NCount = NEdges; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); // Net->GetEdges() is not correct for the loops (x == y), // skip the loops in this test if (x != y && !Net->IsEdge(x,y)) { n = Net->AddEdge(x, y, x+y+10); NCount--; } } PrintNStats("UpdateEdgeData:Net", Net); // verify edge data, x+y+10 ok = true; for (TNodeEDatNet<TInt, TInt>::TEdgeI EI = Net->BegEI(); EI < Net->EndEI(); EI++) { SrcNId = EI.GetSrcNId(); DstNId = EI.GetDstNId(); EdgeDat = Net->GetEDat(SrcNId, DstNId); Value = SrcNId+DstNId+10; if (EdgeDat != Value) { ok = false; } } printf("network UpdateEdgeData:Net, status1 %s\n", (ok == true) ? "ok" : "ERROR"); // update edge data, x+y+5 for (TNodeEDatNet<TInt, TInt>::TEdgeI EI = Net->BegEI(); EI < Net->EndEI(); EI++) { Net->SetEDat(EI.GetSrcNId(),EI.GetDstNId(),EI.GetSrcNId()+EI.GetDstNId()+5); } // verify edge data, x+y+5 ok = true; for (TNodeEDatNet<TInt, TInt>::TEdgeI EI = Net->BegEI(); EI < Net->EndEI(); EI++) { SrcNId = EI.GetSrcNId(); DstNId = EI.GetDstNId(); EdgeDat = Net->GetEDat(SrcNId, DstNId); Value = SrcNId+DstNId+5; if (EdgeDat != Value) { ok = false; } } printf("network UpdateEdgeData:Net, status2 %s\n", (ok == true) ? "ok" : "ERROR"); }
// Test node, edge creation void ManipulateNodesEdges() { int NNodes = 10000; int NEdges = 100000; const char *FName = "demo.net.dat"; TPt <TNodeEDatNet<TInt, TInt> > Net; TPt <TNodeEDatNet<TInt, TInt> > Net1; TPt <TNodeEDatNet<TInt, TInt> > Net2; int i; int n; int NCount; int ECount1; int ECount2; int x,y; bool t; Net = TNodeEDatNet<TInt, TInt>::New(); t = Net->Empty(); // create the nodes for (i = 0; i < NNodes; i++) { Net->AddNode(i); } t = Net->Empty(); n = Net->GetNodes(); // create random edges NCount = NEdges; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); // Net->GetEdges() is not correct for the loops (x == y), // skip the loops in this test if (x != y && !Net->IsEdge(x,y)) { n = Net->AddEdge(x, y); NCount--; } } PrintNStats("ManipulateNodesEdges:Net", Net); // get all the nodes NCount = 0; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { NCount++; } // get all the edges for all the nodes ECount1 = 0; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { for (int e = 0; e < NI.GetOutDeg(); e++) { ECount1++; } } // get all the edges directly ECount2 = 0; for (TNodeEDatNet<TInt, TInt>::TEdgeI EI = Net->BegEI(); EI < Net->EndEI(); EI++) { ECount2++; } printf("network ManipulateNodesEdges:Net, nodes %d, edges1 %d, edges2 %d\n", NCount, ECount1, ECount2); // assignment Net1 = TNodeEDatNet<TInt, TInt>::New(); *Net1 = *Net; PrintNStats("ManipulateNodesEdges:Net1",Net1); // save the network { TFOut FOut(FName); Net->Save(FOut); FOut.Flush(); } // load the network { TFIn FIn(FName); Net2 = TNodeEDatNet<TInt, TInt>::Load(FIn); } PrintNStats("ManipulateNodesEdges:Net2",Net2); // remove all the nodes and edges for (i = 0; i < NNodes; i++) { n = Net->GetRndNId(); Net->DelNode(n); } PrintNStats("ManipulateNodesEdges:Net",Net); Net1->Clr(); PrintNStats("ManipulateNodesEdges:Net1",Net1); }
// Test update node data void UpdateNodeData() { int NNodes = 10000; int NEdges = 100000; TPt <TNodeEDatNet<TInt, TInt> > Net; TPt <TNodeEDatNet<TInt, TInt> > Net1; TPt <TNodeEDatNet<TInt, TInt> > Net2; int i; int n; int NCount; int x,y; bool t; int NodeDat; int Value; bool ok; Net = TNodeEDatNet<TInt, TInt>::New(); t = Net->Empty(); // create the nodes for (i = 0; i < NNodes; i++) { Net->AddNode(i,i+5); } t = Net->Empty(); n = Net->GetNodes(); // create random edges NCount = NEdges; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); // Net->GetEdges() is not correct for the loops (x == y), // skip the loops in this test if (x != y && !Net->IsEdge(x,y)) { n = Net->AddEdge(x, y); NCount--; } } PrintNStats("UpdateNodeData:Net", Net); // read and test node data ok = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { NodeDat = Net->GetNDat(NI.GetId()); Value = NI.GetId()+5; if (NodeDat != Value) { ok = false; } } printf("network UpdateNodeData:Net, status1 %s\n", (ok == true) ? "ok" : "ERROR"); // update node data, node ID + 10 for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { Net->SetNDat(NI.GetId(), NI.GetId()+10); } // read and test node data ok = true; for (TNodeEDatNet<TInt, TInt>::TNodeI NI = Net->BegNI(); NI < Net->EndNI(); NI++) { NodeDat = Net->GetNDat(NI.GetId()); Value = NI.GetId()+10; if (NodeDat != Value) { ok = false; } } printf("network UpdateNodeData:Net, status2 %s\n", (ok == true) ? "ok" : "ERROR"); }
float Lowpass::main_body_quality( Streamline *st, float radius, int nsamples, float dist, Window2d *win, int &which_side ) { int i; float rad; float delta; float x,y; float sum = 0; int count = 0; VectorField *vf = st->vf; /* kluge to work around problems at the image borders */ float xmin = 2.0 / xsize; float ymin = 2.0 / ysize; float xmax = 1 - 2.0 / xsize; float ymax = image->getaspect() - 2.0 / ysize; /* measure the quality at several random positions along the streamline */ for (i = 0; i < nsamples; i++) { int index = (int) (st->samples * drand48()); SamplePoint *sample = &st->pts[index]; x = sample->x; y = sample->y; /* don't measure near the borders */ if (x < xmin || x > xmax || y < ymin || y > ymax) continue; rad = radius * rad_image->get_value(x,y) / xsize; delta = 0.3 * rad / nsamples; /* find out how to move perpendicular to the vector field */ float dx = - delta * vf->yval(x,y); float dy = delta * vf->xval(x,y); /* sample along either side of the streamline */ float x1 = x + dx; float y1 = y + dy; float x2 = x - dx; float y2 = y - dy; /* measure the quality at the two points */ float value1 = image->get_value(x1,y1); float value2 = image->get_value(x2,y2); // printf("value1: %f, value2: %f\n",value1,value2); sum += value1 - value2; count++; } /* return quality */ if (count == 0) return (0.0); else { if (sum > 0) which_side = LEFT; else which_side = RIGHT; return (fabs (sum / count)); } }
int main(int argc, char *argv[], char *envp[]) { double *A, *B, *C; double elapsed = 0, totalElapsed = 0; double gflops = 0; int i, j, k; unsigned int start = 1, end = 1, skip = 1, count = 1; unsigned int size = 1, algorithm = 1, debug = 0; char c; struct timespec startTime, endTime; struct rusage ruStart, ruEnd; while((c = getopt(argc, argv, "c:s:e:j:a:d:")) != -1) switch(c) { case 's': start = atoll(optarg); break; case 'e': end = atoll(optarg); break; case 'j': skip = atoll(optarg); break; case 'c': count = atoll(optarg); break; case 'a': algorithm = atoll(optarg); break; case 'd': debug = atoll(optarg); break; default: goto error0; } if(debug > 0) fprintf(stderr, "start = %d, end = %d, skip = %d, count = %d\n", start, end, skip, count); for(size=start; size<=end; size+=skip) { if(debug > 0) fprintf(stderr, "Starting size = %d\n", size); totalElapsed = 0; for(j=0; j<count; j++) { if(debug > 0) fprintf(stderr, "Computing matrix count = %d\n", j); A = calloc(size * size, sizeof(double)); B = calloc(size * size, sizeof(double)); C = calloc(size * size, sizeof(double)); for(k=0; k<size * size; k++) { A[k] = drand48(); B[k] = drand48(); } #ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &startTime); #else getrusage(RUSAGE_SELF, &ruStart); startTime.tv_sec = ruStart.ru_utime.tv_sec + ruStart.ru_stime.tv_sec; startTime.tv_nsec = (ruStart.ru_utime.tv_usec + ruStart.ru_stime.tv_usec)*1000; #endif switch(algorithm) { case 1: dMM(A, B, C, size, size, size); break; case 2: dMMT(A, B, C, size, size, size); break; case 3: dMMT2(A, B, C, size, size, size); break; case 4: dMMT2r(A, B, C, size, size, size); break; case 5: strassenMM(A, B, C, size, size, size); break; default: goto error1; } #ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &endTime); #else getrusage(RUSAGE_SELF, &ruEnd); endTime.tv_sec = ruEnd.ru_utime.tv_sec + ruEnd.ru_stime.tv_sec; endTime.tv_nsec = (ruEnd.ru_utime.tv_usec + ruEnd.ru_stime.tv_usec) * 1000; #endif elapsed = endTime.tv_sec; elapsed += (double)endTime.tv_nsec / 10e9; elapsed -= startTime.tv_sec; elapsed -= (double)startTime.tv_nsec / 10e9; totalElapsed += elapsed; if(debug > 0) { fprintf(stderr, "size = %d, alg = %d, start = %f, end = %f, elapsed = %f, Gops = %f\n", size, algorithm, startTime.tv_sec + (double)(startTime.tv_nsec)/1e9, endTime.tv_sec + (double)(endTime.tv_nsec)/1e9, elapsed, ((double)2.0*size*size*size-size*size)/10e9 ); } free(A); free(B); free(C); } gflops = ((((double)2.0*size*size*size-size*size))/10e9)/totalElapsed; printf("%u %u %f\n", size, count, gflops); } return(0); error1: fprintf(stderr, "Unknown algorithm\n"); exit(-1); error0: fprintf(stderr, "Usage: %s -n N\n", argv[0]); fprintf(stderr, "N = matrix size\n"); exit(-1); }
static int EvalClassExpression(EvalContext *ctx, Constraint *cp, Promise *pp) { int result_and = true; int result_or = false; int result_xor = 0; int result = 0, total = 0; char buffer[CF_MAXVARSIZE]; Rlist *rp; FnCall *fp; Rval rval; if (cp == NULL) { Log(LOG_LEVEL_ERR, "EvalClassExpression internal diagnostic discovered an ill-formed condition"); } if (!IsDefinedClass(ctx, pp->classes, PromiseGetNamespace(pp))) { return false; } if (EvalContextPromiseIsDone(ctx, pp)) { return false; } if (IsDefinedClass(ctx, pp->promiser, PromiseGetNamespace(pp))) { if (PromiseGetConstraintAsInt(ctx, "persistence", pp) == 0) { Log(LOG_LEVEL_VERBOSE, " ?> Cancelling cached persistent class %s", pp->promiser); EvalContextHeapPersistentRemove(pp->promiser); } return false; } switch (cp->rval.type) { case RVAL_TYPE_FNCALL: fp = (FnCall *) cp->rval.item; /* Special expansion of functions for control, best effort only */ FnCallResult res = FnCallEvaluate(ctx, fp, pp); FnCallDestroy(fp); cp->rval = res.rval; break; case RVAL_TYPE_LIST: for (rp = (Rlist *) cp->rval.item; rp != NULL; rp = rp->next) { rval = EvaluateFinalRval(ctx, "this", (Rval) {rp->item, rp->type}, true, pp); RvalDestroy((Rval) {rp->item, rp->type}); rp->item = rval.item; rp->type = rval.type; } break; default: rval = ExpandPrivateRval(ctx, "this", cp->rval); RvalDestroy(cp->rval); cp->rval = rval; break; } if (strcmp(cp->lval, "expression") == 0) { if (cp->rval.type != RVAL_TYPE_SCALAR) { return false; } if (IsDefinedClass(ctx, (char *) cp->rval.item, PromiseGetNamespace(pp))) { return true; } else { return false; } } if (strcmp(cp->lval, "not") == 0) { if (cp->rval.type != RVAL_TYPE_SCALAR) { return false; } if (IsDefinedClass(ctx, (char *) cp->rval.item, PromiseGetNamespace(pp))) { return false; } else { return true; } } // Class selection if (strcmp(cp->lval, "select_class") == 0) { char splay[CF_MAXVARSIZE]; int i, n; double hash; total = 0; for (rp = (Rlist *) cp->rval.item; rp != NULL; rp = rp->next) { total++; } if (total == 0) { Log(LOG_LEVEL_ERR, "No classes to select on RHS"); PromiseRef(LOG_LEVEL_ERR, pp); return false; } snprintf(splay, CF_MAXVARSIZE, "%s+%s+%ju", VFQNAME, VIPADDRESS, (uintmax_t)getuid()); hash = (double) OatHash(splay, CF_HASHTABLESIZE); n = (int) (total * hash / (double) CF_HASHTABLESIZE); for (rp = (Rlist *) cp->rval.item, i = 0; rp != NULL; rp = rp->next, i++) { if (i == n) { EvalContextHeapAddSoft(ctx, rp->item, PromiseGetNamespace(pp)); return true; } } } /* If we get here, anything remaining on the RHS must be a clist */ if (cp->rval.type != RVAL_TYPE_LIST) { Log(LOG_LEVEL_ERR, "RHS of promise body attribute '%s' is not a list", cp->lval); PromiseRef(LOG_LEVEL_ERR, pp); return true; } // Class distributions if (strcmp(cp->lval, "dist") == 0) { for (rp = (Rlist *) cp->rval.item; rp != NULL; rp = rp->next) { result = IntFromString(rp->item); if (result < 0) { Log(LOG_LEVEL_ERR, "Non-positive integer in class distribution"); PromiseRef(LOG_LEVEL_ERR, pp); return false; } total += result; } if (total == 0) { Log(LOG_LEVEL_ERR, "An empty distribution was specified on RHS"); PromiseRef(LOG_LEVEL_ERR, pp); return false; } double fluct = drand48(); double cum = 0.0; for (rp = (Rlist *) cp->rval.item; rp != NULL; rp = rp->next) { double prob = ((double) IntFromString(rp->item)) / ((double) total); cum += prob; if (fluct < cum) { break; } } snprintf(buffer, CF_MAXVARSIZE - 1, "%s_%s", pp->promiser, (char *) rp->item); /* FIXME: figure why explicit mark and get rid of it */ EvalContextMarkPromiseDone(ctx, pp); if (strcmp(PromiseGetBundle(pp)->type, "common") == 0) { EvalContextHeapAddSoft(ctx, buffer, PromiseGetNamespace(pp)); } else { EvalContextStackFrameAddSoft(ctx, buffer); } return true; } /* and/or/xor expressions */ for (rp = (Rlist *) cp->rval.item; rp != NULL; rp = rp->next) { if (rp->type != RVAL_TYPE_SCALAR) { return false; } result = IsDefinedClass(ctx, (char *) (rp->item), PromiseGetNamespace(pp)); result_and = result_and && result; result_or = result_or || result; result_xor ^= result; } // Class combinations if (strcmp(cp->lval, "or") == 0) { return result_or; } if (strcmp(cp->lval, "xor") == 0) { return (result_xor == 1) ? true : false; } if (strcmp(cp->lval, "and") == 0) { return result_and; } return false; }
// Test node, edge creation void ManipulateNodesEdges() { int NNodes = 10000; int NEdges = 100000; const char *FName = "demo.graph.dat"; PNGraph Graph; PNGraph Graph1; PNGraph Graph2; int i; int n; int NCount; int ECount1; int ECount2; int x,y; bool t; Graph = TNGraph::New(); t = Graph->Empty(); // create the nodes for (i = 0; i < NNodes; i++) { Graph->AddNode(i); } t = Graph->Empty(); n = Graph->GetNodes(); // create random edges NCount = NEdges; while (NCount > 0) { x = (long) (drand48() * NNodes); y = (long) (drand48() * NNodes); // Graph->GetEdges() is not correct for the loops (x == y), // skip the loops in this test if (x != y && !Graph->IsEdge(x,y)) { n = Graph->AddEdge(x, y); NCount--; } } PrintGStats("ManipulateNodesEdges:Graph",Graph); // get all the nodes NCount = 0; for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NCount++; } // get all the edges for all the nodes ECount1 = 0; for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { for (int e = 0; e < NI.GetOutDeg(); e++) { ECount1++; } } // get all the edges directly ECount2 = 0; for (TNGraph::TEdgeI EI = Graph->BegEI(); EI < Graph->EndEI(); EI++) { ECount2++; } printf("ManipulateNodesEdges:Graph, nodes %d, edges1 %d, edges2 %d\n", NCount, ECount1, ECount2); // assignment Graph1 = TNGraph::New(); *Graph1 = *Graph; PrintGStats("ManipulateNodesEdges:Graph1",Graph1); // save the graph { TFOut FOut(FName); Graph->Save(FOut); FOut.Flush(); } // load the graph { TFIn FIn(FName); Graph2 = TNGraph::Load(FIn); } PrintGStats("ManipulateNodesEdges:Graph2",Graph2); // remove all the nodes and edges for (i = 0; i < NNodes; i++) { n = Graph->GetRndNId(); Graph->DelNode(n); } PrintGStats("ManipulateNodesEdges:Graph",Graph); Graph1->Clr(); PrintGStats("ManipulateNodesEdges:Graph1",Graph1); }
void bwa_aln2seq_core(int n_aln, const bwt_aln1_t *aln, bwa_seq_t *s, int set_main, int n_multi) { int i, cnt, best; if (n_aln == 0) { s->type = BWA_TYPE_NO_MATCH; s->c1 = s->c2 = 0; return; } if (set_main) { best = aln[0].score; for (i = cnt = 0; i < n_aln; ++i) { const bwt_aln1_t *p = aln + i; if (p->score > best) break; if (drand48() * (p->l - p->k + 1 + cnt) > (double)cnt) { s->n_mm = p->n_mm; s->n_gapo = p->n_gapo; s->n_gape = p->n_gape; s->strand = p->a; s->score = p->score; s->sa = p->k + (bwtint_t)((p->l - p->k + 1) * drand48()); } cnt += p->l - p->k + 1; } s->c1 = cnt; for (; i < n_aln; ++i) cnt += aln[i].l - aln[i].k + 1; s->c2 = cnt - s->c1; s->type = s->c1 > 1? BWA_TYPE_REPEAT : BWA_TYPE_UNIQUE; } if (n_multi) { int k, rest, n_occ, z = 0; for (k = n_occ = 0; k < n_aln; ++k) { const bwt_aln1_t *q = aln + k; n_occ += q->l - q->k + 1; } if (s->multi) free(s->multi); if (n_occ > n_multi + 1) { // if there are too many hits, generate none of them s->multi = 0; s->n_multi = 0; return; } /* The following code is more flexible than what is required * here. In principle, due to the requirement above, we can * simply output all hits, but the following samples "rest" * number of random hits. */ rest = n_occ > n_multi + 1? n_multi + 1 : n_occ; // find one additional for ->sa s->multi = calloc(rest, sizeof(bwt_multi1_t)); for (k = 0; k < n_aln; ++k) { const bwt_aln1_t *q = aln + k; if (q->l - q->k + 1 <= rest) { bwtint_t l; for (l = q->k; l <= q->l; ++l) { s->multi[z].pos = l; s->multi[z].gap = q->n_gapo + q->n_gape; s->multi[z].mm = q->n_mm; s->multi[z++].strand = q->a; } rest -= q->l - q->k + 1; } else { // Random sampling (http://code.activestate.com/recipes/272884/). In fact, we never come here. int j, i, k; for (j = rest, i = q->l - q->k + 1, k = 0; j > 0; --j) { double p = 1.0, x = drand48(); while (x < p) p -= p * j / (i--); s->multi[z].pos = q->l - i; s->multi[z].gap = q->n_gapo + q->n_gape; s->multi[z].mm = q->n_mm; s->multi[z++].strand = q->a; } rest = 0; break; } } s->n_multi = z; for (k = z = 0; k < s->n_multi; ++k) if (s->multi[k].pos != s->sa) s->multi[z++] = s->multi[k]; s->n_multi = z < n_multi? z : n_multi; } }
int main(void) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 50; // keep playing until game over double bdx = drand48()/10; double bdy = drand48()/10; while (lives > 0 && bricks > 0) { // TODO //move paddle // check for mouse event GEvent event = getNextEvent(MOUSE_EVENT); // if we heard one if (event != NULL) { // if the event was movement if (getEventType(event) == MOUSE_MOVED) { double x; // ensure circle follows top cursor x = getX(event)-getWidth(paddle)/2; if (getX(event)>=400-getWidth(paddle)/2) x = 400-getWidth(paddle); if (getX(event)<=getWidth(paddle)/2) x = 0; setLocation(paddle, x, 580); } } // Move ball move(ball,bdx,bdy); // bounce off edges // left or right if ((getX(ball) + getWidth(ball) >= WIDTH) || getX(ball) <= 0) bdx = -bdx; // top else if ( getY(ball) <= 0) bdy = -bdy; else if ( (getY(ball) + getHeight(ball) >= HEIGHT)) { lives--; setLocation(ball, 190, 290); waitForClick(); } GObject object = detectCollision(window, ball); if (object!=NULL && object!=label) bdy = -bdy; if (object!=NULL && object!=paddle && object!=label) { points--; removeGWindow(window, object); } GLabel initScoreboard(GWindow window); updateScoreboard(window, label, points); } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
void HairyBrush::paintLine(KisPaintDeviceSP dab, KisPaintDeviceSP layer, const KisPaintInformation &pi1, const KisPaintInformation &pi2, qreal scale, qreal rotation) { m_counter++; qreal x1 = pi1.pos().x(); qreal y1 = pi1.pos().y(); qreal x2 = pi2.pos().x(); qreal y2 = pi2.pos().y(); qreal dx = x2 - x1; qreal dy = y2 - y1; // TODO:this angle is different from the drawing angle in sensor (info.angle()). The bug is caused probably due to // not computing the drag vector properly in paintBezierLine when smoothing is used //qreal angle = atan2(dy, dx); qreal angle = rotation; qreal mousePressure = 1.0; if (m_properties->useMousePressure) { // want pressure from mouse movement qreal distance = sqrt(dx * dx + dy * dy); mousePressure = (1.0 - computeMousePressure(distance)); scale *= mousePressure; } // this pressure controls shear and ink depletion qreal pressure = mousePressure * (pi2.pressure() * 2); Bristle *bristle = 0; KoColor bristleColor(dab->colorSpace()); m_dabAccessor = dab->createRandomAccessorNG((int)x1, (int)y1); m_dab = dab; // initialization block if ( firstStroke() ){ initAndCache(); } // if this is first time the brush touches the canvas and we use soak the ink from canvas if (firstStroke() && m_properties->useSoakInk){ if (layer){ colorifyBristles(layer, pi1.pos()); }else{ kWarning() << "Can't soak the ink from the layer"; } } qreal fx1, fy1, fx2, fy2; qreal randomX, randomY; qreal shear; float inkDeplation = 0.0; int inkDepletionSize = m_properties->inkDepletionCurve.size(); int bristleCount = m_bristles.size(); int bristlePathSize; qreal treshold = 1.0 - pi2.pressure(); for (int i = 0; i < bristleCount; i++) { if (!m_bristles.at(i)->enabled()) continue; bristle = m_bristles[i]; randomX = (drand48() * 2 - 1.0) * m_properties->randomFactor; randomY = (drand48() * 2 - 1.0) * m_properties->randomFactor; shear = pressure * m_properties->shearFactor; m_transform.reset(); m_transform.rotateRadians(-angle); m_transform.scale(scale, scale); m_transform.translate(randomX, randomY); m_transform.shear(shear, shear); if (firstStroke() || (!m_properties->connectedPath)){ // transform start dab m_transform.map(bristle->x(), bristle->y(), &fx1, &fy1); // transform end dab m_transform.map(bristle->x(), bristle->y(), &fx2, &fy2); }else{ // continue the path of the bristle from the previous position fx1 = bristle->prevX(); fy1 = bristle->prevY(); m_transform.map(bristle->x(), bristle->y(), &fx2, &fy2); } // remember the end point bristle->setPrevX(fx2); bristle->setPrevY(fy2); // all coords relative to device position fx1 += x1; fy1 += y1; fx2 += x2; fy2 += y2; if ( m_properties->threshold && (bristle->length() < treshold) ) continue; // paint between first and last dab const QVector<QPointF> bristlePath = m_trajectory.getLinearTrajectory(QPointF(fx1, fy1), QPointF(fx2, fy2), 1.0); bristlePathSize = m_trajectory.size(); memcpy(bristleColor.data(), bristle->color().data() , m_pixelSize); for (int i = 0; i < bristlePathSize ; i++) { if (m_properties->inkDepletionEnabled){ inkDeplation = fetchInkDepletion(bristle,inkDepletionSize); if (m_properties->useSaturation && m_transfo != 0) { saturationDepletion(bristle, bristleColor, pressure, inkDeplation); } if (m_properties->useOpacity) { opacityDepletion(bristle, bristleColor, pressure, inkDeplation); } }else{ bristleColor.setOpacity(bristle->length()); } addBristleInk(bristle, bristlePath.at(i), bristleColor); bristle->setInkAmount(1.0 - inkDeplation); bristle->upIncrement(); } } //repositionBristles(angle,slope); m_dab = 0; m_dabAccessor = 0; }
/* * Create a random colour. */ void getRandomColor(color *c) { c->red = (GLfloat) drand48(); c->blue = (GLfloat) drand48(); c->green = (GLfloat) drand48(); }
void * fail_prone_realloc(void *ptr, size_t size) { return drand48() < ALLOC_ERR_PROB ? NULL : __libc_realloc(ptr, size); }
void teleport(Client *c) { c->x = (int)(drand48()*BOARD_WIDTH); c->y = (int)(drand48()*BOARD_HEIGHT); }
int main(void) { // seed pseudorandom number generator srand48(time(NULL)); // instantiate window GWindow window = newGWindow(WIDTH, HEIGHT); // instantiate bricks initBricks(window); // instantiate ball, centered in middle of window GOval ball = initBall(window); // instantiate paddle, centered at bottom of window GRect paddle = initPaddle(window); // instantiate scoreboard, centered in middle of window, just above ball GLabel label = initScoreboard(window); // number of bricks initially int bricks = COLS * ROWS; // number of lives initially int lives = LIVES; // number of points initially int points = 0; //velocity double velocityx = drand48() * 2; double velocityy = 2.0; //update scoreboard updateScoreboard(window, label, points); int count = 1, lala = 0; // keep playing until game over while (lives > 0 && bricks > 0) { // TODO //move paddle GEvent event = getNextEvent(MOUSE_EVENT); if(event != NULL) { if (getEventType(event) == MOUSE_MOVED) { double x = getX(event) - getWidth(paddle)/2 ; setLocation(paddle, x, 550); } } //move ball move(ball, velocityx, velocityy); if(getX(ball) + getWidth(ball) >= getWidth(window)) velocityx = -velocityx; else if(getX(ball) <= 0) velocityx = -velocityx; else if(getY(ball) <= 0) velocityy = -velocityy; pause(10); //detect collision GObject object = detectCollision(window, ball); if (object != NULL) { if(strcmp(getType(object), "GLabel") == 0 && object != NULL) { continue; } if(strcmp(getType(object), "GRect") == 0) { if (object == paddle) velocityy = -velocityy; else { removeGWindow(window,object); velocityy = -velocityy; count++; if (count > 25) { points += 2; updateScoreboard(window, label, points); if(lala == 0) { velocityx *= 2; velocityy *= 2; } lala = 1; } else if (count >= 25 && count < 45) { points += 3; updateScoreboard(window, label, points); if(lala == 1) { velocityx *= 2; velocityy *= 2; } lala = 0; } else if (count >= 45 && count < 50) { points += 4; updateScoreboard(window, label, points); if(lala == 0) { velocityx *= 2; velocityy *= 2; } lala = 1; } else { points++; updateScoreboard(window, label, points); } } } } //loose life for dropping the ball if(getY(ball) + getHeight(ball) >= getHeight(window)) { lives--; points -= 5; //waitForClick(); setLocation(ball, 192, 342); setLocation(paddle, 160, 550); waitForClick(); continue; } } // wait for click before exiting waitForClick(); // game over closeGWindow(window); return 0; }
int main(int argc, char **argv) { int i; double x; /* results of /bin/ls with mica v02 */ /* TODO - read this from a file */ total=994400; counts[MEM_READ]=379835; counts[MEM_WRITE]=182969; counts[BRANCH]=195902; // counts[INTEGER]=706400; counts[INTEGER]=145734; counts[FP]=0; counts[STACK]=39869; counts[SHIFT]=13528; counts[STRING]=648; counts[SSE]=0; counts[OTHER]=35915; make_ratios(); for(i=0;i<TOTAL;i++) { fprintf(stderr,"%i %f %f\n",i,ratios[i],ranges[i]); } printf("\t.globl _start\n"); printf("_start:\n"); for(i=0;i<total;i++) { x=drand48(); if (x<ranges[MEM_READ]) mem_read_insn(); else if (x<ranges[MEM_WRITE]) mem_write_insn(); else if (x<ranges[BRANCH]) branch_insn(); else if (x<ranges[INTEGER]) integer_insn(); else if (x<ranges[FP]) fp_insn(); else if (x<ranges[STACK]) stack_insn(); else if (x<ranges[SHIFT]) shift_insn(); else if (x<ranges[STRING]) string_insn(); else if (x<ranges[SSE]) sse_insn(); else other_insn(); } printf("\t#================================\n"); printf("\t# Exit\n"); printf("\t#================================\n"); printf("exit:\n"); printf("\txor %%ebx,%%ebx\n"); printf("\txor %%eax,%%eax\n"); printf("\tinc %%eax\t\t\t# put exit syscall number (1) in eax\n"); printf("\tint $0x80\t\t\t# and exit\n"); printf("\n"); /* data segment */ printf(".data\n"); printf("data_begin: .byte "); for(i=0;i<data_size;i++) { printf("0"); if (i!=data_size-1) { printf(","); } else { printf("\n"); } } /* bss segment */ printf(".bss\n"); printf(".lcomm bss_begin,%d\n",bss_size); return 0; }
void M2_p2o1::each_train_one_iter() { //per-sentence approach int num_sentences = training_corpus->size(); //statistics int skip_sent_num = 0; int all_forward_instance = 0; int all_inst_right = 0; int all_inst_wrong = 0; //some useful info int odim = mach->get_odim(); //training time_t now; time(&now); //ctime is not rentrant ! use ctime_r() instead if needed cout << "##*** //p2o1// Start the training for iter " << cur_iter << " at " << ctime(&now) << "with lrate " << cur_lrate << endl; cout << "#Sentences is " << num_sentences << " and resample (about)" << num_sentences*hp->CONF_NN_resample << endl; for(int i=0;i<num_sentences;){ //random skip (instead of shuffling every time) if(drand48() > hp->CONF_NN_resample){ skip_sent_num ++; i ++; continue; } mach->prepare_batch(); //if nesterov update before each batch (pre-update) if(hp->CONF_NESTEROV_MOMENTUM) mach->nesterov_update(hp->CONF_UPDATE_WAY,hp->CONF_MOMENTUM_ALPHA); //main batch int this_sentence = 0; int this_instance = 0; int this_tokens = 0; for(;;){ //forward DependencyInstance* x = training_corpus->at(i); nn_input* the_inputs; REAL *fscores = forward_scores_o1(x,mach,&the_inputs,dict->get_helper(),0,hp); double* rscores = 0; double* tmp_marginals = 0; this_instance += the_inputs->get_numi(); all_forward_instance += the_inputs->get_numi(); all_inst_right += the_inputs->inst_good; all_inst_wrong += the_inputs->inst_bad; this_sentence ++; this_tokens += x->length()-1; i++; adjust_scores_before(the_inputs, fscores, odim, hp->CONF_margin); //two situations int length = x->length(); if(!hp->CONF_labeled){ //calculate prob rscores = rearrange_scores_o1(x,mach,the_inputs,fscores,0,0,hp); tmp_marginals = encodeMarginals(length,rscores); } else{ //calculate prob rscores = rearrange_scores_o1(x,mach,the_inputs,fscores,0,0,hp); tmp_marginals = LencodeMarginals(length,rscores,mach->get_odim()); } adjust_scores_after(the_inputs, fscores, odim, hp->CONF_margin); //set gradients int HERE_dim = the_inputs->num_width; REAL* to_assign = fscores; for(int ii=0;ii<the_inputs->num_inst*HERE_dim;ii+=HERE_dim){ int tmph = the_inputs->inputs->at(ii); int tmpm = the_inputs->inputs->at(ii+1); int tmp_goal = the_inputs->goals->at(ii/HERE_dim); for(int once=0;once<odim;once++,to_assign++){ if(tmp_goal == once) *to_assign = -1 * (1 - tmp_marginals[get_index2(length,tmph,tmpm,once,odim)]) + *to_assign * hp->CONF_score_p2reg; else *to_assign = tmp_marginals[get_index2(length,tmph,tmpm,once,odim)] + *to_assign * hp->CONF_score_p2reg; //now object is maximum } } //backward mach->backward(fscores); //mach->check_gradients(the_inputs); delete the_inputs; delete []fscores; delete []rscores; delete []tmp_marginals; //out of the mini-batch if(i>=num_sentences) break; if(hp->CONF_minibatch > 0){ if(this_sentence >= hp->CONF_minibatch) break; } else{ if(this_instance >= -1*hp->CONF_minibatch) break; } } //real update if(hp->CONF_mbatch_way == 1) mach->set_this_mbsize(this_tokens*this_tokens); else if(hp->CONF_mbatch_way == 2) mach->set_this_mbsize(this_sentence*this_sentence); mach->update(hp->CONF_UPDATE_WAY,cur_lrate,hp->CONF_NN_WD,hp->CONF_MOMENTUM_ALPHA,hp->CONF_RMS_SMOOTH); } cout << "Iter done, skip " << skip_sent_num << " sentences and f&b " << all_forward_instance << ";good/bad: " << all_inst_right << "/" << all_inst_wrong << endl; }
float Lowpass::random_samples_quality( Streamline *st, float radius, int nsamples, float dist, Window2d *win ) { int i; int num; int index; float x,y; float rad; float sum = 0; float xmin = 2.0 / xsize; float ymin = 2.0 / ysize; float xmax = 1 - 2.0 / xsize; float ymax = image->getaspect() - 2.0 / ysize; /* kluge to work around problems at the image borders */ int inside_points = 0; for (i = 0; i < st->samples; i++) { x = st->pts[i].x; y = st->pts[i].y; if (x > xmin && x < xmax && y > ymin && y < ymax) { inside_points = 1; break; } } if (inside_points == 0) return (0); // num = 2 * nsamples / 3; num = nsamples; for (i = 0; i < num; i++) { /* pick a random sample near the streamline in the lowpass image */ do { float pick = drand48(); if (pick < 0.3333) { index = (int) floor (drand48() * st->samples); rad = radius; } else if (pick < 0.6666) { index = 0; rad = 2 * radius; } else { index = st->samples - 1; rad = 2 * radius; } SamplePoint *sample = &st->pts[index]; x = sample->x + rad * (2 * drand48() - 1); y = sample->y + rad * (2 * drand48() - 1); } while (x < xmin || x > xmax || y < ymin || y > ymax); /* debug drawing of samples */ if (win) { win->set_color_index (255); win->line (x, y, x, y); } sum += Square (target - image->get_value(x,y)); } return (sum); }
/* makeObstacle: * Given a node, return an obstacle reflecting the * node's geometry. pmargin specifies how much space to allow * around the polygon. * Returns the constructed polygon on success, NULL on failure. * Failure means the node shape is not supported. * * If isOrtho is true, we have to use the bounding box of each node. * * The polygon has its vertices in CW order. * */ Ppoly_t *makeObstacle(node_t * n, expand_t* pmargin, boolean isOrtho) { Ppoly_t *obs; polygon_t *poly; double adj = 0.0; int j, sides; pointf polyp; boxf b; pointf pt; field_t *fld; epsf_t *desc; int isPoly; pointf* verts = NULL; pointf vs[4]; pointf p; pointf margin; switch (shapeOf(n)) { case SH_POLY: case SH_POINT: obs = NEW(Ppoly_t); poly = (polygon_t *) ND_shape_info(n); if (isOrtho) { isPoly = 1; sides = 4; verts = vs; margin.x = margin.y = 0; /* For fixedshape, we can't use the width and height, as this includes * the label. We only want to use the actual node shape. */ if (poly->option & FIXEDSHAPE) { b = polyBB (poly); vs[0] = b.LL; vs[1].x = b.UR.x; vs[1].y = b.LL.y; vs[2] = b.UR; vs[3].x = b.LL.x; vs[3].y = b.UR.y; } else { p.x = -ND_lw(n); p.y = -ND_ht(n)/2.0; vs[0] = p; p.x = ND_lw(n); vs[1] = p; p.y = ND_ht(n)/2.0; vs[2] = p; p.x = -ND_lw(n); vs[3] = p; } } else if (poly->sides >= 3) { isPoly = 1; sides = poly->sides; verts = poly->vertices; margin.x = pmargin->x; margin.y = pmargin->y; } else { /* ellipse */ isPoly = 0; sides = 8; adj = drand48() * .01; } obs->pn = sides; obs->ps = N_NEW(sides, Ppoint_t); /* assuming polys are in CCW order, and pathplan needs CW */ for (j = 0; j < sides; j++) { double xmargin = 0.0, ymargin = 0.0; if (isPoly) { if (pmargin->doAdd) { if (sides == 4) { switch (j) { case 0 : xmargin = margin.x; ymargin = margin.y; break; case 1 : xmargin = -margin.x; ymargin = margin.y; break; case 2 : xmargin = -margin.x; ymargin = -margin.y; break; case 3 : xmargin = margin.x; ymargin = -margin.y; break; } polyp.x = verts[j].x + xmargin; polyp.y = verts[j].y + ymargin; } else { double h = LEN(verts[j].x,verts[j].y); polyp.x = verts[j].x * (1.0 + margin.x/h); polyp.y = verts[j].y * (1.0 + margin.y/h); } } else { polyp.x = verts[j].x * margin.x; polyp.y = verts[j].y * margin.y; } } else { double c, s; c = cos(2.0 * M_PI * j / sides + adj); s = sin(2.0 * M_PI * j / sides + adj); if (pmargin->doAdd) { polyp.x = c*(ND_lw(n)+ND_rw(n)+pmargin->x) / 2.0; polyp.y = s*(ND_ht(n)+pmargin->y) / 2.0; } else { polyp.x = pmargin->x * c * (ND_lw(n) + ND_rw(n)) / 2.0; polyp.y = pmargin->y * s * ND_ht(n) / 2.0; } } obs->ps[sides - j - 1].x = polyp.x + ND_coord(n).x; obs->ps[sides - j - 1].y = polyp.y + ND_coord(n).y; } break; case SH_RECORD: fld = (field_t *) ND_shape_info(n); b = fld->b; obs = NEW(Ppoly_t); obs->pn = 4; obs->ps = N_NEW(4, Ppoint_t); /* CW order */ pt = ND_coord(n); if (pmargin->doAdd) { obs->ps[0] = genPt(b.LL.x-pmargin->x, b.LL.y-pmargin->y, pt); obs->ps[1] = genPt(b.LL.x-pmargin->x, b.UR.y+pmargin->y, pt); obs->ps[2] = genPt(b.UR.x+pmargin->x, b.UR.y+pmargin->y, pt); obs->ps[3] = genPt(b.UR.x+pmargin->x, b.LL.y-pmargin->y, pt); } else { obs->ps[0] = recPt(b.LL.x, b.LL.y, pt, pmargin); obs->ps[1] = recPt(b.LL.x, b.UR.y, pt, pmargin); obs->ps[2] = recPt(b.UR.x, b.UR.y, pt, pmargin); obs->ps[3] = recPt(b.UR.x, b.LL.y, pt, pmargin); } break; case SH_EPSF: desc = (epsf_t *) (ND_shape_info(n)); obs = NEW(Ppoly_t); obs->pn = 4; obs->ps = N_NEW(4, Ppoint_t); /* CW order */ pt = ND_coord(n); if (pmargin->doAdd) { obs->ps[0] = genPt(-ND_lw(n)-pmargin->x, -ND_ht(n)-pmargin->y,pt); obs->ps[1] = genPt(-ND_lw(n)-pmargin->x, ND_ht(n)+pmargin->y,pt); obs->ps[2] = genPt(ND_rw(n)+pmargin->x, ND_ht(n)+pmargin->y,pt); obs->ps[3] = genPt(ND_rw(n)+pmargin->x, -ND_ht(n)-pmargin->y,pt); } else { obs->ps[0] = recPt(-ND_lw(n), -ND_ht(n), pt, pmargin); obs->ps[1] = recPt(-ND_lw(n), ND_ht(n), pt, pmargin); obs->ps[2] = recPt(ND_rw(n), ND_ht(n), pt, pmargin); obs->ps[3] = recPt(ND_rw(n), -ND_ht(n), pt, pmargin); } break; default: obs = NULL; break; } return obs; }
void shadow_render (int w, int h) { double scale_x, scale_y; int move_done; double shadow_offset_x, shadow_offset_y; double light_x, light_y; light_x = w / 2.0; light_y = h / 2.0; cairo_save (cr); cairo_save (cr); cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE); scale_x = ((double) w) / (double) bg_width; scale_y = ((double) h) / (double) bg_height; cairo_scale (cr, scale_x, scale_y); cairo_set_source_surface (cr, bg_surface, 0.0, 0.0); cairo_paint (cr); cairo_restore (cr); cairo_set_operator (cr, CAIRO_OPERATOR_OVER); if (!(shadow_cnt % 10)) render_clock (); else if (!(shadow_cnt % 5)) render_fakewin (); shadow_cnt++; if (shadow_cnt >= 1000000) shadow_cnt = 0; cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 1.0); cairo_set_operator (cr, CAIRO_OPERATOR_OVER); shadow_offset_x = max_shadow_offset * ((fw_x + fakewin_width / 2) - light_x) / (w / 2.0); shadow_offset_y = max_shadow_offset * ((fw_y + fakewin_height / 2) - light_y) / (h / 2.0); cairo_save (cr); cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, shadow_alpha); cairo_mask_surface (cr, fakewin_surface, fw_x + shadow_offset_x - 0.05 * fakewin_width, fw_y + shadow_offset_y - 0.05 * fakewin_height); cairo_paint (cr); cairo_restore (cr); cairo_save (cr); cairo_translate (cr, (int) fw_x, (int) fw_y); cairo_set_source_surface (cr, fakewin_surface, 0.0, 0.0); cairo_paint (cr); cairo_restore (cr); shadow_offset_x = max_shadow_offset * ((cl_x + CLOCK_W / 2) - light_x) / (w / 2.0); shadow_offset_y = max_shadow_offset * ((cl_y + CLOCK_H / 2) - light_y) / (h / 2.0); cairo_save (cr); cairo_set_source_rgba (cr, 0.0, 0.0, 0.0, shadow_alpha); cairo_mask_surface (cr, clock_surface, cl_x + shadow_offset_x - 0.05 * CLOCK_W, cl_y + shadow_offset_y - 0.05 * CLOCK_H); cairo_paint (cr); cairo_restore (cr); cairo_save (cr); cairo_translate (cr, (int) cl_x, (int) cl_y); cairo_set_source_surface (cr, clock_surface, 0.0, 0.0); cairo_paint (cr); cairo_restore (cr); if (which) { move_done = shadow_move_towards_point (&fw_x, &fw_y); } else { move_done = shadow_move_towards_point (&cl_x, &cl_y); } if (move_done) { which = (int) (drand48 () + 0.5); dst_x = drand48 () * (w - ((which)? fakewin_width : CLOCK_W) - max_shadow_offset); dst_y = drand48 () * (h - ((which)? fakewin_height: CLOCK_H) - max_shadow_offset); if (which) { start_x = fw_x; start_y = fw_y; } else { start_x = cl_x; start_y = cl_y; } } cairo_restore (cr); }