Пример #1
0
	/**
	 * @brief        Swap a ranges order
	 */
    void SwapRange (const Matrix<size_t>& sol, Matrix<size_t>& nsol) {
		
		size_t i, x, y, pos, nr = numel(sol);
		
		// copy the current solution
		nsol = sol;
		
		// pick two places do not touch start 
		x = gsl_rng_uniform_int (m_rng, nr-1) + 1;
		y = gsl_rng_uniform_int (m_rng, nr-1) + 1;
	    
		// Swap
		if (y < x) {
			pos = x; x = y;	y = pos;
		} else if (x == y)
			return;
	
		// Create a temporary array that holds all the values between place1 and place2
		size_t len = y - x + 1;
		container<size_t> cut (len);

		i = len;
		while (i--)
			nsol[x+len-1-i] = sol[x+i];
		
    }
Пример #2
0
pcat_knob_value_ random_knob_value_uniform( pcat_knob k, gsl_rng *r )
{
    pcat_knob_value_ v;
    switch ( k->kind )
    {
        case PCAT_KNOBK_DISCRETE:
        {
            if( k->_.d.range < 1000000 )
            {
                unsigned long int i = gsl_rng_uniform_int( r, (unsigned long int)k->_.d.range );
                v.d = i + k->_.d.min;
                return v;
            }
            assert( FALSE );
        }
        case PCAT_KNOBK_CONTINUOUS:
        {
            v.c = k->_.c.range * gsl_rng_uniform( r ) + k->_.c.min;
            return v;
        }
        case PCAT_KNOBK_UNORDERED:
        {
            v.u = (uint8_t)gsl_rng_uniform_int( r, (unsigned long int)k->_.u._->option_count );
            return v;
        }
        default:
            assert( FALSE );
    }
}
Пример #3
0
void
mutate (evolve_int_chrom_t *chrom)
{
  size_t point = gsl_rng_uniform_int (rng, chrom->size - 1);
  while (!chrom->vector[point]) /* chrom->vector[point] != 1 */
    point = gsl_rng_uniform_int (rng, chrom->size - 1);
  chrom->vector[point] = 0;
}
Пример #4
0
/* Erdos-Renyi : G(n,M)
*/
igraph_t *ggen_generate_erdos_gnm(gsl_rng *r, unsigned long n, unsigned long m)
{
    igraph_matrix_t adj;
    igraph_t *g = NULL;
    int err;
    unsigned long i,j;
    unsigned long added_edges = 0;

    ggen_error_start_stack();
    if(r == NULL)
        GGEN_SET_ERRNO(GGEN_EINVAL);

    if(m > (n*(n-1)/2))
        GGEN_SET_ERRNO(GGEN_EINVAL);

    g = malloc(sizeof(igraph_t));
    GGEN_CHECK_ALLOC(g);
    GGEN_FINALLY3(free,g,1);

    if(m == 0 || n <= 1)
    {
        GGEN_CHECK_IGRAPH(igraph_empty(g,n,1));
        goto end;
    }
    if(m == (n*(n-1))/2)
    {
        GGEN_CHECK_IGRAPH(igraph_full_citation(g,n,1));
        goto end;
    }

    GGEN_CHECK_IGRAPH(igraph_matrix_init(&adj,n,n));
    GGEN_FINALLY(igraph_matrix_destroy,&adj);

    igraph_matrix_null(&adj);

    while(added_edges < m) {
        GGEN_CHECK_GSL_DO(i = gsl_rng_uniform_int(r,n));
        GGEN_CHECK_GSL_DO(j = gsl_rng_uniform_int(r,n));

        if(i < j && igraph_matrix_e(&adj,i,j) == 0)
        {
            igraph_matrix_set(&adj,i,j,1);
            added_edges++;
        }

    }

    GGEN_CHECK_IGRAPH(igraph_adjacency(g,&adj,IGRAPH_ADJ_DIRECTED));
end:
    ggen_error_clean(1);
    return g;
ggen_error_label:
    return NULL;
}
Пример #5
0
void IsingModel2dDipole::metropolis_mirror()
{
  // vertical or horizontal mirroring?
  bool mode = gsl_rng_uniform_int( rng, 2 );
  unsigned int fmline = gsl_rng_uniform_int( rng, size - 1 ) + 1;
  unsigned int fmcol = gsl_rng_uniform_int( rng, size - 1 ) + 1;

  if ( mode ) {
    // mirroring: horizontal
    for ( unsigned int l = fmline; l < size; l++ ) {
      for ( unsigned int c = 0; c < size; c++ ) {
        spin[l][c].flip();
      }
    }
  } else {
    // mirroring: vertical
    for ( unsigned int c = fmcol; c < size; c++ ) {
      for ( unsigned int l = 0; l < size; l++ ) {
        spin[l][c].flip();
      }
    }
  }

  // energy difference
  double deltaH = H() - H_memory;

  if ( deltaH > 0 ) {
    // accept the new state?
    if ( gsl_rng_uniform( rng ) > exp( - deltaH / T ) ) {
      // new state rejected ... reverting!
      if ( mode ) {
        // mirroring: horizontal
        for ( unsigned int l = fmline; l < size; l++ ) {
          for ( unsigned int c = 0; c < size; c++ ) {
            spin[l][c].flip();
          }
        }
      } else {
        // mirroring: vertical
        for ( unsigned int c = fmcol; c < size; c++ ) {
          for ( unsigned int l = 0; l < size; l++ ) {
            spin[l][c].flip();
          }
        }
      }
      return;
    }
  }

  H_memory += deltaH;
}
Пример #6
0
//**********************************************************************
//**********************************************************************
///a function that chooses two edgess at random that if they are swaped we avoid multipledges or selfedges.
/// we try to choose a second link E times. if we dont find it we return a 0
int choose_2_edges_random(GRAPH* G,int *pos_r,int *pos_s,gsl_rng* randgsl){
	
	int j,rand1,rand2=0,r1,r2,s1,s2,correct,tries;

	rand1 = gsl_rng_uniform_int(randgsl,G->E);	///we choose an edges at random
	
	r1 = G->edge[rand1].s;
	r2 = G->edge[rand1].d;
	
	if(r1==r2){printf("there is a selflink!!!\n");fflush(stdout);}
	
	correct=0;	///in order to be able to enter into the loop 
	
	tries = 0;	///a variable that controls how many times we have tried to choose another link

	while(!correct && tries < G->E){///we choose a second edges at random with some constrains
		
		rand2 = gsl_rng_uniform_int(randgsl,G->E);
		
		s1 = G->edge[rand2].s;
		s2 = G->edge[rand2].d;
		
		if(s1==s2){printf("there is a selflink!!!\n");fflush(stdout);}
		
		correct=1;											/// we assume that it is correct
		
		if(s1==r1 || s1==r2 || s2==r1 || s2==r2)correct=0;	/// we look if all the for nodes are different
		
		else {
			for(j=0;j<G->node[s1].k;++j){						 
				if(G->node[s1].out[j]==r2) correct=0;		/// we look if the node s1 is not already connected with r2 to avoid a multiple link
			}
			for(j=0;j<G->node[r1].k;++j){						
				if(G->node[r1].out[j]==s2) correct=0;		/// we look if the node r1 is not already connected with s2 to avoid a multiple link
			}
		}
		
		tries++;
		
	}

	*pos_r = rand1;
	*pos_s = rand2;
	
	if(tries == G->E) return 0;	///we could not fins a proper pair of links we return a 0. 
	else return 1;
	
}
void MoleculePopulateProcess::populateUniformSparse(Species* aSpecies)
{
  Comp* aComp(aSpecies->getComp());
  if(!aSpecies->getIsPopulated())
    {
      if(UniformRadiusX == 1 && UniformRadiusY == 1 && UniformRadiusZ == 1 &&
         !OriginX && !OriginY && !OriginZ)
        {
          unsigned int aSize(aSpecies->getPopulateMoleculeSize());
          int availableVoxelSize(aComp->coords.size());
          for(unsigned int j(0); j != aSize; ++j)
            {
              Voxel* aVoxel;
              do
                {
                  aVoxel = theSpatiocyteStepper->coord2voxel(
                     aComp->coords[gsl_rng_uniform_int(
                                getStepper()->getRng(), availableVoxelSize)]);
                }
              while(aVoxel->id != aComp->vacantID);
              aSpecies->addMolecule(aVoxel);
            }
        }
      else
        { 
          populateUniformRanged(aSpecies);
        }
      aSpecies->setIsPopulated();
    }
}
Пример #8
0
void do_balanced_multi_tree_inference(FILE *logfp, mcmc_t *mcmc, node_t **subtrees, node_t **wholetrees, gslws_t *wses, sampman_t *sms, ubertree_t *ut, int burnin, int samples, int lag) {
	int i, j;
	/* Burn in */
	for(i=0; i<burnin; i++) balanced_multi_tree_mcmc_iteration(logfp, mcmc, subtrees, wses);
	/* Take samples */
	for(i=0; i<samples; i++) {
		if(gsl_rng_uniform_int(mcmc->r, 10000) >= 9999) {
			/* Random restart! */
			random_restart(mcmc);
			compute_balanced_multi_tree_probabilities(mcmc, subtrees, wses);
			for(j=0; j<burnin; j++) balanced_multi_tree_mcmc_iteration(logfp, mcmc, subtrees, wses);
		}

		for(j=0; j<lag; j++) {
			balanced_multi_tree_mcmc_iteration(logfp, mcmc, subtrees, wses);
		}

		build_q(mcmc);
		for(j=0; j<NUM_TREES; j++) {
			upwards_belprop(logfp, wholetrees[j], mcmc->Q, &wses[j]);
			process_sample(&sms[j], mcmc, &wses[j], wholetrees[j]);
		}
		if(ut != NULL) update_ubertree(ut, wholetrees, mcmc->Q, &wses[0]);
	}
}
Пример #9
0
/* l is a degree number, between 1 and the degree of the polynomial
   associated with the dimension being initialized */ 
