示例#1
0
double randn ( void ) {
	double rand1 = genrand_real2();
	double rand2 = genrand_real2();
	double R = sqrt(-2.0 * log(rand1));
	double T = 2 * M_PI * rand2;
	return R * cos(T);
}
示例#2
0
extern void Stochastic(_parameter *par, double *Time, double *sigma_react, double *exp_rand){

	int    j,fire;
	double z[Sto_rapi_Num], p[Sto_rapi_Num]={0};
	double random;

	//generate random number
	func1(p,par->Sto_rapi,par->Sto_conc,&(*Time));
	*sigma_react = *sigma_react + dt * p[Sto_rapi_Num-1];

	//initilize the change of molecules
	if (*sigma_react >= *exp_rand){

		for(j=0; j < Sto_rapi_Num ; j++)z[j] = 0;
		fire = 0;

		//generate random variable
		random = p[Sto_rapi_Num-1] * genrand_real2();

		//choose fired reaction
		if(random < p[0]){ z[0] = 1 ; fire = 1 ; }
		else{
		  for(j = 1 ; j < Sto_rapi_Num ; j++){
		    if(fire == 1)break;
	    	    if(( p[j-1] <= random) && (random < p[j] )){
		      z[j] = 1 ;
		      fire = 1 ;
		    }
		  }
		}
		*sigma_react = 0.0;
		func2(z, par->Sto_conc);
		*exp_rand = -1*log(genrand_real2());
	}
}
示例#3
0
文件: main.c 项目: stocyr/Carme-Snake
/**
 * Zufallspositionsgenerator.
 * Liefert innerhalb der Spielfeldgrösse eine zufällige Position zurück.
 * @return liefert eine zufällige Position zurück
 */
