Ejemplo n.º 1
0
void average_bin(double* array_x, double* array_y, double* bins, 
	double* binned_array, double *error_array, int bin_size, int array_size)
{
#ifdef PRINT_INFO
	fprintf(stdout, "\nBinning and averaging into %d bins an array of size:%d...", bin_size, array_size);
#endif
	int i=0, j=0; 

	gsl_histogram *h = gsl_histogram_alloc (bin_size-1);
	gsl_histogram *g = gsl_histogram_alloc (bin_size-1);
	gsl_histogram_set_ranges (h, bins, bin_size);
	gsl_histogram_set_ranges (g, bins, bin_size);
		
		for(i=0; i<array_size; i++)
		{
			gsl_histogram_increment  (h, array_x[i]);
			gsl_histogram_accumulate (g, array_x[i], array_y[i]);
		}

			for(j=0; j<bin_size-1; j++)
			{
				binned_array[j] = g->bin[j]/h->bin[j];
					if(h->bin[j]>0)	// Assuming poissonian error
						error_array[j] = g->bin[j] / sqrt(h->bin[j]);
			}

	gsl_histogram_free(h);
	gsl_histogram_free(g);
}
Ejemplo n.º 2
0
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;
}
Ejemplo n.º 3
0
void ALEXHistogramsWidget::plotHistogramS()
{
    // pr histogram
    plot=ui->widPlotHistS;
    JKQTPdatastore* ds=plot->get_plotter()->getDatastore();
    plot->get_plotter()->clearGraphs(true);
    ds->clear();
    plot->get_plotter()->getYAxis()->set_axisLabel("S");
    plot->get_plotter()->getXAxis()->set_axisLabel("frequency");
    int nbins=ui->spinBoxBins->value();
    gsl_histogram * histS=gsl_histogram_calloc_uniform(nbins,ad->rangeALEX.minP,ad->rangeALEX.maxP);
    gsl_histogram * histSFiltered=gsl_histogram_calloc_uniform(nbins,ad->rangeALEX.minP,ad->rangeALEX.maxP);
    for(int i=0;i<ad->burstVectorDual.size();++i) {
        gsl_histogram_increment(histS,ad->burstVectorDual.at(i).stoichiometryRatio);
        if(!ad->burstVectorDual.at(i).isMasked(ad->FRETparams))
            gsl_histogram_increment(histSFiltered,ad->burstVectorDual.at(i).stoichiometryRatio);
    }

    qDebug("plot S histogram");
    unsigned long long nrows=histS->n;
    size_t yColumn=ds->addCopiedColumn(histS->range, nrows, "s"); // adds column and returns column ID
    size_t xColumn=ds->addCopiedColumn(histS->bin, nrows, "all");
    size_t xColumnFiltered=ds->addCopiedColumn(histSFiltered->bin, nrows, "selected");
    gsl_histogram_free(histS);
    gsl_histogram_free(histSFiltered);

    JKQTPbarVerticalGraph* g=new JKQTPbarVerticalGraph(plot->get_plotter()); // g->set_title("S");
    g->set_xColumn(xColumn);
    g->set_yColumn(yColumn);
    g->set_shift(0);
    g->set_width(1);
    g->set_style(Qt::NoPen);
    g->set_fillColor(QColor(DISTRIBUTION_COLOR));
    plot->addGraph(g);

    g=new JKQTPbarVerticalGraph(plot->get_plotter());
    g->set_xColumn(xColumnFiltered);
    g->set_yColumn(yColumn);
    g->set_shift(0);
    g->set_width(1);
    g->set_style(Qt::NoPen);
    g->set_fillColor(QColor(DISTRIBUTION_COLOR_SELECTED));
    plot->addGraph(g);

    plot->get_plotter()->zoomToFit();

//    JKQTPhorizontalRange *gr;
//    gr = new JKQTPhorizontalRange(plot->get_plotter());
//    gr->set_rangeMin(ad->FRETparams.MinS);
//    gr->set_rangeMax(ad->FRETparams.MaxS);
//    gr->set_invertedRange(true);
//    QColor col = QColor(Qt::lightGray);
//    col.setAlpha(ui->spinBoxAlpha->value());
//    gr->set_fillColor(col);
//    gr->set_style(Qt::NoPen);
//    gr->set_plotCenterLine(false);
    //    plot->addGraph(gr);
}
Ejemplo n.º 4
0
/* 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);
}
Ejemplo n.º 5
0
int
main (void)
{
  struct data ntuple_row;
  int i;

  gsl_ntuple *ntuple = gsl_ntuple_open ("test.dat", &ntuple_row,
                                        sizeof (ntuple_row));

  gsl_histogram *h = gsl_histogram_calloc_uniform (100, 0., 10.);

  gsl_ntuple_select_fn S;
  gsl_ntuple_value_fn V;

  double scale = 1.5;

  S.function = &sel_func;
  S.params = &scale;

  V.function = &val_func;
  V.params = 0;

  gsl_ntuple_project (h, ntuple, &V, &S);

  gsl_histogram_fprintf (stdout, h, "%f", "%f");

  gsl_histogram_free (h);

  gsl_ntuple_close (ntuple);
}
Ejemplo n.º 6
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);
}
Ejemplo n.º 7
0
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);
}
Ejemplo n.º 8
0
bool myHistogram::Convert(vector<double> &x)
{
	gsl_histogram *r;
	size_t n=x.size();
	if(n<=2) return false;
	double *res;
	res=new double[n];
	size_t i;
	for(i=0;i<n;i++) res[i]=x[i];
	double std=gsl_stats_sd(res,1,n);
	double bin=3.49*std/pow(n*1.0,1.0/3);//Scott's ruler
	if(bin<=0) 
	{
		delete []res;
		return false;
	}
	double a=gsl_stats_min(res,1,n);
	double b=gsl_stats_max(res,1,n);
	int num=(int)((b-a)/bin);
	r=gsl_histogram_alloc(num);
	gsl_histogram_set_ranges_uniform(r,a,b);
	for(i=0;i<n;i++)
	{
		gsl_histogram_increment(r,res[i]);
	}	
	Convert(r,n);	
	gsl_histogram_free(r);
	delete []res;	
	return true;
}
Ejemplo n.º 9
0
Archivo: kde.c Proyecto: gulkhan007/kde
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;
}
Ejemplo n.º 10
0
int main(void) {
	struct data ntuple_row;

	gsl_ntuple *ntuple
	= gsl_ntuple_open ("test.dat", &ntuple_row,
	sizeof (ntuple_row));
	double lower = 1.5;

	gsl_ntuple_select_fn S;
	gsl_ntuple_value_fn V;

	gsl_histogram *h = gsl_histogram_alloc (100);
	gsl_histogram_set_ranges_uniform(h, 0.0, 10.0);

	S.function = &sel_func;
	S.params = &lower;

	V.function = &val_func;
	V.params = 0;

	gsl_ntuple_project (h, ntuple, &V, &S);

	gsl_histogram_fprintf (stdout, h, "%f", "%f");
	gsl_histogram_free (h);
	gsl_ntuple_close (ntuple);

	return 0;
}
Ejemplo n.º 11
0
/* ==== */
void
wanglandau_free_memory(void)
{
  gsl_histogram_free(h);
  gsl_histogram_free(g);
  gsl_rng_free(r);
  free(pt);
  free(s0);
  free(s1);
  free(wanglandau_opt.sequence);
  free(wanglandau_opt.structure);
  free(wanglandau_opt.basename);
  free(P);
  free(out_prefix);
  dealloc_gengetopt();
  return;
}
Ejemplo n.º 12
0
int
main (int argc, char **argv)
{
  double a = 0.0, b = 1.0;
  size_t n = 10;

  if (argc != 3 && argc !=4)
    {
      printf ("Usage: gsl-histogram xmin xmax [n]\n");
      printf (
"Computes a histogram of the data on stdin using n bins from xmin to xmax.\n"
"If n is unspecified then bins of integer width are used.\n");
      exit (0);
    }

  a = atof (argv[1]);
  b = atof (argv[2]);

  if (argc == 4) 
    {
      n = atoi (argv[3]);
    }
  else
    {
      n = (int)(b - a) ;
    }

  {
    double x;
    gsl_histogram *h = gsl_histogram_alloc (n);

    gsl_histogram_set_ranges_uniform (h, a, b);

    while (fscanf(stdin, "%lg", &x) == 1)
      {
        gsl_histogram_increment(h, x);
      }

#ifdef DISPLAY_STATS
    {
      double mean = gsl_histogram_mean (h);
      double sigma = gsl_histogram_sigma (h);
      fprintf (stdout, "# mean = %g\n", mean);
      fprintf (stdout, "# sigma = %g\n", sigma);
    }
#endif

    gsl_histogram_fprintf (stdout, h, "%g", "%g");

    gsl_histogram_free (h);
  }

  return 0;
}
Ejemplo n.º 13
0
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);
}
Ejemplo n.º 14
0
Archivo: i2c.c Proyecto: useche/btstats
void i2c_destroy(struct plugin *p)
{
	unsigned int i;

	DECL_ASSIGN_I2C(i2c,p->data);

	if(i2c->oio_f)
		fclose(i2c->oio_f);

	if(i2c->oio_hist_f)
		fclose(i2c->oio_hist_f);

	for (i = 0; i <= i2c->maxouts; i++) {
		gsl_histogram_free(i2c->oio[i].op[READ]);
		gsl_histogram_free(i2c->oio[i].op[WRITE]);
	}
	free(i2c->oio);

	g_free(p->data);
}
Ejemplo n.º 15
0
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 );
    }

}
Ejemplo n.º 16
0
		/* Number the entries per bin in a given array */
