Esempio 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);
}
Esempio n. 2
0
// receive vector<vector<unsigned int>> representing a list of tuples
// these tuples have pairs of particleTypeIds which should be considered
// in rdf calculation.
RadialDistribution::RadialDistribution(
	std::vector<double>& range,
	bool isPeriodic,
	double boxsize,
	std::vector< std::vector<unsigned int> > considered,
	std::string inFilename)
{
	this->recPeriod    = 1;
	this->clearPeriod  = 0;
	this->filename     = inFilename;
	this->isPeriodic   = isPeriodic;
	this->boxsize      = boxsize;
	this->numberOfBins = range.size() - 1;
	this->radialDistribution = gsl_histogram_alloc(this->numberOfBins);
	this->rangeOfBins  = range;
	const double * cRange = &range[0];
	gsl_histogram_set_ranges(this->radialDistribution, cRange, range.size());
	// calculate centers of bins
	double center;
	for (int i=0; i < (rangeOfBins.size() - 1) ; i++) {
		center = 0.5 * ( rangeOfBins[i] + rangeOfBins[i+1] );
		this->binCenters.push_back(center);
		this->bins.push_back(0.);
	}
	this->consideredPairs = considered;
}
Esempio n. 3
0
File: kde.c Progetto: 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;
}
Esempio n. 4
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);
}
Esempio n. 5
0
CAMLprim value ml_gsl_histogram_set_ranges(value vh, value range)
{
  gsl_histogram h;
  histo_of_val(&h, vh);
  gsl_histogram_set_ranges(&h, Double_array_val(range), 
			   Double_array_length(range));
  return Val_unit;
}
Esempio n. 6
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);
}
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 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);
}
Esempio n. 9
0
/* ==== */
static void
initialize_wl(void)
{
  int bins,fnlen=512;
  char *res_string=NULL;
  double low,high,lo,hi,hmin,hmax,erange,*range = NULL;
  
  srand(time(NULL));
  if(wanglandau_opt.verbose){
    printf("[[initialize_wl()]]\n");
  }
  /* assign function pointers */
  initialize_model = initialize_RNA;  /* for RNA */
  pre_process_model  = pre_process_RNA;
  post_process_model = post_process_RNA;
  
  /* set energy paramters for current model; compute mfe */
  initialize_model(wanglandau_opt.sequence); 

  range = (double*)calloc((wanglandau_opt.bins+1), sizeof(double));
  assert(range!=NULL);

  /* initialize histograms */
  hmin=mfe;
  if(wanglandau_opt.res_given){ /* determine histogram ranges manually */
    int i;
    range[0]=mfe;
    for(i=1;i<=wanglandau_opt.bins;i++){
      range[i]=range[i-1]+wanglandau_opt.res;
    }
    if(wanglandau_opt.verbose){
      /* info output */
      fprintf(stderr,"#allocating %lu bins of width %g\n",
	      wanglandau_opt.bins,wanglandau_opt.res);
      /* fprintf(stderr,"#histogram ranges:\n #");
	 for(i=0;i<=wanglandau_opt.bins;i++){
	 fprintf(stderr, "%6.2f ",range[i]);
      
      }
      fprintf(stderr,"\n");
      */
    }
  
    if(wanglandau_opt.max_given){
      hmax=wanglandau_opt.max;
    }
    else{
      wanglandau_opt.max=range[wanglandau_opt.bins]; /* the last element */
      hmax=wanglandau_opt.max;
    }
    h = gsl_histogram_alloc(wanglandau_opt.bins);
    g = gsl_histogram_alloc(wanglandau_opt.bins);
    s = gsl_histogram_alloc(wanglandau_opt.bins);
    gsl_histogram_set_ranges(h,range,(wanglandau_opt.bins+1));
    gsl_histogram_set_ranges(g,range,(wanglandau_opt.bins+1));
    gsl_histogram_set_ranges(s,range,(wanglandau_opt.bins+1));
  }
  else{  /* determine histogram ranges automatically */
    if(wanglandau_opt.max_given){
      hmax = wanglandau_opt.max;
    }
    else{
      hmax=20*fabs(mfe);
    }
    h = ini_histogram_uniform(wanglandau_opt.bins,hmin,hmax);
    g = ini_histogram_uniform(wanglandau_opt.bins,hmin,hmax);
    s = ini_histogram_uniform(wanglandau_opt.bins,hmin,hmax);
  }
  fprintf (stderr, "# sampling energy range is %6.2f - %6.2f\n",
	   hmin,hmax);
  free(range);
  
  /* get the energy range up to which we will compute true DOS via
     RNAsubopt */
  gsl_histogram_get_range(s,0,&lo,&hi);
  low = lo;
  gsl_histogram_get_range(s,(wanglandau_opt.truedosbins-1),&lo,&hi);
  high = hi;
  wanglandau_opt.erange=(float)fabs(mfe-high+0.01);
  if(wanglandau_opt.verbose){
    printf("Using true DOS for bins 0-%d: (%6.3g -- %6.3g) wl_opt.erange=%6.3f\n",
	   (wanglandau_opt.truedosbins-1),low,high,wanglandau_opt.erange);
  }
  
  /* prepare gsl random-number generation */
  (void) clock_gettime(CLOCK_REALTIME, &ts);
  if(wanglandau_opt.seed_given){
    seed = wanglandau_opt.seed;
  }
  else {
    seed =   ts.tv_sec ^ ts.tv_nsec;
  }
  fprintf(stderr, "initializing random seed: %d\n",seed);
  gsl_rng_env_setup();
  r = gsl_rng_alloc (gsl_rng_mt19937);
  gsl_rng_set( r, seed );
  /* end gsl */

  /* make prefix for output */
  out_prefix = (char*)calloc(fnlen, sizeof(char));
  res_string = (char*)calloc(16, sizeof(char));
  sprintf(res_string,"%3.1f", wanglandau_opt.res);
  strcpy(out_prefix, wanglandau_opt.basename); strcat(out_prefix, ".res");
  strcat(out_prefix, res_string); strcat(out_prefix, ".");
  free(res_string);
  return;
}
Esempio n. 10
0
//Run the generator
void RandPSSMGen::RunGenerator()
{
	int c, i, j, k,l,m,q,w,z, curr_len;
	double curr_depth;
	double x, r;
	int zeros=0;
	double col_sum=0;
	double firstDraw, secondDraw, thirdDraw, sum;
	gsl_histogram* width_hist;
	gsl_histogram_pdf* width_pdf;
	gsl_histogram* depth_hist;
	gsl_histogram_pdf* depth_pdf;
	double invariant_cols[6];
	double total_cols[6];
	double invariant_prob[6];
	double abszero_cells[6];
	double total_cells[6];
	double abszero_prob[6];
	gsl_histogram* first_edge_hist;
	gsl_histogram_pdf* first_edge_pdf;
	gsl_histogram* first_inner_hist;
	gsl_histogram_pdf* first_inner_pdf;
	gsl_histogram* second_edge_hist[5];
	gsl_histogram_pdf* second_edge_pdf[5];
	gsl_histogram* second_inner_hist[5];
	gsl_histogram_pdf* second_inner_pdf[5];
	gsl_histogram* third_edge_hist[5];
	gsl_histogram_pdf* third_edge_pdf[5];
	gsl_histogram* third_inner_hist[5];
	gsl_histogram_pdf* third_inner_pdf[5];
	FILE* out;
	bool edge;
	double known_zeros=0, known_total=0;
	double new_zeros=0, new_total=0;

	out = fopen(outFN, "w");
	if(out==NULL)
	{	printf("Error: cannot open file named %s\n", outFN);
		exit(1);
	}

	//How many random matrices?
	printf("%d Matrices Will Be Generated\n", numRandomMats);

	//Read in the matrices
	printf("%d Matrices Read In\n", numMatrices);
	
	//1) The first step is to read in the width distribution
	width_hist = gsl_histogram_alloc(7); //7 places in the histogram
	double width_range[8] = {3, 5, 8, 10, 12, 14, 16, 25};
	gsl_histogram_set_ranges(width_hist, width_range, 8);
	for(i=0; i<numMatrices; i++) {//Go through each matrix, adding size to histogram
		gsl_histogram_increment(width_hist, (double)matrices[i]->len);
	}
	width_pdf= gsl_histogram_pdf_alloc(7);
	gsl_histogram_pdf_init(width_pdf, width_hist);
	//1.1) Find the sequence depth distribution
	depth_hist = gsl_histogram_alloc(7); //20 places in the histogram
	double depth_range[8] = {0,5,10,20,40,80,160,1000};
	gsl_histogram_set_ranges(depth_hist, depth_range, 8);
	for(i=0; i<numMatrices; i++) {//Go through each matrix, adding each column depth to histogram
		for(j=0; j<matrices[i]->len; j++){
			double sum=0;	
			for(k=0; k<B; k++){
				sum += matrices[i]->n[j][k];
			}
            gsl_histogram_increment(depth_hist, sum);
		}
	}
	depth_pdf = gsl_histogram_pdf_alloc(7);
	gsl_histogram_pdf_init(depth_pdf, depth_hist);


	//2) The second step is to find the probability of invariance given the position of the column
	//Also find the probability of an absolute zero (not including the invariant columns)
	for(i=0; i<6; i++) {
		invariant_cols[i]=0;
		total_cols[i]=0;
		abszero_cells[i]=0;
		total_cells[i]=0;
	}
	bool inv=false;
	for(i=0; i<numMatrices; i++) {
		curr_len = matrices[i]->len;
		for(j=0; j<curr_len; j++){
			//Is the column invariant?
			inv = Invariant(matrices[i]->n[j], zeros);
			//What column are we in?
			z = WhatColumn(j, curr_len);
			total_cols[z]++;
			invariant_cols[z]+=inv;

			//Find zeros in a variable column
			if(!inv) {
				total_cells[z]+=4;
				abszero_cells[z]+=zeros;
			}
			known_total+=4; known_zeros+=zeros;
		}
	}
	for(i=0; i<6; i++){
		invariant_prob[i]=invariant_cols[i]/total_cols[i];
		abszero_prob[i]=abszero_cells[i]/total_cells[i];
	}
	printf("Known Zeros: %lf\n", known_zeros/known_total);
	//3) Fill the First, Second, and Third Draw Histograms.
	first_edge_hist = gsl_histogram_alloc(5);
	gsl_histogram_set_ranges_uniform (first_edge_hist, 0.0001, 0.99999);
	first_inner_hist = gsl_histogram_alloc(5);
	gsl_histogram_set_ranges_uniform (first_inner_hist, 0.0001, 0.99999);
	for(i=0; i<5; i++){
		second_edge_hist[i] = gsl_histogram_alloc(5);
		gsl_histogram_set_ranges_uniform(second_edge_hist[i], 0.0001, 0.99999);
		second_inner_hist[i] = gsl_histogram_alloc(5);
		gsl_histogram_set_ranges_uniform(second_inner_hist[i], 0.0001, 0.99999);
	}
	for(i=0; i<5; i++){
		third_edge_hist[i] = gsl_histogram_alloc(5);
		gsl_histogram_set_ranges_uniform(third_edge_hist[i], 0.0001, 0.99999);
		third_inner_hist[i] = gsl_histogram_alloc(5);
		gsl_histogram_set_ranges_uniform(third_inner_hist[i], 0.0001, 0.99999);
	}
	
	for(i=0; i<numMatrices; i++) {
		curr_len = matrices[i]->len;
		for(j=0; j<curr_len; j++){
			if(WhatColumn(j, curr_len)==0)
				edge=true;
			else
				edge=false;
			//Discard Invariant Columns
			if(!Invariant(matrices[i]->n[j], zeros)) {
				col_sum = SumColumn(matrices[i]->n[j]);
				for(k=0; k<B; k++) {
					//Update first draw distribution
					firstDraw =matrices[i]->n[j][k];
					if(firstDraw!=0){//Discard Zeros
						if(edge)
							gsl_histogram_increment(first_edge_hist, firstDraw/col_sum);
						else
							gsl_histogram_increment(first_inner_hist, firstDraw/col_sum);
					}

					//Update second draw distribution
					for(l=0; l<B; l++){
						if(l!=k) {
							secondDraw = matrices[i]->n[j][l];
							if(secondDraw!=0) {
								if(edge)
									gsl_histogram_increment(second_edge_hist[(int)floor((firstDraw/col_sum)*5)], secondDraw/col_sum);
								else
									gsl_histogram_increment(second_inner_hist[(int)floor((firstDraw/col_sum)*5)], secondDraw/col_sum);
							}
							sum = secondDraw + firstDraw;
							//Update third draw distribution
							for(m=0; m<B; m++){
								if(m!=k && m!=l) {
									thirdDraw = matrices[i]->n[j][m];
									if(thirdDraw!=0) {
										if(edge)
											gsl_histogram_increment(third_edge_hist[(int)floor((sum/col_sum)*5)], thirdDraw/col_sum);
										else
											gsl_histogram_increment(third_inner_hist[(int)floor((sum/col_sum)*5)], thirdDraw/col_sum);
									}
								}
							}
						}
					}
				}
			}
		}
	}
	//Start the PDFs here
	first_edge_pdf= gsl_histogram_pdf_alloc(5);
	gsl_histogram_pdf_init(first_edge_pdf, first_edge_hist);
	first_inner_pdf= gsl_histogram_pdf_alloc(5);
	gsl_histogram_pdf_init(first_inner_pdf, first_inner_hist);
	for(i=0; i<5; i++) {
		second_edge_pdf[i]= gsl_histogram_pdf_alloc(5);
		gsl_histogram_pdf_init(second_edge_pdf[i], second_edge_hist[i]);
		second_inner_pdf[i]= gsl_histogram_pdf_alloc(5);
		gsl_histogram_pdf_init(second_inner_pdf[i], second_inner_hist[i]);
	}
	for(i=0; i<5; i++) {
		third_edge_pdf[i]= gsl_histogram_pdf_alloc(5);
		gsl_histogram_pdf_init(third_edge_pdf[i], third_edge_hist[i]);
		third_inner_pdf[i]= gsl_histogram_pdf_alloc(5);
		gsl_histogram_pdf_init(third_inner_pdf[i], third_inner_hist[i]);
	}


	////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////// All information gathered... generating random samples from here on in /////////////////////////////
	////////////////////////////////////////////////////////////////////////////////////////////////////////////
	Motif* newPSSM = new Motif(31);
	for(z=0; z<numRandomMats; z++) {
		double r;
		int base;
		int first, second, third, fourth;
		//first step: pick a length
		r=((double)rand())/RAND_MAX;
		curr_len = (int)gsl_histogram_pdf_sample(width_pdf, r);
		if(curr_len>30){curr_len=30;}

		for(i=0; i<curr_len; i++) { //Generate one column at a time
			//Reset the column
			for(j=0; j<B; j++)
				newPSSM->f[i][j]=0;

			if(WhatColumn(i, curr_len)==0)
				edge=true;
			else
				edge=false;
			//Is the column variable? 
			r=((double)rand())/RAND_MAX;
			c = WhatColumn(i, curr_len);
			if(r<invariant_prob[c]) { //The column has been chosen as invariant
				//Which base is invariant? 
				r = ((double)rand())/RAND_MAX;
				if(r<0.285){base=0;}
				else if(r<0.57){base=3;}
				else if(r<0.785){base=1;}
				else{base=2;}

				newPSSM->f[i][base]=1;
				for(j=0; j<B; j++) {
					if(j!=base)
						newPSSM->f[i][j]=0;
				}
			}else{//the column has been chosen as variable
				sum=0;
				//Which base will be the focus of the first draw?
				first = rand()%B;
				//Is the first draw an absolute zero?
				r=((double)rand())/RAND_MAX;
				if(r<abszero_prob[WhatColumn(i, curr_len)]){//the cell is zero
					newPSSM->f[i][first]=0;
				}else{//the cell isn't zero
					//Sample from the first cell pdf
					r=((double)rand())/RAND_MAX;
					if(edge)
						newPSSM->f[i][first] = gsl_histogram_pdf_sample(first_edge_pdf, r);
					else
						newPSSM->f[i][first] = gsl_histogram_pdf_sample(first_inner_pdf, r);
				}
				sum+=newPSSM->f[i][first];
				//Onto the second draw
				second=rand()%B;
				while(second==first)
				{	second=rand()%B;}

				r=((double)rand())/RAND_MAX;
				if(r<abszero_prob[WhatColumn(i, curr_len)]){//the cell is zero
					newPSSM->f[i][second]=0;
				}else{//the cell isn't zero
					//Sample from the first cell pdf
					r=((double)rand())/RAND_MAX;
					if(edge)
						newPSSM->f[i][second] = gsl_histogram_pdf_sample(second_edge_pdf[(int)floor((sum)*5)], r);
					else
						newPSSM->f[i][second] = gsl_histogram_pdf_sample(second_inner_pdf[(int)floor((sum)*5)], r);
				}
				sum+=newPSSM->f[i][second];
				//NORMALIZING! Check if anything is over 1 at this stage!
				if(sum>1)
				{	newPSSM->f[i][first] = newPSSM->f[i][first]/sum;
					newPSSM->f[i][second] = newPSSM->f[i][second]/sum;
					sum=1;
				}else{
					//Deal with the third draw here
					third=rand()%B;
					while(third==first || third==second)
					{	third=rand()%B;}

					r=((double)rand())/RAND_MAX;
					if(r<abszero_prob[WhatColumn(i, curr_len)]){//the cell is zero
						newPSSM->f[i][third]=0;
					}else{//the cell isn't zero
						//Sample from the first cell pdf
						r=((double)rand())/RAND_MAX;
						if(edge)
							newPSSM->f[i][third] = gsl_histogram_pdf_sample(third_edge_pdf[(int)floor((sum)*5)], r);
						else
							newPSSM->f[i][third] = gsl_histogram_pdf_sample(third_inner_pdf[(int)floor((sum)*5)], r);
					}
					sum+=newPSSM->f[i][third];
					//NORMALIZING! Check if anything is over 1 at this stage!
					if(sum>1)
					{	newPSSM->f[i][first] = newPSSM->f[i][first]/sum;
						newPSSM->f[i][second] = newPSSM->f[i][second]/sum;
						newPSSM->f[i][third] = newPSSM->f[i][third]/sum;
						sum=1;
					}else{
						//Deal with the last base here
						fourth=0;
						while(fourth==first||fourth==second||fourth==third)
							fourth++;
						newPSSM->f[i][fourth]=1-sum;
					}
				}
			}	
			Invariant(newPSSM->f[i], zeros);
			new_total+=4; new_zeros+=zeros;
		}
		//PSSM Generated!

		//Convert to n's
		r=((double)rand())/RAND_MAX;
		curr_depth = gsl_histogram_pdf_sample(depth_pdf, r);
		if(curr_depth<5){curr_len=5;}
		for(q=0; q<curr_len; q++){
			for(w=0; w<B; w++){
				newPSSM->n[q][w] = ceil(newPSSM->f[q][w]*curr_depth);
			}
		}

		//Output in TRANSFAC format
		fprintf(out, "DE\tRAND%d\n", z);
		for(q=0; q<curr_len; q++){
			fprintf(out, "%d\t%lf\t%lf\t%lf\t%lf\tX\n", q, newPSSM->n[q][0],newPSSM->n[q][1],newPSSM->n[q][2],newPSSM->n[q][3]);
		}
		fprintf(out, "XX\n");
	}
printf("New Zeros: %lf\n", new_zeros/new_total);
	/////////////////// Memory cleaning area ///////////////////////////////////////////////////////////////////
	delete newPSSM;
	gsl_histogram_free(width_hist);
	gsl_histogram_pdf_free(width_pdf);
	gsl_histogram_free(first_edge_hist);
	gsl_histogram_pdf_free(first_edge_pdf);
	gsl_histogram_free(first_inner_hist);
	gsl_histogram_pdf_free(first_inner_pdf);
	for(i=0; i<5; i++) {
		gsl_histogram_free(second_edge_hist[i]);
		gsl_histogram_pdf_free(second_edge_pdf[i]);
		gsl_histogram_free(second_inner_hist[i]);
		gsl_histogram_pdf_free(second_inner_pdf[i]);
	}
	for(i=0; i<5; i++) {
		gsl_histogram_free(third_edge_hist[i]);
		gsl_histogram_pdf_free(third_edge_pdf[i]);
		gsl_histogram_free(third_inner_hist[i]);
		gsl_histogram_pdf_free(third_inner_pdf[i]);
	}
	fclose(out);		

}