static int sobol_init_direction(gsl_rng *r, int l)
{
  /* See Peter Jaeckel, Monte Carlo Methods in Finance, Wiley 2002, p86. 
   */ 
  int wkl = gsl_rng_uniform_int(r, 1<<l) | 1; 
  return wkl; 
}
Пример #10
0
void population::evolve(int gen) { //Wright-Fisher Model - Population size is held constant. Parental genotypes are chosen randomly. 
    for (int j=0; j<gen; j++){
        vector<genome> newPop (N);
        avgFit = 0;
        for(int i=0; i<N; i++) {
            if (r == 1) {   
                newPop[i] = progeny(selectParents());
                avgFit += newPop[i].get_fit();
            }
            else if ((r != 0) && gsl_rng_uniform(rng) <= r) {
                newPop[i] = progeny(selectParents());
                avgFit += newPop[i].get_fit();
            }
            else {
                if (neutral) {newPop[i] = pop[(int)gsl_rng_uniform_int(rng,N)];}
                else {
                    double fit_rand = selective_weight[N-1]*gsl_rng_uniform(rng);
                    newPop[i] = pop[binarySearch_int(selective_weight, 0, N-1, fit_rand)];
                    avgFit += newPop[i].get_fit();
                }            
            }
        }
        avgFit/= N;
        pop = newPop;
        gen_pop++;
        update_weights();
        //updateBlockSizes();
        if (!neutral) {update_selection_weights();}
    }
    update_weights();
    updateBlockSizes();
    //if (WRITEHIST) {writeBlockHist();}
}
Пример #11
0
// len is number of edges,
void update_allele(dBNode** allele, int len, int colour, int covg, int eff_read_len)
{

  const gsl_rng_type * T;
  gsl_rng * r;
  gsl_rng_env_setup();
  T = gsl_rng_default;
  r = gsl_rng_alloc (T);
     
  int i;
  //add covg number of reads, placing them randomly on the allele
  for (i = 0; i < covg; i++) 
    {
      int u=0;
      while (u==0)
	{
	  u = gsl_rng_uniform_int(r,len);
	}
      //now add coverage:
      int j;
      for (j=u; (j<u+eff_read_len) && (j<len); j++)
	{
	  db_node_increment_coverage(allele[j], colour);
	}
    }
     
  gsl_rng_free (r);
     

}
Пример #12
0
void do_single_tree_inference(FILE *logfp, mcmc_t *mcmc, node_t *tree, gslws_t *ws, sampman_t *sm, int burnin, int samples, int lag) {
	int i, j;
	/* Burn in */
	for(i=0; i<burnin; i++) single_tree_mcmc_iteration(logfp, mcmc, tree, ws);
	/* Take samples */
	for(i=0; i<samples; i++) {
		if(gsl_rng_uniform_int(mcmc->r, 10000) >= 9999) {
			/* Random restart! */
			random_restart(mcmc);
			compute_single_tree_probabilities(mcmc, tree, ws);
			for(j=0; j<burnin; j++) single_tree_mcmc_iteration(logfp, mcmc, tree, ws);
		}

		for(j=0; j<lag; j++) {
			single_tree_mcmc_iteration(logfp, mcmc, tree, ws);
		}

		build_q(mcmc);
		upwards_belprop(logfp, tree, mcmc->Q, ws);

		/* Record sample */
		process_sample(sm, mcmc, ws, tree);
	}
	/* Do computations for Q matrices sampled from the pior
	 * and log stuff so we can do importance sampling for
	 * marginal likelihood later */
	for(i=0; i<samples; i++) {
		draw_proposal_from_prior(mcmc, ws);
		mcmc->log_prior = get_log_prior(mcmc->stabs_dash, mcmc->trans_dash);
		mcmc->log_lh = get_model_loglh(tree, mcmc->Q_dash, ws);
		mcmc->log_poster = mcmc->log_prior + mcmc->log_lh;
		process_prior_sample(sm, mcmc, ws);
	}
}
Пример #13
0
//function to test the fourier transform, output is written to the error stream
int hypercube_lowd::test()
{
	int tp, sign;
	double res;
	cerr <<"hypercube_lowd::test()...\n";
	for (int i=0; i<100; i++)
	{
		res=0;
		//draw a random integer
		tp=gsl_rng_uniform_int(rng,1<<dim);
		for (int c=0; c<(1<<dim); c++)		//assemble the function value from its spins, go over all coeffcients, index c
		{
			sign=1;
			for (int k=0; k<dim; k++)
			{
				if (!(tp&(1<<k)) && (c&(1<<k)))		//determine the sign the coeff enters
				{
					sign*=-1;						//multiply by minus one, every time a bit is not set although it the contribution depends on the bit
				}
			}
			res+=sign*coeff[c];						//add the coeff with the correct sign
		}
		cerr <<setw(15)<<func[tp]<<setw(15)<<res<<setw(15)<<func[tp]-res<<endl;	//output result, function value and difference, the latter should be zero
	}
	cerr <<"done\n";
	return 0;
}
Пример #14
0
std::map<STM::ParName, double> Metropolis::do_sample(int n, bool saveDeviance)
// n is the number of samples to take
// returns a map of acceptance rates keyed by parameter name
{
	// 	shuffle the order of parameters
	std::vector<STM::ParName> parNames (parameters.active_names());
	std::random_shuffle(parNames.begin(), parNames.end(), 
			[this](int n){ return gsl_rng_uniform_int(rng.get(), n); });
	
	std::map<STM::ParName, int> numAccepted;
	for(const auto & par : parNames)
		numAccepted[par] = 0;

	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < thinSize; j++)
		{
			// step through each parameter
			for(const auto & par : parNames) {
				STM::ParPair proposal = propose_parameter(par);
				numAccepted[par] += select_parameter(proposal);
			}
		}
		parameters.increment();
		currentSamples.push_back(parameters.current_state());
		if(saveDeviance)
			sampleDeviance.push_back(std::pair<double, int>(-2 * currentLL, 1));

		//		if desired, some debugging output
		if(outputLevel >= EngineOutputLevel::Verbose) {
			std::cerr << "  iteration " << parameters.iteration() - 1 << 
					"    posterior probability: " << currentPosteriorProb <<
					"    likelihood: " << currentLL << "\n";
			if(outputLevel >= EngineOutputLevel::ExtraVerbose) {
			std::ios_base::fmtflags oldflags = std::cerr.flags();
				std::streamsize oldprecision = std::cerr.precision();

				std::cerr << std::fixed << std::setprecision(3) << " ";
				STM::ParMap st = parameters.current_state();
				int coln = 0;
				for(auto pa : st) {
					std::cerr << std::setw(6) << pa.first << std::setw(8) << pa.second;
					if(++coln >= 7) {
						std::cerr << "\n ";
						coln = 0;
					}
				}
				std::cerr << std::endl;
			
				std::cerr.flags (oldflags);
				std::cerr.precision (oldprecision);
			}
		}
}

	std::map<STM::ParName, double> acceptanceRates;
	for(const auto & par : parNames)
		acceptanceRates[par] = double(numAccepted[par]) / (n*thinSize);
	return acceptanceRates;
}
Пример #15
0
void
rng_parallel_state_test (const gsl_rng_type * T)
{
  unsigned long int test_a[N], test_b[N];
  unsigned long int test_c[N], test_d[N];
  double test_e[N], test_f[N];

  int i;

  gsl_rng *r1 = gsl_rng_alloc (T);
  gsl_rng *r2 = gsl_rng_alloc (T);

  for (i = 0; i < N; ++i)
    {
      gsl_rng_get (r1);         /* throw away N iterations */
    }

  gsl_rng_memcpy (r2, r1);              /* save the intermediate state */

  for (i = 0; i < N; ++i)
    {
      /* check that there is no hidden state intermixed between r1 and r2 */
      test_a[i] = gsl_rng_get (r1);     
      test_b[i] = gsl_rng_get (r2);
      test_c[i] = gsl_rng_uniform_int (r1, 1234);       
      test_d[i] = gsl_rng_uniform_int (r2, 1234);
      test_e[i] = gsl_rng_uniform (r1); 
      test_f[i] = gsl_rng_uniform (r2);
    }

  {
    int status = 0;
    for (i = 0; i < N; ++i)
      {
        status |= (test_b[i] != test_a[i]);
        status |= (test_c[i] != test_d[i]);
        status |= (test_e[i] != test_f[i]);
      }
    /*gsl_test (status, "%s, parallel random number state
 * consistency",*/
              /*gsl_rng_name (r1));*/
  }

  gsl_rng_free (r1);
  gsl_rng_free (r2);

}
Пример #16
0
int random_int(int a, int b) {
  init_rand();
#ifdef HAVE_LIBGSL
  return ((int) gsl_rng_uniform_int(rng, b-a+1)) + a;
#else
  return a + rand() % (b-a+1);
#endif
}
Пример #17
0
Файл: rng.c Проект: Fudge/rb-gsl
static VALUE rb_gsl_rng_uniform_int(VALUE obj, VALUE n)
{
  gsl_rng *r = NULL;
  unsigned long int nn;
  nn = NUM2UINT(n);
  Data_Get_Struct(obj, gsl_rng, r);
  return UINT2NUM(gsl_rng_uniform_int(r, nn));
}
Пример #18
0
/*
  We will use a 30-bit random prime, so that all operations can be represented
  with 32-bit integers, since the alphabet ACGT can be represented with 2 bits.
*/
static uint32_t random_prime(gsl_rng* generator) {
        uint32_t p = 0;
        do {
                p = 2 * gsl_rng_uniform_int(generator, 1 << 29) + 1;
        } while (p < (1 << 16) || !primep(p));
        assert(p < (1<<30));
        return p;
}
 virtual void fire()
   {
     int col(gsl_rng_uniform_int(getStepper()->getRng(),
                                 theComp->maxCol-theComp->minCol-4));
     col += theComp->minCol;
     theSpatiocyteStepper->growCompartment(theComp, Axis, col);
     theTime += theStepInterval;
     thePriorityQueue->moveTop();
   }