location randomize_location()
{
	location pos;
	pos.x = genrand_real2()*PLAYGROUND_X_MAX;
	pos.y = genrand_real2()*PLAYGROUND_Y_MAX;

	return pos;
}
示例#4
0
void initialise(int A[], int B[], double d[], double d2[]){
    int i;
    // initialise the lattice randomly and zero the density to start with.
    for (i = 0; i < Ns; i++){
        if ( genrand_real2() <= 0.5) A[i] = 1;
        else A[i] = 0;     
        
        if ( genrand_real2() <= 0.5) B[i] = 1;
        else B[i] = 0;     

        d[i]  =  0.0;          //initialise the density to be zero on the site.
        d2[i]  = 0.0;          //initialise the density to be zero on the site.
        }
}
示例#5
0
void kitagawa_resampling
    (double *w, size_t n_weights, size_t *s_res, size_t n_res)
{
    // deterministic Kitagawa resampling
    double *u = malloc(sizeof(double) * n_res);
    double x = genrand_real2();
    for (size_t i = 0; i < n_res; ++i)
    {
        u[i] = ((double)i + x) / (double)(n_res);
    }

    double *cdf = malloc(sizeof(double) * n_weights);
    build_multinomial_cdf(cdf, w, n_weights);
    for (size_t i = 0; i < n_res; ++i)
    {
        size_t idx = n_res;
        for (size_t j = 0; j < n_weights; ++j)
        {
            if (u[i] <= cdf[j])
            {
                idx = j;
                break;
            }
        }

        s_res[i] = idx;
    }

    free(u);
    free(cdf);
}
示例#6
0
// move the particle in 2D
// Movement of particles on the lattice depending on the BCs.
void moveParticle2D(int C[], int D[], int rn){
    int r1 = D[rn] + D[rn+1];
    double rate = (1 + (beta-1)*r1/2.0);
    if (genrand_real2() <= rate){
        C[rn] = 0;   
        C[rn+1]=1;
    }
}
示例#7
0
size_t sample_uniform(size_t pdf_size)
{
    double x = genrand_real2();
    size_t result = (size_t)floor(x * (double)pdf_size);

    if (result == pdf_size)
    {
        result = pdf_size - 1;
    }

    return result;
}
void parameter_sampler(double parameter[])
{
  double unit_r;
  int chosen_num;

  unit_r = genrand_real2();
  chosen_num = (int)(PARA_N*unit_r);
  
  unit_r = genrand_real1();
  parameter[chosen_num] = parameter[chosen_num]*pow(10.0, (unit_r-0.5)*STEP_PARA);

}
示例#9
0
void cMatMul(double* A, double* B, double* C, double scalar_k, int m, int n) {

init_genrand(12);
    int i, j ;
    int index = 0 ;

    for (i = 0; i < m; i++) {
        for (j = 0; j < n; j++) {
            C[index] = scalar_k * A[index] * B[index] + genrand_real2();
            index ++ ;
            }
        }
    return ;
}
示例#10
0
//-----------------------------------------------------------------------------
// 関数
//-----------------------------------------------------------------------------
static RXREAL GaussianNoise()
{
	RXREAL x1, x2;
	RXREAL ret;
	
	RXREAL r2;

	do {

		x1 = 2.0 * genrand_real2() - 1.0;	/* [-1, 1) */
		x2 = 2.0 * genrand_real2() - 1.0;

		r2 = x1*x1 + x2*x2;

	} while ((r2 == 0) || (r2 > 1.0));

	ret = x1 * sqrt((-2.0 * log(r2))/r2);
	ret *= 0.25;		// Possibility of ( N(0, 1) < 4.0 ) = 100%

	if (ret < -1.0) ret = -1.0; /* Account for loss of precision. */
	if (ret >  1.0) ret = 1.0;

	return ret;
}
示例#11
0
int main ( int argc, char * const argv[] )
{
	printf( "Testing output and speed of inventors' Mersenne Twister program\n" );
	printf( "\nTest of random integer generation:\n" );
	
	unsigned long oneSeed = 4357UL;
	unsigned long bigSeed[4] = { 0x123UL, 0x234UL, 0x345UL, 0x456UL };
	
	printf( "\nTest of random integer generation:\n" );
	init_by_array( bigSeed, 4 );
	unsigned long i;
	for( i = 0; i < 1000UL; ++i )
	{
		printf( "%10lu ", genrand_int32() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	printf( "\nTest of random real number [0,1) generation:\n" );
	for( i = 0; i < 1000UL; ++i )
	{
		printf( "%10.8f ", genrand_real2() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	printf( "\nTest of random real number [0,1] generation:\n" );
	init_genrand( oneSeed );
	for( i = 0; i < 2000UL; ++i )
	{
		printf( "%10.8f ", genrand_real1() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	printf( "\nTest of time to generate one billion random integers:\n" );
	init_genrand( oneSeed );
	unsigned long junk = 0;
	clock_t start = clock();
	for( i = 0; i < 1000000000UL; ++i )
	{
		junk ^= genrand_int32();
	}
	clock_t stop = clock();
	if( junk == 0 ) printf( "jinx\n" );
	printf( "Time elapsed = " );
	printf( "%8.3f", double( stop - start ) / CLOCKS_PER_SEC );
	printf( " s\n" );
		
	return 0;
}
示例#12
0
size_t sample_multinomial_cdf(double *cdf, size_t cdf_size)
{
    double x = genrand_real2();

    // linear search to find the corresponding idx
    for (size_t i = 0; i < cdf_size; ++i)
    {
        if (x <= cdf[i])
        {
            return i;
        }
    }

    printf("ERR: sample_multinomial_cdf() failed\n");
    return -1;
}
示例#13
0
static int Lvaluei(lua_State *L)		/** valuei(c,a,[b]) */
{
 MT *c=Pget(L,1);
 int a,b;
 if (lua_gettop(L)==2)
 {
  a=1;
  b=luaL_checkint(L,2);
 }
 else
 {
  a=luaL_checkint(L,2);
  b=luaL_checkint(L,3);
 }
 lua_pushnumber(L,floor(a+genrand_real2(c)*(b-a+1)));
 return 1;
}
示例#14
0
void        NNMatrixSampler (long index, _Matrix& bnds, _SimpleList& varList, _SimpleList& reidx, _Matrix* modelMatrix, _List& trainIn, _List& trainOut)
{
    _Parameter lb = bnds (index,0),
               ub = bnds (index,1);

    if (ub<=lb)
        // freq parameter
    {
        ub = 1.;
        lb = 0.;
        for (long k = index-1; k>=0; k--) {
            ub -= LocateVar (varList.lData[reidx.lData[k]])->Value();
            if (bnds (k,1) > bnds (k,0)) {
                break;
            }
        }

        if ((index == varList.lLength - 1)||(bnds (index+1,1) > bnds (index+1,0))) {
            lb = ub;
        }
    }

    _Constant cv (lb + genrand_real2 () * (ub-lb));
    LocateVar (varList.lData[reidx.lData[index]])->SetValue (&cv);

    if (index == varList.lLength - 1) {
        _Matrix*  inMx = new _Matrix (index+1,1,false,true);

        checkPointer (inMx);

        for (long m = 0; m <= index; m++) {
            inMx->Store (m,0,LocateVar (varList.lData[reidx.lData[m]])->Value());
        }

        trainIn << inMx;

        DeleteObject (inMx);

        _Matrix  *em = ((_Matrix*)modelMatrix->ComputeNumeric())->Exponentiate();
        trainOut <<  em;
        DeleteObject (em);
    } else {
        NNMatrixSampler (index+1, bnds, varList, reidx, modelMatrix, trainIn, trainOut);
    }
}
示例#15
0
int main(void)
{
	unsigned long oneSeed = 4357UL;
	unsigned long bigSeed[4] = { 0x123, 0x234, 0x345, 0x456 };
	
	printf( "Testing output and speed of mt19937ar-c*k.c\n" );
	printf( "\nTest of random integer generation:\n" );
	init_by_array( bigSeed, 4 );
	for( i = 0; i < 1000; ++i )
	{
		printf( "%10lu ", genrand_int32() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	printf( "\nTest of random real number [0,1) generation:\n" );
	for( i = 0; i < 1000; ++i )
	{
		printf( "%10.8f ", genrand_real2() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	printf( "\nTest of random real number [0,1] generation:\n" );
	init_genrand( oneSeed );
	for( i = 0; i < 1000; ++i )
	{
		printf( "%10.8f ", genrand_real1() );
		if( i % 5 == 4 ) printf("\n");
	}
	
	
	printf( "\nTest of time to generate 300 million random integers:\n" );
	init_genrand( oneSeed );
	start = clock();
	for( i = 0; i < 300000000; ++i )
	{
		junk = genrand_int32();
	}
	stop = clock();
	printf( "Time elapsed = " );
	printf( "%8.3f", (double)( stop - start ) / CLOCKS_PER_SEC );
	printf( " s\n" );
	
	return 0;
}
void parameter_sampler(double parameter[])
{
  double unit_r;
  int chosen_num, i;

  for( ; ; ){
    unit_r = genrand_real2();
    chosen_num = (int)(PARA_N*unit_r);
  
    if(chosen_num < 7){
      unit_r = genrand_real1();
      parameter[chosen_num] = parameter[chosen_num]*pow(10.0, (unit_r-0.5)*STEP_PARA);
      break;
    }
    else{
      continue;
    }
  }
}
示例#17
0
int main(void)
{
    int i;
    unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
    init_by_array(init, length);
    /* This is an example of initializing by an array.       */
    /* You may use init_genrand(seed) with any 32bit integer */
    /* as a seed for a simpler initialization                */
    printf("1000 outputs of genrand_int32()\n");
    for (i=0; i<1000; i++) {
      printf("%10lu ", genrand_int32());
      if (i%5==4) printf("\n");
    }
    printf("\n1000 outputs of genrand_real2()\n");
    for (i=0; i<1000; i++) {
      printf("%10.8f ", genrand_real2());
      if (i%5==4) printf("\n");
    }

    return 0;
}
示例#18
0
// A stupid, basic and crappy linear search-based sampling algorithm.
int sample_from_discrete_log_pd(double *log_pd, int log_pd_size)
{
    double log_x = log(genrand_real2());
    double log_F = log(DBL_MIN);
    int i = 0;

    int sampled_idx = -1;

    for (i = 0; i < log_pd_size; ++i)
    {
        log_F = log_sum_exp(log_F, log_pd[i]);

        if (log_F >= log_x)
        {
            sampled_idx = i;
            break;
        }
    }

    if (sampled_idx < 0)
    {
        if (exp(log_F) < 1)
        {
            // This is due to rounding errors resulting in log_pd not
            // log-exp-summing up to exactly 1.0, so allocate that round-off
            // error to the last element in the multinomial pd.
            return log_pd_size - 1;
        }
        else
        {
            // OMG WTF this is badness.
            // Should really be throwing an exception, but whatevs.
            return -1;
        }
    }

    return sampled_idx;
}
示例#19
0
int NewPosition(double new_xyz[3], double xyz[3], double vel[3]) {
/*                                                                       */
/*  DESCRIPTION                                                          */
/*                                                                       */
/*     9/19/2011                                                         */
/*     I split up Sunny's NewPosition (see description below) into two:  */
/*     i.e., giving tau_goal using a random number here, and do the      */
/*     remaining calculations in the other subroutine, namely,           */
/*     "NewPosition4givenTau".                                           */
/*                                                                       */
/*     --- (Sunny's description                                          */
/*     Get a new position new_xyz[3] from the current position xyz[3],   */
/*     given unit displacement vector vel[3], by calculating optical     */
/*     depth (in situ) of the model nebula extended from Rmin to Rmax    */
/*       Destiny 1 : photon_will_be_out of the entire nebula             */
/*       Destiny 2 : achieved, tau -> tau_goal in the photon path        */
/*                                                                       */
/*      distance2border = X = distance from xyz[3] to a border at r0     */
/*      xyz[3] = (x,y,z)                   = position vector             */
/*      vel[3] = (dx_norm,dy_norm,dz_norm) = unit velocity vector        */
/*      -->  | vec{r} + X vec{dr_norm} |^2 = r0^2                        */
/*      -->  X^2 + 2 B X + C = 0   where  B = vec{r} * vec{dr_norm}      */
/*                                        C = r^2 - r0^2                 */
/*      -->  X = -B +/- sqrt( B^2 - C )                                  */
/*                                                                       */
/*  INPUTS                                                               */
/*     xyz[3]                                                            */
/*     vel[3]                                                            */
/*     disk[][91]                                                        */
/*     (Rmin, Rmax)                                                      */
/*  OUTPUT                                                               */
/*     new_xyz[3]                                                        */
/*     photon_will_be_out                                                */
/*                                                                       */
/*                                              2011-09-01  Hyosun Kim   */
/*                                                                       */
/*  ---                                                                  */
/*                                                                       */
/*  Revision by Hiro                                                     */
/*                                                                       */
/*  9/19/2011                                                            */
/*  Now the correct tau is provided when the photon goes out from the    */
/*   nebula. (The calculation for the last step was skipped in Hyoson's  */
/*   original code.)                                                     */
/*  I also have temporarily set dpath constant (0.3).                    */
/*                                                                       */
/*  2/22/2012                                                            */
/*  I have changed the unit of the coordinate to AU.                     */
/*                                                                       */
/*  3/3/2012                                                             */
/*  The array for opacity distribution ("disk") is removed.              */
/*  We alternatively use the Shakura & Sunyaev function.                 */
/*                                                                       */

  int photon_goes_out;
  double tau_goal;

  tau_goal = -log(genrand_real2());
  photon_goes_out=NewPosition4givenTau(tau_goal,new_xyz,xyz,vel);

  return photon_goes_out;
}
示例#20
0
// remove particle
void removeParticle(int A[], double rbc){
    double rn1;
    rn1 = genrand_real2();
    if (rn1 <=rbc) A[Ns-1]=0;
}
示例#21
0
文件: IM_unif.c 项目: pmangg/AdaptSAW
void 
sampleIM_unif(const IMInputModel * p_in_model,
              const IMSimParams * p_sim_params,
              IMMCMCDiagnostics * p_out_data)
{
    SAWData         saw_data;
    IMState         im_state;

    initIMState(&im_state, p_in_model, p_sim_params);

    double gamma_min = p_sim_params->gammas[0];
    double gamma_max = p_sim_params->gammas[p_sim_params->n_gammas - 1];

    // Set up the heaps, etc.
	initSAWData(&saw_data, p_in_model, p_sim_params);

    int nruns_until_next_param_update = 0;
    int n_accepted = 0;
    int n_proposed = 0;

    for (int curr_move = 0; curr_move < p_sim_params->n_moves; curr_move++)
    {
        if (nruns_until_next_param_update == 0)
        {
            nruns_until_next_param_update = p_sim_params->nruns_per_param_update;
            saw_data.SAW_length = p_sim_params->SAW_length_min;

            // Draw SAW length from NAIVE uniform distribution
            // U[SAW_length_min, SAW_length_max]
            saw_data.SAW_length =
                p_sim_params->SAW_length_min +
                (int) (genrand_real2() *
                       (p_sim_params->SAW_length_max -
                        p_sim_params->SAW_length_min + 1));

            // Draw gamma from NAIVE uniform distribution
            // U[gammas[0], gammas[n_gammas - 1]]
            saw_data.gamma_up =
                gamma_min +
                (genrand_real2() * (gamma_max - gamma_min));
            saw_data.gamma_down = saw_data.gamma_up;
        }

        --nruns_until_next_param_update;

        double E_initial = im_state.E;
        proposeIMMove(&saw_data, &im_state, p_in_model, p_sim_params);

        // Compute MH_ratio
        double MH_ratio = p_sim_params->beta_true * (E_initial - im_state.E);
        MH_ratio += (saw_data.log_f_rev - saw_data.log_f_fwd);
        MH_ratio = exp(MH_ratio);
        MH_ratio = MH_ratio > 1.0 ? 1.0 : MH_ratio;

        storeDiagnosticsData(p_out_data, curr_move, E_initial, im_state.E,
                             saw_data.log_f_fwd, saw_data.log_f_rev, MH_ratio,
                             saw_data.SAW_length, saw_data.gamma_up);

        // If rejection, restore state:
        if (genrand_real2() > MH_ratio)
        {
            undoIMMove(&saw_data, &im_state, p_in_model, p_sim_params);
        }
    }

    storeEndState(p_out_data, im_state.S, p_in_model->num_nodes);

    freeIMState(&im_state, p_in_model, p_sim_params);
    freeSAWData(&saw_data, p_in_model, p_sim_params);
}
示例#22
0
int main(){
    //// Declarations
    // define functions for modularity
    void initialise(    int [], int [], double [], double []);
    void addParticle(   int [], double);
    void removeParticle(int [], double);
    void moveParticle(  int [], int   );
    void moveParticle2D(int [], int [], int   );
    
    int iter=1e8;                           // lattice and iterations to be done on them.
    int i, j, ii, rn;
    int intrvl = 100;                       // interval after how many iterations at which observation is made.
    double lbc=0.4, rbc=0.2;                // boundary conditions (BCs) on the left and right boundaries.
    double lbc2=0.001, rbc2=0.8;              // boundary conditions (BCs) on the left and right boundaries.
    int A[Ns], B[Ns];                       // occupancy of the site on the two lattices
    double d[Ns], d2[Ns];                   // density on the two lattices          


	init_genrand(time(NULL));               // seed the random number generator with the NULL of the time!

    initialise(A, B, d, d2);                // initialise the array!  
    
    
    // now simulate
    for (j=1; j<iter; j++){                  
        rn = genrand_real2()*(Ns+1);        // NOTE that we have generated N+1 RNs for N sized lattice.    

        if (genrand_real2() <0.5){          // choose the lattice randomly!

            // case corresponding to the addition of particle
            if (( rn == Ns) && (A[0]==0) )           addParticle(A, lbc);      

            // case corresponding to the particle removal
            else if ( (rn == Ns-1) && (A[Ns-1]==1) ) removeParticle(A, rbc);    
                          
            // move the  particles on the lattice 
            else if ( (A[rn]==1) && (A[rn+1]==0) )   moveParticle2D(A, B, rn);       
            }
       
        // lattice 2
        else{       
        
            // case corresponding to the addition of particle
            if (( rn == Ns) && (B[0]==0) )           addParticle(B, lbc2);      

            // case corresponding to the particle removal
            else if ( (rn == Ns-1) && (B[Ns-1]==1) ) removeParticle(B, rbc2);    
                          
            // move the  particles on the lattice 
            else if ( (B[rn]==1) && (B[rn+1]==0) )   moveParticle2D(B, A, rn);       
            }

        // take the observation with this interval!
        if (j>1e5 && j%intrvl==0){                                           
            for (ii=0; ii<Ns; ii++) {
                d[ii] +=A[ii];
                d2[ii]+=B[ii];
            }
        } 
    }


    //simulation completed! Now plot, save, etc. with the data.       
    FILE *fp;
    fp = fopen("testData.txt", "w");
    for (i=0; i<Ns; i++){
        printf(     "%d \t %0.4f\t%0.4f\t \n", i, intrvl*d[i]/iter, intrvl*d2[i]/iter);
        fprintf(fp, "%d \t %0.4f\t%0.4f\t \n", i, intrvl*d[i]/iter, intrvl*d2[i]/iter);
    }
    fclose(fp);


// that is all!
return 0;
}
int main(void)
{
  double y[EQ_N][2];
  double (*func[EQ_N])();
  double parameter[PARTICLE_N][PARA_N], parameter_memory[PARA_N], resampled_parameter[PARTICLE_N][PARA_N];
  double time_point[TIME_POINT_N];
  double ref_time_point[TIME_POINT_N];

  int i, j, k, l, m;
  int mcmc_num, pa_num, integral_num, particle_num, rk_num, timepoint_num, parameter_num, equation_num;
  
  int x_flag = 0;
  double X, dt;

  double probability_before, probability_after, probability_ratio;
  int move_count = 0;

  double weight[PARTICLE_N], weight_tmp[PARTICLE_N];
  double total_weight = 0, power_total_weight, partial_total_weight, upper_weight, lower_weight;
  double log_weight[PARTICLE_N], log_weight_tmp[PARTICLE_N];
  double total_likelihood[PARTICLE_N], total_likelihood_previous[PARTICLE_N];
  double log_likelihood[PARTICLE_N], total_log_likelihood;
  double epsilon[POPULATION_N] = {2, 1, 0.75, 0.5, 0.25};
  double ess;
  int sampling_num;
  int resampling_count = 0;
  int weighten_particle_num[POPULATION_N] = {0, 0, 0, 0, 0}, last_weighten_particle_num = 0;
  int resampling_flag[POPULATION_N] = {0, 0, 0, 0, 0};

  double effective_particle_num = 0, total_effective_particle_num = 0;
  double weighten_particle_multiplier = 1;

  int mcmc_step;

  double unit_r, chosen_num;

  FILE *fp1, *fp2, *fp3, *fp4, *fp5, *fp6, *fp7, *fin;

  clock_t start, end;

  dt = 0.01;
  X = 1.0;


  function_set(func);


/*** 計算開始 **********************************************************************************************************************************/

  /* 時間を計る */
  start = clock();
  
  /* 乱数の初期化 */
  init_genrand(12);

  /* ファイル設定 */
  fp1 = fopen("information12.data","w");

  /* 実験データの読み込み */
  fin = fopen("ref_time_point.data","r");

  for(timepoint_num=0;timepoint_num<TIME_POINT_N;timepoint_num++){
    fscanf(fin, "%lf", &ref_time_point[timepoint_num]);
  }

  fclose(fin);
  /* 実験データの読み込み終了 */






  /* サンプル番号初期化 */
  sampling_num = 0;

  printf("0 th population\n");

  /* ランダムサンプリングによる 粒子数個のパラメータセットの発生 **************************************************************************************/
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

    /* パラメータ、合計濃度、変動係数を発生させる */
    parameter_set(parameter[particle_num]);
    parameter_generation(parameter[particle_num]);

  }


  /* 重みを初期化 正規化 */
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
    weight[particle_num] = 1.0/PARTICLE_N;
  }


  /* ランダムサンプリングによる初期パラメータ発生 終了 ************************************************************************************************/









  
  /* Population annealing 開始 *****************************************************************************************************************/
  for(pa_num=0;pa_num<POPULATION_N;pa_num++){

    printf("%d th population\n", pa_num+1);
    
    /* 各粒子ごとに尤度の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      total_likelihood[particle_num] = 0; /* 初期化 */
      total_likelihood_previous[particle_num] = 0; /* 初期化 */
    }


    /* 中間分布の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

      /* time point データの発生 */
      y[0][0] = 0.0;
      y[1][0] = 0.0;
      rk_search(X, dt, func, y, parameter[particle_num], time_point);

      /* 尤度の計算 */
      total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

      if(pa_num==0){
        total_likelihood_previous[particle_num] = 1;
      }
      else{
        total_likelihood_previous[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num-1]);
      }

    }
    /* 中間分布の計算終了 */


    /* 重みの計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      weight[particle_num] = weight[particle_num] * total_likelihood[particle_num]/total_likelihood_previous[particle_num];
      if(total_likelihood[particle_num]==0 || total_likelihood_previous[particle_num]==0) weight[particle_num] = 0.0;
    }

    total_weight = 0.0;

    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      total_weight = total_weight + weight[particle_num];
    }
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      weight[particle_num] = weight[particle_num]/total_weight;
    }


    /* 重みを持つ粒子数の計算 */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      if(weight[particle_num]!=0) weighten_particle_num[pa_num]++;
    }
    fprintf(fp1, "weighten particle num = %d\n", weighten_particle_num[pa_num]);





    /* 各粒子ごとに */
    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){

      /* 重みが0なら飛ばす */
      if(weight[particle_num]==0) continue;

      /* フラグの初期化 */
      x_flag = 0;


      /* MCMC 計算 */
      for(mcmc_num=0;mcmc_num<MCMC_MAX_STEP;mcmc_num++){
 
        /* 許容されなければ、元のままのパラメータ */
        if(x_flag == 1){
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
        }


        /* 確率の初期化 */
        probability_before = 1.0;
        probability_after = 1.0;
    

        /* フラグの初期化 */
        x_flag = 0;


        /* 新候補の計算前の値を記憶 */
        for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
          parameter_memory[parameter_num] = parameter[particle_num][parameter_num];
        }


        /* 移動前の確率を計算 */
        probability_before = probability_before*pdf_uniform_parameter(parameter[particle_num]); /* 事前分布を乗じる */

        
        total_likelihood[particle_num] = 0.0; /* 初期化 */

        /* time point データの発生 */
        y[0][0] = 0.0;
        y[1][0] = 0.0;
        rk_search(X, dt, func, y, parameter[particle_num], time_point);

        /* 尤度の計算 */
        total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

        probability_before = probability_before * total_likelihood[particle_num]; /* 移動前の確率 */  


        /* 新候補を計算 パラメータの中から1つだけ動かす */
        unit_r = genrand_real2();
        chosen_num = PERTURB_PARA_N*unit_r;
        parameter_sampler(parameter[particle_num]);


        /* 移動後の確率を計算 : 一様事前分布を乗じる */
        probability_after = probability_after*pdf_uniform_parameter(parameter[particle_num]); /* 事前分布を乗じる */
        

        if(probability_after == 0.0){
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }



        /* 移動後の確率を計算 */
        total_likelihood[particle_num] = 0.0; /* 初期化 */

        /* time point データの発生 */
        y[0][0] = 0.0;
        y[1][0] = 0.0;
        rk_search(X, dt, func, y, parameter[particle_num], time_point);

        /* 尤度の計算 */
        total_likelihood[particle_num] = indicator_function(time_point, ref_time_point, epsilon[pa_num]);

        probability_after = probability_after * total_likelihood[particle_num]; /* 移動後の確率 */


        if(probability_after == 0.0){
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }



        /* 移動前と移動後の確率の比の計算 */
        probability_ratio = probability_after/probability_before;

        /* [0,1) 単位乱数の発生 */
        unit_r = genrand_real2();   


        /* 移動の判定 */
        if(probability_ratio > unit_r){ 
          move_count++;
        }
        else{
          x_flag = 1;
          for(parameter_num=0;parameter_num<PARA_N;parameter_num++){
            parameter[particle_num][parameter_num] = parameter_memory[parameter_num];
          }
          continue;
        }
    
      }
      /* particle_num 番目の粒子の MCMC 終了 */
    }
    /* 全粒子の MCMC 終了 */
 




 
    /* リサンプリング ********************************************************/
    power_total_weight = 0.0;
    ess = 0.0;

    for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
      power_total_weight = power_total_weight + pow(weight[particle_num], 2);
    }


    /* Effective Sample Size の計算 */
    ess = 1.0/power_total_weight;
    //if(pa_num==4) ess = 0.0;

    fprintf(fp1, "%d th population", pa_num);
    fprintf(fp1, "ESS = %f\t particle_num/2 = %f\n\n", ess, PARTICLE_N/2.0);
    

    /* リサンプリングの判定と実行 */
    if(ess < PARTICLE_N/2){

      fprintf(fp1, "resampling\n");
      resampling_count++;
      resampling_flag[pa_num] = 1;
      fprintf(fp1, "resampling flag = %d\n", resampling_flag[pa_num]);
      
      /* 粒子数個リサンプリングする 重複可 */
      for(m=0;m<PARTICLE_N;m++){

        /* [0,1) 乱数発生 */
        unit_r = genrand_real2();

        partial_total_weight = 0.0;

        /* l 番目の粒子が選ばれる */
        for(l=0;l<PARTICLE_N;l++){
          partial_total_weight = partial_total_weight + weight[l];

          upper_weight = partial_total_weight;
          lower_weight = partial_total_weight - weight[l];

          if((unit_r >= lower_weight) && (unit_r < upper_weight)){
            for(i=0;i<PARA_N;i++){
              resampled_parameter[m][i] = parameter[l][i];
            }
            break;
          }
        }

      }
      /* 粒子数個リサンプリング終了 */



      /* リサンプル後のパラメータと活性化時間の再設定 */
      for(l=0;l<PARTICLE_N;l++){
        for(i=0;i<PARA_N;i++){
          parameter[l][i] = resampled_parameter[l][i];
        }
      }



      /* リサンプル後の重みを初期化 正規化 */
      for(l=0;l<PARTICLE_N;l++){
        weight[l] = 1.0/PARTICLE_N;
      }


    }
    /* リサンプリングの判定と実行 終了 */
    /* リサンプリング終了 ****************************************************/

  }
  /* Population annealing 終了 *****************************************************************************************************************/
  

  for(pa_num=0;pa_num<POPULATION_N;pa_num++){
    if(resampling_flag[pa_num]==1){
      weighten_particle_multiplier = weighten_particle_multiplier * weighten_particle_num[pa_num]/PARTICLE_N;
    }
  }

  /* 重みを持つ粒子数の計算 */
  last_weighten_particle_num = 0;
  for(particle_num=0;particle_num<PARTICLE_N;particle_num++){
    if(weight[particle_num]!=0) last_weighten_particle_num++;
  }
  effective_particle_num = last_weighten_particle_num*weighten_particle_multiplier;
  
  fprintf(fp1, "effective particle number = %f\n", effective_particle_num);



  /* 移動回数、 リサンプリング回数、 モデル数を出力 */
  fprintf(fp1, "%d times move\n", move_count);
  fprintf(fp1, "%d times resampling\n", resampling_count);
  end = clock();
  /* 計算時間の出力 */
  fprintf(fp1, "%f min\n", (double)(end - start)/CLOCKS_PER_SEC/60.0);



  fclose(fp1);

  return 0;
}
示例#24
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void acvmpm(EMMPM_Data* data, EMMPM_CallbackFunctions* callbacks)
{
  double* yk;
  double sqrt2pi, current, con[EMMPM_MAX_CLASSES];
  double x, post[EMMPM_MAX_CLASSES], sum, edge;
  int k, l, prior;
  int i, j, d;
  size_t ld, ijd, ij, lij, i1j1;
  int dims = data->dims;
  int rows = data->rows;
  int cols = data->columns;
  int classes = data->classes;
  unsigned char* y = data->y;
  unsigned char* xt = data->xt;
  double* probs = data->probs;
  double* m = data->m;
  double* v = data->v;
  double* ccost = data->ccost;
  double* ns = data->ns;
  double* ew = data->ew;
  double* sw = data->sw;
  double* nw = data->nw;
  char msgbuff[256];
  float totalLoops;
  float currentLoopCount = 0.0;
//  double local_beta;

  size_t nsCols = data->columns - 1;
 // size_t nsRows = data->rows;
  size_t ewCols = data->columns;
//  size_t ewRows = data->rows - 1;
  size_t swCols = data->columns - 1;
//  size_t swRows = data->rows - 1;
  size_t nwCols = data->columns-1;
//  size_t nwRows = data->rows-1;

  memset(post, 0, EMMPM_MAX_CLASSES * sizeof(double));
  memset(con, 0,  EMMPM_MAX_CLASSES * sizeof(double));

  totalLoops = (float)(data->emIterations * data->mpmIterations + data->mpmIterations);
  memset(msgbuff, 0, 256);
  data->progress++;

  yk = (double*)malloc(cols * rows * classes * sizeof(double));

  sqrt2pi = sqrt(2.0 * M_PI);

  unsigned long long int millis = EMMPM_getMilliSeconds();


  for (l = 0; l < classes; l++)
  {
    con[l] = 0;
    for (d = 0; d < dims; d++)
    {
      ld = dims * l + d;
      con[l] += -log(sqrt2pi * sqrt(v[ld]));
    }
  }

  for (i = 0; i < rows; i++)
  {
    for (j = 0; j < cols; j++)
    {
      for (l = 0; l < classes; l++)
      {
        lij = (cols * rows * l) + (cols * i) + j;
        probs[lij] = 0;
        yk[lij] = con[l];
        for (d = 0; d < dims; d++)
        {
          ld = dims * l + d;
          ijd = (dims * cols * i) + (dims * j) + d;
          yk[lij] += ((y[ijd] - m[ld]) * (y[ijd] - m[ld]) / (-2.0 * v[ld]));
        }
      }
    }
  }

  printf("Serial Millis to complete initialization: %llu \n", EMMPM_getMilliSeconds() - millis);


  /* Perform the MPM loops */
  for (k = 0; k < data->mpmIterations; k++)
  {
    data->currentMPMLoop = k;
    if (data->cancel) { data->progress = 100.0; break; }
    data->inside_mpm_loop = 1;
    millis = EMMPM_getMilliSeconds();

    for (i = 0; i < rows; i++)
    {
      for (j = 0; j < cols; j++)
      {
        ij = (cols * i) + j;
        sum = 0;
        for (l = 0; l < classes; l++)
        {
          /* edge penalties (in both x and y) */
          prior = 0;
          edge = 0;
          if (i - 1 >= 0)
          {
            if (j - 1 >= 0)
            {
              i1j1 = (cols*(i-1))+j-1;
              if (xt[i1j1] != l)
              {
                prior++;
                i1j1 = (swCols*(i-1))+j-1;
                edge += sw[i1j1];
              }
            }

            //Mark1
            i1j1 = (cols*(i-1))+j;
            if (xt[i1j1] != l)
            {
              prior++;
              i1j1 = (ewCols*(i-1))+j;
              edge += ew[i1j1];
            }
            //mark2
            if (j + 1 < cols)
            {
              i1j1 = (cols*(i-1))+j+1;
              if (xt[i1j1] != l)
              {
                prior++;
                i1j1 = (nwCols*(i-1))+j;
                edge += nw[i1j1];
              }
            }
          }

          //mark3
          if (i + 1 < rows)
          {
            if (j - 1 >= 0)
            {
              i1j1 = (cols*(i+1))+j-1;
              if (xt[i1j1] != l)
              {
                prior++;
                i1j1 = (nwCols*(i))+j-1;
                edge += nw[i1j1];
              }
            }
            //mark4
            i1j1 = (cols*(i+1))+j;
            if (xt[i1j1] != l)
            {
              prior++;
              i1j1 = (ewCols*(i))+j;
              edge += ew[i1j1];
            }
            //mark5
            if (j + 1 < cols)
            {
              i1j1 = (cols*(i+1))+j+1;
              if (xt[i1j1] != l)
              {
                prior++;
                i1j1 = (swCols*(i))+j;
                edge += sw[i1j1];
              }
            }
          }
          //mark6
          if (j - 1 >= 0)
          {
            i1j1 = (cols*(i))+j-1;
            if (xt[i1j1] != l)
            {
              prior++;
              i1j1 = (nsCols*(i))+j-1;
              edge += ns[i1j1];
            }
          }
          //mark7
          if (j + 1 < cols)
          {
            i1j1 = (cols*(i))+j+1;
            if (xt[i1j1] != l)
            {
              prior++;
              i1j1 = (nsCols*(i))+j;
              edge += ns[i1j1];
            }
          }
          lij = (cols * rows * l) + (cols * i) + j;
          post[l] = exp(yk[lij] - (data->workingBeta * (double)prior) - edge - (data->beta_c * ccost[lij]) - data->w_gamma[l]);
          sum += post[l];
        }
        x = genrand_real2(data->rngVars);
        current = 0;
        for (l = 0; l < classes; l++)
        {
          lij = (cols * rows * l) + (cols * i) + j;
          ij = (cols*i)+j;
          if ((x >= current) && (x <= (current + post[l] / sum)))
          {
            xt[ij] = l;
            probs[lij] += 1.0;
          }
          current += post[l] / sum;
        }
      }
    }
    printf("Millis to complete loop: %llu \n", EMMPM_getMilliSeconds() - millis);
    EMMPM_ConvertXtToOutputImage(data, callbacks);
    if (callbacks->EMMPM_ProgressFunc != NULL)
    {
      data->currentMPMLoop = k;
      snprintf(msgbuff, 256, "MPM Loop %d", data->currentMPMLoop);
      callbacks->EMMPM_ProgressFunc(msgbuff, data->progress);
    }
    if (NULL != callbacks->EMMPM_ProgressStatsFunc)
    {
      currentLoopCount = data->mpmIterations * data->currentEMLoop + data->currentMPMLoop;
      data->progress = currentLoopCount / totalLoops * 100.0;
      callbacks->EMMPM_ProgressStatsFunc(data);
    }

  }
  data->inside_mpm_loop = 0;

  if (!data->cancel)
  {
  /* Normalize probabilities */
    for (i = 0; i < data->rows; i++)
    {
      for (j = 0; j < data->columns; j++)
      {
        for (l = 0; l < classes; l++)
        {
          lij = (cols * rows * l) + (cols * i) + j;
          data->probs[lij] = data->probs[lij] / (double)data->mpmIterations;
        }
      }
    }
  }

  /* Clean Up Memory */
  free(yk);

}
Simulation::Simulation( const unsigned long rabbitsNum, const int month, double survivalRateYoung, double survivalRateAdult )
: _month( month ), _rabbitsNum( rabbitsNum ), _survivalRateYoung( survivalRateYoung ), _survivalRateAdult( survivalRateAdult )
{	// Allocation for the table of rabbits
        _population = new std::list<Rabbits*>*[ _month + 1 ]; // month m + 1 is a buffer
        for( int i = 0; i < _month; ++i ) _population[ i ] = new std::list<Rabbits*>;
	// Allocation for the pool of rabbits
        _pool = new Rabbits*[ _rabbitsNum ];
        for( unsigned long i = 0; i < _rabbitsNum; ++i ) _pool[ i ] = new Rabbits( false, genrand_real2(  ) >= 0.5 );

        // This pointer points to the last unusued rabbit in the pool
        _pt = _pool + _rabbitsNum - 1;
        
        _newRabbits = 0;
        
        _file = NULL;
}
示例#26
0
int EddSPM_cycle(struct SimData *SD, double n) {
  if (SD->flags & S12_FLAG_INCOMPAT & ~S12_FLAG_FROZEN ) {
    printf("Incompatible features seen: %d (bxcon)\n", SD->flags);
    exit(205);
  }
  if (SD->MLLlen == 0 && SD->MLLlen_down == 0) {
    // If no moves are possible, then time passes by instantly.
    SD->MLLextraTime = 0;
    return(0);
  }
  int frozenEnabled = SD->flags & S12_FLAG_FROZEN;

  int naccept = 0;
  //struct LList llist; llist.n = 0;

  double maxTime = (double) n;
  double time = SD->MLLextraTime;
  //printf("eddCycle: time:%f maxTime%f\n", time, maxTime);

  double c = 1./(1. + exp(SD->beta));
  //printf("beta:%f c:%f\n", SD->beta, c);
  double wUp = 1-(c);
  double wDown = c;
  double eta = 0;
  if (SD->hardness != 1./0.)
    eta = exp(-SD->beta*SD->hardness);

  double pdf_wDown        = wDown * (SD->MLLlen_down);
  double pdf_wUp          = wUp   * (SD->MLLlen     );
  double pdf_wDown_frozen = eta*wDown*(SD->lattSize - SD->N - SD->MLLlen_down);
  double pdf_wUp_frozen   = eta*wUp  *(SD->lattSize);
  double cdf_wDown        =                    pdf_wDown;
  double cdf_wUp          = cdf_wDown        + pdf_wUp;
  double cdf_wDown_frozen = cdf_wUp          + pdf_wDown_frozen;
  double cdf_wUp_frozen   = cdf_wDown_frozen + pdf_wUp_frozen;

  double wTot = cdf_wUp_frozen ;

  if (time == -1.) {
    // pre-move, advance time until the first event.  Otherwise we
    // always end up moving right at time == 0
    double timestep = 1./wTot;
    timestep *= -log(genrand_real3());
    time = timestep;
  }

  while (time < maxTime) {
    int pos;
    double rand = genrand_real2() * wTot;

    if (rand < cdf_wDown) {
      // pick some down spin to flip up
      int i = (int) (rand / wDown);
      pos = SD->MLL_down[i];
      if (debugedd)
	printf("move: flipping down->up at pos:%d\n", pos);
      FAremoveFromMLL(SD, 'd', pos);
      addParticle(SD, pos, SD->inserttype);
      FAaddToMLL(SD, 'u', pos);
      SD->persist[pos] = 1;
    } else if (rand < cdf_wUp) {
      // pick some up spin to flip down
      int i = (int) ((rand - cdf_wDown)  / wUp);
      pos = SD->MLL[i];
      if (debugedd) {
	printf("move: flipping up->down at pos:%d\n", pos);
	if (i > SD->MLLlen )
	  exit(158);
      }
      FAremoveFromMLL(SD, 'u', pos);
      delParticle(SD, pos);
      FAaddToMLL(SD, 'd', pos);
      SD->persist[pos] = 1;
    } else if (rand < cdf_wDown_frozen) {
      // Pick a immobile down spin to flip.
      exit(56); // This is not working yet!
      while (1) {
	// Find a down spin that isn't active
	pos = SD->lattSize * genrand_real2();
	if (SD->lattsite[pos] == S12_EMPTYSITE && /* site is down */ 
	    SD->MLLr[pos] == -1 )                 /* site is not mobile */
	  break;
      }
      if (debugedd) {
	// Some error checking
	printf("move: (immoblie) flipping down->up at pos:%d\n", pos);
      }
      if ( frozenEnabled && SD->frozen[pos]) {
	// If we are frozen, do nothing.
      } else {
	addParticle(SD, pos, SD->inserttype);
	SD->persist[pos] = 1;
      }
    } else { // (rand < cdf_wUp_frozen)
      // Pick a immobile up spin to flip.
      exit(56); // This is not working yet!
      while (1) {
	// Find a down spin that isn't active
	int i = SD->N * genrand_real2();
	pos = SD->atompos[i];
	if (SD->MLLr[pos] == -1 )                 /* site is not mobile */
	  break;
      }
      if (debugedd) {
	// Some error checking
	printf("move: (immobile) flipping up->down at pos:%d\n", pos);
	if (SD->lattsite[pos] == S12_EMPTYSITE) exit(165);
      }
      if ( frozenEnabled && SD->frozen[pos]) {
	// If we are frozen, do nothing.
      } else {
	delParticle(SD, pos);
	SD->persist[pos] = 1;
      }
    }

    //llist.n = 0;

    EddSPM_updateLatNeighbors(SD, pos);

    naccept += 1;

    pdf_wDown        = wDown * (SD->MLLlen_down);
    pdf_wUp          = wUp   * (SD->MLLlen     );
    pdf_wDown_frozen = eta*wDown*(SD->lattSize - SD->N - SD->MLLlen_down);
    pdf_wUp_frozen   = eta*wUp  *(SD->lattSize);
    cdf_wDown        =                    pdf_wDown;
    cdf_wUp          = cdf_wDown        + pdf_wUp;
    cdf_wDown_frozen = cdf_wUp          + pdf_wDown_frozen;
    cdf_wUp_frozen   = cdf_wDown_frozen + pdf_wUp_frozen;

    wTot = cdf_wUp_frozen ;

    // Advance time
    double timestep = 1./wTot;
    timestep *= -log(genrand_real3());  // exponential distribution of times.
                                        // genrand_real3()  -> (0, 1)
    time += timestep;
    //printf("interval: %f\n", (SD->N * SD->connMax) / (double)SD->MLLlen);
    //if (naccept == 1)
    //return(naccept);
  }
  // MLLextraTime is a positive, the amount to increment before our next stop.
  SD->MLLextraTime = time - maxTime;
  //printf("eddCycle: final time:%f maxTime:%f extraTime:%f\n", 
  // time, maxTime, SD->MLLextraTime);

  return(naccept);
}
示例#27
0
int cycleSPM(struct SimData *SD, double n) {

  printf("error: Using SPM without event driven dynamics does NOT WORK(yet)\n");
  printf("Enable event-driven dynamics (.eddEnable())\n");
  exit(94);

  int i_trial;
  int naccept = 0;

  int N = SD->N;   // initial N value, use SD->N for instantaneous
  double c = 1./(1. + exp(SD->beta));
  //printf("beta:%f c:%f\n", SD->beta, c);
  double wUp = 1-(c);
  double wDown = c;
  //double maxTime = N*n;
  //double time ;

  //for (i_trial=0 ; i_trial<(n*SD->N) ; i_trial++) {
  for (i_trial=0 ; naccept<(N*n) ; i_trial++ ) {

    // otherwise, do a regular move (this should be the most common
    // case and thus inlined)

    // Find a lattice site with a particle:
    if (SD->N == 0) {
      printf("we are out of particles!\n");
      exit(165);
    }
    int pos;
    int atomtype;
    int state;
    while(1) {
      pos = (int)(SD->lattSize * genrand_real2());
      if (SD->lattsite[pos] != S12_EMPTYSITE) {
	// particle present, can we flip it down?
	atomtype = atomType(SD, pos);
	state = 1;
      } else { // trip flipping down to up.
	atomtype = SD->inserttype;
	state = 0;
      }
      if (SD->nneighbors[pos] >= atomtype)
	// we are mobile here-- continue with the move function from this spot.
	break;
    }
    
    double rand = genrand_real2();
    if (state == 1 && rand < wUp) {
      if(debugedd) 
	printf("accepting FA move: %d up -> down\n", pos);
      naccept += 1;
      delParticle(SD, pos);
    } else if (state == 0 && rand < wDown) {
      if(debugedd) 
	printf("accepting FA move: %d down -> up\n", pos);
      naccept += 1;
      addParticle(SD, pos, SD->inserttype);
    } else {
      if(debugedd) 
	printf("rejecting FA move FA move: %d (was %d)\n", pos, state);
    }
  }

  return(naccept);  // Return 1, since we accepted one move
}
// Call the destructor
// void Simulation::End(  ) { ~Simulation(  ); }
// The simulation
// time: the number of months the simulation has to last. Can end earlier if no rabbits are left in the pool.
int Simulation::MonthSimul( int time ) {
	clock_t simulBegin = clock(  );
	clock_t simulEnd;
	int j = 0; // The current month
	unsigned long tmp = 0;
	unsigned long died = 0; // The number of rabbits which have died this month
	unsigned long newBorns = 0;
	unsigned long females = 0;
	unsigned long reproduction = 0;
	
	_newRabbits = 0; // This variable stores the number of rabbits which should be created when the simulation ends
/**/	
	for( int i = 0; i < time; ++i ) {
/**
		fprintf( _file, "%d\n", i ); died = 0;
/**/
		// std::cout<< "Month: " << i << std::endl;
		// At the last month, all living rabbits die.
		for( _it = _population[ _month - 1 ]->begin(  ); _it != _population[ _month - 1 ]->end(  ); ) {
			++died;
			++_pt; *_pt = *_it;
			_it = _population[ _month - 1 ]->erase( _it );
		}
/**		
		fprintf( _file, "%d\t%ld\n", _month - 1, died ); died = 0;
/**/		
		// Mature and old rabbits [9-132-240]
		for( j = _month ; j > 8; --j ) {
			// Move the lists to the left
			_population[ j ] = _population[ j - 1 ];
			
			for( _it = _population[ j ]->begin(  ); _it != _population[ j ]->end(  ); ++_it ) {
				if( !death( j ) ) {
					if( (*_it)->get_sex(  ) ) {
						++females;
						if( genrand_real1(  ) >= 0.60 ) {
							++reproduction;
							tmp = (*_it)->reproduce( *_it );
							newBorns += tmp;
							_newRabbits += tmp;
						}
					}
					++_it;
				}
				else ++died;
			}
/**/
			fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size(  ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0;
/**/
		}
		// Final deadline for maturity [8-8]
		_population[ j ] = _population[ j - 1 ]; // On decale les listes de lapins vers la gauche
		for( _it = _population[ j ]->begin(  ); _it != _population[ j ]->end(  ); ) {
			if( !death( j ) ) {
				if( !(*_it)->get_mature(  ) ) {
					(*_it)->set_mature( true );
					if( (*_it)->get_sex(  ) ) {
						++females;
						++reproduction;
						tmp = (*_it)->reproduce( *_it );
						newBorns += tmp;
						_newRabbits += tmp;
					}
				}
				else {
					if( (*_it)->get_sex(  ) ) {
						++females;
						if( genrand_real1(  ) >= 0.60 ) {
							++reproduction;
							tmp = (*_it)->reproduce( *_it );
							newBorns += tmp;
							_newRabbits += tmp;
						}
					}
				}
				++_it;
			}
			else ++died;
		}
/**/
			fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size(  ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0;
/**/		
		// Rabbits getting maturity [5-7]
		for( j = 7; j >= 5; --j ) {
			// On decale les listes de lapins vers la gauche
			_population[ j ] = _population[ j - 1 ];
			
			for( _it = _population[ j ]->begin(  ); _it != _population[ j ]->end(  ); ++_it ) {
				if( !death( j ) ) {
					if( !(*_it)->get_mature(  ) ) {
						if( genrand_real1(  ) >= 0.2 ) {
							// 80% of becoming mature each month
							(*_it)->set_mature( true );
							if( (*_it)->get_sex(  ) ) {
								++females;
								++reproduction;
								// Females reproduce their first month of maturity
								tmp = (*_it)->reproduce( *_it );
								newBorns += tmp;
								_newRabbits += tmp;
							}
						}
					}
					else {
						if( (*_it)->get_sex(  ) ) {
							++females;
							if( genrand_real1(  ) >= 0.60 ) {
								++reproduction;
								tmp = (*_it)->reproduce( *_it );
								newBorns += tmp;
								_newRabbits += tmp;
							}
						}
					}
					++_it;
				}
				else ++died;
			}
/**/
			fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size(  ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0;
/**/
		}
		// Newly-born, young rabbits [1-4]
		for( j = 4; j > 0; --j ) {
			_population[ j ] = _population[ j - 1 ]; // On decale les listes de lapins vers la gauche
			
			for( _it = _population[ j ]->begin(  ); _it != _population[ j ]->end(  ); ) {
				if( !death( j ) ) {
					if( (*_it)->get_sex(  ) ) {
						++females;
					}
					++_it;
				}
				else ++died;
			}
/**/
			fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size(  ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0;
/**/
		}
		// Moving the dead 20 years old rabbits' list to the new born's list
		_population[ 0 ] = _population[ _month ];
		_population[ _month ] = NULL;
		// std::cout << "Death of " << died << " rabbits" << std::endl;
		if( _pt - _pool < _newRabbits ) {
			// End of the simulation
			i = time;
			// std::cout<< "Still " << _pt - _pool << " rabbits staying versus " << _newRabbits << " rabbits to be born" << std::endl;
		}
		else {
			// std::cout<< "Still " << _pt - _pool << " rabbits" << std::endl;
			// std::cout<< "Birthing of " << _newRabbits << " rabbits" << std::endl;
			for( j = 0; j < _newRabbits; ++j ) {	
				// // std::cout << "Birthing of a rabbit" << std::endl;
				// initialisation of the rabbits
				(*_pt)->set_sex( ( genrand_real2(  ) >= 0.5 ) );
				if( (*_pt)->get_sex(  ) ) {
					++females;
				}
				(*_pt)->set_mature( false );
				(*_pt)->set_monthsPassed( 0 );
				// Rabbits are being born
				_population[ 0 ]->push_back( *_pt );
				*_pt = NULL;
				if( _pt > _pool ) --_pt;
			}
			_newRabbits = 0;
/**/
			fprintf( _file, "%d\t%d\t%d\t%ld\t%ld\t%d\n", 0, 0, 0, _population[ 0 ]->size(  ), females, 0 ); females = 0;
/**/
		}
/**/
	}
/**/
	simulEnd = clock(  );
	fprintf( _file, "%ld\t%f\t", (long) ( simulEnd - simulBegin ), (double) ( simulEnd - simulBegin ) / CLOCKS_PER_SEC );

	return _newRabbits;
}
void main()
{
	std::ifstream fdata;
	fdata.open("Curves1020");
	integer NN = 100, num = 1020, n = NN + 1, d = 2;
	double *data = new double[d * NN * num + 2 * d * n];
	double *C1 = data + d * NN * num;
	double *C2 = C1 + d * n;

	for (integer i = 0; i < NN; i++)
	{
		for (integer j = 0; j < num; j++)
		{
			for (integer k = 0; k < 2; k++)
			{
				fdata >> data[k * NN + i + j * 2 * NN];
			}
		}
	}
	// choose a random seed
	unsigned tt = (unsigned)time(NULL);
	tt = 1425718285;
	std::cout << "rand seed:" << tt << std::endl;//--
	init_genrand(tt);
	integer idx1 = static_cast<integer> (floor(genrand_real2() * 1020)), idx2 = static_cast<integer> (floor(genrand_real2() * 1020));
	//idx1 = 0;
	//idx2 = 2;
	std::cout << "idx1:" << idx1 << ", idx2:" << idx2 << std::endl;//--
	for (integer i = 0; i < n; i++)
	{
		for (integer j = 0; j < d; j++)
		{
			C1[i + j * n] = data[i + j * NN + idx1 * d * NN];
			C2[i + j * n] = data[i + j * NN + idx2 * d * NN];
		}
	}

	for (integer j = 0; j < d; j++)
	{
		C1[NN + j * n] = C1[0 + j * n];
		C2[NN + j * n] = C2[0 + j * n];
	}

	//double O[] = { cos(0.5), -sin(0.5), sin(0.5), cos(0.5) };
	//char *transn = const_cast<char *> ("n");
	//double one = 1, zero = 0;
	//dgemm_(transn, transn, &n, &d, &d, &one, C1, &n, O, &d, &zero, C2, &n);
	//ForDebug::Print("O first:", O, d, d);//---

	//ForDebug::Print("C1:", C1, n, d);//--
	//ForDebug::Print("C2:", C2, n, d);//--

	//for (integer i = 0; i < n; i++)///---------
	//{
	//	C1[i + 0 * n] = i / (n - 1);
	//	C1[i + 1 * n] = sin(static_cast<double> (i) / (n - 1) / 2);
	//	C2[i + 0 * n] = i / (n - 1);
	//	C2[i + 1 * n] = sin(static_cast<double> (i) / (n - 1) / 2 + PI / 6);
	//}//-------

	integer numofmanis = 3;
	integer numofmani1 = 1;
	integer numofmani2 = 1;
	integer numofmani3 = 1;
	L2SphereVariable *FNSV = new L2SphereVariable(n);
	OrthGroupVariable *OGV = new OrthGroupVariable(d);
	EucVariable *EucV = new EucVariable(1);
	ProductElement *Xopt = new ProductElement(numofmanis, FNSV, numofmani1, OGV, numofmani2, EucV, numofmani3);

	bool rotated = true;
	bool isclosed = true;
	bool onlyDP = false;
	bool swap;
	integer autoselectC = 1;
	double *fopts = new double[10];
	double *comtime = fopts + 5;
	integer ns, lms;

	DriverElasticCurvesRO(C1, C2, d, n, 0.01, rotated, isclosed, onlyDP, 4, "LRTRSR1", autoselectC, Xopt, swap, fopts, comtime, ns, lms);

	delete[] fopts;
	delete[] data;
	delete FNSV;
	delete OGV;
	delete EucV;
	delete Xopt;

#ifdef _WIN64
#ifdef _DEBUG
	_CrtDumpMemoryLeaks();
#endif
#endif
};
示例#30
0
LRESULT CALLBACK WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
    // Build list when first playing a file
    if ( uMsg == WM_USER && lParam == IPC_PLAYING_FILE )
    {
        OutputDebugString( "IPC_PLAYING_FILE" );
        OutputDebugString(( char* )wParam );
        
        if ( !master_built )
        {
			OutputDebugString( "Play: Rebuilding track lists" );
            
            build_master();
            copy_master();
            
            master_built = 1;
        }
        
        // Restore playing status
        if ( is_pause )
        {
            OutputDebugString( "Pausing:" );
            SendMessage( hwnd, WM_COMMAND, WINAMP_PAUSE, 0 );
        }
        
        is_pause = 0;
    }
    
    // Mark the playlist as dirty upon any modification
    if ( uMsg == WM_USER && lParam == IPC_PLAYLIST_MODIFIED )
    {
        master_built = 0;
        
        // Clear the history
        history_clear();
    }
    
    
    if ( uMsg == WM_USER && lParam == IPC_GET_PREVIOUS_PLITEM )
    {
        // If plugin not enabled, let winamp do default action
        if ( !cfg_enabled )
            return -1;
            
        // If there is history, return that and rebuild the random list
        if ( history_size() > 0 )
        {
			// Get playing status
            status = SendMessage( hwnd, WM_WA_IPC, 0, IPC_ISPLAYING );

            // Pretend it is paused if anything but playing.
            is_pause = ( status != IS_PLAY );
            
            if ( is_pause )
                OutputDebugString( "Prev track: Is paused" );

			OutputDebugString( "Prev track: Rebuilding track lists" );

            copy_master();
            return history_pop();
        }
    }
    
    if ( uMsg == WM_USER && lParam == IPC_GET_NEXT_PLITEM )
    {
        // Playlist is dirty! Rebuild
        if ( !master_built )
        {
			OutputDebugString( "Next track: Rebuilding track lists" );
            
            build_master();
            copy_master();
            
            master_built = 1;
        }

		if(	atrack_size() == 0 )
		{
			/* Apparently Winamp crashes anyways if your playlist is all separators
			 * and you can't do anything to stop it. This is stupid. */

			OutputDebugString( "Next track: No playable tracks" );
			return -1;
		}

        index = SendMessage( plugin.hwndParent, WM_WA_IPC, 0, IPC_GETLISTPOS );
        
        // Check for any other plugin that wants to modify the next item
        // Especially JTFE
        ft_index = CallWindowProc( lpWndProcOld, hwnd, uMsg, wParam, lParam );
        
        if ( ft_index != -1 )
        {
            wsprintf( debug_string, "Next track: Fall through index: %d", ft_index );
            OutputDebugString( debug_string );
            
            if ( cfg_enabled )
            {
                history_add( index );
                copy_master();
            }
            
            return ft_index;
        }
        
        // If plugin is not enabled, let Winamp shuffle
        if ( !cfg_enabled )
        {
            return -1;
        }
        
        playlist_wnd = get_playlist_hwnd();
        
        pl_len = SendMessage( hwnd, WM_WA_IPC, 0, IPC_GETLISTLENGTH );
        
        file.fileindex = index; // This is zero indexed
        ret = SendMessage( playlist_wnd, WM_WA_IPC, IPC_PE_GETINDEXTITLE, ( LPARAM ) & file );
        
        // If it returns 0 then track information was received
        if ( !ret )
        {
            // Check the track type to determine our behavior
            
            int type = atrack_type( index );
            
            // Get playing status
            status = SendMessage( hwnd, WM_WA_IPC, 0, IPC_ISPLAYING );

            // Pretend it is paused if anything but playing. Don't include separators because they are always stopped.
            is_pause = ( status != IS_PLAY && type != IS_ALBUM_SEP && type != IS_RANDOM_SEP );
            
            if ( is_pause )
                OutputDebugString( "Next track: Is paused" );
                
            wsprintf( debug_string, "Next track: Track type: %d", type );
            OutputDebugString( debug_string );
            
            if ( ( type == IS_ALBUM || type == IS_ALBUM_SEP ) && index < pl_len - 1 )
            {
                /* Track is an album separator or is in an album. Do not shuffle. Return
                 * the next in the playlist */
                OutputDebugString( "In an album:" );
                wsprintf( debug_string, "Old index: %d", index );
                OutputDebugString( debug_string );
                
                if ( type == IS_ALBUM )
                    history_add( index );
                    
                return ( index + 1 ) % pl_len;
            }
            else
            {
                /* Track is a random separator, the end of an album, the last album separator,
				 * or in a random section.
                 * Select a random track from the remaining list */
                is_shuffle = SendMessage( hwnd, WM_WA_IPC, 0, IPC_GET_SHUFFLE );
                
                if ( is_shuffle )
                {
                    int rand_i;
                    
                    // Return random number in interval [0 atrack_size()]
                    OutputDebugString( "Next track: Not in an album / exiting an album" );
                    
                    wsprintf( debug_string, "Next track: Items remaining: %d", atrack_size() );
                    OutputDebugString( debug_string );
                    
                    // Select random entry and play the entry
                    rand_i = ( unsigned int )( atrack_size() * genrand_real2() );
                    next = rm_atrack( rand_i );
                    
                    wsprintf( debug_string, "Next track: Random selected: %d", next );
                    OutputDebugString( debug_string );
                    
                    // If the list of random tracks is empty, copy from the master list
                    if ( atrack_size() == 0 )
                    {
                        OutputDebugString( "Next track: Track list empty, rebuilding the list" );
                        copy_master();
                    }
                    
                    // Don't add separators to the history
                    if ( type == IS_ALBUM_LAST || type == IS_RANDOM )
                        history_add( index );
                        
                    return next;
                }
                else
                    return -1;
            }
        }
        return -1;
    }
    
    return CallWindowProc( lpWndProcOld, hwnd, uMsg, wParam, lParam );
}