void DistToPA(gsl_histogram * h, double mag, double sigma) { double m1 = 0.5*mag + 0.5; double s1 = 0.25*sigma; double n1 = m1*(1. - m1)/s1 - 1.; double a1 = m1*n1; double b1 = (1. - m1)*n1; for (int pa = 1; pa < 8; pa++) { char line[80]; double x; double data[6000]; int size = 0; int nbins = h->n; gsl_histogram * hpa = gsl_histogram_alloc( nbins); gsl_histogram_set_ranges_uniform( hpa, 0.0, 1.0); char fname[50]; sprintf(fname,"/home/jonatas/mzanlz/mZ_pa%d.dat",pa); FILE * fp; fp = fopen(fname,"rt"); while(fgets(line,80,fp) != NULL){ x = atof(line); size++; data[size] = x; gsl_histogram_increment( hpa, x); } double m2 = 0.5*gsl_stats_mean( data, 1, size ) + 0.5; double s2 = 0.25*gsl_stats_variance( data, 1, size ); double n2 = m2*(1. - m2)/s2 - 1.; double a2 = m2*n2; double b2 = (1. - m2)*n2; NormalizaGSLHistograma( hpa ); //char hname[100]; //sprintf(hname,"pa%d",pa); //PrintGSLHistogram( hpa, hname ); gsl_histogram_sub( hpa, h); double D = 0; for (size_t i = 0; i < nbins; i++) { D += gsl_histogram_get( hpa , i )*gsl_histogram_get( hpa , i ); } // printf("%g %g ", sqrt(D), KLbetas(a1,b1,a2,b2)); fclose(fp); gsl_histogram_free( hpa ); } }
double chisq ( gsl_histogram* values, gsl_histogram* expected ) { gsl_histogram*t = gsl_histogram_clone(values); gsl_histogram_sub(t, expected); int j; double chi = 0; for (j=0; j<B; ++j) { chi += pow(gsl_histogram_get(t, j), 2)/gsl_histogram_get(expected, j); } return gsl_cdf_chisq_Q(chi, B-1); }
double kolsmir ( gsl_histogram* values, gsl_histogram* expected ) { double D = 0; double cv = 0, ce = 0; int j; for (j=0; j<B; ++j) { cv += gsl_histogram_get(values, j); ce += gsl_histogram_get(expected, j); D = fmax(D, fabs(cv-ce)); } return D / sqrt(1.0 * B); }
void QwtHistogram::loadDataFromMatrix() { if (!d_matrix) return; int size = d_matrix->numRows() * d_matrix->numCols(); const double *data = d_matrix->matrixModel()->dataVector(); int n; gsl_histogram *h; if (d_autoBin) { double min, max; d_matrix->range(&min, &max); d_begin = floor(min); d_end = ceil(max); d_bin_size = 1.0; n = static_cast<int>(floor((d_end - d_begin) / d_bin_size)); if (!n) return; h = gsl_histogram_alloc(n); if (!h) return; gsl_histogram_set_ranges_uniform(h, floor(min), ceil(max)); } else { n = static_cast<int>((d_end - d_begin) / d_bin_size + 1); if (!n) return; h = gsl_histogram_alloc(n); if (!h) return; double *range = new double[n + 2]; for (int i = 0; i <= n + 1; i++) range[i] = d_begin + i * d_bin_size; gsl_histogram_set_ranges(h, range, n + 1); delete[] range; } for (int i = 0; i < size; i++) gsl_histogram_increment(h, data[i]); QVarLengthArray<double> X(n), Y(n); // stores ranges (x) and bins (y) for (int i = 0; i < n; i++) { Y[i] = gsl_histogram_get(h, i); double lower, upper; gsl_histogram_get_range(h, i, &lower, &upper); X[i] = lower; } setData(X.data(), Y.data(), n); d_mean = gsl_histogram_mean(h); d_standard_deviation = gsl_histogram_sigma(h); d_min = gsl_histogram_min_val(h); d_max = gsl_histogram_max_val(h); gsl_histogram_free(h); }
int histc(double *data, int length, double *xmesh, int n , double *bins) { XML_IN; printf("-1\n"); gsl_histogram * h = gsl_histogram_alloc(n-1); printf("0\n"); gsl_histogram_set_ranges (h, xmesh, n); double h_max = gsl_histogram_max(h); double h_min = gsl_histogram_min(h); printf("h_min: %g h_max: %g\n",h_min,h_max); for (int i=0; i<length; i++) gsl_histogram_increment (h, data[i]); printf("2\n"); for (int i=0;i<n-1;i++) bins[i] = gsl_histogram_get (h, i); printf("3\n"); gsl_histogram_fprintf (stdout, h, "%g", "%g"); /*...*/ gsl_histogram_free(h); XML_OUT; return 0; }
void AlexSim::simTestLognormal() { int n=10000; // number of samples int nbins=100; // number of bins for the histogram QFile file("./AlexSimTestLognormal.txt"); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) QMessageBox::information(0, "error", file.errorString()); QTextStream out(&file); out <<"# Test lognormal distribution. Parameters are: burstDuration="<<burstDuration<<"\tvariance="<<burstDurationVar<<"\n"; out <<"# burst duration in ms\tfrequency\n"; out.setRealNumberPrecision(11); gsl_histogram * hist = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (hist, 0, 10*burstDuration); for (int ii=0;ii<n;ii++) { gsl_histogram_increment (hist,gsl_ran_lognormal(r,mu,sigma)); } for(unsigned int ii=0;ii<hist->n;ii++) { out << hist->range[ii]*1e3 << "\t" << gsl_histogram_get(hist,ii) << "\n"; } file.close(); gsl_histogram_free (hist); }
void AlexSim::writeHist(const QString filename) const { long ii; long nbins=(long)((t-tStart)/burstDuration*10); if(nbins==0||photons.size()==0) qWarning()<<"writeHist: no photon records "; gsl_histogram * histDonor = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (histDonor, tStart, t); // change t to tEnd if the latter is implemented gsl_histogram * histAcceptor = gsl_histogram_alloc (nbins); gsl_histogram_set_ranges_uniform (histAcceptor, tStart, t); // change t to tEnd if the latter is implemented for (ii=0;ii<photons.size();ii++) { #ifdef PHOTONMACRO if(isChannel(photons.at(ii),DonorEm)) gsl_histogram_increment (histDonor, photons.at(ii).time); #else if(photons.at(ii).isChannel(DonorEm)) gsl_histogram_increment (histDonor, photons.at(ii).time); #endif else gsl_histogram_increment (histAcceptor, photons.at(ii).time); } QFile file(filename); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) QMessageBox::warning(0, "error", file.errorString()); QTextStream out(&file); out <<"# Simulation data. photon count over time. parameters are:\n"; out <<"# rateDonor="<<rateDemDex<<"\trateAcceptor="<<rateAemAex<<"\trateBackground="<<rateBackground<<"\tburstDuration="<<burstDuration<<"\tsigma="<<sigma<<"\ttStart="<<tStart<<"\ttEnd="<<tEnd()<<"\n"; out.setRealNumberPrecision(11); out <<"# time in ms \tdonor channel \tacceptor channel\n"; for(ii=0;ii<histDonor->n;ii++) { out << histDonor->range[ii]*1e3 << "\t" << gsl_histogram_get(histDonor,ii) << "\t" << gsl_histogram_get(histAcceptor,ii) << "\n"; } file.close(); gsl_histogram_free (histDonor); gsl_histogram_free (histAcceptor); qDebug()<<nbins<<"histogram entries written to file "<<filename; }
/* Record the radial distribution already normalized * correctly for the current timestep. */ void RadialDistribution::record( std::vector<Particle>& activeParticles, double t) { double radius = 0.; for (int i=0; i<activeParticles.size(); i++) { for (int j=0; j<activeParticles.size(); j++) { if (this->isInConsidered( activeParticles[i].typeId, activeParticles[j].typeId)) { if (i != j) { getMinDistanceSquared( radius, activeParticles[i].position, activeParticles[j].position, this->isPeriodic, this->boxsize); radius = sqrt(radius); gsl_histogram_increment(this->radialDistribution, radius); } } } } // copy the hist to 'bins' while scaling every value correctly for (int i=0; i<bins.size(); i++) { bins[i] += gsl_histogram_get(this->radialDistribution, i) / (binCenters[i] * binCenters[i]); } gsl_histogram_reset(this->radialDistribution); }
/* Histogram a PETSC vector * * x is the vector * nbins -- number of bins * xmin, xmax -- histogram xmin, xmax -- assume uniform bins * hh -- output vector -- assumed to be defined. */ void VecHist(const Vec& x, int nbins, double xmin, double xmax, vector<double>& hh) { gsl_histogram *h1; double *_x, x1; PetscInt lo, hi; vector<double> tmp(nbins); // Set up the histogram struct h1 = gsl_histogram_alloc(nbins); gsl_histogram_set_ranges_uniform(h1, xmin, xmax); // Get the array VecGetOwnershipRange(x, &lo, &hi); hi -= lo; VecGetArray(x, &_x); for (PetscInt ii=0; ii < hi; ++ii) { x1 = _x[ii]; if (x1 < xmin) x1 = xmin; if (x1 >= xmax) x1 = xmax - 1.e-10; gsl_histogram_increment(h1, x1); } VecRestoreArray(x, &_x); // Fill the temporary output vector for (int ii =0; ii<nbins; ++ii) tmp[ii] = gsl_histogram_get(h1, ii); // MPI Allreduce MPI_Allreduce(&tmp[0], &hh[0], nbins, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); // Clean up gsl_histogram_free(h1); }
/* ==== */ static short histogram_is_flat(const gsl_histogram *z) { double val,avg,sum = 0.0; size_t lbin,gbin; /* lowest/greatest populated bin */ int i,b=0,is_flat=1; /* get lowest populated bin */ for (i=0; i<wanglandau_opt.bins; i++){ val = gsl_histogram_get(z,i); if (val>0){ lbin=i; break; } } /* printf("lbin is %i\n",lbin);*/ // get highest populated bin for (i=wanglandau_opt.bins-1; i>=0; i--){ val = gsl_histogram_get(z,i); if (val > 0){ gbin=i; break; } } /* printf("gbin is %i\n",gbin);*/ // compute average over interval [lbin;gbin] for (i=lbin;i<=gbin;i++){ if ((val = gsl_histogram_get(z,i)) != 0){ sum += val; b++; } } avg = sum/b; // evaluate if populated bins are all within accepted range for (i=lbin;i<=gbin;i++){ if ((val = gsl_histogram_get(z,i)) != 0){ if( val < wanglandau_opt.flat*avg){ is_flat = 0; break; } } } return is_flat; }
void QwtHistogram::initData(double *Y, int size) { if(size<2 || (size == 2 && Y[0] == Y[1])) {//non valid histogram data double x[2], y[2]; for (int i = 0; i<2; i++ ){ y[i] = 0; x[i] = 0; } setData(x, y, 2); return; } int n = 10;//default value QVarLengthArray<double> x(n), y(n);//double x[n], y[n]; //store ranges (x) and bins (y) gsl_histogram * h = gsl_histogram_alloc (n); if (!h) return; gsl_vector *v; v = gsl_vector_alloc (size); for (int i = 0; i<size; i++ ) gsl_vector_set (v, i, Y[i]); double min, max; gsl_vector_minmax (v, &min, &max); gsl_vector_free (v); d_begin = floor(min); d_end = ceil(max); gsl_histogram_set_ranges_uniform (h, floor(min), ceil(max)); for (int i = 0; i<size; i++ ) gsl_histogram_increment (h, Y[i]); for (int i = 0; i<n; i++ ){ y[i] = gsl_histogram_get (h, i); double lower, upper; gsl_histogram_get_range (h, i, &lower, &upper); x[i] = lower; } setData(x.data(), y.data(), n);//setData(x, y, n); d_bin_size = (d_end - d_begin)/(double)n; d_autoBin = true; d_mean = gsl_histogram_mean(h); d_standard_deviation = gsl_histogram_sigma(h); d_min = gsl_histogram_min_val(h); d_max = gsl_histogram_max_val(h); gsl_histogram_free (h); }
/* ==== */ static gsl_histogram * scale_dos(gsl_histogram *y) { int i,maxbin; size_t bins; double maxval=-1., sum=0., x=0, factor=0., GZero=0, exp_G_norm=0.; const size_t n = y->n; /* nr of bins */ /* FIRST: scale it via the ground state */ /* ln[gn(E)] = ln[g(E)]-ln[g(Egs)]+ln[Q] */ /* where Q is the # of structures found in the lowest bin/groundstate */ bins = gsl_histogram_bins(y); /* get value of y[0] */ GZero = gsl_histogram_get(y,0); /* compute scaling factor just from the very lowest bin for now */ for(i=0;i<1;i++){ factor += gsl_histogram_get(s,i); } /* subtract g[0] [ln(g(Egs))] from each entry to get smaller numbers and add scaling factor*/ for (i=wanglandau_opt.truedosbins-1;i<n;i++){ if(y->bin[i] == 0.){ continue;} else{y->bin[i] += log(factor)-GZero;} } /* exponentiate to get effective DOS */ /* for(i=0;i<n;i++){ y->bin[i]=exp(y->bin[i]); } */ output_dos(y,'s'); return y; }
/* ==== */ static void output_dos(const gsl_histogram *x, const char T) { int i,fnlen; FILE *dos_fp=NULL; char *dos_fn=NULL, *lDoS_suffix="lDoS", *sDoS_suffix="sDoS"; char s[50]; double val,lo,hi; sprintf(s,"%li",steps); fnlen = strlen(out_prefix)+strlen(lDoS_suffix)+64; dos_fn = (char*)calloc(fnlen,sizeof(char)); strcpy(dos_fn, out_prefix); strcat(dos_fn, s); strcat(dos_fn,"."); switch (T){ case 'l': /* output logarithmic g, usually during the calculation */ strcat(dos_fn, lDoS_suffix); break; case 's': /* output scaled g, eg for in-process convergence checks */ strcat(dos_fn, sDoS_suffix); break; default: fprintf (stderr, "%s:%d output_dos(): No handler for type %c", __FILE__, __LINE__, T); exit(EXIT_FAILURE); } dos_fp = fopen(dos_fn, "w+"); fprintf(dos_fp, "# estimated DOS after %li steps\n",steps); fprintf(dos_fp, "# sampling range: %6.2f -- %6.2f\n", gsl_histogram_min(g),gsl_histogram_max(g)); fprintf(dos_fp, "# bin resolution: %g\n",wanglandau_opt.res); /* loop over histogram g */ for (i=0;i<=maxbin;i++){ val = gsl_histogram_get(x,i); if (val == 0.){continue;} gsl_histogram_get_range(x,i,&lo,&hi); fprintf(dos_fp,"%6.2f\t%20.6f\n",lo+(hi-lo)/2,val); } fclose(dos_fp); free(dos_fn); return; }
QVector<QPointF> DistanceToAtom::histogram(int bins) { QVector<QPointF> histogramVector; if(!m_isValid) { qFatal("DistanceToAtom is not valid. Run compute() first."); exit(1); } float minValue = 1e90; float maxValue = 0; for(const float &val : m_values) { if(val >= 0) { minValue = std::min(minValue, (float)sqrt(val)); maxValue = std::max(maxValue, (float)sqrt(val)); } } gsl_histogram *hist = gsl_histogram_alloc (bins); gsl_histogram_set_ranges_uniform (hist, minValue, maxValue); for(const float &value : m_values) { if(value >= 0) { gsl_histogram_increment (hist, sqrt(value)); } } histogramVector.resize(bins); for(int i=0; i<bins; i++) { double upper, lower; gsl_histogram_get_range(hist, i, &lower, &upper); float middle = 0.5*(upper+lower); histogramVector[i].setX(middle); histogramVector[i].setY(gsl_histogram_get(hist,i)); } gsl_histogram_free (hist); return histogramVector; }
bool FrequencyCountDialog::apply() { if (!d_col_values){ QMessageBox::critical(this, tr("QtiPlot - Error"), tr("Not enough data points, operation aborted!")); return false; } double from = boxStart->value(); double to = boxEnd->value(); if (from >= to){ QMessageBox::critical(this, tr("QtiPlot - Frequency input error"), tr("Please enter frequency limits that satisfy: From < To !")); boxEnd->setFocus(); return false; } int old_bins = d_bins; double bin_size = boxStep->value(); d_bins = int((to - from)/bin_size + 1); if (!d_bins) return false; ApplicationWindow *app = (ApplicationWindow *)parent(); if (!app) return false; if (!d_result_table){ d_result_table = app->newTable(30, 4, app->generateUniqueName(tr("Count"), true), tr("Frequency count of %1").arg(d_col_name)); d_result_table->setColName(0, tr("BinCtr")); d_result_table->setColName(1, tr("Count")); d_result_table->setColName(2, tr("BinEnd")); d_result_table->setColName(3, tr("Sum")); d_result_table->showMaximized(); } gsl_histogram *h = gsl_histogram_alloc(d_bins); if (!h) return false; double *range = (double *) malloc((d_bins + 2)*sizeof(double)); if (!range) return false; for (int i = 0; i <= d_bins + 1; i++) range[i] = from + i*bin_size; gsl_histogram_set_ranges (h, range, d_bins + 1); free(range); int dataSize = d_col_values->size; for (int i = 0; i < dataSize; i++ ) gsl_histogram_increment (h, gsl_vector_get(d_col_values, i)); if (d_bins > d_result_table->numRows()) d_result_table->setNumRows(d_bins); for(int i = d_bins; i < old_bins; i++){ d_result_table->setText(i, 0, ""); d_result_table->setText(i, 1, ""); d_result_table->setText(i, 2, ""); d_result_table->setText(i, 3, ""); } double sum = 0.0; for (int i = 0; i<d_bins; i++ ){ double aux = gsl_histogram_get (h, i); sum += aux; double lower, upper; gsl_histogram_get_range (h, i, &lower, &upper); d_result_table->setCell(i, 0, 0.5*(lower + upper)); d_result_table->setCell(i, 1, aux); d_result_table->setCell(i, 2, upper); d_result_table->setCell(i, 3, sum); } return true; }
void compute_average_autocorrelations(struct State *S) /* Compute spike-time autocorrelation */ { struct Network *ntw = &S->ntw; struct Dynamic_Array *nrn_train; int n_neurons_sample = 1000; size_t num_spikes_total = 0; const size_t n_bins = 201; const double max_lag = 50; /* in ms */ double bin_width = 2 * max_lag / (double) n_bins; char filename[100]; gsl_histogram *h = gsl_histogram_alloc(n_bins); gsl_histogram_set_ranges_uniform(h, -max_lag, max_lag); FILE *f; report("Computing average autocorrelation...\n"); sprintf(filename, "autocorrelation_%s", S->sim.suffix); double t_sp; size_t l, r; f = fopen(filename, "w"); for (int i = 0; i < n_neurons_sample; i++) { l = 0; r = 0; nrn_train = &ntw->cell[i].spike_train; num_spikes_total += nrn_train->n; for (size_t j = 0; j < nrn_train->n; j++) { t_sp = nrn_train->data[j]; /* look for left index */ while (l < nrn_train->n && nrn_train->data[l] < t_sp - max_lag) l++; /* look for right index */ while (r < nrn_train->n && nrn_train->data[r] < t_sp + max_lag) r++; /* And feed the histogram with the relevant spikes */ for (size_t k = l; k < r; k++) gsl_histogram_increment(h, t_sp - nrn_train->data[k]); } } /* gsl_histogram_fprintf(f, h, "%g", "%g"); */ /* correct for boundary effects and substract mean */ double w; double T = S->sim.total_time - S->sim.offset; /* double nu = num_spikes_total / (T * (double) n_neurons_sample); */ double lower, upper, ac; int status; for (size_t j = 0; j < n_bins; j++) { w = T - fabs( (n_bins - 1.0) / 2.0 - j ) * bin_width; ac = gsl_histogram_get(h, j) / (w * n_neurons_sample); ac -= (pow(num_spikes_total / (T * n_neurons_sample), 2) * bin_width); /* ac /= pow(nu * bin_width, 2); [> Normalization <] */ status = gsl_histogram_get_range(h, j, &lower, &upper); if (status==0) { fprintf(f, "% 9.4f % 9.4f % 9.7f\n", lower, upper, ac); } else { report("Something wrong here.\n"); exit(2); } } fclose(f); gsl_histogram_free(h); }
void compute_global_autocorrelations(struct State *S) /* Compute population rate autocorrelation */ { struct Network *ntw = &S->ntw; int n_neurons_sample = 100; const size_t n_bins = 201; const double max_lag = 100; /* maximal lag in ms */ double bin_width = 2 * max_lag / (double) n_bins; /* 2*max_lag */ char filename[100]; gsl_histogram *h = gsl_histogram_alloc(n_bins); gsl_histogram_set_ranges_uniform(h, -max_lag, max_lag); FILE *f; struct Dynamic_Array poptrain; size_t num_spikes_total = 0; for (int i = 0; i < n_neurons_sample; i++) num_spikes_total += ntw->cell[i].spike_train.n; poptrain.data = emalloc(num_spikes_total * sizeof(double)); poptrain.n = 0; poptrain.size = num_spikes_total; report("Computing global (population rate) autocorrelation...\n"); fill_population_spike_train(S, &poptrain, n_neurons_sample); gsl_sort(poptrain.data, 1, num_spikes_total); sprintf(filename, "global_autocorrelation_%s", S->sim.suffix); double t_sp; f = fopen(filename, "w"); size_t l = 0; size_t r = 0; for (size_t j = 0; j < poptrain.n; j++) { t_sp = poptrain.data[j]; /* look for left index */ while (l < poptrain.n && poptrain.data[l] < t_sp - max_lag) l++; /* look for right index */ while (r < poptrain.n && poptrain.data[r] < t_sp + max_lag) r++; /* And feed the histogram with the relevant spikes */ for (size_t k = l; k < r; k++) gsl_histogram_increment(h, t_sp - poptrain.data[k]); } /* gsl_histogram_fprintf(f, h, "%g", "%g"); */ /* correct for boundary effects and substract mean */ double w; double T = S->sim.total_time - S->sim.offset; /* double nu = num_spikes_total / (T * (double) n_neurons_sample); */ double lower, upper, ac; int status; for (size_t j = 0; j < n_bins; j++) { w = T - fabs( (n_bins - 1.0) / 2.0 - j ) * bin_width; ac = gsl_histogram_get(h, j) / (w * n_neurons_sample); ac -= (pow(num_spikes_total / (T * n_neurons_sample), 2) * bin_width); /* ac /= pow(nu * bin_width, 2); [> Normalization <] */ status = gsl_histogram_get_range(h, j, &lower, &upper); if (status==0) { fprintf(f, "% 9.4f % 9.4f % 9.6f\n", lower, upper, ac); } else { report("Somehting wrong here.\n"); exit(2); } } fclose(f); free(poptrain.data); gsl_histogram_free(h); }
double InformacionMalla::getFrecuenciaHistograma(int bin) { return gsl_histogram_get(h,bin); }
void test1d_resample (void) { size_t i; int status = 0; gsl_histogram *h; gsl_ieee_env_setup (); h = gsl_histogram_calloc_uniform (10, 0.0, 1.0); gsl_histogram_increment (h, 0.1); gsl_histogram_increment (h, 0.2); gsl_histogram_increment (h, 0.2); gsl_histogram_increment (h, 0.3); { gsl_histogram_pdf *p = gsl_histogram_pdf_alloc (10); gsl_histogram *hh = gsl_histogram_calloc_uniform (100, 0.0, 1.0); gsl_histogram_pdf_init (p, h); for (i = 0; i < 100000; i++) { double u = urand(); double x = gsl_histogram_pdf_sample (p, u); gsl_histogram_increment (hh, x); } for (i = 0; i < 100; i++) { double y = gsl_histogram_get (hh, i) / 2500; double x, xmax; size_t k; double ya; gsl_histogram_get_range (hh, i, &x, &xmax); gsl_histogram_find (h, x, &k); ya = gsl_histogram_get (h, k); if (ya == 0) { if (y != 0) { printf ("%d: %g vs %g\n", (int) i, y, ya); status = 1; } } else { double err = 1 / sqrt (gsl_histogram_get (hh, i)); double sigma = fabs ((y - ya) / (ya * err)); if (sigma > 3) { status = 1; printf ("%g vs %g err=%g sigma=%g\n", y, ya, err, sigma); } } } gsl_histogram_pdf_free (p) ; gsl_histogram_free (hh); gsl_test (status, "gsl_histogram_pdf_sample within statistical errors"); } gsl_histogram_free (h); }
/* ==== */ static void wl_montecarlo(char *struc) { short *pt=NULL; move_str m; int e,enew,emove,eval_me,status,debug=1; long int crosscheck=1000000; /* used for convergence checks */ long int crosscheck_limit = 100000000000000000; double g_b1,g_b2,prob,lnf = 1.; /* log modification parameter f */ size_t b1,b2; /* indices in g/h corresponding to old/new energies */ gsl_histogram *gcp=NULL; /* clone of g used during crosscheck output */ eval_me = 1; /* paranoid checking of neighbors against RNAeval */ if (wanglandau_opt.verbose){ printf("[[wl_montecarlo()]]\n"); } pt = vrna_pt_get(struc); //mtw_dump_pt(pt); //char *str = vrna_pt_to_db(pt); //printf(">%s<\n",str); e = vrna_eval_structure_pt(wanglandau_opt.sequence,pt,P); /* determine bin where the start structure goes */ status = gsl_histogram_find(g,(float)e/100,&b1); if (status) { if (status == GSL_EDOM){ printf ("error: %s\n", gsl_strerror (status)); } else {fprintf(stderr, "GSL error: gsl_errno=%d\n",status);} exit(EXIT_FAILURE); } printf("%s\n", wanglandau_opt.sequence); print_str(stderr,pt); printf(" (%6.2f) bin:%d\n",(float)e/100,b1); if (wanglandau_opt.verbose){ fprintf(stderr,"\nStarting MC loop ...\n"); } while (lnf > wanglandau_opt.ffinal) { if(wanglandau_opt.debug){ fprintf(stderr,"\n==================\n"); fprintf(stderr,"in while: lnf=%8.6f\n",lnf); fprintf(stderr,"steps: %d\n",steps); fprintf(stderr,"current histogram g:\n"); gsl_histogram_fprintf(stderr,g,"%6.2f","%30.6f"); fprintf(stderr,"\n"); print_str(stderr,pt); fprintf(stderr, " (%6.2f) bin:%d\n",(float)e/100,b1); /* mtw_dump_pt(pt); */ } /* make a random move */ m = get_random_move_pt(wanglandau_opt.sequence,pt); /* compute energy difference for this move */ emove = vrna_eval_move_pt(pt,s0,s1,m.left,m.right,P); /* evaluate energy of the new structure */ enew = e + emove; if(wanglandau_opt.debug){ fprintf(stderr, "random move: left %i right %i enew(%6.4f)=e(%6.4f)+emove(%6.4f)\n", m.left,m.right,(float)enew/100,(float)e/100,(float)emove/100); } /* ensure the new energy is within sampling range */ if ((float)enew/100 >= wanglandau_opt.max){ fprintf(stderr, "New structure has energy %6.2f >= %6.2f (upper energy bound)\n", (float)enew/100,wanglandau_opt.max); fprintf(stderr,"Please increase --bins or adjust --max! Exiting ...\n"); exit(EXIT_FAILURE); } /* determine bin where the new structure goes */ status = gsl_histogram_find(g,(float)enew/100,&b2); if (status) { if (status == GSL_EDOM){ printf ("error: %s\n", gsl_strerror (status)); } else {fprintf(stderr, "GSL error: gsl_errno=%d\n",status);} exit(EXIT_FAILURE); } steps++; /* # of MC steps performed so far */ /* lookup current values for bins b1 and b2 */ g_b1 = gsl_histogram_get(g,b1); g_b2 = gsl_histogram_get(g,b2); /* core MC steps */ prob = MIN2(exp(g_b1 - g_b2), 1.0); rnum = gsl_rng_uniform (r); if ((prob == 1 || (rnum <= prob)) ) { /* accept & apply the move */ apply_move_pt(pt,m); if(wanglandau_opt.debug){ print_str(stderr,pt); fprintf(stderr, " %6.2f bin:%d [A]\n", (float)enew/100,b2); } b1 = b2; e = enew; } else { /* reject the move */ if(wanglandau_opt.debug){ print_str(stderr,pt); fprintf(stderr, " (%6.2f) bin:%d [R]\n", (float)enew/100,b2); } } /* update histograms g and h */ if(wanglandau_opt.truedosbins_given && b2 <= wanglandau_opt.truedosbins){ /* do not update if b2 <= truedosbins, i.e. keep true DOS values in those bins */ if (wanglandau_opt.debug){ fprintf(stderr, "NOT UPDATING bin %d\n",b1); } } else{ if(wanglandau_opt.debug){ fprintf(stderr, "UPDATING bin %d\n",b1); } status = gsl_histogram_increment(h,(float)e/100); status = gsl_histogram_accumulate(g,(float)e/100,lnf); } maxbin = MAX2(maxbin,(int)b1); // stuff that can be skipped /* printf ("performed move l:%4d r:%4d\t Energy +/- %6.2f\n",m.left,m.right,(float)emove/100); print_str(stderr,pt);printf(" %6.2f bin:%d\n",(float)enew/100,b2); e = vrna_eval_structure_pt(wanglandau_opt.sequence,pt,P); if (eval_me == 1 && e != enew){ fprintf(stderr, "energy evaluation against vrna_eval_structure_pt() mismatch... HAVE %6.2f != %6.2f (SHOULD BE)\n",(float)enew/100, (float)e/100); exit(EXIT_FAILURE); } print_str(stderr,pt);printf(" %6.2f\n",(float)e/100); */ // end of stuff that can be skipped /* output DoS every x*10^(1/4) steps, starting with x=10^6 (we used this fopr comparing perfomance and convergence of different DoS sampling methods */ if((steps % crosscheck == 0) && (crosscheck <= crosscheck_limit)){ fprintf(stderr,"# crosscheck reached %li steps ",crosscheck); gcp = gsl_histogram_clone(g); if(wanglandau_opt.verbose){ fprintf(stderr,"## gcp before scaling\n"); gsl_histogram_fprintf(stderr,gcp,"%6.2f","%30.6f"); } scale_dos(gcp); /* scale estimated g; make ln(g[0])=0 */ if(wanglandau_opt.verbose){ fprintf(stderr,"## gcp after scaling\n"); gsl_histogram_fprintf(stderr,gcp,"%6.2f","%30.6f"); } double Z = partition_function(gcp); output_dos(gcp,'s'); fprintf(stderr, "Z=%10.4g\n", Z); crosscheck *= (pow(10, 1.0/4.0)); gsl_histogram_free(gcp); fprintf(stderr,"-> new crosscheck will be performed at %li steps\n", crosscheck); } if(steps % wanglandau_opt.checksteps == 0) { if( histogram_is_flat(h) ) { lnf /= 2; fprintf(stderr,"# steps=%20li | f=%12g | histogram is FLAT\n", steps,lnf); gsl_histogram_reset(h); } else { fprintf(stderr, "# steps=%20li | f=%12g | histogram is NOT FLAT\n", steps,lnf); } output_dos(g,'l'); } /* stop criterion */ if(steps % wanglandau_opt.steplimit == 0){ fprintf(stderr,"maximun number of MC steps (%li) reached, exiting ...", wanglandau_opt.steplimit); break; } } /* end while */ free(pt); return; }
main (int argc,char *argv[]) { int ia,ib,ic,id,it,inow,ineigh,icont; int in,ia2,ia3,irun,icurrent,ORTOGONALFLAG; int RP, P,L,N,NRUNS,next,sweep,SHOWFLAG; double u,field1,field2,field0,q,aux1,aux2; double alfa,aux,Q1,Q2,QZ,RZQ,rho,R; double pm,D,wmax,mQ,wx,wy,h_sigma,h_mean; double TOL,MINLOGF,E; double DELTA; double E_new,Ex,DeltaE,ER; double EW,meanhist,hvalue,wE,aratio; double logG_old,logG_new,lf; size_t i_old,i_new; long seed; double lGvR,lGv,DlG; size_t iL,iR,i1,i2; int I_endpoint[NBINS]; double lower,upper; size_t i0; FILE * wlsrange; FILE * dos; FILE * thermodynamics; FILE * canonical; FILE * logfile; //FILE * pajek; //*********************************** // Help //*********************************** if (argc<15){ help(); return(1); } else{ DELTA = atof(argv[1]); P = atoi(argv[2]); RP = atoi(argv[3]); L = atoi(argv[4]); N = atoi(argv[5]); TOL = atof(argv[6]); MINLOGF = atof(argv[7]); } wlsrange=fopen(argv[8],"w"); dos=fopen(argv[9],"w"); thermodynamics=fopen(argv[10],"w"); canonical=fopen(argv[11],"w"); logfile=fopen(argv[12],"w"); SHOWFLAG = atoi(argv[13]); ORTOGONALFLAG = atoi(argv[14]); if ((ORTOGONALFLAG==1) && (P>L)) P=L; //maximum number of orthogonal issues if (SHOWFLAG==1){ printf("# parameters are DELTA=%1.2f P=%d ",DELTA,P); printf("D=%d L=%d M=%d TOL=%1.2f MINLOGF=%g \n",L,N,RP,TOL,MINLOGF); } fprintf(logfile,"# parameters are DELTA=%1.2f P=%d D=%d",DELTA,P,L); fprintf(logfile,"L=%d M=%d TOL=%1.2f MINLOGF=%g\n",L,RP,TOL,MINLOGF); //********************************************************************** // Alocate matrices //********************************************************************** gsl_matrix * sociedade = gsl_matrix_alloc(SIZE,L); gsl_matrix * issue = gsl_matrix_alloc(P,L); gsl_vector * current_issue = gsl_vector_alloc(L); gsl_vector * v0 = gsl_vector_alloc(L); gsl_vector * v1 = gsl_vector_alloc(L); gsl_vector * Z = gsl_vector_alloc(L); gsl_vector * E_borda = gsl_vector_alloc(NBINS); //********************************************************************** // Inicialization //********************************************************************** const gsl_rng_type * T; gsl_rng * r; gsl_rng_env_setup(); T = gsl_rng_default; r=gsl_rng_alloc (T); seed = time (NULL) * getpid(); //seed = 13188839657852; gsl_rng_set(r,seed); igraph_t graph; igraph_vector_t neighbors; igraph_vector_t result; igraph_vector_t dim_vector; igraph_real_t res; igraph_bool_t C; igraph_vector_init(&neighbors,1000); igraph_vector_init(&result,0); igraph_vector_init(&dim_vector,DIMENSION); for(ic=0;ic<DIMENSION;ic++) VECTOR(dim_vector)[ic]=N; gsl_histogram * HE = gsl_histogram_alloc (NBINS); gsl_histogram * logG = gsl_histogram_alloc (NBINS); gsl_histogram * LG = gsl_histogram_alloc (NBINS); //******************************************************************** // Social Graph //******************************************************************** //Barabasi-Alberts network igraph_barabasi_game(&graph,SIZE,RP,&result,1,0); /* for (inow=0;inow<SIZE;inow++){ igraph_neighbors(&graph,&neighbors,inow,IGRAPH_OUT); printf("%d ",inow); for(ic=0;ic<igraph_vector_size(&neighbors);ic++) { ineigh=(int)VECTOR(neighbors)[ic]; printf("%d ",ineigh); } printf("\n"); }*/ //pajek=fopen("graph.xml","w"); // igraph_write_graph_graphml(&graph,pajek); //igraph_write_graph_pajek(&graph, pajek); //fclose(pajek); //********************************************************************** //Quenched issues set and Zeitgeist //********************************************************************** gsl_vector_set_zero(Z); gera_config(Z,issue,P,L,r,1.0); if (ORTOGONALFLAG==1) gsl_matrix_set_identity(issue); for (ib=0;ib<P;ib++) { gsl_matrix_get_row(current_issue,issue,ib); gsl_blas_ddot(current_issue,current_issue,&Q1); gsl_vector_scale(current_issue,1/sqrt(Q1)); gsl_vector_add(Z,current_issue); } gsl_blas_ddot(Z,Z,&QZ); gsl_vector_scale(Z,1/sqrt(QZ)); //********************************************************************** // Ground state energy //********************************************************************** double E0; gera_config(Z,sociedade,SIZE,L,r,0); E0 = hamiltoneana(sociedade,issue,SIZE,L,P,DELTA,graph); double EMIN=E0; double EMAX=-E0; double E_old=E0; gsl_histogram_set_ranges_uniform (HE,EMIN,EMAX); gsl_histogram_set_ranges_uniform (logG,EMIN,EMAX); if (SHOWFLAG==1) printf("# ground state: %3.0f\n",E0); fprintf(logfile,"# ground state: %3.0f\n",E0); //********************************************************************** // Find sampling interval //********************************************************************** //printf("#finding the sampling interval...\n"); lf=1; sweep=0; icont=0; int iflag=0; int TMAX=NSWEEPS; while(sweep<=TMAX){ if (icont==10000) { //printf("%d sweeps\n",sweep); icont=0; } for(it=0;it<SIZE;it++){ igraph_vector_init(&neighbors,SIZE); //choose a random site do{ inow=gsl_rng_uniform_int(r,SIZE); }while((inow<0)||(inow>=SIZE)); gsl_matrix_get_row(v1,sociedade,inow); igraph_neighbors(&graph,&neighbors,inow,IGRAPH_OUT); //generates a random vector v1 gsl_vector_memcpy(v0,v1); gera_vetor(v1,L,r); //calculates energy change when v0->v1 // in site inow DeltaE=variacaoE(v0,v1,inow,sociedade, issue,N,L,P,DELTA,graph,neighbors); E_new=E_old+DeltaE; //WL: accepts in [EMIN,EMAX] if ((E_new>EMIN) && (E_new<EMAX)) { gsl_histogram_find(logG,E_old,&i_old); logG_old=gsl_histogram_get(logG,i_old); gsl_histogram_find(logG,E_new,&i_new); logG_new=gsl_histogram_get(logG,i_new); wE = GSL_MIN(exp(logG_old-logG_new),1); if (gsl_rng_uniform(r)<wE){ E_old=E_new; gsl_matrix_set_row(sociedade,inow,v1); } } //WL: update histograms gsl_histogram_increment(HE,E_old); gsl_histogram_accumulate(logG,E_old,lf); igraph_vector_destroy(&neighbors); } sweep++; icont++; } gsl_histogram_fprintf(wlsrange,HE,"%g","%g"); double maxH=gsl_histogram_max_val(HE); //printf("ok\n"); Ex=0; hvalue=maxH; while((hvalue>TOL*maxH)&&(Ex>EMIN)){ gsl_histogram_find(HE,Ex,&i0); hvalue=gsl_histogram_get(HE,i0); Ex-=1; if(Ex<=EMAX)TMAX+=10000; } EMIN=Ex; Ex=0; hvalue=maxH; while((hvalue>TOL*maxH)&&(Ex<EMAX)) { gsl_histogram_find(HE,Ex,&i0); hvalue=gsl_histogram_get(HE,i0); Ex+=1; if(Ex>=EMAX)TMAX+=10000; } EMAX=Ex; EMAX=GSL_MIN(10.0,Ex); if (SHOWFLAG==1) printf("# the sampling interval is [%3.0f,%3.0f] found in %d sweeps \n\n" ,EMIN,EMAX,sweep); fprintf(logfile, "# the sampling interval is [%3.0f,%3.0f] found in %d sweeps \n\n" ,EMIN,EMAX,sweep); gsl_histogram_set_ranges_uniform (HE,EMIN-1,EMAX+1); gsl_histogram_set_ranges_uniform (logG,EMIN-1,EMAX+1); gsl_histogram_set_ranges_uniform (LG,EMIN-1,EMAX+1); //********************************************************************** // WLS //********************************************************************** int iE,itera=0; double endpoints[NBINS]; double w = WINDOW; //(EMAX-EMIN)/10.0; //printf("W=%f\n",w); lf=1; //RESOLUTION ----> <------RESOLUTION***** do{ int iverify=0,iborda=0,flat=0; sweep=0; Ex=EMAX; EW=EMAX; E_old=EMAX+1; iE=0; endpoints[iE]=EMAX; iE++; gsl_histogram_reset(LG); //WINDOWS --> <--WINDOWS******* while((Ex>EMIN)&&(sweep<MAXSWEEPS)){ //initial config gera_config(Z,sociedade,SIZE,L,r,0); E_old = hamiltoneana(sociedade,issue,SIZE,L,P,DELTA,graph); while( (E_old<EMIN+1)||(E_old>Ex) ){ //printf("%d %3.1f\n",E_old); do{ inow=gsl_rng_uniform_int(r,SIZE); }while((inow<0)||(inow>=SIZE)); gsl_matrix_get_row(v0,sociedade,inow); gera_vetor(v1,L,r); gsl_matrix_set_row(sociedade,inow,v1); E_old = hamiltoneana(sociedade,issue,SIZE,L,P,DELTA,graph); if (E_old>Ex){ gsl_matrix_set_row(sociedade,inow,v0); E_old = hamiltoneana(sociedade,issue,SIZE,L,P,DELTA,graph); } //printf("%3.1f %3.1f %3.1f\n",EMIN+1,E_old, Ex); } if (SHOWFLAG==1){ printf("# sampling [%f,%f]\n",EMIN,Ex); printf("# walking from E=%3.0f\n",E_old); } fprintf(logfile,"# sampling [%f,%f]\n",EMIN,Ex); fprintf(logfile,"# walking from E=%3.0f\n",E_old); do{ //FLAT WINDOW------> <------FLAT WINDOW***** //MC sweep ----> <------MC sweep******** for(it=0;it<SIZE;it++){ igraph_vector_init(&neighbors,SIZE); //escolhe sítio aleatoriamente do{ inow=gsl_rng_uniform_int(r,SIZE); }while((inow<0)||(inow>=SIZE)); gsl_matrix_get_row(v1,sociedade,inow); igraph_neighbors(&graph,&neighbors,inow,IGRAPH_OUT); //gera vetor aleatorio v1 gsl_vector_memcpy(v0,v1); gera_vetor(v1,L,r); //calculates energy change when //v0->v1 in site inow DeltaE=variacaoE(v0,v1,inow,sociedade,issue, N,L,P,DELTA,graph,neighbors); E_new=E_old+DeltaE; //WL: accepts in [EMIN,Ex] if ((E_new>EMIN) && (E_new<Ex)) { gsl_histogram_find(logG,E_old,&i_old); logG_old=gsl_histogram_get(logG,i_old); gsl_histogram_find(logG,E_new,&i_new); logG_new=gsl_histogram_get(logG,i_new); wE = GSL_MIN(exp(logG_old-logG_new),1); if (gsl_rng_uniform(r)<wE){ E_old=E_new; gsl_matrix_set_row(sociedade,inow,v1); } } //WL: updates histograms gsl_histogram_increment(HE,E_old); gsl_histogram_accumulate(logG,E_old,lf); itera++; igraph_vector_destroy(&neighbors); } //MC sweep ----> <--------MC sweep**** sweep++; iverify++; if( (EMAX-EMIN)<NDE*DE ) { EW=EMIN; }else{ EW=GSL_MAX(Ex-w,EMIN); } if (iverify==CHECK){//Verify flatness if (SHOWFLAG==1) printf(" #verificando flatness em [%f,%f]\n",EW,Ex); fprintf(logfile," #verificando flatness em [%f,%f]\n" ,EW,Ex); iverify=0; flat=flatness(HE,EW,Ex,TOL,itera,meanhist,hvalue); if (SHOWFLAG==1) printf("#minH= %8.0f\t k<H>=%8.0f\t %d sweeps\t ", hvalue,TOL*meanhist,sweep,flat); fprintf(logfile, "#minH= %8.0f\t k<H>=%8.0f\t %d sweeps\t ", hvalue,TOL*meanhist,sweep,flat); } }while(flat==0);// <------FLAT WINDOW****** flat=0; //Find ER //printf("# EMAX=%f EMIN = %f Ex =%f\n",EMAX, EMIN, Ex); if( (EMAX-EMIN)<NDE*DE ) { Ex=EMIN; endpoints[iE]=EMIN; } else { if (EW>EMIN){ ER=flatwindow(HE,EW,TOL,meanhist); if (SHOWFLAG==1) printf("# extending flatness to[%f,%f]\n",ER,Ex); fprintf(logfile, "# extending flatness to [%f,%f]\n",ER,Ex); if((ER-EMIN)<1){ ER=EMIN; Ex=EMIN; endpoints[iE]=EMIN; }else{ endpoints[iE]=GSL_MIN(ER+DE,EMAX); Ex=GSL_MIN(ER+2*DE,EMAX); } } else{ endpoints[iE]=EMIN; Ex=EMIN; ER=EMIN; } } if (SHOWFLAG==1) printf("# window %d [%3.0f,%3.0f] is flat after %d sweeps \n", iE,endpoints[iE],endpoints[iE-1],sweep); fprintf(logfile,"# window %d [%3.0f,%3.0f] is flat after %d sweeps\n", iE,endpoints[iE],endpoints[iE-1],sweep); //saves histogram if (iE==1){ gsl_histogram_find(logG,endpoints[iE],&i1); gsl_histogram_find(logG,endpoints[iE-1],&i2); for(i0=i1;i0<=i2;i0++){ lGv=gsl_histogram_get(logG,i0); gsl_histogram_get_range(logG,i0,&lower,&upper); E=0.5*(upper+lower); gsl_histogram_accumulate(LG,E,lGv); } }else{ gsl_histogram_find(logG,endpoints[iE],&i1); gsl_histogram_find(logG,endpoints[iE-1],&i2); lGv=gsl_histogram_get(logG,i2); lGvR=gsl_histogram_get(LG,i2); DlG=lGvR-lGv; //printf("i1=%d i2=%d lGv=%f lGvR=%f DlG=%f\n",i1,i2,lGv,lGvR,DlG); for(i0=i1;i0<i2;i0++){ lGv=gsl_histogram_get(logG,i0); lGv=lGv+DlG; gsl_histogram_get_range(logG,i0,&lower,&upper); E=(upper+lower)*0.5; //printf("i0=%d E=%f lGv=%f\n",i0,E,lGv); gsl_histogram_accumulate(LG,E,lGv); } } //printf("#########################################\n"); //gsl_histogram_fprintf(stdout,LG,"%g","%g"); //printf("#########################################\n"); iE++; if((Ex-EMIN)>NDE*DE) { if (SHOWFLAG==1) printf("# random walk is now restricted to [%3.0f,%3.0f]\n" ,EMIN,Ex); fprintf(logfile,"# random walk is now restricted to [%3.0f,%3.0f]\n" ,EMIN,Ex); } gsl_histogram_reset(HE); } //WINDOWS --> if(sweep<MAXSWEEPS){ if (SHOWFLAG==1) printf("# log(f)=%f converged within %d sweeps\n\n",lf,sweep); fprintf(logfile,"# log(f)=%f converged within %d sweeps\n\n",lf,sweep); lf=lf/2.0; gsl_histogram_reset(HE); gsl_histogram_memcpy(logG,LG); }else { if (SHOWFLAG==1) printf("# FAILED: no convergence has been attained."); fprintf(logfile, "# FAILED: no convergence has been attained. Simulation ABANDONED."); return(1); } }while(lf>MINLOGF); //RESOLUTION --> <-----RESOLUTION**** //***************************************************************** //Density of states //***************************************************************** double minlogG=gsl_histogram_min_val(logG); gsl_histogram_shift(logG,-minlogG); gsl_histogram_fprintf(dos,logG,"%g","%g"); //***************************************************************** //Thermodynamics //***************************************************************** double beta,A,wT,Zmin_beta; double lGvalue,maxA,betaC,CTMAX=0; double Z_beta,U,U2,CT,F,S; for (beta=0.01;beta<=30;beta+=0.01) { //****************************************************************** //Energy, free-energy, entropy, specific heat and Tc //****************************************************************** maxA=0; for (ia2=0; ia2<NBINS;ia2++) { lGvalue=gsl_histogram_get(logG,ia2); gsl_histogram_get_range(logG,ia2,&lower,&upper); E=(lower+upper)/2; A=lGvalue-beta*E; if (A>maxA) maxA=A; } gsl_histogram_find(logG,EMIN,&i0); Z_beta=0;U=0;U2=0; for (ia2=0; ia2<NBINS;ia2++) { lGvalue=gsl_histogram_get(logG,ia2); gsl_histogram_get_range(logG,ia2,&lower,&upper); E=(lower+upper)/2; A=lGvalue-beta*E-maxA; Z_beta+=exp(A); U+=E*exp(A); U2+=E*E*exp(A); if(ia2==i0) Zmin_beta=exp(A); } wT=Zmin_beta/Z_beta; F=-log(Z_beta)/beta - maxA/beta; U=U/Z_beta; S= (U-F)*beta; U2=U2/Z_beta; CT=(U2-U*U)*beta*beta; if(CT>CTMAX){ CTMAX=CT; betaC=beta; } fprintf(thermodynamics,"%f %f %f %f %f %f %f \n" ,beta,1/beta,F/(double)(SIZE),S/(double)(SIZE), U/(double)(SIZE),CT/(double)(SIZE),wT); } if (SHOWFLAG==1) printf("# BETAc: %f Tc:%f \n",betaC,1/betaC); fprintf(logfile,"# BETAc: %f Tc:%f \n",betaC,1/betaC); //****************************************************************** //canonical distribuition at Tc //****************************************************************** beta=betaC; double distr_canonica; maxA=0; for (ia2=0; ia2<NBINS;ia2++) { lGvalue=gsl_histogram_get(logG,ia2); gsl_histogram_get_range(logG,ia2,&lower,&upper); E=(lower+upper)/2; A=lGvalue-beta*E; if (A>maxA) maxA=A; } for (ia2=0; ia2<NBINS;ia2++) { lGvalue=gsl_histogram_get(logG,ia2); gsl_histogram_get_range(logG,ia2,&lower,&upper); E=(lower+upper)/2; A=lGvalue-beta*E-maxA; distr_canonica=exp(A); fprintf(canonical,"%f %f %f\n", E/(double)(SIZE),distr_canonica,A); } //***************************************************************** // Finalization //***************************************************************** igraph_destroy(&graph); igraph_vector_destroy(&neighbors); igraph_vector_destroy(&result); gsl_matrix_free(issue); gsl_vector_free(current_issue); gsl_vector_free(v1); gsl_vector_free(v0); gsl_matrix_free(sociedade); gsl_rng_free(r); fclose(wlsrange); fclose(dos); fclose(thermodynamics); fclose(canonical); fclose(logfile); return(0); }
void QwtHistogram::loadData() { if (d_matrix){ loadDataFromMatrix(); return; } int r = abs(d_end_row - d_start_row) + 1; QVarLengthArray<double> Y(r); int ycol = d_table->colIndex(title().text()); int size = 0; for (int i = 0; i<r; i++ ){ QString yval = d_table->text(i, ycol); if (!yval.isEmpty()){ bool valid_data = true; Y[size] = ((Graph *)plot())->locale().toDouble(yval, &valid_data); if (valid_data) size++; } } if(size < 2 || (size==2 && Y[0] == Y[1])){//non valid histogram double X[2]; Y.resize(2); for (int i = 0; i<2; i++ ){ Y[i] = 0; X[i] = 0; } setData(X, Y.data(), 2); return; } int n; gsl_histogram *h; if (d_autoBin){ n = 10; h = gsl_histogram_alloc (n); if (!h) return; gsl_vector *v = gsl_vector_alloc (size); for (int i = 0; i<size; i++ ) gsl_vector_set (v, i, Y[i]); double min, max; gsl_vector_minmax (v, &min, &max); gsl_vector_free (v); d_begin = floor(min); d_end = ceil(max); d_bin_size = (d_end - d_begin)/(double)n; gsl_histogram_set_ranges_uniform (h, floor(min), ceil(max)); } else { n = int((d_end - d_begin)/d_bin_size + 1); h = gsl_histogram_alloc (n); if (!h) return; double *range = new double[n+2]; for (int i = 0; i<= n+1; i++ ) range[i] = d_begin + i*d_bin_size; gsl_histogram_set_ranges (h, range, n+1); delete[] range; } for (int i = 0; i<size; i++ ) gsl_histogram_increment (h, Y[i]); #ifdef Q_CC_MSVC QVarLengthArray<double> X(n); //stores ranges (x) and bins (y) #else double X[n]; //stores ranges (x) and bins (y) #endif Y.resize(n); for (int i = 0; i<n; i++ ){ Y[i] = gsl_histogram_get (h, i); double lower, upper; gsl_histogram_get_range (h, i, &lower, &upper); X[i] = lower; } #ifdef Q_CC_MSVC setData(X.data(), Y.data(), n); #else setData(X, Y.data(), n); #endif d_mean = gsl_histogram_mean(h); d_standard_deviation = gsl_histogram_sigma(h); d_min = gsl_histogram_min_val(h); d_max = gsl_histogram_max_val(h); gsl_histogram_free (h); }
void histo_maker(int n, double* omega, double hmax) { //Histogramme int i; int ncolumns = 2; int nbhist = 5000; double hmin = 5; double *histogram = new double [nbhist]; double *N = new double [nbhist]; double **outtable = new double* [nbhist]; for( i=0 ; i < nbhist ; i++ ) outtable[i] = new double[ncolumns]; //2:nb de colonnes size_t nhist = size_t(nbhist); gsl_histogram *h = gsl_histogram_alloc(nhist); gsl_histogram_set_ranges_uniform (h, hmin, hmax); for (i = 0 ; i < n ; i++) { gsl_histogram_increment (h, omega[i]); } for (i = 0 ; i < nbhist ; i++) { histogram[i] = gsl_histogram_get (h, i); //N[i] = (-(double(nbhist) - 1) / 2 + i) * hmax * 2 / nbhist; N[i] = hmin + (hmax - hmin) * (i + 1/2.) / nbhist ; outtable[i][0]=N[i]; outtable[i][1]=histogram[i]; } gsl_histogram_free (h); int *size = new int [2]; size[0] = nbhist; // lignes size[1] = ncolumns; // colonnes string filename="histo_result.csv"; //écriture dans les fichiers (taille, pointeur vers un tableau, nom fichier) file_maker(size, outtable, filename); /* size[0] = n; size[1] = 1; double **outtable2 = new double* [n]; for( i=0 ; i < n ; i++ ) outtable2[i] = new double[2]; //1:nb de colonnes filename = "raw_result.csv"; for ( i = 0 ; i < n ; i++) { outtable2[i][0] = omega[i]; outtable2[i][1] = 0; } file_maker(size, outtable2, filename); // ménage for( i=0 ; i < n ; i++ ) delete [] outtable2[i]; delete [] outtable2; */ for( i=0 ; i < nbhist ; i++ ) delete [] outtable[i]; delete [] outtable; delete [] size; delete [] N; delete [] histogram; }
void test1d_trap (void) { gsl_histogram *h; double result, lower, upper; size_t i; gsl_set_error_handler (&my_error_handler); gsl_ieee_env_setup (); status = 0; h = gsl_histogram_calloc (0); gsl_test (!status, "gsl_histogram_calloc traps zero-length histogram"); gsl_test (h != 0, "gsl_histogram_calloc returns NULL for zero-length histogram"); status = 0; h = gsl_histogram_calloc_uniform (0, 0.0, 1.0); gsl_test (!status, "gsl_histogram_calloc_uniform traps zero-length histogram"); gsl_test (h != 0, "gsl_histogram_calloc_uniform returns NULL for zero-length histogram"); status = 0; h = gsl_histogram_calloc_uniform (10, 1.0, 1.0); gsl_test (!status, "gsl_histogram_calloc_uniform traps equal endpoints"); gsl_test (h != 0, "gsl_histogram_calloc_uniform returns NULL for equal endpoints"); status = 0; h = gsl_histogram_calloc_uniform (10, 2.0, 1.0); gsl_test (!status, "gsl_histogram_calloc_uniform traps invalid range"); gsl_test (h != 0, "gsl_histogram_calloc_uniform returns NULL for invalid range"); h = gsl_histogram_calloc_uniform (N, 0.0, 1.0); status = gsl_histogram_accumulate (h, 1.0, 10.0); gsl_test (status != GSL_EDOM, "gsl_histogram_accumulate traps x at xmax"); status = gsl_histogram_accumulate (h, 2.0, 100.0); gsl_test (status != GSL_EDOM, "gsl_histogram_accumulate traps x above xmax"); status = gsl_histogram_accumulate (h, -1.0, 1000.0); gsl_test (status != GSL_EDOM, "gsl_histogram_accumulate traps x below xmin"); status = gsl_histogram_increment (h, 1.0); gsl_test (status != GSL_EDOM, "gsl_histogram_increment traps x at xmax"); status = gsl_histogram_increment (h, 2.0); gsl_test (status != GSL_EDOM, "gsl_histogram_increment traps x above xmax"); status = gsl_histogram_increment (h, -1.0); gsl_test (status != GSL_EDOM, "gsl_histogram_increment traps x below xmin"); result = gsl_histogram_get (h, N); gsl_test (result != 0, "gsl_histogram_get traps index at n"); result = gsl_histogram_get (h, N + 1); gsl_test (result != 0, "gsl_histogram_get traps index above n"); status = gsl_histogram_get_range (h, N, &lower, &upper); gsl_test (status != GSL_EDOM, "gsl_histogram_get_range traps index at n"); status = gsl_histogram_get_range (h, N + 1, &lower, &upper); gsl_test (status != GSL_EDOM, "gsl_histogram_get_range traps index above n"); status = 0; gsl_histogram_find (h, -0.01, &i); gsl_test (status != GSL_EDOM, "gsl_histogram_find traps x below xmin"); status = 0; gsl_histogram_find (h, 1.0, &i); gsl_test (status != GSL_EDOM, "gsl_histogram_find traps x at xmax"); status = 0; gsl_histogram_find (h, 1.1, &i); gsl_test (status != GSL_EDOM, "gsl_histogram_find traps x above xmax"); gsl_histogram_free (h); }