void lin_bin(double* array, double* bins, int bin_size, int array_size, int* binned_array)
{
	int i=0, j=0;
#ifdef PRINT_INFO
	fprintf(stdout, "\nBinning into %d bins an array of size:%d...", bin_size, array_size);
#endif
	gsl_histogram *h = gsl_histogram_alloc (bin_size-1);
	gsl_histogram_set_ranges (h, bins, bin_size);
		
		for(i=0; i<array_size; i++)
			gsl_histogram_increment(h, array[i]);
		
		for(j=0; j<bin_size-1; j++)
			binned_array[j] = (int) h->bin[j];

	gsl_histogram_free(h);
}
Ejemplo n.º 17
0
bool HistList::AddHist(double *res,int n,double m,double sd,CString raw)
{
	gsl_histogram *r;
	if(n<=0) return false;
	double std=gsl_stats_sd(res,1,n);
	double bin=3.49*std/pow(n*1.0,1.0/3);//Scott's ruler
	if(bin<=0) return false;	
	double a=gsl_stats_min(res,1,n);
	double b=gsl_stats_max(res,1,n);
	int num=(int)((b-a)/bin);
	r=gsl_histogram_alloc(num);
	gsl_histogram_set_ranges_uniform(r,a,b);
	for(int i=0;i<n;i++)
	{
		gsl_histogram_increment(r,res[i]);
	}
	bool bResult=AddHist(r,m,sd,raw);
	gsl_histogram_free(r);
	return bResult;
}
Ejemplo n.º 18
0
bool myHistogram::Convert(double *res,int n)
{
	gsl_histogram *r;
	if(n<=2) return false;
	double std=gsl_stats_sd(res,1,n);
	double bin=3.49*std/pow(n*1.0,1.0/3);//Scott's ruler
	if(bin<=0) return false;	
	double a=gsl_stats_min(res,1,n);
	double b=gsl_stats_max(res,1,n);
	int num=(int)((b-a)/bin);
	r=gsl_histogram_alloc(num);
	gsl_histogram_set_ranges_uniform(r,a,b);
	for(int i=0;i<n;i++)
	{
		gsl_histogram_increment(r,res[i]);
	}	
	Convert(r,n);	
	gsl_histogram_free(r);	
	return true;
}
Ejemplo n.º 19
0
/** @short Markov Chain Monte Carlo 
		@param rng the GSL random number generator 
		@param p the vector of parameters being searched over 
		@param x the vector of observations */
