void muste_nterm(int argc, char *argv[]) { int i; /* if (argc==1) { Rprintf("This program can be used as a SURVO 84C module only."); return; } */ s_init(argv[1]); i=init_sequence(); if (i<0) { s_end(argv[1]); return; } i=init_regressors(); if (i<0) return; i=linear_regression(seq_n,10); if (i<0) return; data_close(&data); edwrite(nterm_output_buffer,nterm_output_line,1); s_end(argv[1]); }
int main(int argc, char *argv[]) { printf("Linear Regression\n"); printf("=================\n\n"); // Check for a filename if (argc == 2) { FILE *input = fopen(argv[1], "r"); if (input == NULL) { perror(argv[1]); exit(1); } else { DataSet theData = load_data(input); fclose(input); LinRegResult linReg = linear_regression(theData); clean(theData); printf("\nSlope \tm = %15.6e\n", DESCALE(linReg.m)); // print slope printf("y-intercept\tb = %15.6e\n", DESCALE(linReg.b)); // print y-intercept printf("Correlation\tr = %15.6e\n", DESCALE(linReg.r)); // print correlation } } else { printf("ERROR: Must enter filename after ./linReg\n"); } return 0; }
void test_symplectic_central_force(void** state) { // We use the symplectic Crank-Nicolson method to integrate the trajectory // of a particle under the influence of a central force. We test that its // energy is conserved, and that the integration error converges to zero // at second order accuracy. ode_integrator_t* I = symplectic_central_force_integrator(); real_t rel_tol = 1e-4, abs_tol = 1e-6; euler_ode_integrator_set_tolerances(I, rel_tol, abs_tol); real_t R = 1.0; // radius of circular orbit. real_t V = 1.0; // Linear velocity magnitude. real_t T = 2.0 * M_PI * R / V; // period of rotation int num_trials = 4; int num_steps_array[4] = {16, 32, 64, 128}; real_t L2_array[num_trials]; for (int i = 0; i < num_trials; ++i) { int num_steps = num_steps_array[i]; real_t X[4] = {R, 0.0, 0.0, V}; // {x, y, vx, vy} real_t dt = T / num_steps; // Integrate the trajectory with the given time step. real_t t = 0.0; for (int j = 0; j < num_steps; ++j) { bool success = ode_integrator_step(I, dt, &t, X); //printf("%g %g %g %g %g\n", t, X[0], X[1], X[2], X[3]); assert_true(success); } // Check energy conservation. real_t E = 0.5 * (X[2]*X[2] + X[3]*X[3]); assert_true(fabs(E - 0.5) < 1e-3); // Compute error norms. real_t L2 = sqrt((X[0]-R)*(X[0]-R) + X[1]*X[1] + X[2]*X[2] + (X[3]-V)*(X[3]-V)); L2_array[i] = L2; } // Compute the convergence rate of the L2 error norm. real_t log_n_ratios[num_trials-1], log_L2_ratios[num_trials-1]; for (int i = 0; i < num_trials-1; ++i) { log_n_ratios[i] = log(pow(2.0, i)); log_L2_ratios[i] = log(L2_array[i+1] / L2_array[0]); } real_t A, B, sigma; linear_regression(log_n_ratios, log_L2_ratios, num_trials-1, &A, &B, &sigma); real_t L2_conv_rate = -A; log_urgent("symplectic central force L2 error conv rate = %g\n", L2_conv_rate); assert_true(L2_conv_rate >= 1.9947); // Clean up. ode_integrator_free(I); }
/* COMPUTE_SMOOTH_TIME_MAP compute regression line and estimate point at i Number of points in regression is smooth (an odd number). First index to compute is (smooth-1)/2. Use that line for the first (smooth+1)/2 points. The last index to compute is (file0_frames - (smooth+1)/2). Use that line for the last (smooth+1)/2 points. */ void Scorealign::compute_smooth_time_map() { int i; int hw = (smooth - 1) / 2; // half width of smoothing window // find the first point for (i = 0; i < first_x; i++) { smooth_time_map[i] = NOT_MAPPED; } // do the first points: float a, b; linear_regression(first_x + hw, smooth, a, b); for (i = first_x; i <= first_x + hw; i++) { smooth_time_map[i] = a + b * i; } // do the middle points: for (i = first_x + hw + 1; i < last_x - hw; i++) { linear_regression(i, smooth, a, b); smooth_time_map[i] = a + b * i; #if DEBUG_LOG fprintf(dbf, "time_map[%d] = %g, smooth_time_map[%d] = %g\n", i, time_map[i], i, a + b*i); #endif } // do the last points linear_regression(last_x - hw, smooth, a, b); for (i = last_x - hw; i <= last_x; i++) { smooth_time_map[i] = a + b * i; } // finally, fill with NOT_MAPPED for (i = last_x + 1; i < file0_frames; i++) smooth_time_map[i] = NOT_MAPPED; }
void test_stiffly_accurate_kinetics(void** state) { // We use the symplectic Crank-Nicolson method to integrate the trajectory // of a particle under the influence of a central force. We test that its // energy is conserved, and that the integration error converges to zero // at second order accuracy. ode_integrator_t* I = stiffly_accurate_kinetics_integrator(); // Reference values. real_t T = 400.0; real_t X0 = 0.4505440, X1 = 3.223217e-06, X2 = 5.494528e-01; int num_trials = 11; int num_steps_array[11] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}; real_t L2_array[num_trials]; for (int i = 0; i < num_trials; ++i) { int num_steps = num_steps_array[i]; real_t X[3] = {1.0, 0.0, 0.0}; real_t dt = T / num_steps; // Integrate with the given time step. real_t t = 0.0; for (int j = 0; j < num_steps; ++j) { bool success = ode_integrator_step(I, dt, &t, X); assert_true(success); } // Compute error norms from reference values. real_t L2 = sqrt((X[0]-X0)*(X[0]-X0) + (X[1]-X1)*(X[1]-X1) + (X[2]-X2)*(X[2]-X2)); L2_array[i] = L2; } // Compute the convergence rate of the L2 error norm. real_t log_n_ratios[num_trials-1], log_L2_ratios[num_trials-1]; for (int i = 0; i < num_trials-1; ++i) { log_n_ratios[i] = log(pow(2.0, i)); log_L2_ratios[i] = log(L2_array[i+1] / L2_array[0]); } real_t A, B, sigma; linear_regression(log_n_ratios, log_L2_ratios, num_trials-1, &A, &B, &sigma); real_t L2_conv_rate = -A; log_urgent("stiffly accurate kinetics L2 error conv rate = %g\n", L2_conv_rate); assert_true(L2_conv_rate >= 0.93); // Clean up. ode_integrator_free(I); }
int main(int argc, char **argv) { extern char *optarg; int optchar; char *treefile_name = NULL, *genomefile_name = NULL, *outfile_name = NULL, *corrfile_name = NULL; FILE *treefile, *genomefile, *outfile, *corrfile; long genome_generation, tree_generation, i, j, num_trees; double tree_d, gen_d, change_rate, m1, m_a, mutation_rate; double *tree_dist = NULL, *m_app = NULL; double grade, y0, r; long num_data; PHYLTREE phyltree; POPULATION population; int ret_code; phyl_init_tree(&phyltree); while ((optchar = getopt(argc, argv, "hg:t:o:c:m:")) != -1) { switch (optchar) { case 'g': genomefile_name = optarg; break; case 't': treefile_name = optarg; break; case 'c': corrfile_name = optarg; break; case 'o': outfile_name = optarg; break; case 'h': printf("mutcheck -- analyze apparent mutation rates\n"); printf("\n"); printf("Command line usage:\n"); printf("-g <filename>: Specify genome file (mandatory)\n"); printf("-t <filename>: Specify tree file (mandatory)\n"); printf("-o <filename>: Specify name for individual generation's output file\n"); printf("-c <filename>: Specify file for treedist vs reconstructed dist correlations\n"); printf("-h: Print this help and exit\n"); exit (EXIT_SUCCESS); } } if (treefile_name == NULL) { fprintf(stderr, "no tree file specified -- exit\n"); exit (EXIT_FAILURE); } if ((treefile = fopen(treefile_name, "r")) == NULL) { fprintf(stderr, "failed to open tree file \"%s\" -- exit\n", treefile_name); exit (EXIT_FAILURE); } if (genomefile_name == NULL) { fprintf(stderr, "No genome file specified -- exit\n"); fclose(treefile); exit (EXIT_FAILURE); } if ((genomefile = fopen(genomefile_name, "r")) == NULL) { fprintf(stderr, "Failed to open genome file \"%s\" -- exit\n", genomefile_name); fclose(treefile); exit (EXIT_FAILURE); } if (corrfile_name) { if ((corrfile = fopen(corrfile_name, "w")) == NULL) { fprintf(stderr, "Failed to open \"%s\" for correlation output -- exit\n", corrfile_name); fclose(treefile); fclose(genomefile); exit (EXIT_FAILURE); } } else { corrfile = stdout; corrfile_name = "stdout"; } if (outfile_name) { if ((outfile = fopen(outfile_name, "w")) == NULL) { fprintf(stderr, "mutcheck: Failed to open %s for output -- exit\n", outfile_name); fclose(treefile); fclose(genomefile); if (corrfile_name) fclose(corrfile); exit (EXIT_FAILURE); } } else outfile = NULL; while (!feof(genomefile) && !ferror(genomefile) && !feof(treefile) && !ferror(treefile)) { fgets(buf, 256, treefile); if ((buf[0] != 'g') || (buf[1] != ' ')) { fprintf(stderr, "Treefile corrupt after generation %ld\n", tree_generation); break; } tree_generation = strtol(buf + 2, NULL, 10); fgets(buf, 256, genomefile); if ((buf[0] != 'g') || (buf[1] != ' ')) { fprintf(stderr, "Genome file corrupt after generation %ld\n", genome_generation); break; } genome_generation = strtol(buf + 2, NULL, 10); fgets(buf, 256, treefile); num_trees = strtol(buf, (char **) NULL, 10); if (num_trees != 1) { fprintf(stderr, "%ld trees in generation %ld -- skipping\n", num_trees, tree_generation); for (i = 0; i < num_trees; i++) { phyl_read_tree(treefile, &phyltree); phyl_free_tree(&phyltree); } } else phyl_read_tree(treefile, &phyltree); read_genomes(genomefile, &population); if ((num_trees == 1) && (tree_generation == genome_generation)) { if ((tree_dist = (double *) malloc((population.size * population.size - 1) / 2 * sizeof(double))) == NULL) fprintf(stderr, "Failed to allocate array of tree distances\n"); else { if ((m_app = (double *) malloc(population.size * (population.size - 1) / 2 * sizeof(double))) == NULL) fprintf(stderr, "Failed to allocate array of reconstructed distances\n"); else { num_data = 0; for (i = 0; i < population.size; i++) { for (j = 0; j < i; j++) { tree_d = phyl_leafdistance(&phyltree, population.seq[i].name, population.seq[j].name); if (tree_d < 0) { fprintf(stderr, "Generation %ld: Trees and genomes inconsistent: error #%f\n", tree_generation, tree_d); break; } gen_d = diffchar_distance(population.seq[i].genome.length, population.seq[i].genome.g, population.seq[j].genome.length, population.seq[j].genome.g); change_rate = gen_d / (population.seq[i].genome.length); m1 = 1.0 - 256.0 / 255.0 * change_rate; if (m1 > 0.0) { errno = 0; m_a = 1.0 - pow(m1, 1.0 / 2.0 / tree_d); if (errno) perror("mutcheck: error in pow()"); else { tree_dist[num_data] = tree_d; m_app[num_data] = m_a; num_data++; if (outfile) fprintf(outfile, "%f %f\n", tree_d, m_a); } } else if (outfile) fprintf(outfile, "# Negative base operand to exponentiation: %f)\n", m1); } if (j < i) break; } if ((ret_code = linear_regression(num_data, tree_dist, m_app, &grade, &y0, &r)) < 0) { fprintf(stderr, "Error #%d in linear regression\n", ret_code); } else { mutation_rate = 1.0 - exp(grade); if (corrfile) fprintf(corrfile, "%ld %f %f\n", tree_generation, grade, r); } free(m_app); } free(tree_dist); } } phyl_free_tree(&phyltree); free_population(&population); #ifdef MEMDEBUG print_MemdebugStatistics(); #endif } if (corrfile != stdout) fclose(corrfile); if (outfile) fclose(outfile); fclose(treefile); fclose(genomefile); return (EXIT_SUCCESS); }
int main(int argc, char **argv) { int i,j,k; /* counters */ int ns=0; /* number of samples in input data */ int nwavelet=1024; /* number of samples in mother wavelet */ float base=0.0; /* base */ float first=0.0; /* first exponent */ float expinc=0.0; /* exponent increment */ float last=0.0; /* last exponent */ float exponent=0.0; /* each exponent */ float maxscale=0.0; /* maximum scale value */ float minscale=0.0; /* minimum scale value */ float x=0.0; float dx=0.0; /* xvalues incr */ float xmin=0.0; /* last xvalues - first vval */ float xcenter=0.0; /* x value of center of wavelet */ float xmax=0.0; /* last xvalues - first vval */ float sigma=1.0; /* sharpening parameter */ float waveletinc=0.0; /* wavelet interval */ float fmin=0.0; /* min, max filt value (debug) */ float *xvalues=NULL; /* wavelet xvalues */ float **filt=NULL; /* filter used for each conv */ float *f=NULL; /* scratch for filter fliplr */ float *sucwt_buff=NULL; /* scratch for convolution */ float *scales=NULL; /* scales */ float *waveletsum=NULL; /* cumulative sum of wavelet */ float *rt=NULL; /* temp data storage */ float *qt=NULL; /* temp hilbert transformed data storage */ float **tmpdata=NULL; /* temp data storage */ int wtype=0; /* type of wavelet selected */ float *wavelet=NULL; /* pointer to data constituting the wavelet */ int verbose=0; /* verbose flag */ int *index=NULL; /* wavelet subscripts to use for filter */ int *nconv=NULL; /* length of each filter */ int nscales=0; /* number of scales */ int holder=0; /* =1 compute the Holder-Lipschitz regularity */ float divisor=1.0; /* divisor used in Holder exponent calculation*/ /* Initialize */ initargs(argc, argv); requestdoc(1); /* Get parameters */ if(!getparfloat("base",&base)) base = 10.; if(!getparfloat("first",&first)) first = -1.0; if(!getparfloat("expinc",&expinc)) expinc = 0.01; if(!getparfloat("last",&last)) last = 1.5; if(!getparint("wtype",&wtype)) wtype = 0; if(!getparint("nwavelet",&nwavelet)) nwavelet = 1024; if(!getparfloat("xmin",&xmin)) xmin = -20.0; if(!getparfloat("xcenter",&xcenter)) xmin = 0.0; if(!getparfloat("xmax",&xmax)) xmax = 20.0; if(!getparfloat("sigma",&sigma)) sigma = 1.0; if(!getparint("holder",&holder)) holder = 0; if(!getparfloat("divisor",&divisor)) divisor = 1.0; if(!getparint("verbose",&verbose)) verbose = 0; if(verbose) warn("base=%f, first=%f, expinc=%f, last=%f",base,first,expinc,last); /* Allocate space */ xvalues = ealloc1float(nwavelet); wavelet = ealloc1float(nwavelet); memset((void *) xvalues, 0, nwavelet*FSIZE); memset((void *) wavelet, 0, nwavelet*FSIZE); /* Compute wavelet */ if (wtype == 0 ) { /* so far only Mex. Hat function */ MexicanHatFunction(nwavelet, xmin, xcenter, xmax, sigma, wavelet); } else { err("%d type of wavelet not yet implemented",wtype); } /* wavelet increment */ waveletinc = (xmax - xmin)/(nwavelet - 1); /* verbose warning */ if(verbose) warn("xmin=%f, xmax=%f, nwavelet=%d, waveletinc=%f", xmin,xmax,nwavelet,waveletinc); /* form xvalues[] array */ for(i=0,x=xmin; i<nwavelet; ++i,x+=waveletinc) xvalues[i] = x; xvalues[nwavelet-1] = xmax; /* compute scales */ scales = ealloc1float(SHRT_MAX); memset((void *) scales, 0, SHRT_MAX*FSIZE); exponent = first; x = 0; nscales = 0; minscale = pow(base,first); maxscale = pow(base,last); while(x <= maxscale) { x = pow(base,exponent); scales[nscales] = x; exponent+=expinc; ++nscales; if(nscales == SHRT_MAX) err("Too many scales, change params and re-run\n"); } --nscales; /* Allocate space */ nconv = ealloc1int(nscales); index = ealloc1int(nwavelet); waveletsum = ealloc1float(nwavelet); filt = ealloc2float(nwavelet,nscales); f = ealloc1float(nwavelet); /* Zero out arrays */ memset((void *) nconv, 0, nscales*ISIZE); memset((void *) index, 0, nwavelet*ISIZE); memset((void *) waveletsum, 0, nwavelet*FSIZE); memset((void *) filt[0], 0, nwavelet*nscales*FSIZE); memset((void *) f, 0, nwavelet*FSIZE); /* Form difference of xvalues */ for(i=nwavelet-1; i>=0; --i) xvalues[i] = xvalues[i] - xvalues[0]; dx = xvalues[1]; xmax = xvalues[nwavelet-1]; /* verbose warning */ if(verbose) { warn("first xvalues=%f, last xvalues=%f", xvalues[0],xvalues[nwavelet-1]); warn("dx=%f, xmax=%f",dx,xmax); } /* waveletsum is cumulative sum of wavelet multipled by dx */ fmin = 0; for(i=0; i<nwavelet; ++i) { fmin += wavelet[i]; waveletsum[i] = fmin * dx; } /* Build filters from summed wavelet */ for(i=0; i<nscales; ++i) { nconv[i] = 1 + (int)(scales[i] * xmax); for(j=0; j<nconv[i]; ++j) index[j] = 1 + j / (scales[i] * dx); for(j=0; j<nconv[i]; ++j) f[j] = waveletsum[index[j]-1]; /* flip left right */ for(j=0,k=nconv[i]-1; j<nconv[i]; ++j,--k) filt[i][j] = f[k]; } /* Verbose warning */ if(verbose) { warn("Convolution Lengths"); for(i=0; i<nscales; ++i) warn("%d ",nconv[i]); } if(verbose) warn("%d scales will be used for transforms",nscales); /* Get information from first trace */ if(!gettr(&tr)) err("Cannot get first trace\n"); ns = tr.ns; /* Allocate temporary storage space */ rt = ealloc1float(ns); qt = ealloc1float(ns); tmpdata = ealloc2float(nscales,ns); /* Zero out rt and qt */ memset((void *) rt, 0, ns*FSIZE); memset((void *) qt, 0, ns*FSIZE); /* Alloc sucwt_buffer for longest convolution */ sucwt_buff = ealloc1float(ns+nconv[nscales-1]+1); do { /* main loop over traces */ outtr.d2 = waveletinc; outtr.f2 = minscale; memcpy((void *)&outtr,(const void *)&tr,HDRBYTES); /* Apply filters to produce wavelet transform */ for(i=0; i<nscales; ++i) { /* loop over scales */ for(j=0; j<ns+nconv[nscales-1]+1; ++j) sucwt_buff[j] = 0; /* convolve wavelet with data */ conv(ns,0,tr.data,nconv[i],0, filt[i],ns,0,sucwt_buff); for(j=0; j<ns; ++j) rt[j] = sucwt_buff[j+nconv[i]/2-1]; for(j=ns-1; j>0; --j) rt[j] = rt[j] - rt[j-1]; for(j=0; j<ns; ++j) rt[j] = -sqrt(scales[i]) * rt[j]; /* form the hilbert transform of rt */ hilbert(ns,rt,qt); /* If not holder, then output envelope */ if (!holder) { for (j=0 ; j<ns; ++j) { outtr.data[j] = sqrt(rt[j]*rt[j] + qt[j]*qt[j]); } outtr.cdpt = i + 1; puttr(&outtr); } else { /* compute the modulus */ for (j=0 ; j<ns; ++j) { tmpdata[j][i] = sqrt(rt[j]*rt[j] + qt[j]*qt[j]); } } } if (holder) { /* compute the Holder regularity traces */ float *x; float *y; float lrcoeff[4]; x = ealloc1float(nscales); y = ealloc1float(nscales); /* Compute an estimate of the Lipschitz (Holder) * regularity. Following Mallat (1992) * * ln | Wf(x,s)| < ln C + alpha * ln|s| * * alpha here is the Holder or Lipschitz exponent * s is the length scale, and Wf(x,s) is f in the * wavelet basis. * * Here we merely fit a straight line * through the log-log graph of the of our wavelet * transformed data and return the slope as * the regularity measure. * */ for ( j =0 ; j< ns ; ++j ) { int icount=0; x[0]=0; for ( i = 1 ; i < nscales ; ++i ) { /* We stay away from values that will make */ /* NANs in the output */ if ((i>1) && (tmpdata[j][i-1] - tmpdata[j][1] > 0.0)) { y[icount] = log(ABS(tmpdata[j][i] - tmpdata[j][1])); x[icount] = log(scales[i]-scales[1]); ++icount; } } --icount; /* straight line fit, return slope */ if ((icount> 10) && (divisor==1.0) ) { linear_regression(y, x, icount, lrcoeff); /* lrcoeff[0] is the slope of the line */ /* which is the Holder (Lipschitz) */ /* exponent */ outtr.data[j] = lrcoeff[0]; } else if ((icount> 10) && (divisor>1.0) ) { float maxalpha=0.0; float interval=icount/divisor; for ( k = interval; k < icount; k+=interval){ linear_regression(y, x, k, lrcoeff); maxalpha = MAX(lrcoeff[0],maxalpha); } outtr.data[j] = maxalpha; } else if ((icount < 10) && (divisor>=1.0)) { outtr.data[j] = 0.0; } else if ( divisor < 1.0 ) { err("divisor = %f < 1.0!", divisor); } } puttr(&outtr); /* output holder regularity traces */ } } while(gettr(&tr)); return(CWP_Exit()); }
void a1(void) { int N = 3, M = 1; data *dat = (data*) malloc(N*sizeof(data)); dat[0] = (data) { .val = 299793.0, .delta = 2.0 }; dat[1] = (data) { .val = 299792.0, .delta = 4.5 }; dat[2] = (data) { .val = 299782.0, .delta = 25.0 }; double avg = average_value(N, dat), sig_i = sigma_square_intern(N, dat), sig_e = sigma_square_extern(M, N, dat); printf("c_avg = %f\n", avg); printf("sigma_i = %f\n", sqrt(sig_i)); printf("sigma_e = %f\n", sqrt(sig_e)); } void a2(void) { int N; measurement *m = read_measurements("dat/a2.txt", &N); double a, b, sig_a, sig_b, chi; printf("\nLinear regression I = b*U:\n"); linear_regression(N, m, NULL, &b, NULL, &sig_b); chi = chi_square_(N, m, 0, b); printf("b = %f +/- %f, chi = %f\n", b, sqrt(sig_b)/2, sqrt(chi)); printf("\nLinear regression I = a + b*U:\n"); linear_regression(N, m, &a, &b, &sig_a, &sig_b); chi = chi_square_(N, m, a, b); printf("a = %f +/- %f, b = %f +/- %f, chi = %f\n", a, sqrt(sig_a)/2, b, sqrt(sig_b)/2, sqrt(chi)); } void a3(void) { // order of polynoms + 1 int N[5] = {3, 5, 9, 13, 17}; // output function (%i = current N) char *output_p_gp = "results/a3/poly-%i.gp", *output_p_txt = "results/a3/poly-%i.txt", *output_l_dat = "results/a3/legendre-%i.dat", *output_l_txt = "results/a3/legendre-%i.txt"; // read data matrix dat = read_data("dat/a3.txt"); int i; for (i = 0; i < sizeof(N)/sizeof(int); i++) { // // use polynoms // matrix F = init_F(dat, N[i], &polynom); vector b = init_b(dat, N[i], &polynom); // solve system of linear equations vector x = solve_gauss(F,b); char fp[100]; // parameter output snprintf(fp, sizeof(fp), output_p_txt, N[i]-1); printf("Opening file %s...\n", fp); FILE *file = fopen(fp, "w+"); vector_fprint(file, x); fclose(file); // gnuplot output snprintf(fp, sizeof(fp), output_p_gp, N[i]-1); printf("Opening file %s...\n", fp); file = fopen(fp, "w+"); fprintf(file, "plot "); int k; for (k = 0; k < x.N; k++) { fprintf(file, "%e * x**%i", VectorGET(x,k), k); if (k < x.N-1) fprintf(file, " + "); } fprintf(file, "\n"); fclose(file); // // Use legendre polynoms // F = init_F(dat, N[i], &legendre_polynom); b = init_b(dat, N[i], &legendre_polynom); // solve system of linear equations x = solve_gauss(F,b); // parameter output snprintf(fp, sizeof(fp), output_l_txt, N[i]-1); printf("Opening file %s...\n", fp); file = fopen(fp, "w+"); vector_fprint(file, x); // "plot" data for legendre polynoms snprintf(fp, sizeof(fp), output_l_dat, N[i]-1); printf("Opening file %s...\n", fp); file = fopen(fp, "w+"); double r = -1.0, dr = 0.01; while (r <= 1.0) { double sum = 0; for (k = 0; k < x.N; k++) { sum += VectorGET(x,k) * legendre_polynom(k,r); } fprintf(file, "%f %e\n", r, sum); r += dr; } fclose(file); file = NULL; } } int main() { //a1(); //a2(); a3(); return 0; }
int main(int argc, char **argv) { extern char *optarg; int optchar; char *treefile_name = NULL, *genomefile_name = NULL, *outfile_name = NULL, *corrfile_name = NULL, *mutfile_name = NULL; FILE *treefile, *genomefile, *outfile, *corrfile, *mutfile; long genome_generation, tree_generation, i, j, num_trees; double tree_d, rec_d, rec_d1, change_rate, mutation_rate; double *tree_dist = NULL, *reconst_dist = NULL; double lambda, y0, r; long num_data; PHYLTREE phyltree; POPULATION population; int ret_code; phyl_init_tree(&phyltree); while ((optchar = getopt(argc, argv, "hg:t:o:c:m:")) != -1) { switch (optchar) { case 'g': genomefile_name = optarg; break; case 't': treefile_name = optarg; break; case 'c': corrfile_name = optarg; break; case 'm': mutfile_name = optarg; break; case 'o': outfile_name = optarg; break; case 'h': printf("treecorr -- check correlation between corrected\n"); printf(" edit or hamming diatance and true tree distance\n"); printf("\n"); printf("Command line usage:\n"); printf("-g <filename>: Specify genome file (mandatory)\n"); printf("-t <filename>: Specify tree file (mandatory)\n"); printf("-o <filename>: Specify base name for individual generation's output file\n"); printf("-c <filename>: Specify file for treedist vs reconstructed dist correlations\n"); printf("-m <filename>: Specify file for reconstructed mutation rates\n"); printf("-h: Print this help and exit\n"); exit (EXIT_SUCCESS); } } if (treefile_name == NULL) { fprintf(stderr, "no tree file specified -- exit\n"); exit (EXIT_FAILURE); } if ((treefile = fopen(treefile_name, "r")) == NULL) { fprintf(stderr, "failed to open tree file \"%s\" -- exit\n", treefile_name); exit (EXIT_FAILURE); } if (genomefile_name == NULL) { fprintf(stderr, "No genome file specified -- exit\n"); fclose(treefile); exit (EXIT_FAILURE); } if ((genomefile = fopen(genomefile_name, "r")) == NULL) { fprintf(stderr, "Failed to open genome file \"%s\" -- exit\n", genomefile_name); fclose(treefile); exit (EXIT_FAILURE); } if (corrfile_name) { if ((corrfile = fopen(corrfile_name, "w")) == NULL) { fprintf(stderr, "Failed to open \"%s\" for correlation output -- exit\n", corrfile_name); fclose(treefile); fclose(genomefile); exit (EXIT_FAILURE); } } else { corrfile = stdout; corrfile_name = "stdout"; } if (mutfile_name) { if ((mutfile = fopen(mutfile_name, "w")) == NULL) { fprintf(stderr, "Failed to open \"%s\" for mutation output -- exit\n", mutfile_name); fclose(treefile); fclose(genomefile); if (corrfile != stdout) fclose(corrfile); exit (EXIT_FAILURE); } } else mutfile = NULL; while (!feof(genomefile) && !ferror(genomefile) && !feof(treefile) && !ferror(treefile)) { fgets(buf, 256, treefile); if ((buf[0] != 'g') || (buf[1] != ' ')) { fprintf(stderr, "Treefile corrupt after generation %ld\n", tree_generation); break; } tree_generation = strtol(buf + 2, NULL, 10); fgets(buf, 256, genomefile); if ((buf[0] != 'g') || (buf[1] != ' ')) { fprintf(stderr, "Genome file corrupt after generation %ld\n", genome_generation); break; } genome_generation = strtol(buf + 2, NULL, 10); fgets(buf, 256, treefile); num_trees = strtol(buf, (char **) NULL, 10); if (num_trees != 1) { fprintf(stderr, "%ld trees in generation %ld -- skipping\n", num_trees, tree_generation); for (i = 0; i < num_trees; i++) { phyl_read_tree(treefile, &phyltree); phyl_free_tree(&phyltree); } } else phyl_read_tree(treefile, &phyltree); read_genomes(genomefile, &population); if ((num_trees == 1) && (tree_generation == genome_generation)) { if ((tree_dist = (double *) malloc((population.size * population.size - 1) / 2 * sizeof(double))) == NULL) fprintf(stderr, "Failed to allocate array of tree distances\n"); else { if ((reconst_dist = (double *) malloc(population.size * (population.size - 1) / 2 * sizeof(double))) == NULL) fprintf(stderr, "Failed to allocate array of reconstructed distances\n"); else { if (outfile_name) { sprintf(buf, "%s-%05ld.gpd", outfile_name, tree_generation); outfile = fopen(buf, "w"); fprintf(outfile, "# generation %ld\n", tree_generation); } num_data = 0; for (i = 0; i < population.size; i++) { for (j = 0; j < i; j++) { tree_d = phyl_leafdistance(&phyltree, population.seq[i].name, population.seq[j].name); if (tree_d < 0) { fprintf(stderr, "Generation %ld: Trees and genomes inconsistent: error #%f\n", tree_generation, tree_d); break; } rec_d = diffchar_distance(population.seq[i].genome.length, population.seq[i].genome.g, population.seq[j].genome.length, population.seq[j].genome.g); change_rate = rec_d / (population.seq[i].genome.length); rec_d1 = 1.0 - 256.0 / 255.0 * change_rate; if (rec_d1 > 0.0) { rec_d = log(rec_d1); tree_dist[num_data] = tree_d; reconst_dist[num_data] = rec_d; num_data++; if (outfile) fprintf(outfile, "%f %f\n", tree_d, rec_d); } else if (outfile) fprintf(outfile, "# Infinite distance (log operand: %f)\n", rec_d1); } if (j < i) break; } if (outfile_name && outfile) fclose(outfile); if ((ret_code = linear_regression(num_data, tree_dist, reconst_dist, &lambda, &y0, &r)) < 0) { fprintf(stderr, "Error #%d in linear regression\n", ret_code); } else { mutation_rate = 1.0 - exp(lambda); if (corrfile) fprintf(corrfile, "%ld %f\n", tree_generation, r); if (mutfile) fprintf(mutfile, "%ld %f\n", tree_generation, mutation_rate); } free(reconst_dist); } free(tree_dist); } } phyl_free_tree(&phyltree); free_population(&population); #ifdef MEMDEBUG print_MemdebugStatistics(); #endif } if (mutfile) fclose(mutfile); if (corrfile != stdout) fclose(corrfile); fclose(treefile); fclose(genomefile); return (EXIT_SUCCESS); }
void ICharacter::calculateStats () { boost::unique_lock<boost::mutex> statsLock(m_stats_mutex); boost::mutex::scoped_lock property_lock(m_property_mutex); /// SET BASE STATS AND RECALCULATE m_MA = std::make_pair(0,0); m_PA = std::make_pair(0,0); m_PAbs = 0; m_MAbs = 0; m_PD = m_property->PhysicalDefense; m_MD = m_property->MagicalDefense; m_BR = m_property->BlockRatio; m_CR = 0; m_PR = m_property->ParryRatio; m_HR = m_property->HitRatio; m_PBalance = 0; m_MBalance = 0; m_PRate = 0; m_MRate = 0; m_AD = 0; float wlkspeed = m_property->WalkSpeed; float runspeed = m_property->RunSpeed; float bskspeed = m_property->BersekSpeed; property_lock.unlock(); bool hasWall = false; uint32_t curWallHP = m_Effects[STAT_WALL_HP]; m_Effects.clear(); short speed_percent = 0; short hp_percent = 0; short mp_percent = 0; short pr_percent = 0; short hr_percent = 0; short pd_percent = 0; short md_percent = 0; std::vector<std::pair<CHAR_STATS,int32_t> > bonus; calculatePreStats(bonus); boost::mutex::scoped_lock buff_lock(m_buff_mutex); for ( std::map<uint32_t,Buff>::const_iterator k = m_buff_list.begin(); k != m_buff_list.end(); ++k) { for (Skill::buff_const_iterator j = k->second.skill->buff_begin(); j != k->second.skill->buff_end(); ++j) { switch(j->ID) { case BUFF_CRITICAL_INC: m_CR += j->Arg[0]; break; case BUFF_SPEED_INC: case BUFF_SPEED_INC2: case BUFF_SPEED_INC3: speed_percent += j->Arg[0]; break; case BUFF_PARRY_INC: m_PR += j->Arg[0]; pr_percent += j->Arg[1]; break; case BUFF_PARRY_DEC: m_PR -= j->Arg[0]; break; case BUFF_HIT_INC: m_HR += j->Arg[0]; hr_percent += j->Arg[1]; break; case BUFF_HIT_DEC: m_HR -= j->Arg[0]; break; case BUFF_HP_INC: m_MaxHP += j->Arg[0]; hp_percent += j->Arg[1]; break; case BUFF_MP_INC: m_MaxMP += j->Arg[0]; mp_percent += j->Arg[1]; break; case BUFF_RANGE_INC: m_AD += j->Arg[0]; break; case BUFF_DAMAGE_INC: m_PRate += j->Arg[0]; m_MRate += j->Arg[0]; break; case BUFF_INT_INC: case BUFF_STR_INC: case BUFF_SHIELD_PWR_4_DAMAGE: calculateBuffEffects(bonus,*j); break; case BUFF_REINCARNATION: m_Effects[STAT_HP_RGN] += j->Arg[0]; m_Effects[STAT_MP_RGN] += j->Arg[1]; break; case BUFF_IGNORE_DEFENSE: m_Effects[STAT_IGD] += j->Arg[0]; break; case BUFF_CRIT_PARRY_INC: m_Effects[STAT_CPR] += j->Arg[0]; break; case BUFF_GOLD_DROP_INC: m_Effects[STAT_GOLD_DROP] += j->Arg[0]; break; case BUFF_MAGICOPTION_LUCK_INC: m_Effects[STAT_MOL] += j->Arg[0]; break; case BUFF_ENCHANT_LUCK_INC: m_Effects[STAT_ETL] += j->Arg[0]; break; case BUFF_MP_ABSORB: m_Effects[STAT_MP_ABSORB] += j->Arg[0]; break; case BUFF_DAMAGE_PWR_INC: m_PA.first += j->Arg[0]; m_PA.second += j->Arg[0]; m_MA.first += j->Arg[1]; m_MA.second += j->Arg[1]; break; case BUFF_DETECT: case BUFF_DETECT_V2: //(5 Stealth) (6 Invisible) (7 All) //Max level break; case BUFF_HEAL_INC: m_Effects[STAT_HP_HEAL] += j->Arg[0]; m_Effects[STAT_MP_HEAL] += j->Arg[1]; break; case BUFF_ABSORB_WALL: hasWall = true; m_Effects[STAT_WALL] = j->Arg[0] == WALL_TYPE_PHYSICAL; m_Effects[STAT_WALL_MAX] = j->Arg[1]; m_Effects[STAT_WALL_RATE] = j->Arg[3]; m_Effects[STAT_WALL_ID] = k->first; break; case BUFF_BLOCK_INC: //BLOCK TYPE +0 (15 ALL) (11 Magic %) (7 Physical %) //BLOCK RATE +1 m_BR += j->Arg[1]; break; case BUFF_DAMAGE_REFLECT: //PROBABILITY [%] //PHY DAMAGE RETURNED [%] //MAG DAMAGE RETURNED [%] //RETURN RANGE break; case BUFF_ABSORB: //TYPE (3 - Physical Absorb) (12 & 15 - Absorb all) (4 Physical) (8 Magical) (6 Physical ranged) //Amount (%) //0 break; case BUFF_DEFENSE_INC: m_PD += j->Arg[0]; m_MD += j->Arg[1]; //Caster Range break; case BUFF_DEFENSE_DEC: pd_percent -= j->Arg[0]; md_percent -= j->Arg[1]; break; case BUFF_DAMAGE_DEC: m_PRate -= j->Arg[0]; m_MRate -= j->Arg[1]; break; case BUFF_HP_DEC: //Duration //0 hp_percent -= j->Arg[2]; //2 break; default: break; } } } if (hasWall) { uint32_t wallMax = m_Effects[STAT_WALL_MAX]; if (curWallHP > wallMax) m_Effects[STAT_WALL_HP] = wallMax; } buff_lock.unlock(); for (std::vector<std::pair<CHAR_STATS,int32_t> >::const_iterator it = bonus.begin(); it != bonus.end(); ++it) { switch(it->first) { case STAT_HP_PERCENT: hp_percent += it->second; break; case STAT_HR_PERCENT: hr_percent += it->second; break; case STAT_MP_PERCENT: mp_percent += it->second; break; case STAT_PR_PERCENT: pr_percent += it->second; break; default: break; } } calculatePostStats(); if (hp_percent) m_MaxHP = linear_regression(m_MaxHP,hp_percent); if (m_HP > m_MaxHP) m_HP = m_MaxHP; if (mp_percent) m_MaxMP = linear_regression(m_MaxMP,mp_percent); if (m_MP > m_MaxMP) m_MP = m_MaxMP; if (pr_percent) m_PR = linear_regression(m_PR,pr_percent); if (hr_percent) m_HR = linear_regression(m_HR,hr_percent); if (pd_percent) m_PD = linear_regression(m_PD,pd_percent); if (md_percent) m_MD = linear_regression(m_MD,md_percent); if (speed_percent) { wlkspeed = linear_regression(wlkspeed,speed_percent); runspeed = linear_regression(runspeed,speed_percent); bskspeed = linear_regression(bskspeed,speed_percent); } if (IsBerserk()) { wlkspeed *=2; runspeed *=2; bskspeed *=2; m_PA.first *= 2; m_PA.second *= 2; m_MA.first *= 2; m_MA.second *= 2; } m_WalkSpeed = wlkspeed; m_RunSpeed = runspeed; m_BerserkSpeed = bskspeed; calculateStatus(); statsLock.unlock(); if (!signal_stats.empty()) signal_stats(); if (!signal_speed.empty()) signal_speed(m_WalkSpeed,m_RunSpeed); }
/* main routine */ int main(int argc, char *argv[]){ FILELog::ReportingLevel() = logINFO; VARIABLES vars; vars = commandline_input(argc, argv); clock_t init, final; int number_of_particles = vars.num; double timestep = vars.dt; bool use_T2 = vars.use_T2; // = false (no T2 decay), = true (T2 decay) int num_of_repeat = vars.num_of_repeat; //Number of times to repeat simulation. For every repeat all data is flushed and we start the simulation again. int number_of_timesteps; number_of_timesteps = (int)ceil(vars.gs/timestep); double permeability = 0.0; double radius = .00535; double d = sqrt( 2.0*PI*radius*radius/( sqrt(3.0)*.79 ) ); //double lattice_size = 0.00601922026995422789215053328651; double grad_duration = 4.5; double D_extra = 2.5E-6; double D_intra = 1.0E-6; double T2_e = 200; double T2_i = 200; FILE_LOG(logINFO) << "f = " << 2.0*PI*radius*radius/(sqrt(3.0)*d*d) << std::endl; Vector3 xhat(1.0,0.0,0.0); Vector3 yhat(0.0,1.0,0.0); Vector3 zhat(0.0,0.0,1.0); Lattice<Cylinder_XY> lattice(D_extra, T2_e, permeability); lattice.setLatticeVectors(d,2.0*d*0.86602540378443864676372317075294,d,xhat,yhat,zhat); lattice.addBasis(Cylinder_XY(d/2.0, 0.0, radius, T2_i, D_intra, 1)); lattice.addBasis(Cylinder_XY(0.0, d*0.86602540378443864676372317075294, radius, T2_i, D_intra, 2)); lattice.addBasis(Cylinder_XY(d/2.0, 2.0*d*0.86602540378443864676372317075294, radius, T2_i, D_intra, 3)); lattice.addBasis(Cylinder_XY(d, d*0.86602540378443864676372317075294, radius, T2_i, D_intra, 4)); double gspacings [] = { 8.0 , 10.5 , 14.0 , 18.5 , 24.5 , 32.5 , 42.5 , 56.5 }; double bvals [] = {108780, 154720, 219040, 301730, 411980, 558990, 742420, 1000000 }; double G [9]; for (int kk = 0; kk < num_of_repeat; kk++) { vector<PGSE> measurements_x; vector<PGSE> measurements_y; vector<PGSE> measurements_z; for (int i = 0; i < 8; i++){ double echo_time = 2.0*grad_duration + gspacings[i]; G[0] = 0.0; G[i+1] = sqrt(bvals[i]/(GAMMA*GAMMA*grad_duration*grad_duration*(grad_duration + gspacings[i] - (grad_duration/3.0)))); measurements_x.push_back(PGSE(grad_duration,gspacings[i], timestep, G[0], echo_time, number_of_particles, xhat)); measurements_y.push_back(PGSE(grad_duration,gspacings[i], timestep, G[0], echo_time, number_of_particles, yhat)); measurements_z.push_back(PGSE(grad_duration,gspacings[i], timestep, G[0], echo_time, number_of_particles, zhat)); measurements_x.push_back(PGSE(grad_duration,gspacings[i], timestep, G[i+1], echo_time, number_of_particles, xhat)); measurements_y.push_back(PGSE(grad_duration,gspacings[i], timestep, G[i+1], echo_time, number_of_particles, yhat)); measurements_z.push_back(PGSE(grad_duration,gspacings[i], timestep, G[i+1], echo_time, number_of_particles, zhat)); } vector<double> lnsignal(2); vector<double> b(2); cout << " trial = " << kk << endl; Particles ensemble(number_of_particles,timestep, use_T2); lattice.initializeUniformly(ensemble.getGenerator() , ensemble.getEnsemble() ); for (int k = 0; k < measurements_x.size();k++){ measurements_x[k].updatePhase(ensemble.getEnsemble(), 0.0); measurements_y[k].updatePhase(ensemble.getEnsemble(), 0.0); measurements_z[k].updatePhase(ensemble.getEnsemble(), 0.0); } for (int i = 1; i <= number_of_timesteps; i++){ ensemble.updateposition(lattice); for (int k = 0; k < measurements_x.size();k++){ measurements_x[k].updatePhase(ensemble.getEnsemble(), i*timestep); measurements_y[k].updatePhase(ensemble.getEnsemble(), i*timestep); measurements_z[k].updatePhase(ensemble.getEnsemble(), i*timestep); } } for (int i = 0; i < 8*2; i+=2){ double ADCx, ADCy, ADCz, diff_time; lnsignal[0] = log(measurements_x[i].get_signal()); b[0] = measurements_x[i].get_b(); lnsignal[1] = log(measurements_x[i+1].get_signal()); b[1] = measurements_x[i+1].get_b(); ADCx = -1.0*linear_regression(lnsignal,b); //std::cout << b[0] << " " << lnsignal[0] << " " << b[1] << " " << lnsignal[1] << " "; lnsignal[0] = log(measurements_y[i].get_signal()); b[0] = measurements_y[i].get_b(); lnsignal[1] = log(measurements_y[i+1].get_signal()); b[1] = measurements_y[i+1].get_b(); ADCy = -1.0*linear_regression(lnsignal,b); //std::cout << b[0] << " " << lnsignal[0] << " " << b[1] << " " << lnsignal[1] << " "; lnsignal[0] = log(measurements_z[i].get_signal()); b[0] = measurements_z[i].get_b(); lnsignal[1] = log(measurements_z[i+1].get_signal()); b[1] = measurements_z[i+1].get_b(); ADCz = -1.0*linear_regression(lnsignal,b); //std::cout << b[0] << " " << lnsignal[0] << " " << b[1] << " " << lnsignal[1] << std::endl; diff_time = measurements_x[i].get_DT(); std::cout << i << " " << diff_time << " " << ADCx << " " << ADCy << " " << ADCz << " " << b[1] << " " << G[1] << std::endl; } } final= clock()-init; //final time - intial time