Ejemplo n.º 1
0
inline RandGen :: RandGen (unsigned long seed_)
{
   // Set the seed for mt19937.
   //setmt19937 (seed_);
   //init_randmt (seed_);
   if (seed_ == 0) gen.seed ();
   else gen.seed (seed_);
   // Store the seed.
   _seed = gen.get_seed();
}
Ejemplo n.º 2
0
void HPRC4LikeCipher::Init(const uint8 *key, uint32 size)
{
    // align key to 32 bits
    std::vector<uint32> keycopy((size + sizeof(uint32) - 1) / sizeof(uint32));
    DEBUG(ASSERT(keycopy.size() * sizeof(uint32) >= size));
    // the last 3 bytes may be incomplete, null those before copying
    keycopy[keycopy.size() - 1] = 0;
    memcpy(&keycopy[0], key, size);

#if IS_BIG_ENDIAN
    for(uint32 i = 0; i < keycopy.size(); ++i)
        ToLittleEndian(keycopy[i]);
#endif

    MTRand mt;
    mt.seed((uint32*)&keycopy[0], keycopy.size());

    for(uint32 i = 0; i < 256; ++i)
        _sbox[i] = i | (mt.randInt() << 8); // lowest bit is always the exchange index, like in original RC4

    uint32 a = 0, b = 0;

    for(uint32 i = 0; i < std::max<uint32>(256, size); ++i)
    {
        b += key[a] + _sbox[i & 0xFF];
        iswap(_sbox[i & 0xFF], _sbox[b & 0xFF]);
        ++a;
        a %= size;
    }
}
Ejemplo n.º 3
0
static cell_t SetURandomSeed(IPluginContext *ctx, const cell_t *params)
{
	MTRand *randobj = s_RandHelpers.RandObjForPlugin(ctx);
	cell_t *addr;
	ctx->LocalToPhysAddr(params[1], &addr);
	/* We're 32-bit only. */
	randobj->seed((MTRand::uint32*)addr, params[2]);
	return 1;
}
Ejemplo n.º 4
0
void p3d_init_random_seed(int seed)
{
  // SHOULD THAT BE IN THERE ?? (TRO deadline 2016)
  std::srand((unsigned int) (seed)); // C library implementation
	mersenne_twister_rng.seed(seed);
#ifdef USE_GSL
	_gsl_seed = gsl_rng_alloc (gsl_rng_taus);
#endif
  printf("Used Seed (set user) = %u\n", seed);
}
Ejemplo n.º 5
0
int main(int argc, char* argv[])
{
    cl_parse(argc,argv);
    print_stats();

    rng.seed(seed);

    densityOperator::Params pA;
    pA.b = bA;
    pA.L = L;
    pA.Ns = Ns;
    pA.Nz = Nz;
    pA.Ny = Ny;
    pA.Nx = Nx;
    
    densityOperator::Params pB;
    pB.b = bB;
    pB.L = L;
    pB.Ns = Ns;
    pB.Nz = Nz;
    pB.Ny = Ny;
    pB.Nx = Nx;

    densOpA = new densityOperator(pA);
    densOpB = new densityOperator(pB);

    initRandom(wA);
    initRandom(wB);

    double chi_inv = 1.0 / chi;

    int padlength = tostring(nsteps).length() + 3;
    for(long long counter = 0; counter <= nsteps;counter++)
    {
        if(counter % REPORT == 0)
        {
            timer();
            cout<<"% Done: "<<fixed<<setprecision(5)<<counter<<"/"<<nsteps<<"\n";
        }

        if(counter % PICTURE == 0)
        {
            int err = writeSilo(output_prefix+"/"+tostring(counter,padlength,'0')+".silo","w",&saveSilo);
            if(err) std::cout<<"Warning: writeSilo returned errors!\n";
        }

        Array<complex<double>,3> factor1((0.5*rho_0/chi_inv)*(wB - wA));
        
        wA += dt*( Na*densOpA->solve(&wA) - factor1 );
        wB += dt*( Nb*densOpB->solve(&wB) + factor1 );
    }

    return 0;
}
Ejemplo n.º 6
0
double ran(){
  //<<<<<<< HEAD
  MTRand random;
  random.seed();
  return random.rand();
  // return rand()/double(RAND_MAX);
  //=======
  static MTRand my_mtrand;
  return my_mtrand.randExc(); // which is the range of [0,1)
  //>>>>>>> 2511a06ab322dcea9f3f70080c443d0938562932
}
Ejemplo n.º 7
0
uint p3d_init_random(void)
{
	// srand(time(NULL)); // C library implementation
  uint t = (uint)time(NULL);
  printf("Used Seed = %u\n", t);
  mersenne_twister_rng.seed(t);
#ifdef USE_GSL
	_gsl_seed = gsl_rng_alloc (gsl_rng_taus);
#endif
  return t;
}
Ejemplo n.º 8
0
void SpaceStation::Render(const vector3d &viewCoords, const matrix4x4d &viewTransform)
{
	/* Well this is nice... */
	static int poo=0;
	if (!poo) {
		poo = 1;
		LmrGetModelsWithTag("advert", s_advertModels);
	}
	// it is silly to do this every render call
	//
	// random advert models in pFlag[16 .. 19]
	// station name in pText[0]
	// docking port in pText[1]
	MTRand rand;
	rand.seed(m_sbody->seed);
	
	LmrObjParams &params = GetLmrObjParams();
	/* random advert models */
	params.argStrings[4] = s_advertModels[rand.Int32(s_advertModels.size())]->GetName();
	params.argStrings[5] = s_advertModels[rand.Int32(s_advertModels.size())]->GetName();
	params.argStrings[6] = s_advertModels[rand.Int32(s_advertModels.size())]->GetName();
	params.argStrings[7] = s_advertModels[rand.Int32(s_advertModels.size())]->GetName();
	params.argStrings[0] = GetLabel().c_str();
	SetLmrTimeParams();

	for (int i=0; i<MAX_DOCKING_PORTS; i++) {
		params.argDoubles[ARG_STATION_BAY1_STAGE + i] = double(m_shipDocking[i].stage);
		params.argDoubles[ARG_STATION_BAY1_POS + i] = m_shipDocking[i].stagePos;
	}

	RenderLmrModel(viewCoords, viewTransform);
	
	/* don't render city if too far away */
	if (viewCoords.Length() > 1000000.0) return;

	// find planet Body*
	Planet *planet;
	{
		Body *_planet = GetFrame()->m_astroBody;
		if ((!_planet) || !_planet->IsType(Object::PLANET)) {
			// orbital spaceport -- don't make city turds
		} else {
			planet = static_cast<Planet*>(_planet);
		
			if (!m_adjacentCity) {
				m_adjacentCity = new CityOnPlanet(planet, this, m_sbody->seed);
			}
			m_adjacentCity->Render(this, viewCoords, viewTransform);
		}
	}
}
Ejemplo n.º 9
0
CityOnPlanet::CityOnPlanet(Planet *planet, SpaceStation *station, Uint32 seed)
{
	m_buildings.clear();
	m_planet = planet;
	m_frame = planet->GetFrame();
	m_detailLevel = Pi::detail.cities;

	/* Resolve city model numbers since it is a bit expensive */
	if (!s_cityBuildingsInitted) {
		s_cityBuildingsInitted = true;
		for (int i=0; i<MAX_BUILDING_LISTS; i++) {
			lookupBuildingListModels(&s_buildingLists[i]);
		}
	}

	Aabb aabb;
	station->GetAabb(aabb);
	
	matrix4x4d m;
	station->GetRotMatrix(m);

	vector3d mx = m*vector3d(1,0,0);
	vector3d mz = m*vector3d(0,0,1);
		
	MTRand rand;
	rand.seed(seed);

	vector3d p = station->GetPosition();

	vector3d p1, p2, p3, p4;
	double sizex = START_SEG_SIZE;// + rand.Int32((int)START_SEG_SIZE);
	double sizez = START_SEG_SIZE;// + rand.Int32((int)START_SEG_SIZE);
	
	// always have random shipyard buildings around the space station
	cityflavour[0].buildingListIdx = 0;//2;
	cityflavour[0].center = p;
	cityflavour[0].size = 500;

	for (int i=1; i<CITYFLAVOURS; i++) {
		cityflavour[i].buildingListIdx = MAX_BUILDING_LISTS>1 ? rand.Int32(MAX_BUILDING_LISTS-1) : 0;
		citybuildinglist_t *blist = &s_buildingLists[cityflavour[i].buildingListIdx];
		double a = rand.Int32(-1000,1000);
		double b = rand.Int32(-1000,1000);
		cityflavour[i].center = p + a*mx + b*mz;
		cityflavour[i].size = rand.Int32(int(blist->minRadius), int(blist->maxRadius));
	}
	
	for (int side=0; side<4; side++) {
		/* put buildings on all sides of spaceport */
		switch(side) {
			case 3:
				p1 = p + mx*(aabb.min.x) + mz*aabb.min.z;
				p2 = p + mx*(aabb.min.x) + mz*(aabb.min.z-sizez);
				p3 = p + mx*(aabb.min.x+sizex) + mz*(aabb.min.z-sizez);
				p4 = p + mx*(aabb.min.x+sizex) + mz*(aabb.min.z);
				break;
			case 2:
				p1 = p + mx*(aabb.min.x-sizex) + mz*aabb.max.z;
				p2 = p + mx*(aabb.min.x-sizex) + mz*(aabb.max.z-sizez);
				p3 = p + mx*(aabb.min.x) + mz*(aabb.max.z-sizez);
				p4 = p + mx*(aabb.min.x) + mz*(aabb.max.z);
				break;
			case 1:
				p1 = p + mx*(aabb.max.x-sizex) + mz*aabb.max.z;
				p2 = p + mx*(aabb.max.x) + mz*aabb.max.z;
				p3 = p + mx*(aabb.max.x) + mz*(aabb.max.z+sizez);
				p4 = p + mx*(aabb.max.x-sizex) + mz*(aabb.max.z+sizez);
				break;
			default:
			case 0:
				p1 = p + mx*aabb.max.x + mz*aabb.min.z;
				p2 = p + mx*(aabb.max.x+sizex) + mz*aabb.min.z;
				p3 = p + mx*(aabb.max.x+sizex) + mz*(aabb.min.z+sizez);
				p4 = p + mx*aabb.max.x + mz*(aabb.min.z+sizez);
				break;
		}

		PutCityBit(rand, m, p1, p2, p3, p4);
	}
	AddStaticGeomsToCollisionSpace();
}
Ejemplo n.º 10
0
// seed with a provided value
void SoarSeedRNG(const uint32_t seed)
{
    gSoarRand.seed(seed);
}
Ejemplo n.º 11
0
// automatically seed with a value based on the time or /dev/urandom
void SoarSeedRNG()
{
    gSoarRand.seed();
}
Ejemplo n.º 12
0
//----------------------------------------------------------------------
//
//   Function to generate rough surfaces (optionally unique) between
//   multiple materials at the interface of min/max.
//
//   A local height is defined which overrides the min/max values of
//   the extent of the material as defined in the material file. No
//   atoms are added or removed by the process, but this will override
//   structural effects such as core-shell systems.
//
//   The roughness is generated by creating seed points with a random
//   radius with a flat distribution around the mean. Within this
//   radius a stepwise change in the local height is defined, again
//   Gaussian distributed with a mean step height of zero. A maximum
//   Height is specified which truncates outlying values. Typical
//   values of the maximum step height would be 1-5 monolayers.
//
//   The seed points are used to generate a 2D array defining the local
//   height for any point in space. A loop over all atoms then reassigns
//   atoms to materials according to the local height, overriding the
//   materials set in the crsytal.
//
//------------------------------------------------------------------------
//
void roughness(std::vector<cs::catom_t> & catom_array){

	// Output instructuve message to log file
	zlog << zTs() << "Calculating interfacial roughness for generated system." << std::endl;

	// Construct a 2D array of height according to roughness resoution
	const double resolution=cs::interfacial_roughness_height_field_resolution; // Angstroms
	const unsigned int seed_density=cs::interfacial_roughness_seed_count;
	const double seed_radius=cs::interfacial_roughness_mean_seed_radius;
	const double seed_height_mean=cs::interfacial_roughness_mean_seed_height;
	const double seed_height_max=cs::interfacial_roughness_seed_height_max;
	const double seed_radius_variance=cs::interfacial_roughness_seed_radius_variance;

	// Declare array to store height field
	std::vector<std::vector<double> >height_field(0);

	// Calculate size of height_field array
	double nx = int(vmath::iceil(cs::system_dimensions[0]/resolution));
	double ny = int(vmath::iceil(cs::system_dimensions[1]/resolution));

	// Resize height_field array
	height_field.resize(nx);
	for(int i=0; i<nx; i++) height_field.at(i).resize(ny);

	// Generate seed points and radii
	std::vector<seed_point_t> seed_points(0);

	// Define local random generator for surface roughness
	MTRand rgrnd;

	// Initialise random number generator
	rgrnd.seed(cs::interfacial_roughness_random_seed);

	for(unsigned int p=0; p < seed_density ; p++){
		// Generate random point coordinates
		double x=rgrnd()*cs::system_dimensions[0];
		double y=rgrnd()*cs::system_dimensions[1];

		// Generate random radius with flat profile r = r0 +/- variance*rnd()
		double r=seed_radius*(1.0+seed_radius_variance*(2.0*rgrnd()-1.0));

		// Generate random height with gaussian profile
		double h=seed_height_mean*mtrandom::gaussianc(rgrnd);

		// Overwrite generated height if greater than maximum
		if(fabs(h)>seed_height_max) h=vmath::sign(h)*seed_height_max;

		// Check for type of roughness
		// Troughs
		if(cs::interfacial_roughness_type==-1) h = -1.0*fabs(h);
		// Peaks
		else if(cs::interfacial_roughness_type==1) h = fabs(h);

		// Save point characteristics to array
		seed_point_t tmp;
		tmp.x = x;
		tmp.y = y;
		tmp.radius = r;
		tmp.height = h;
		seed_points.push_back(tmp);
	}

	// Now apply seed points to generate local height field
	// Loop over all height field coordinates
	for(int ix = 0; ix < nx; ix++){
		for(int iy = 0; iy < ny; iy++){

			const double x = double(ix)*resolution; // real space coordinates
			const double y = double(iy)*resolution;

			// Loop over all seed points
			for(unsigned int p=0; p < seed_density ; p++){
				double rx=x-seed_points.at(p).x;
				double ry=y-seed_points.at(p).y;

				// Check for point in range
				if(rx*rx+ry*ry <= seed_points.at(p).radius*seed_points.at(p).radius) height_field.at(ix).at(iy)=seed_points.at(p).height;
			}
		}
	}

	// Assign materials to generated atoms
	for(unsigned int atom=0;atom<catom_array.size();atom++){

		// Determine height field coordinates
		const int hx = int(catom_array[atom].x/resolution);
		const int hy = int(catom_array[atom].y/resolution);

		// Loop over all materials and determine local height
		for(int mat=0;mat<mp::num_materials;mat++){

			double min=create::internal::mp[mat].min*cs::system_dimensions[2];
			double max=create::internal::mp[mat].max*cs::system_dimensions[2];
			double local_height = height_field.at(hx).at(hy);
         bool fill = mp::material[mat].fill;

			// optionally specify a material specific height here -- not yet implemented
			//if(cs::interfacial_roughness_local_height_field==true){
			//double local_height = height_field.at(mat).at(hx).at(hy);
			//}
         const int atom_uc_cat = catom_array[atom].uc_category;
         const int mat_uc_cat = create::internal::mp[mat].unit_cell_category;

			// Include atoms if within material height
			const double cz=catom_array[atom].z;
			if((cz>=min+local_height) && (cz<max+local_height) && (fill==false)  && (atom_uc_cat == mat_uc_cat) ){
				catom_array[atom].material=mat;
				catom_array[atom].include=true;
			}
		}
	}

	return;

}
Ejemplo n.º 13
0
int main (int argc, char *argv[]) {

	setlocale(LC_NUMERIC,"en_US"); //TR Check whether or not it can be removed when C++ standard

	MTRand rndDoubleGen; /// double random number generator

	/*---------------\
    |                |
	| INITIALIZATION |
    |       		 |
	\ --------------*/ 

	/*----------------
		CREATE ENVIRONMENT
		-----------------*/ 

	// Declare and inizialize the environment
	environment* puddle = new environment(argv[1]);

	//INITIZIALIZE PSEUDO RANDOM NUMBER GENERATOR
	rndDoubleGen.seed(puddle->getRandomSeed());

	/*----------------------------------
		CREATE INITIAL MOLECULE POPULATION
		----------------------------------*/

	//LOAD SPECIES FROM FILE
	if(!puddle->createInitialMoleculesPopulationFromFileSTD(argv[3], rndDoubleGen))
		ExitWithError("createInitialMoleculesPopulationFromFile", "Problem with the species STANDARD loading process");
	// LOAD INFLUX LAYERS FROM FILE (if the system is open with a simulated flux)

	if((puddle->getSysArch() == PROTOCELLFLUXFINITE) || (puddle->getSysArch() == CSTRSYSTEM))
	{
		if(!puddle->createInfluxLayersFromFileSTD(argv[3]))
			ExitWithError("CreateInfluxLayersFromFile", "Problem with influx layers loading process");
	}

	// LOAD BOOLEAN FUNCTION CONCERNING THE ENERGY CONFIGURATION
	if(puddle->getEnergy() <= 1)
	{
		//if(!puddle->createNrgBooleanFunctionsFromFile(a.arguments().at(3)))
		if(!puddle->createNrgBooleanFunctionsFromFileSTD(argv[3]))
			ExitWithError("createNrgBooleanFunctionsFromFile", "Problem with rct Bool fncs loading process");
	}
	//LOAD REACTIONS STRUCTURE FROM FILE (standard C++ libraries)
	if(!puddle->createInitialReactionsLayerFromFileSTD(argv[3]))
		ExitWithError("createInitialReactionLayerFromFile", "Problem with the reactions loading process");

	//LOAD CATALYSIS STRUCTURE FROM FILE (catalysis links species with reactions catalyzed)
	if(!puddle->createInitialCatalysisLayerFromFileSTD(argv[3]))
		ExitWithError("createInitialCatalysisLayerFromFile", "Problem with the catalysis loading process");

	if(puddle->getDebugLevel() >= MEDIUM_DEBUG){puddle->printInitialCondition();}

	// SAVE TO FILE INITIAL CONDITIONS
	saveInitialConditionsToFile(argv[2], puddle, 0, 0, 0);

	if(!puddle->structureCoherenceCheckUp())
	{
		cout << endl;
		ExitWithError("structureCoherenceCheckUp", "PROBLEM WITH STRUCTURE COHERENCE... THE SIMULATION WILL BE ABORTED!!!");
	}


	// - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - 

	/*------------\
	|            |
	| SIMULATION |
	|            |
	\ ----------*/

	//STORE INITIAL STRUCTURES DATA IN ORDER TO REINITIALIZE THE STRUCTURE AFTER EACH SIMULATION
	puddle->storeInitialStructures();

	Timer timer;
	acs_double timeElapsed;

	if(puddle->getDebugLevel() >= RUNNING_VERSION)
	{
		cout << endl;
		cout << "*** SIMULATION START ***" << endl;
		cout << endl;
	}

	// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	// SIMULATIONS
	// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+

	acs_int totalNumberOfSimulations = puddle->getNsim(); // Simulation counter
	acs_int totalNumberOfGenerations = puddle->getNgen(); // generation are not used now (it will be usefull with protocell division)
	acs_int actSTEP; // declare simulation step
	acs_int previousStepLastStructuresSaving; // declare previousStep
	acs_int previousStepLastTimesSaving; // declare previousStep
	acs_int previousStepLastAmountSaving; // declare previousStep
	acs_int previousStepLastBufferTimesSaving; // declare previousStep
	acs_int previousStepLastBufferRctSaving; // declare previousStep
	acs_int previousStepLastBufferAmountSaving; // declare previousStep
	bool growing = false; // This variable is used to stop the growth of the protocell

	for(acs_int actSIM = 1; actSIM <= puddle->getNsim(); actSIM++)
	{
		if(puddle->getDebugLevel() >= RUNNING_VERSION){cout << "\n|- - - - - - - - - - - - - - - " << endl;}
		if(puddle->getDebugLevel() >= RUNNING_VERSION){cout << "|- SIMULATION NUMBER " << actSIM << endl;}
		if(puddle->getDebugLevel() >= RUNNING_VERSION){cout << "|- - - - - - - - - - - - - - - \n" << endl;}


		// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		// GENERATIONS PER SIMULATIONS
		// +-+-+-+-+-+-+-+-+-+-+-+-+-+-


		for(acs_int actGEN = 1; actGEN <= totalNumberOfGenerations; actGEN++)
		{
			if(puddle->getVolumeGrowth()) growing = true;
			// IF THE ATTEMPTS ARE MORE THAN THE MAX NUMBER THIS SIMULATION IS STOPPED
			if((puddle->getCurrentAttempts() <= puddle->getMAXattempts()) || (puddle->getMAXattempts() == 0))
			{
				if(actGEN > 1)
				{
					// Reset structures stats and set concentrations to initial values
					puddle->resetConcentrationToInitialConditions(rndDoubleGen);
					puddle->clearGilScores();
					saveToFile(argv[2], puddle, actGEN, actSIM, 0);

				}
				acs_double dataStoredCounter = 0;
				acs_double TimesStoredCounter = 0;
				acs_double AmountsStoredCounter = 0;
				acs_int bufferTimesCountRow = 0;
				acs_int bufferSpeciesCountRow = 0;
				if(puddle->getDebugLevel() >= MINIMAL_PROMPT)
				{
					cout << "|- GEN NUMBER " << actGEN << " OF " << puddle->getNgen()
                         << " - SIM NUMBER " << actSIM << " OF " << totalNumberOfSimulations << endl;
				}

				// start timer
				timer.start();
				actSTEP = 1;
				previousStepLastStructuresSaving = 1;
				previousStepLastTimesSaving = 1;
				previousStepLastAmountSaving = 1;
				previousStepLastBufferTimesSaving = 1;
				previousStepLastBufferRctSaving = 1;
				previousStepLastBufferAmountSaving = 1;

				// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
				// SECONDS / REACTIONS PER GENERATION
				// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

				while(((puddle->getActualTime() <= puddle->getNseconds()) & (actSTEP <= puddle->getNreactions()) & (puddle->getVolumeGrowth() == 0))
						||
						growing)
				{
					timer.stop();
					timeElapsed = timer.getElapsedTimeInMilliSec();
					// IF PROTOCELL CHECK THE OVERALL CONCENTRATION. If the concentration is greater than a threshold, we assume that the protocell is going to be a stone and
					// the simulaiton is stopped.
					// double(puddle->getMols()+puddle->getNcpxMols())/(puddle->getVolume()*AVO)
					if(puddle->getTheta() > 0){

						if(double(puddle->getMols()+puddle->getNcpxMols())/(puddle->getVolume()*AVO) > MAXALLOWCONCENTRATION){
							cout << endl << endl <<  "-----------------------------------------------------------------------" << endl;
							cout << "| WARNING :: The protocell is going to be a stone, simulation will be stopped   |" << endl;
							cout << "-----------------------------------------------------------------------" << endl;
							ExitWithError("warning in overall concentration in protocell","main");
						}

					}

					// IF NUMBER OF MILLISECONDS IS LESS THAN THE MAX NUMBER
					if(( timeElapsed < (puddle->getMAXhours()*60*60)) || (puddle->getMAXhours() == 0))
					{
						//GILLESPIE COMPUTATION (CORE OF THE SOFTWARE)
						if(puddle->getDebugLevel() == SMALL_DEBUG)cout << "Step " << actSTEP << endl;
						try{
							// IF the system can expand its structures, se the old gillespie algorithm must be used
							if(puddle->getSystemExpFlag())
							{
								if(!puddle->performOPTGillespieComputation(rndDoubleGen, timer, actGEN, actSIM, actSTEP, argv[2]))
									ExitWithError("performGillespieComputation", "Problems with the Gillespie computation");
							}else{ // If structures are fixed new optimized Gillespie algorithm can be used
								if(!puddle->perform_FIXED_GillespieComputation(rndDoubleGen, timer, actGEN, actSIM, actSTEP, argv[2]))
									ExitWithError("performGillespieComputation", "Problems with the Gillespie computation");
							}
						}catch(exception&e){
							cout << "Source Code Line: " << __LINE__ << endl;
							cerr << "exceptioncaught:" << e.what() << endl;
							ExitWithError("MAIN function __ Gillespie computation","exceptionerrorthrown");
						}
						if(puddle->getDebugLevel() == SMALL_DEBUG)
							puddle->showGillEngagementInSpecies();

						// DISPLAY SIMULATION CONTROL VARIABLES
						if(puddle->getDebugLevel() >= RUNNING_VERSION)
						{
							if((actSTEP % PROMPT_TIME == 0) || (actSTEP == 1) ||
									(puddle->getMols() == puddle->getOverallLoadedMolsCounter()))
							{
								timer.stop();
								cout<< "--------------------------------------------------------------------" << endl
										<< "G: "<< actGEN << "/" << totalNumberOfGenerations
										<< " - S: " << actSIM << "/" << totalNumberOfSimulations
										<< " - T: " << puddle->getActualTime() << "/" << puddle->getNseconds()
										<< " - R: " << actSTEP // << "/" << puddle->getNreactions()
										<< " - CT (seconds): " << timer.getElapsedTimeInSec()
										<< " - Gill: " << puddle->getNumberOfGillespieCOPYpossibleRcts() << endl
										<< "\t- ENVIRONMENT" << endl
										<< "\t\t|- Volume: " << puddle->getVolume()
										<< " - Surface: " << puddle->getSurface()
										<< " - Lipids: " << puddle->getLipids() << endl
										<< "\t\t|- S: " << puddle->getNspecies()
										<< " - NS: " << puddle->getNnewSpecies()
										<< " - M: " << puddle->getMols()
										<< " - NM: " << puddle->getNewMols() << endl
										<< "\t\t|- Cp: " << puddle->getNcpx()
										<< " - #Cp: " << puddle->getNcpxMols() << endl
										<< "\t\t|- M: " << puddle->getTotalNumberOfMonomers()
										<< " - Mols+Complex: " << puddle->getMols() + puddle->getNcpxMols()
										<< " - Tot Conc: " << double(puddle->getMols()+puddle->getNcpxMols())/(puddle->getVolume()*AVO) << endl
										<< "\t- ENERGY" << endl
										<< "\t\t|- Loaded Mols: " << puddle->getOverallLoadedMolsCounter()
										<< " - Loaded (second Method): " << puddle->getTotNumberOfChargedMols() << endl
										<< "\t- GILLESPIE INFO" << endl
										<< "\t\t|- Gil Mean: " << puddle->getGillespieMean()
										<< " - Gil SD: " << puddle->getgillespieSD()
										<< " - Gil Entropy: " << puddle->getgillespieEntropy() << endl
										<< "\t\t|- Gil NS ratio: " << puddle->getRatioBetweenNewGillTotGill()
										<< " - Back and Forw Ratio: " << puddle->getRatioBetweenBackandForw() << endl
										<< "\t- REACTIONS COUNTERS" << endl
										<< "\t\t|- Theoretical Average Connectivity:" << (double)puddle->getNumberOfCatalysis() / puddle->getTotalNumberOfPossibleCatalysts() << endl
										<< "\t\t|- Cond: " << puddle->getCondensationCounter()
										<< " - Endo Cond: " << puddle->getEndoCondensationCounter() << endl
										<< "\t\t|- Cleav: " << puddle->getCleavageCounter()
										<< " - Endo Cleav: " << puddle->getEndoCleavageCounter() << endl
										<< "\t\t|- Spont Cleav: " << puddle->getSpontDissCounter()
										<< " - Spont Cond: "<< puddle->getSpontAssCounter() << endl
										<< "\t\t|- Cpx: " << puddle->getCpxFormCounter()
										<< " - Cpx Diss: " << puddle->getCpxDissCounter() << endl;

							}
						}

						// SAVE STRUCTURES TO FILE EVERY puddle->getTimeStructuresSavingInterval() SECONDS
						if(puddle->getActualTime() >= (puddle->getTimeStructuresSavingInterval() + dataStoredCounter) &&
								(puddle->getTimeStructuresSavingInterval() >= 0))
						{
							saveToFile(argv[2], puddle, actGEN, actSIM, actSTEP);
							dataStoredCounter = dataStoredCounter + puddle->getTimeStructuresSavingInterval();
							previousStepLastStructuresSaving = actSTEP; // save last step moment
						}

						// STORE ON FILE TIMES EVERY fileTimesSaveInterval seconds (if at least something happen)
						if(((puddle->getActualTime() >= (puddle->getFileTimesSavingInterval() + TimesStoredCounter)) ||
								(puddle->getActualTime() == 0) || (puddle->getFileTimesSavingInterval() == 0)) &&
								(puddle->getFileTimesSavingInterval() >= 0))
						{
							//cout << puddle->getActualTime() << " " << puddle->getFileTimesSavingInterval() << " " << TimesStoredCounter << endl;
							puddle->saveTimesSTD(actSTEP);
							if(puddle->getActualTime() > 0)
							{
								TimesStoredCounter = TimesStoredCounter + puddle->getFileTimesSavingInterval();
								previousStepLastTimesSaving = actSTEP;
							}
							bufferTimesCountRow++;
						}

						// STORE SPECIES AMOUNTS
						if(((puddle->getActualTime() > (puddle->getFileAmountSavingInterval() + AmountsStoredCounter)) ||
						   (puddle->getActualTime() == 0) ||  (puddle->getFileAmountSavingInterval() == 0)) &&
						   (puddle->getFileAmountSavingInterval() >= 0))
						{
							//saveLivingSpeciesIDSTD(tmp_ActGEN, tmp_ActSIM, tmp_ActSTEP, tmp_StoringPath);
							//saveLivingSpeciesAmountSTD(tmp_ActGEN, tmp_ActSIM, tmp_StoringPath);
							//saveLivingSpeciesConcentrationSTD(tmp_ActGEN, tmp_ActSIM, tmp_StoringPath);
							puddle->saveTimeSpeciesAmountSTD(actSTEP);
							if(puddle->getActualTime() > 0) {
								AmountsStoredCounter += puddle->getFileAmountSavingInterval();
								previousStepLastAmountSaving = actSTEP;
							}
							bufferSpeciesCountRow++;
						}

						//write times and reactions parameter to files
						if(bufferTimesCountRow == N_BUFFER) {
							//save data buffers to file
							puddle->saveTimeReactionBuffersToFile(actGEN, actSIM, argv[2]);
							previousStepLastBufferTimesSaving = actSTEP;
							bufferTimesCountRow = 0;
						}

						//write reactions parameter to files getBufferRctsCountRow
						if(puddle->getBufferRctsCountRow() == N_BUFFER) {
							//save data buffers to file
							puddle->saveReactionBuffersToFile(actGEN, actSIM, argv[2]);
							previousStepLastBufferRctSaving = actSTEP;
							puddle->setBufferRctsCountRow(0);
						}

						//write timeSpeciesAmount to files
						if(bufferSpeciesCountRow == N_BUFFER) {
							//save data buffers to file
							puddle->saveAmountBuffersToFile(actGEN, actSIM, argv[2]);
							previousStepLastBufferAmountSaving = actSTEP;
							bufferSpeciesCountRow = 0;
						}

						actSTEP++; // step update

					}else{ // if(( (((float)clock() - tStart) / CLOCKS_PER_SEC) < (puddle->getMAXhours()*60*60)) || (puddle->getMAXhours() == 0))
						// Increase number of attempts
						puddle->increaseAttempts();
						puddle->resetConcentrationToInitialConditions(rndDoubleGen);
						puddle->clearGilScores();
						// STOP WHILE
						actGEN = actGEN - 1;
						break;

					}
					// If necessary, check the volume condition
					if(puddle->getTheta() > 0)
					{
						//if(puddle->getInitVolume()*puddle->getTheta() < puddle->getVolume()){growing = false;}
						if(puddle->getInitLipids()*puddle->getTheta() < puddle->getLipids()){growing = false;}
					}
				} // while((puddle->getActualTime() <= puddle->getNseconds()) & (actSTEP <= puddle->getNreactions()) & growing)

				// Final species ages update
				puddle->updateSpeciesAges();

				// SAVE FINAL STRUCTURES TO FILE if actSTEP is different from the previous one
				if(previousStepLastStructuresSaving < actSTEP-1)
					saveToFile(argv[2], puddle, actGEN, actSIM, actSTEP);

				if(previousStepLastTimesSaving < actSTEP-1)
					puddle->saveTimesSTD(actSTEP);

				if(previousStepLastAmountSaving < actSTEP-1)
					puddle->saveTimeSpeciesAmountSTD(actSTEP);

				if(previousStepLastBufferTimesSaving < actSTEP-1)
					puddle->saveTimeReactionBuffersToFile(actGEN, actSIM, argv[2]);

				if((previousStepLastBufferRctSaving < actSTEP-1) && puddle->getsaveReactionParameters())
					puddle->saveReactionBuffersToFile(actGEN, actSIM, argv[2]);

				if(previousStepLastBufferAmountSaving < actSTEP-1)
					puddle->saveAmountBuffersToFile(actGEN, actSIM, argv[2]);


				//CHECK STRUCTURES, THE COHERENCE OF THE INTERNAL STRUCTURES ARE CONTROLLED
				if(!puddle->structureCoherenceCheckUp())
				{
					cout << endl;
					ExitWithError("structureCoherenceCheckUp", "PROBLEM WITH STRCTURE COHERENCE... BE CARE TO THE SIMULATION OUTCOMES!!!");
				}
			}else{ // for if(puddle->getCurrentAttempts() <= puddle->getMAXattempts())
				// SIMULATION IS STOPPED
				ExitWithError("MAIN", "FATAL ERROR: The number of MAXIMUM attempts has been exceeded!!!");
				break;

			}
		} // end for(acs_int actGEN = 1; actGEN <= puddle->getNgen(); actGEN++)
		// RESET STRUCTURES and TIME TO THE INITIAL VALUES FOR THE NEXT SIMULATION
		puddle->clearAllStructures();
		puddle->clearGilScores();
	} // end for(acs_int actSIM = 1; actSIM <= puddle->getNsim(); actSIM++)

	//DELETE ALL MAIN HEAP OBJECTS
	delete puddle;
	return 0;
}
Ejemplo n.º 14
0
int main(){

	//clock_t CPUtime=clock();
	//time_t walltime=time(NULL);
	//read parameters from a file
	ifstream infile;
	infile.open("params");
	int Lx=value_from_file(infile,3);
//	cout<<this->nrows()<<endl;
	double Jx=value_from_file(infile,1.);
	double hx=value_from_file(infile,1.);
	double hy=value_from_file(infile,1.);
	double hz=value_from_file(infile,1.);
	#ifndef USE_COMPLEX
	if(hy!=0){
		cout<<"you can't use hy!=0 if you don't enable complex numbers!"<<endl;
		exit(0);
	}
	#endif	
	int seed=value_from_file(infile,1);
	infile.close();

	//setup random coefficients
	MTRand ran;
	ran.seed(seed);
	vector<double> alphax=vector<double>(Lx,0);
	vector<double> alphay=vector<double>(Lx,0);
	vector<double> alphaz=vector<double>(Lx,0);
	ofstream datfile;
	datfile.open("nicrans");
	for(int i=0; i<Lx; i++){
		alphax[i]= 2.*hx*(ran.rand()  -0.5);
		alphay[i]= 2.*hy*(ran.rand()  -0.5);
		alphaz[i]= 2.*hz*(ran.rand()  -0.5);
//getting random alphas from a file file sent by nicolas
		datfile<<setprecision(14)<<alphax[i]<<" "<<alphay[i]<<" "<<alphaz[i]<<endl;
//		cout<<alphax[i]<<" "<<alphay[i]<<" "<<alphaz[i]<<endl;
	}
	datfile.close();

#ifdef USE_COMPLEX
	MatrixTFIM< complex<double> > A(Lx,1,Jx,Jx,Jx,alphax,alphay,alphaz,-1);
#else
	MatrixTFIM<double> A(Lx,1,Jx,Jx,0,alphax,alphay,alphaz,Lx/2);
#endif

	bool sparseSolve=false;
	if(Lx>14) sparseSolve=true;
	int N_output_states,start,end;
	if(!sparseSolve){	
		A.makeDense();
		N_output_states=A.nrows();
		A.EigenDenseEigs();
		start=A.nrows()/3; end=2*A.nrows()/3;
	}
	else{
		N_output_states=1000;
		N_output_states=A.eigenvalues(N_output_states,0.1);
		start=0; end=N_output_states;
	}
	A.energy_spacings();
	//start=0; end=A.nrows();
	A.entanglement_spacings(start,end,A.rangeToBitstring(0,Lx/2),-100,Lx/4);
	//cout<<"total time is"<<(float)(clock()-CPUtime)/CLOCKS_PER_SEC<<" CPU time and "<<time(NULL)-walltime<<" walltime"<<endl;
}