void mcmc(const gsl_rng *rng, gsl_vector *p, const gsl_vector *x)
{
	gsl_vector * p_test = gsl_vector_alloc(p->size);
	size_t i;
	
	gsl_histogram * hist = gsl_histogram_alloc(nbins);
	gsl_histogram_set_ranges_uniform(hist, min, max);

	for(i=0; i < chain_length; i++)
	{
		gsl_vector_memcpy(p_test,p);
		propose(rng, p_test);
		double lnLikelihoodRatio = ln_lik_fn(p_test, x) - ln_lik_fn(p, x);
		if (take_step(rng, lnLikelihoodRatio))
			p = p_test;
		gsl_histogram_increment(hist, p->data[1]);
	}
	gsl_vector_free(p_test);
	gsl_histogram_fprintf(stdout, hist, "%g", "%g");
	gsl_histogram_free(hist);
}
Ejemplo n.º 20
0
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;
}
Ejemplo n.º 21
0
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);
}
Ejemplo n.º 22
0
/* ==== */
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;
}
Ejemplo n.º 23
0
void ALEXHistogramsWidget::plotHistogramPR()
{
    // pr histogram
    plot=ui->widPlotPrHist;
    JKQTPdatastore* ds=plot->get_plotter()->getDatastore();
    plot->get_plotter()->clearGraphs(true);
    ds->clear();
    plot->get_plotter()->getXAxis()->set_axisLabel("P");
    plot->get_plotter()->getYAxis()->set_axisLabel("frequency");
    int nbins=ui->spinBoxBins->value();
    gsl_histogram * histPr=gsl_histogram_calloc_uniform(nbins,ad->rangeALEX.minP,ad->rangeALEX.maxP);
    gsl_histogram * histPrSelected=gsl_histogram_calloc_uniform(nbins,ad->rangeALEX.minP,ad->rangeALEX.maxP);
    for(int i=0;i<ad->burstVectorDual.size();++i) {
        gsl_histogram_increment(histPr,ad->burstVectorDual.at(i).proximityRatio);
        if(!ad->burstVectorDual.at(i).isMasked(ad->FRETparams))
            gsl_histogram_increment(histPrSelected,ad->burstVectorDual.at(i).proximityRatio);
    }

    qDebug("plot PR histogram");
    unsigned long long nrows=histPr->n;
    size_t xColumn=ds->addCopiedColumn(histPr->range, nrows, "P"); // adds column and returns column ID
    size_t yColumn=ds->addCopiedColumn(histPr->bin, nrows, "all");
    size_t yColumnFiltered=ds->addCopiedColumn(histPrSelected->bin, nrows, "selected");
    gsl_histogram_free(histPr);
    gsl_histogram_free(histPrSelected);

    JKQTPbarHorizontalGraph* g=new JKQTPbarHorizontalGraph(plot->get_plotter()); // g->set_title("pr");
    g->set_xColumn(xColumn);
    g->set_yColumn(yColumn);
    g->set_shift(0);
    g->set_width(1);
    g->set_style(Qt::NoPen);
    g->set_fillColor(QColor(DISTRIBUTION_COLOR));
    plot->addGraph(g);

    g=new JKQTPbarHorizontalGraph(plot->get_plotter());
    g->set_xColumn(xColumn);
    g->set_yColumn(yColumnFiltered);
    g->set_shift(0);
    g->set_width(1);
    g->set_style(Qt::NoPen);
    g->set_fillColor(QColor(DISTRIBUTION_COLOR_SELECTED));
    plot->addGraph(g);



//    double area=0;
//    for(int i=0;i<histPrSelected->n;++i) {
//        area+=fabs(histPrSelected->range[i+1]-histPrSelected->range[i])*histPrSelected->bin[i];
//    }
//    QVector<double> gauss,gauss_x;
//    gauss.reserve(nbins);
//    int k=0;
//    double mu=model.getGMM()->getMu(k,0);
//    double sigma=model.getGMM()->getGauss(k).getSigma()(0,0);

//    double norm=area/sqrt(2*M_PI)/sigma;
//    qDebug()<<"plot gauss\nmu="<<mu<<" sigma="<<sigma<<"norm="<<norm<<"area="<<area;
//    double x_min=histPrSelected->range[0];
//    double x_max=histPrSelected->range[histPrSelected->n];
//    int npoints=200;
//    double step=(x_max-x_min)/(npoints-1);
//    for(int i=0;i<npoints;++i) {
//        gauss_x.append(x_min+i*step);
//    }
//    for(int i=0;i<npoints;++i) {
//        gauss.append(norm*exp(-pow((gauss_x.at(i)-mu),2)/sigma/sigma/2));
//    }
//    size_t xColumnGauss=ds->addCopiedColumn(gauss_x.data(), gauss_x.size(), "gauss P");
//    size_t yColumnGauss=ds->addCopiedColumn(gauss.data(), gauss.size(), "gauss fit");

//    JKQTPxyLineGraph* gg=new JKQTPxyLineGraph(plot->get_plotter());
//    gg->set_xColumn(xColumnGauss);
//    gg->set_yColumn(yColumnGauss);
//    gg->set_style(Qt::SolidLine);
//    gg->set_color(QColor("black"));
//    plot->addGraph(gg);

    plot->get_plotter()->zoomToFit();

//    JKQTPverticalRange *gr;
//    gr = new JKQTPverticalRange(plot->get_plotter());
//    gr->set_rangeMin(ad->FRETparams.MinP);
//    gr->set_rangeMax(ad->FRETparams.MaxP);
//    gr->set_invertedRange(true);
//    QColor col = QColor(Qt::lightGray);
//    col.setAlpha(ui->spinBoxAlpha->value());
//    gr->set_fillColor(col);
//    gr->set_style(Qt::NoPen);
//    gr->set_plotCenterLine(false);
//    plot->addGraph(gr);
}
Ejemplo n.º 24
0
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);
}
Ejemplo n.º 25
0
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);
}
Ejemplo n.º 26
0
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;

}
Ejemplo n.º 27
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);
}
Ejemplo n.º 28
0
void BurstSearchWidget::on_pushButtonBurstView_clicked()
{
    qDebug("on_pushButtonBurstView_clicked");
    if(ad->isEmpty()) return;
    JKQtPlotter* plot = new JKQtPlotter(true,NULL);
    getParameters();

    double binwidth=5e-6, alternationPeriod=ad->getExcitationPeriodDonor();
    int nbins=(int)(alternationPeriod/binwidth+1);
    gsl_histogram * histCh1 = gsl_histogram_alloc (nbins);
    gsl_histogram * histCh2 = gsl_histogram_alloc (nbins);
    gsl_histogram_set_ranges_uniform (histCh1, 0, alternationPeriod*1.1);
    gsl_histogram_set_ranges_uniform (histCh2, 0, alternationPeriod*1.1);
    int last=0;
    int lastExc=0;
    while(ad->photons.at(last).time<ad->markerTimeDexc.at(lastExc)) ++last;
    uint ch1=ui->comboBoxChannel1->channel();
    uint ch2=ui->comboBoxChannel2->channel();
    while((lastExc<1e4)&&(lastExc<ad->markerTimeDexc.size()+1)) { // average first 10000 periods

        while ((last<ad->photons.size()) && ad->photons[last].time<ad->markerTimeDexc.at(lastExc+1)) {
//            qDebug()<<QString::number(ad->photons[last].flags,2)+"\t"<<ch1<<ch2<<"\t"<<ad->photons[last].isPhotonFlag(ch1)<<ad->photons[last].isPhotonFlag(ch2);
#ifdef PHOTONMACRO
            if(isPhotonFlag(ad->photons[last],ch1)) gsl_histogram_increment (histCh1, ad->photons[last].time-ad->markerTimeDexc[lastExc]);
            if(isPhotonFlag(ad->photons[last],ch2)) gsl_histogram_increment (histCh2, ad->photons[last].time-ad->markerTimeDexc[lastExc]);
#else
            if(ad->photons[last].isPhotonFlag(ch1)) gsl_histogram_increment (histCh1, ad->photons[last].time-ad->markerTimeDexc[lastExc]);
            if(ad->photons[last].isPhotonFlag(ch2)) gsl_histogram_increment (histCh2, ad->photons[last].time-ad->markerTimeDexc[lastExc]);
#endif
            last++;
        }
        // end of excitation period
        lastExc++;
    }
    JKQTPdatastore* ds=plot->get_plotter()->getDatastore();
    ds->clear();
    plot->get_plotter()->clearGraphs(true);
    plot->get_plotter()->setGrid(false);

    qDebug("plotHist DA");
    unsigned long long nrows=(unsigned long long)histCh1->n;
    for(size_t i=0;i<histCh1->n;++i) histCh1->range[i] *= 1e6;
    plot->get_xAxis()->set_axisLabel("time in us");
    plot->get_yAxis()->set_axisLabel("countrate in Hz");
    gsl_histogram_scale(histCh1,(1.0)/(lastExc*binwidth)); // convert bins to countrate in Hz (counts averaged over lastDex excitation periods in bin of width binwidth)
    gsl_histogram_scale(histCh2,(1.0)/(lastExc*binwidth));

    size_t xColumn=ds->addCopiedColumn(histCh1->range, nrows, "time"); // adds column (copies values!) and returns column ID
    QVector<size_t> yColumns;
    yColumns.push_back(ds->addCopiedColumn(histCh1->bin, nrows, "Channel 1"));
    yColumns.push_back(ds->addCopiedColumn(histCh2->bin, nrows, "Channel 2"));
    QList<QColor> colors;
    colors.append(QColor(COUNTRATE_COLOR_CH1));
    colors.append(QColor(COUNTRATE_COLOR_CH2));
    gsl_histogram_free(histCh1);
    gsl_histogram_free(histCh2);

    // plot
    double width=0.5;
    double s=-0.5+width/2.0;
    for (int i=0; i<yColumns.size(); ++i) {
        JKQTPbarHorizontalGraph* g=new JKQTPbarHorizontalGraph(plot->get_plotter());
        g->set_xColumn(xColumn);
        g->set_yColumn(yColumns[i]);
        g->set_shift(s);
        g->set_width(width);
        g->set_style(Qt::NoPen);
        g->set_fillColor(colors.at(i));
        s=s+width;
        plot->addGraph(g);
    }
    plot->get_plotter()->set_keyPosition(JKQTPkeyInsideTopRight); // set legend position
    plot->get_plotter()->set_showKey(true);
    plot->zoomToFit();

    plot->show();

    // old:
//    if(ad->burstVectorDual.isEmpty())
//        runBurstSearch();
//    analysisFRET(ad->burstVectorDual,ad->FRETparams);

//    BurstView *burstView= new BurstView(this, ad);
//    burstView->exec();
}
Ejemplo n.º 29
0
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);
}
Ejemplo n.º 30
0
population::~population(){
    if (VERBOSE)
        cout << "Destructing Population...\n"; 
    gsl_histogram_free(blockHist); //Remove usage of histogram!
}