Пример #20
0
int Unifrnd_Int(int range)
{
#if EXTLIB_EXIST(GSL)
  gsl_rng_init();
  return gsl_rng_uniform_int(Random_Generator, range);
#else
  return genrand_int32() % (range + 1);
#endif    
}
Пример #21
0
void IsingModel2dDipole::metropolis_blockflip()
{
  // generate coordinates of the block
  unsigned int temp;
  unsigned int l1 = gsl_rng_uniform_int( rng, size );
  unsigned int l2 = gsl_rng_uniform_int( rng, size );
  if ( l1 > l2 ) {
    temp = l1;
    l1 = l2;
    l2 = temp;
  }
  unsigned int c1 = gsl_rng_uniform_int( rng, size );
  unsigned int c2 = gsl_rng_uniform_int( rng, size );
  if ( c1 > c2 ) {
    temp = c1;
    c1 = c2;
    c2 = temp;
  }

  // flip the block
  for ( unsigned int l = l1; l <= l2; l++ ) {
    for ( unsigned int c = c1; c <= c2; c++ ) {
      spin[l][c].flip();
    }
  }

  // energy difference
  double deltaH = H() - H_memory;

  if ( deltaH > 0 ) {
    // accept the new state?
    if ( gsl_rng_uniform( rng ) > exp( - deltaH / T ) ) {
      // new state rejected ... reverting!
      for ( unsigned int l = l1; l <= l2; l++ ) {
        for ( unsigned int c = c1; c <= c2; c++ ) {
          spin[l][c].flip();
        }
      }
      return;
    }
  }

  H_memory += deltaH;
}
Пример #22
0
int randint(int n) {
	/*
	 * returns a random integer in [0,n-1]
	 */
	if (n <= 0) debug("invalid input to randint");
	unsigned long int r;
	r = gsl_rng_uniform_int(RANDOM_NUMBER, (int)n);
	if (r > INT_MAX) debug("problem in randint");
	return (int)r;
}
void Roulette_wheel::select_ind( int *mum ){
  *mum = gsl_rng_uniform_int (GSL_randon_generator::r_rand, num_tot_solutions );
  double reference = gsl_rng_uniform(GSL_randon_generator::r_rand) * wheel[num_tot_solutions-1];
  for (int selected = num_solutions_truncated; selected  < num_tot_solutions; selected++ ){
    if(reference  < wheel[selected] ){
      *mum = rank[selected];
      break;
    }
  }
}
Пример #24
0
int GlmTest::resampSmryCase(glm *model, gsl_matrix *bT, GrpMat *GrpXs, gsl_matrix *bO, unsigned int i )
{   
    gsl_set_error_handler_off();
    int status, isValid=TRUE;

    unsigned int j, k, id;
    gsl_vector_view yj, oj, xj;
    gsl_matrix *tXX = NULL;
    unsigned int nRows=tm->nRows, nParam=tm->nParam;
    
    if (bootID == NULL) {
       tXX = gsl_matrix_alloc(nParam, nParam);
       while (isValid==TRUE) { // if all isSingular==TRUE
           if (tm->reprand!=TRUE) GetRNGstate();
           for (j=0; j<nRows; j++) {
               // resample Y, X, offsets accordingly
               if (tm->reprand==TRUE)
                   id = (unsigned int) gsl_rng_uniform_int(rnd, nRows);
               else id = (unsigned int) nRows * Rf_runif(0, 1);
               xj = gsl_matrix_row(model->Xref, id);
               gsl_matrix_set_row(GrpXs[0].matrix, j, &xj.vector);
               yj = gsl_matrix_row(model->Yref, id);
               gsl_matrix_set_row(bT, j, &yj.vector);
               oj = gsl_matrix_row(model->Eta, id);
               gsl_matrix_set_row(bO, j, &oj.vector);
           }
           if (tm->reprand!=TRUE) PutRNGstate();
           gsl_matrix_set_identity(tXX);
           gsl_blas_dsyrk(CblasLower,CblasTrans,1.0,GrpXs[0].matrix,0.0,tXX);
           status=gsl_linalg_cholesky_decomp(tXX); 
           if (status!=GSL_EDOM) break;
          //  if (calcDet(tXX)>eps) break; 
       }
       for (k=2; k<nParam+2; k++) 
           subX2(GrpXs[0].matrix, k-2, GrpXs[k].matrix);
    }
    else {
       for (j=0; j<nRows; j++) {
           id = (unsigned int) gsl_matrix_get(bootID, i, j);
           // resample Y and X and offset
           yj=gsl_matrix_row(model->Yref, id);
           gsl_matrix_set_row (bT, j, &yj.vector);
           oj = gsl_matrix_row(model->Eta, id);
           gsl_matrix_set_row(bO, j, &oj.vector);
           xj = gsl_matrix_row(model->Xref, id);
           gsl_matrix_set_row(GrpXs[0].matrix, j, &xj.vector);
       }   
       for (k=2; k<nParam+2; k++) 
           subX2(GrpXs[0].matrix, k-2, GrpXs[k].matrix);
   }

   gsl_matrix_free(tXX);

   return SUCCESS;
}
Пример #25
0
pair<int,int> population::selectParents(){ //Parents are selected at random from population 
    pair<int,int> ancestors;
    if (neutral) { //Neutral Evolution
        ancestors.first = (int)gsl_rng_uniform_int(rng,N);
        ancestors.second = (int)gsl_rng_uniform_int(rng,N);
    }
    else { //Selection!
        double fit_rand1 = selective_weight[N-1]*gsl_rng_uniform(rng);
        double fit_rand2 = selective_weight[N-1]*gsl_rng_uniform(rng);
        ancestors.first = binarySearch_int(selective_weight, 0, N-1, fit_rand1);
        ancestors.second = binarySearch_int(selective_weight, 0, N-1, fit_rand2);
    }
    //Recursive definition to ensure unique parents.
    if (ancestors.second == ancestors.first) {
        return selectParents();
    }
    else {
        return ancestors;
    }
}
Пример #26
0
/* Samples either one change point or one probability */
void sampleMixed(const gsl_rng *r,
		 parameters* p, int nPar,
		 intparameters *ip, int nIPar) {
  static int hello=1;
  double pr=gsl_rng_uniform(r);
  int moveK=pr<mixingRatio;
  const int *CDFdata=getData(), nCDFdata=getNdata();

  if(hello) fprintf(OUT, "sampleMixed()...\n"), hello=0;

  /* Set proposed changepoint locations and probabilities to current
     values.*/
  resetProposals(p, nPar, ip, nIPar);

  /* Assuming there is NO changepoint */
  if(nIPar<=0) moveK=0;
  if(moveK) {
    double pJump=0.1;
    /* Which k shall be moved? */
    int indK=gsl_rng_uniform_int(r, nIPar);
    int kDown=(indK-1>=0)?getIntParameter(ip,indK-1):0;
    int kUp=(indK+1<nIPar)?getIntParameter(ip,indK+1):getNdata();
    int kNew;
    int succ0, succ1;
    int fail0, fail1;
    double p0, p1;


    setIntMin(ip, indK, kDown);
    setIntMax(ip, indK, kUp);

    if(gsl_rng_uniform(r)>=pJump) {
      /*Move only one parameter by width */
      proposeIntConstrainedAB(r, ip, indK, 1);
    } else {
      proposeIntShiftInterval(r, ip, indK, 1);
    }
      /* Update probabilities */
      kNew=getIntProposal(ip,indK);

      succ0=succInterval(CDFdata, kDown, kNew);
      succ1=succInterval(CDFdata, kNew, kUp);
      fail0=kNew-kDown-succ0;
      fail1=kUp-kNew-succ1;
      p0=gsl_ran_beta(r, succ0, fail0);
      p1=gsl_ran_beta(r, succ1,fail1);

      setProposal(p, indK, p0);
      setProposal(p, indK+1, p1);
  }
  else {
    sampleProbabilities(r, CDFdata, nCDFdata, p, nPar, ip, nIPar);
  }
}
Пример #27
0
/* Randomly assigns all spins */
void init ( int ** F, int L, gsl_rng * r ) {
  int i,j;

  /* Visit each position (i,j) in the lattice */
  for (i=0;i<L;i++) {
    for (j=0;j<L;j++) {
      /* 2*x-1, where x is randomly 0,1 */
      F[i][j]=2*(int)gsl_rng_uniform_int(r,2)-1;
    }
  }
}
Пример #28
0
void run_lasso_computation(ProblemData<L, D> &inst, std::vector<D> &h_Li,
		int omp_threads, D sigma, int N, int blockReduction,
		std::vector<gsl_rng *>& rs, ofstream& experimentLogFile,int multiply=100) {
	omp_set_num_threads(omp_threads);
	init_random_seeds(rs);
	L n = inst.n;
	L m = inst.m;
	std::vector<D> residuals(m);
	Losses<L, D, square_loss_traits>::bulkIterations(inst, residuals);
	D fvalInit = Losses<L, D, square_loss_traits>::compute_fast_objective(inst,
			residuals);
	double totalRunningTime = 0;
	double iterations = 0;
	L perPartIterations =multiply* n / blockReduction;
	double additional = perPartIterations / (0.0 + n);
	D fval = fvalInit;
// store initial objective value
	experimentLogFile << setprecision(16) << omp_threads << "," << n << "," << m
			<< "," << sigma << "," << totalRunningTime << "," << iterations
			<< "," << fval << endl;
	//iterate
	for (int totalIt = 0; totalIt < N; totalIt++) {
		double startTime = gettime_();
#pragma omp parallel for
		for (L it = 0; it < perPartIterations; it++) {
			// one step of the algorithm
			unsigned long int idx = gsl_rng_uniform_int(gsl_rng_r, n);
			Losses<L, D, square_loss_traits>::do_single_iteration_parallel(inst,
					idx, residuals, inst.x, h_Li);
		}
		double endTime = gettime_();
		iterations += additional;
		totalRunningTime += endTime - startTime;
		// recompute residuals  - this step is not necessary but if accumulation of rounding errors occurs it is useful
		if (totalIt % 3 == 0) {
			Losses<L, D, square_loss_traits>::bulkIterations(inst,
					residuals);
		}
		fval = Losses<L, D, square_loss_traits>::compute_fast_objective(inst,
				residuals);
		int nnz = 0;
#pragma omp parallel for reduction(+:nnz)
		for (L i = 0; i < n; i++)
			if (inst.x[i] != 0)
				nnz++;
		cout << omp_threads << "," << n << "," << m << "," << sigma << ","
				<< totalRunningTime << "," << iterations << "," << setprecision(15)<<fval << ","
				<< nnz << endl;

		experimentLogFile << setprecision(16) << omp_threads << "," << n << ","
				<< m << "," << sigma << "," << totalRunningTime << ","
				<< iterations << "," << setprecision(15)<<fval << "," << nnz << endl;
	}
}
Пример #29
0
 apop_data * apop_bootstrap_cov_base(apop_data * data, apop_model *model, gsl_rng *rng, int iterations, char keep_boots, char ignore_nans, apop_data **boot_store){
#endif
    Get_vmsizes(data); //vsize, msize1, msize2
    apop_model *e = apop_model_copy(model);
    apop_data *subset = apop_data_copy(data);
    apop_data *array_of_boots = NULL,
              *summary;
    //prevent and infinite regression of covariance calculation.
    Apop_model_add_group(e, apop_parts_wanted); //default wants for nothing.
    size_t i, nan_draws=0;
    apop_name *tmpnames = (data && data->names) ? data->names : NULL; //save on some copying below.
    if (data && data->names) data->names = NULL;

    int height = GSL_MAX(msize1, GSL_MAX(vsize, (data?(*data->textsize):0)));
	for (i=0; i<iterations && nan_draws < iterations; i++){
		for (size_t j=0; j< height; j++){       //create the data set
			size_t randrow	= gsl_rng_uniform_int(rng, height);
            apop_data_memcpy(Apop_r(subset, j), Apop_r(data, randrow));
		}
		//get the parameter estimates.
		apop_model *est = apop_estimate(subset, e);
        gsl_vector *estp = apop_data_pack(est->parameters);
        if (!gsl_isnan(apop_sum(estp))){
            if (i==0){
                array_of_boots	      = apop_data_alloc(iterations, estp->size);
                apop_name_stack(array_of_boots->names, est->parameters->names, 'c', 'v');
                apop_name_stack(array_of_boots->names, est->parameters->names, 'c', 'c');
                apop_name_stack(array_of_boots->names, est->parameters->names, 'c', 'r');
            }
            gsl_matrix_set_row(array_of_boots->matrix, i, estp);
        } else if (ignore_nans=='y'){
            i--; 
            nan_draws++;
        }
        apop_model_free(est);
        gsl_vector_free(estp);
	}
    if(data) data->names = tmpnames;
    apop_data_free(subset);
    apop_model_free(e);
    int set_error=0;
    Apop_stopif(i == 0 && nan_draws == iterations, apop_return_data_error(N),
                1, "I ran into %i NaNs and no not-NaN estimations, and so stopped. "
                       , iterations);
    Apop_stopif(nan_draws == iterations,  set_error++;
            apop_matrix_realloc(array_of_boots->matrix, i, array_of_boots->matrix->size2),
                1, "I ran into %i NaNs, and so stopped. Returning results based "
                       "on %zu bootstrap iterations.", iterations, i);
	summary	= apop_data_covariance(array_of_boots);
    if (boot_store) *boot_store = array_of_boots;
    else            apop_data_free(array_of_boots);
    if (set_error) summary->error = 'N';
	return summary;
}
Пример #30
0
void IsingMatrix::flip() {
	int i = gsl_rng_uniform_int(rnd,s);

	iold = i;
	Eold = E;
	Mold = M;

	matrix[i] *= -1;
	E -= 2*matrix[i]*(J*(matrix[PlusX(i)]+matrix[MinusX(i)]+matrix[PlusY(i)]+matrix[MinusY(i)])+H);
	M += 2*matrix[i];
}