Exemplo n.º 1
0
double poisdev(const double xm)
{
	const double PI=3.141592653589793238;
	static double sq,alxm,g,oldm=(-1.0);
	double em,t,y;

	if (xm < 12.0) {
		if (xm != oldm) {
			oldm=xm;
			g=exp(-xm);
		}
		em = -1;
		t=1.0;
		do {
			++em;
			t *= rnd.rand();;
		} while (t > g);
	} else {
		if (xm != oldm) {
			oldm=xm;
			sq=sqrt(2.0*xm);
			alxm=log(xm);
			g=xm*alxm-gammln(xm+1.0);
		}
		do {
			do {
				y=tan(PI*rnd.rand());
				em=sq*y+xm;
			} while (em < 0.0);
				em=floor(em);
				t=0.9*(1.0+y*y)*exp(em*alxm-gammln(em+1.0)-g);
		} while (rnd.rand() > t);
	}
	return em;
}
Exemplo n.º 2
0
void runServerIO()
{
	SOCKET c = Network::instance()->socket(AF_INET,SOCK_STREAM,IPPROTO_TCP,false);
	sockaddr_in serverEP = {0};
	serverEP.sin_family = AF_INET;
	serverEP.sin_addr.s_addr = ::inet_addr("127.0.0.1");
	serverEP.sin_port = ::htons(65534);

	try {
		Network::instance()->connect(c,serverEP);
	} catch (const NetworkException& e) {
		LOG(Error) << e.what();
		Network::instance()->closeSocket(c);
		::InterlockedIncrement(&failed);
		return;
	}

	// Fill Data
	MTRand r;
	const int MAX = 1 >> 16;
	std::vector<char> data(MAX);
	for (int i = 0; i < MAX; ++i) {
		data[i] = static_cast<char>(r.rand(255));
	}

	// Send and receive data in random chunks
	int recvd = 0;
	int sent = 0;
	std::vector<char> echo(MAX);
	while (sent < MAX) {
		int nBytes = 1 + static_cast<int>(r.rand(MAX - sent - 1));

		try {
			sent += Network::instance()->send(c, &data[sent], nBytes);
		} catch(const NetworkException& e) {
			LOG(Error) << e.what();
		}

		while (recvd < sent) {
			try {
				recvd += Network::instance()->recv(c, &echo[recvd], nBytes);
			} catch(const NetworkException& e) {
				LOG(Error) << e.what();
			}
		}
		CHECK(sent == recvd);
	}

	for (int i = 0; i < MAX; ++i) {
		CHECK(data[i] == echo[i]);
	}

	Network::instance()->closeSocket(c);
	::InterlockedIncrement(&succeeded);
}
Exemplo n.º 3
0
Point GridDatabase2D::randomPositionInRegionWithoutCollisions(const AxisAlignedBox & region, float radius, bool excludeAgents,  MTRand & randomNumberGenerator)
{
	Point ret(0.0f, 0.0f, 0.0f);
	bool notFoundYet;
	unsigned int numTries = 0;
	float xspan = region.xmax - region.xmin - 2*radius;
	float zspan = region.zmax - region.zmin - 2*radius;

	do {

		ret.x = region.xmin + radius + ((float)randomNumberGenerator.rand(xspan));
		ret.y = 0.0f;
		ret.z = region.zmin + radius + ((float)randomNumberGenerator.rand(zspan));

		// assume this new point has no collisions, until we find out below
		notFoundYet = false;

		// check if ret collides with anything
		set<SpatialDatabaseItemPtr> neighbors;
		neighbors.clear();
		float _new_radius = radius;
		getItemsInRange(neighbors, ret.x - _new_radius, ret.x + _new_radius, ret.z - _new_radius, ret.z + _new_radius, NULL);

		set<SpatialDatabaseItemPtr>::iterator neighbor;
		/*
		 * increment must be after loop body or (*neighbor)->isAgent()) will be called on an
		 * element that is beyond the set.
		 */
		for (neighbor = neighbors.begin(); neighbor != neighbors.end(); neighbor++)
		{
			if ((excludeAgents) && ((*neighbor)->isAgent()))
			{
				continue;
			}
			notFoundYet = (*neighbor)->overlaps(ret, radius);
			if (notFoundYet)
			{
				break;
			}
		}
		numTries++;
		if (numTries > 1000)
		{
			cerr << "ERROR: trying too hard to find a random position in region.  The region is probably already too dense." << endl;
			if (numTries > 10000)
			{
				throw GenericException("Gave up trying to find a random position in region.");
			}
		}
	} while (notFoundYet);

	return ret;
}
Exemplo n.º 4
0
Util::Point GridDatabase2D::randomPositionInRegion(const Util::AxisAlignedBox & region, float radius,MTRand & randomNumberGenerator)
{
	Point ret(0.0f, 0.0f, 0.0f);
	float xspan = region.xmax - region.xmin - 2*radius;
	float zspan = region.zmax - region.zmin - 2*radius;

	ret.x = region.xmin + radius + ((float)randomNumberGenerator.rand(xspan));
	ret.y = 0.0f;
	ret.z = region.zmin + radius + ((float)randomNumberGenerator.rand(zspan));

	return ret;
}
Exemplo n.º 5
0
double binldev(const double pp, const int n)
{
	const double PI=3.141592653589793238;
	int j;
	static int nold=(-1);
	double am,em,g,angle,p,bnl,sq,t,y;
	static double pold=(-1.0),pc,plog,pclog,en,oldg;

	p=(pp <= 0.5 ? pp : 1.0-pp);
	am=n*p;
	if (n < 25) {
		bnl=0.0;
		for (j=0;j<n;j++)
			if (rnd.rand() < p) ++bnl;
	} else if (am < 1.0) {
		g=exp(-am);
		t=1.0;
		for (j=0;j<=n;j++) {
			t *= rnd.rand();
			if (t < g) break;
		}
		bnl=(j <= n ? j : n);
	} else {
		if (n != nold) {
			en=n;
			oldg=gammln(en+1.0);
			nold=n;
		} if (p != pold) {
			pc=1.0-p;
			plog=log(p);
			pclog=log(pc);
			pold=p;
		}
		sq=sqrt(2.0*am*pc);
		do {
			do {
				angle=PI*rnd.rand();
				y=tan(angle);
				em=sq*y+am;
			} while (em < 0.0 || em >= (en+1.0));
			em=floor(em);
			t=1.2*sq*(1.0+y*y)*exp(oldg-gammln(em+1.0)
				-gammln(en-em+1.0)+em*plog+(en-em)*pclog);
		} while (rnd.rand() > t);
		bnl=em;
	}
	if (p != pp) bnl=n-bnl;
	return bnl;
}
Exemplo n.º 6
0
  const TwitterEdge operator()(const TwitterEdge & x) const
  {
	short mycount = 1;
	bool myfollow = 0;
	time_t mylatest = static_cast<int64_t>(GlobalMT.rand() * 10000);	// random.randrange(0,10000)

	return TwitterEdge(mycount, myfollow, mylatest);
  }
Exemplo n.º 7
0
/**************************************************************************//**
 *  Return a random position close to the supplied one.
******************************************************************************/
dVec Cylinder::randUpdate (MTRand &random, const dVec &pos) const {
    dVec randPos;
    if (random.rand() < 0.5)
        randPos = randUpdateJumpShell(random,pos);
    else
        randPos = randUpdateSmall(random,pos);
    return randPos;
}
Exemplo n.º 8
0
/**************************************************************************//**
 *  Return a random position close to the supplied one. Same Shell.
******************************************************************************/
dVec Cylinder::randUpdateSmall (MTRand &random, const dVec &pos) const {
    dVec randPos;
    randPos = pos;
    for (int i = 0; i < NDIM; i++)
        randPos[i] += constants()->displaceDelta()*(-0.5 + random.rand());
    putInside(randPos);
    return randPos;
}
Exemplo n.º 9
0
double p3d_random(double a, double b)
{double v;
	
	// C library implementation
	// v =  rand()/((double)RAND_MAX+1); /* nombre aleatoire [0.,1.] */
	v = mersenne_twister_rng.rand();
	v = (b-a)*v + a;
	return(v);
}
Exemplo n.º 10
0
void GenericLayer::initNeurons() {
	this->neurons.clear();
	this->neurons.resize(numNeurons);
	MTRand mt;
	
//	#pragma omp parallel for if(this->numNeurons > 500)
	for (int i=0; i<this->numNeurons; ++i) {
		this->neurons.at(i).biasWeight = mt.rand(2)-1.0f;
	}
}
Exemplo n.º 11
0
// 	a clock can be intialized with source data (parents)
bioClock::bioClock (bioClock source1, bioClock source2)
{
    //  creates an MTRand that can make random numbers
    MTRand randGen;
    double randNum;
    double remainingPercent;

    //  initialize survival score
    mSurvivalScore = 0;

    //  initialize number of working hands
    mNumHands = 0;

    //  get the genome size from one of the parents (doesn't really matter which one)
    mGenomeSize = source1.mGenomeSize;
    mClockGenome.resize(mGenomeSize);

    //  get mutation rate from a parent (doesn't matter which one)
    mMutationRate = source1.mMutationRate;

    //  fill genome with either a random (mutated) gene, or an equal chance of a mother's or father's gene
    for (int i = 0; i < mGenomeSize; i++)
    {
        mClockGenome[i].resize(mGenomeSize);
        for (int j = 0; j < mGenomeSize; j++)
        {
            //  random real number from 0-1
            randNum = randGen.rand();

            //  calculate remaining percent left after accounting for mutation rate
            remainingPercent = 1 - (mMutationRate / 100);

            //  create a random piece upon mutation
            if (randNum > remainingPercent)
            {
                clockPiece tempPiece;
                mClockGenome[i][j] = tempPiece;
            }
            //  otherwise it's split 50/50 for inheritance of traits from mother or father
            //  copy the piece from parent
            else if (randNum > (remainingPercent / 2))
                mClockGenome[i][j] = source1.mClockGenome[i][j];
            else
                mClockGenome[i][j] = source2.mClockGenome[i][j];

            //  reset connection status of copied piece
            mClockGenome[i][j].mIsConnected = false;

            //  reset more data for gears
            mClockGenome[i][j].setIsPowered(false);
            mClockGenome[i][j].setIsAttToHand(false);
            mClockGenome[i][j].setPieceInterval(0);
        }
    }
}
Exemplo n.º 12
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
}
void PhotonMapping::TracePhoton(const Vec3f &position, const Vec3f &direction, 
				const Vec3f &energy, int iter) {


  // ==============================================
  // ASSIGNMENT: IMPLEMENT RECURSIVE PHOTON TRACING
  // ==============================================

  // Trace the photon through the scene.  At each diffuse or
  // reflective bounce, store the photon in the kd tree.

  // One optimization is to *not* store the first bounce, since that
  // direct light can be efficiently computed using classic ray
  // tracing.

  //do ray cast
  Ray r(position,direction*(1/direction.Length()));
  Hit h;
  raytracer->CastRay(r,h,true);
  if (h.getT()>1000)
	  return;
  MTRand mtrand;
  Vec3f refl = h.getMaterial()->getReflectiveColor();
  Vec3f diff = h.getMaterial()->getDiffuseColor();
  double ran=mtrand.rand();
  if (iter==0)
	  ran= mtrand.rand(refl.Length()+diff.Length());
  //std::cout<<iter<<" "<<h.getT()<<" "<<refl.Length()+diff.Length()<<std::endl;
  //send reflective photon
  if (iter<args->num_bounces&&ran<=refl.Length())
	  TracePhoton(r.pointAtParameter(h.getT()),r.getDirection()-2*(r.getDirection().Dot3(h.getNormal()))*h.getNormal(),energy,iter+1);
  else if (iter<args->num_bounces&&ran<=refl.Length()+diff.Length())
	  TracePhoton(r.pointAtParameter(h.getT()),RandomDiffuseDirection(h.getNormal()),energy,iter+1);
  else
  {
	  Photon p(position,direction,energy,iter);
	  kdtree->AddPhoton(p);
  }


}
Exemplo n.º 14
0
Vec3f Face::RandomPoint() const {
  Vec3f a = (*this)[0]->get();
  Vec3f b = (*this)[1]->get();
  Vec3f c = (*this)[2]->get();
  Vec3f d = (*this)[3]->get();

  MTRand r;
  double s = r.rand(); // random real in [0,1]
  double t = r.rand(); // random real in [0,1]

  Vec3f answer = s*t*a + s*(1-t)*b + (1-s)*t*d + (1-s)*(1-t)*c;
  return answer;
}
Exemplo n.º 15
0
int RandomBin::randInt(Stream_type Stream, int minInt, int maxInt)
{
	double randNum = 0;
	int retInt = 0;
	MTRand *streamPtr = GetStream(Stream);
	if (streamPtr != NULL) {
		randNum = streamPtr->rand();
		randNum = randNum * static_cast<double>((maxInt - minInt + 1));
		retInt = static_cast<int>(ceil(randNum)) - 1 + minInt;
		return retInt;
	}
	return 0;
}
Exemplo n.º 16
0
/**************************************************************************//**
 *  Return a random position close to the supplied one. Shell Jump
******************************************************************************/
dVec Cylinder::randUpdateJumpShell (MTRand &random, const dVec &pos) const {
    dVec randPos;
    randPos = pos;
    double theta = atan2(pos[1],pos[0]);
    double oldr = sqrt(pos[0]*pos[0] + pos[1]*pos[1]);
    double newr;

    if (random.rand() > 0.5)
        newr = oldr + (1.00 + 2.50*random.rand());
    else
        newr = oldr - (1.00 + 2.50*random.rand());

    if (newr < 0.0)
        newr *= -1.0;

    double ranTheta = M_PI*(-0.05 + 0.1*random.rand());
    randPos[0] = newr*cos(theta + ranTheta);
    randPos[1] = newr*sin(theta + ranTheta);
    randPos[2] += constants()->displaceDelta()*(-0.5 + random.rand());

    putInside(randPos);
    return randPos;
}
Exemplo n.º 17
0
void setupInitalRandomPos(std::vector<Furniture> &  fVec, Image<Color>& texture){
  // Genereate Random Position
  std::cout << "Randomizing"<< std::endl;

  MTRand mtrand;
  unsigned int curIndex = 0;

  // for each piece of furnature
  while(curIndex < fVec.size()){
    std::cout << "Desk "<< curIndex<<" Tying" << std::endl;

    // random x and y and rotation
    float start_x = mtrand.rand(TEXTURE_SIZE_X);
    float start_y = mtrand.rand(TEXTURE_SIZE_Y);
    double start_rot = mtrand.rand(2* M_PI);

    // set to that random values
    fVec[curIndex].setPos(start_x, start_y);
    fVec[curIndex].setAngle(start_rot);

    // check if were good
    if(insideSpace(fVec[curIndex], texture)){
      
      //debug
      Color avgColor  = getApproxColor(fVec[curIndex] , texture);
      std::cout << "Desk "<< curIndex<<" PASS ";
      std::cout << static_cast<unsigned>(avgColor.r)<< ", ";
      std::cout << static_cast<unsigned>(avgColor.g)<< ", ";
      std::cout << static_cast<unsigned>(avgColor.b)<< std::endl;
      curIndex++;

    }else{
      std::cout << "Desk "<< curIndex<<" FAIL"<< std::endl;
    }
  }
}
Exemplo n.º 18
0
void GenericLayer::initWeights() {
	int j(0);
	MTRand mt;
	
	if ( this->hasChild && this->numNeurons > 0 && this->childLayer->numNeurons > 0) {
		this->weights.clear();
		this->weights.resize(this->numNeurons);
		
//		#pragma omp parallel for private(j) if(this->numNeurons > 500)
		for (int i=0; i<this->numNeurons; ++i) {
			this->weights.at(i).clear();
			this->weights.at(i).resize(this->childLayer->numNeurons);
			
			for (j=0; j<this->childLayer->numNeurons; ++j) {
				this->weights.at(i).at(j) = mt.rand(2)-1.0f;
			}
		}
	}
}
Exemplo n.º 19
0
void deskMove(Furniture& item,double heat, Image<Color>& texture){
  // Moves and saved to item, so long as it is inside

  // Using 
  MTRand mtrand;
  int TIRES = 100;

  while(0 < TIRES){

    double move_x = mtrand.rand(2*heat);
    double move_y = mtrand.rand(2*heat);

    //dummy item
    Furniture dummy(-1, "dummy", 
        item.getAngle(), 
        item.getPos().x , 
        item.getPos().y);

    // we want to be able to fitter forward and backwards
    dummy.setPos(
        dummy.getPos().x - heat,
        dummy.getPos().y - heat);

    // jitter it
    dummy.setPos(
        dummy.getPos().x + move_x,
        dummy.getPos().y + move_y);
    
    if(insideSpace(dummy,texture) ){
      // if we didn't fall off save
      item.setPos(
         dummy.getPos().x,
         dummy.getPos().y);
      break;
    }else{
      //dec
      TIRES--;
    }

  }//while

}//deskMove
Exemplo n.º 20
0
double gasdev()
{
	static int iset=0;
	static double gset;
	double fac,rsq,v1,v2;
	
	//	if (idum < 0) iset=0;
	if (iset == 0) {
		do {
			v1=2.0*rnd.rand()-1.0;
			v2=2.0*rnd.rand()-1.0;
			rsq=v1*v1+v2*v2;
		} while (rsq >= 1.0 || rsq == 0.0);
		fac=sqrt(-2.0*log(rsq)/rsq);
		gset=v1*fac;
		iset=1;
		return v2*fac;
	} else {
		iset=0;
		return gset;
	}
};
Exemplo n.º 21
0
//  constructs a random clockpiece
clockPiece::clockPiece()
{
    //  creates an MTRand that can make random numbers
    MTRand randGen;

    //  initialize data
    mPieceType = randGen.randInt(PTYPE_AMT);
    mPieceInterval = 0;
    mPendulumLength = 0;
    mNumTeeth = 0;
    mIsConnected = false;
    mIsPowered = false;
    mIsAttToHand = false;

    //  determine other member variables based on the part type
    if (mPieceType == PTYPE_PENDULUM)
		//	random length of pendulum between 0 and 1 meter
        mPendulumLength = randGen.rand();
    else if (mPieceType == PTYPE_GEAR)
		//	random number of gear teeth (physical minimum is 3)
        mNumTeeth = randGen.randInt(MAX_TEETH - 3) + 3;
}
Exemplo n.º 22
0
/// Finds a random 2D point, within the specified region, that has no other objects within the requested radius, using an exising (already seeded) Mersenne Twister random number generator.
bool GridDatabase2D::randomPositionInRegionWithoutCollisions(const Util::AxisAlignedBox & region, SpatialDatabaseItemPtr item, bool excludeAgents, MTRand & randomNumberGenerator)
{
	Point ret(0.0f, 0.0f, 0.0f);
	bool notFoundYet;
	unsigned int numTries = 0;
	float radius = 0.0f;
	AgentInterface * ai;
	AgentInitialConditions aic;

	if ( item->isAgent() )
	{
		ai = dynamic_cast<AgentInterface*>(item);
		radius = ai->radius();
		aic = ai->getAgentConditions(ai);
	}
	float xspan = region.xmax - region.xmin - 2*radius;
	float zspan = region.zmax - region.zmin - 2*radius;

	do {

		ret.x = region.xmin + radius + ((float)randomNumberGenerator.rand(xspan));
		ret.y = 0.0f;
		ret.z = region.zmin + radius + ((float)randomNumberGenerator.rand(zspan));

		aic.position = ret;


		// assume this new point has no collisions, until we find out below
		notFoundYet = false;

		// check if ret collides with anything
		set<SpatialDatabaseItemPtr> neighbors;
		neighbors.clear();
		float _new_radius = radius;
		getItemsInRange(neighbors, ret.x - _new_radius, ret.x + _new_radius, ret.z - _new_radius, ret.z + _new_radius, NULL);
		set<SpatialDatabaseItemPtr>::iterator neighbor;
		for (size_t dirs=0; dirs < 10; dirs++)
		{
			float theta = randomNumberGenerator.rand() * M_2_PI;

			double directionX = cos(theta);
			double directionZ = sin(theta);
			aic.direction = Util::Vector(directionX, 0.0f, directionZ);

			ai->reset(aic, ai->getSimulationEngine());
			ai->disable();

			/*
			 * increment must be after loop body or (*neighbor)->isAgent()) will be called on an
			 * element that is beyond the set.
			 */
			for (neighbor = neighbors.begin(); neighbor != neighbors.end(); neighbor++)
			{
				if ((excludeAgents) && ((*neighbor)->isAgent()))
				{
					continue;
				}
				notFoundYet = (*neighbor)->overlaps(ret, radius) ||  ai->overlaps((*neighbor));
				if (notFoundYet)
				{
					std::cout << "Try again placing agent: " << std::endl;
					break;
				}

			}
			if (notFoundYet)
			{ // no intersections
				break;
			}

		}// dirs

		numTries++;
		if (numTries > 1000)
		{
			cerr << "ERROR: trying too hard to find a random position in region.  The region is probably already too dense." << endl;
			if (numTries > 10000)
			{
				throw GenericException("Gave up trying to find a random position in region.");
			}
		}
	} while (notFoundYet);

	return !notFoundYet;
}
Exemplo n.º 23
0
static cell_t GetURandomFloat(IPluginContext *ctx, const cell_t *params)
{
	MTRand *randobj = s_RandHelpers.RandObjForPlugin(ctx);
	return sp_ftoc((float)randobj->rand());
}
void QFRDRFCSFitFunctionSimulator::replotFitFunction() {
    JKQTPdatastore* ds=ui->pltFunction->getDatastore();
    QScopedPointer<QFFitFunction> ffunc(getFitFunction(NULL));

    if (!ffunc) return;

    try {
        ui->pltFunction->set_doDrawing(false);
        ui->pltFunction->clearGraphs();
        ds->clear();
        updateTau();
        if (tauN) {


            /////////////////////////////////////////////////////////////////////////////////
            // retrieve fit parameters and errors. run calcParameters to fill in calculated parameters and make sure
            // we are working with a complete set of parameters
            /////////////////////////////////////////////////////////////////////////////////

            double* fullParams=(double*)qfCalloc(ffunc->paramCount(), sizeof(double));
            double* errors=(double*)qfCalloc(ffunc->paramCount(), sizeof(double));
            double Nparticle=0;
            bool hasNParticle=false;
            for (int p=0; p<ffunc->paramCount(); p++) {
                QFFitFunction::ParameterDescription d=ffunc->getDescription(p);
                QString id=d.id;
                if (params.contains(id)) {
                    fullParams[p]=params[id].value;
                    errors[p]=params[id].error;
                } else {
                    fullParams[p]=d.initialValue;
                    /*double value=0;
                    if (overrideFitFunctionPreset(id, value)) d.initialValue=value;*/

                    errors[p]=0;
                }
            }
            ffunc->calcParameter(fullParams, errors);
            used_params.clear();
            for (int p=0; p<ffunc->paramCount(); p++) {
                QFFitFunction::ParameterDescription d=ffunc->getDescription(p);
                QString id=d.id.toLower();
                bool visible=ffunc->isParameterVisible(ffunc->getParameterNum(id), fullParams);
                if (visible) {
                    if (id=="n_particle") {
                        Nparticle=fullParams[p];
                        hasNParticle=true;
                    }
                    if (id=="1n_particle" && !hasNParticle) {
                        Nparticle=1.0/fullParams[p];
                        hasNParticle=true;
                    }
                    used_params[id]=fullParams[p];
                }
            }

            used_params["tau_min"]=ui->edtMinTau->value();
            used_params["tau_max"]=ui->edtMaxTau->value();
            used_params["runs"]=ui->spinRuns->value();
            used_params["noise_enabled"]=ui->chkNoise->isChecked();
            used_params["model_function"]=ffunc->id();

            csv="";

            // evaluate correlation function and determine small-lag amplitude
            double tau0avg=0;
            for (int r=0; r<runs; r++) {
                for (int i=0; i<tauN; i++) {
                    corr[r*tauN+i]=ffunc->evaluate(tau[i], fullParams);
                }
                tau0avg=tau0avg+corr[r*tauN];
            }
            tau0avg=tau0avg/double(runs);
            if (!hasNParticle) Nparticle=1.0/tau0avg;

            // calc noise
            if (ui->chkNoise->isChecked()) {
                MTRand rng;
                if (ui->cmbNoiseModel->currentIndex()==0) {
                    double I=ui->spinAvgCountRate->value()*1000.0;
                    double I2=sqr(I);
                    double NN=Nparticle;
                    if (NN<=0) NN=1.0;
                    for (int r=0; r<runs; r++) {
                        double corr0=corr[r*tauN];
                        for (int i=0; i<tauN; i++) {
                            double corrT=corr[r*tauN+i];
                            double M=ui->spinMeasDuration->value()/tau[i];
                            double m=tau[0]/tau[i];
                            double var=((1.0+sqr(corr0))*(1.0+sqr(corrT))/(1.0-sqr(corr0))+2.0*m*sqr(corrT))/M/NN/NN+(2.0*(1.0+sqr(corrT))/NN/I+(1.0+corrT/NN)/I2)/M;
                            corr[r*tauN+i]=corr[r*tauN+i]+rng.randNorm(0,1)*sqrt(var);
                        }
                    }
                    used_params["noise_model"]=QString("Koppel");
                    used_params["noise_intensity_kHz"]=I;
                    used_params["noise_measurement_duration"]=ui->spinMeasDuration->value();
                } else if (ui->cmbNoiseModel->currentIndex()==1) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+rng.randNorm(0, 1)*(ui->spinNoiseLevel->value()/100.0*tau0avg);
                        }
                    }
                    used_params["noise_model"]=QString("gaussian");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                } else if (ui->cmbNoiseModel->currentIndex()==2) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+(rng.rand()*2.0-1.0)*ui->spinNoiseLevel->value()/100.0*tau0avg;
                        }
                    }
                    used_params["noise_model"]=QString("uniform");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                } else if (ui->cmbNoiseModel->currentIndex()==3) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+rng.randNorm(0, 1)*(ui->spinNoiseLevel->value()/100.0*corr[r*tauN+i]);
                        }
                    }
                    used_params["noise_model"]=QString("local gaussian");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                } else if (ui->cmbNoiseModel->currentIndex()==4) {
                    for (int r=0; r<runs; r++) {
                        for (int i=0; i<tauN; i++) {
                            corr[r*tauN+i]=corr[r*tauN+i]+(rng.rand()*2.0-1.0)*ui->spinNoiseLevel->value()/100.0*corr[r*tauN+i];
                        }
                    }
                    used_params["noise_model"]=QString("local uniform");
                    used_params["noise_level"]=ui->spinNoiseLevel->value();
                }
            }


            for (int i=0; i<tauN; i++) {
                csv=csv+CDoubleToQString(tau[i]);
                for (int r=0; r<runs; r++) {
                    csv=csv+", "+CDoubleToQString(corr[r*tauN+i]);
                }
                csv=csv+"\n";
            }


            size_t c_tau = ds->addCopiedColumn(tau, tauN, "tau");

            for (int r=0; r<runs; r++) {
                size_t c_fit = ds->addCopiedColumn(&(corr[r*tauN]), tauN, QString("function_r%1").arg(r));
                /////////////////////////////////////////////////////////////////////////////////
                // plot fit model and additional function graphs
                /////////////////////////////////////////////////////////////////////////////////
                JKQTPxyLineGraph* g_fit=new JKQTPxyLineGraph(ui->pltFunction->get_plotter());
                g_fit->set_drawLine(true);
                g_fit->set_title(tr("run %1").arg(r));
                g_fit->set_xColumn(c_tau);
                g_fit->set_yColumn(c_fit);
                ui->pltFunction->addGraph(g_fit);
            }
        }

        ui->pltFunction->zoomToFit();
        ui->pltFunction->set_doDrawing(true);
        ui->pltFunction->update_plot();
    } catch(std::exception& E) {
        services->log_error(tr("error during plotting, error message: %1\n").arg(E.what()));
    }

}
Exemplo n.º 25
0
// real number in [0,n]
double SoarRand(const double& max)
{
    return gSoarRand.rand(max);
}
Exemplo n.º 26
0
// real number in [0,1]
double SoarRand()
{
    return gSoarRand.rand();
}
Exemplo n.º 27
0
void simulate(double runtime, double rand_seed, State init_state, double* init_position,
	      void (*job)(void* dyn, State s, void *job_msg, data_union* job_data,
	      long long iteration), void *job_msg, data_union* job_data) {

  if (FP_EXCEPTION_FATAL) {
    feenableexcept(FE_ALL_EXCEPT);      // NaN generation kills program
    signal(SIGFPE, FPE_signal_handler);
  }

  MTRand* rand = new MTRand(rand_seed);

  Dynein_onebound *dyn_ob;
  Dynein_bothbound *dyn_bb;

  if (init_state == BOTHBOUND) {
    dyn_ob = NULL;
    dyn_bb = new Dynein_bothbound(
			      init_position[0],      // nma_init
				  init_position[1],      // fma_init
				  init_position[2],      // nbx_init
				  init_position[3],      // nby_init
				  init_position[4],      // L
				  NULL,                  // internal forces
				  NULL,                  // brownian forces
				  NULL,                  // equilibrium angles
				  rand);                 // MTRand
  } else {
    dyn_ob = new Dynein_onebound(
				 init_position[0],    // bba_init
				 init_position[1],    // bma_init
				 init_position[2],    // uma_init
				 init_position[3],    // uba_init
				 init_position[4],    // bbx_init
				 init_position[5],    // bby_init
				 init_state,          // Initial state
				 NULL,                // Optional custom internal forces
				 NULL,                // Optional custom brownian forces
				 NULL,                // Optional custom equilibrium angles
				 rand);
    dyn_bb = NULL;
  }

  double t = 0;
  long long iter = 0;
  State current_state = init_state;

  // double rebinding_immune_until = 0; // to prevent immediate rebinding in BB->OB transitions

  bool run_indefinite;
  if (runtime == 0) {
	run_indefinite = true;
    printf("Running indefinitely.\n");
  } else {
	run_indefinite = false;
	printf("Running for %g s\n", runtime);
  }

  double near_unbinding_prob_printing_average = 0;
  int unbinding_prob_printing_n = 0;

  while( t < runtime or run_indefinite) {
    if (current_state == NEARBOUND or current_state == FARBOUND)
      while (t < runtime or run_indefinite) { // loop as long as it is onebound
        if (am_debugging_time) printf("\n==== t = %8g/%8g ====\n", t, runtime);

        double unbinding_prob = dyn_ob->get_unbinding_rate()*dt;
        double binding_prob = dyn_ob->get_binding_rate()*dt;
	if (am_debugging_rates and binding_prob != 0 and rand->rand() < 1e-3) {
	  printf("binding probability: %g, uby %g at time %g s\n", binding_prob, dyn_ob->get_uby(), t);
	}
	if (rand->rand() < unbinding_prob) { // unbind, switch to unbound
	  delete dyn_ob;
	  dyn_ob = NULL;
	  current_state = UNBOUND;
	  break;
	}
	else if (rand->rand() < binding_prob) { // switch to bothbound
	  dyn_bb = new Dynein_bothbound(dyn_ob, rand);
	  if (am_debugging_state_transitions) printf("Transitioning from onebound to bothbound\n");
	  if (am_debugging_state_transitions) printf("just bound b/c binding probability was: %g, boltzmann factor: %g\n",
                                                     binding_prob, exp(-(dyn_bb->get_PE()-dyn_ob->get_PE())/kb/T));
	  delete dyn_ob;
	  dyn_ob = NULL;
	  current_state = BOTHBOUND;
	  job(dyn_bb, current_state, job_msg, job_data, iter);
	  t += dt;
	  iter++;
	  break;
	}
	else { // move like normal
	  job(dyn_ob, current_state, job_msg, job_data, iter);
	  t += dt;
	  iter++;

	  double old_bba = dyn_ob->get_bba() ;
	  double old_bma = dyn_ob->get_bma() ;
	  double old_uma = dyn_ob->get_uma() ;
	  double old_uba = dyn_ob->get_uba() ;

	  bool accept_step = false;
	  int attempts = 0;

	  const long long max_attempts = 1e6;
	  while(!accept_step){
	    if (attempts > max_attempts) {
	      printf("Over %lld attempts needed to avoid a NaN state in onebound at time %g, something must be wrong. Exiting.\n",
                     max_attempts, t);
	      fprintf(stderr, "Over %lld attempts needed to avoid a NaN state at time %g, something must be wrong. Exiting.\n",
                      max_attempts, t);
	      if (am_only_writing_on_crash) on_crash_write_movie_buffer();
	      exit(1);
	    }
	    // if (attempts > 0 and attempts % 1000 == 0) printf("Taking %g rerolls to avoid a NaN velocity at time %g\n", (double) attempts, t);
	    if(attempts > 0){
	      dyn_ob->set_bba(old_bba);
	      dyn_ob->set_bma(old_bma);
	      dyn_ob->set_uma(old_uma);
	      dyn_ob->set_uba(old_uba);
	      dyn_ob->update_velocities();
            }

	     double temp_bba = dyn_ob->get_bba() + dyn_ob->get_d_bba() * dt;
	     double temp_bma = dyn_ob->get_bma() + dyn_ob->get_d_bma() * dt;
	     double temp_uma = dyn_ob->get_uma() + dyn_ob->get_d_uma() * dt;
	     double temp_uba = dyn_ob->get_uba() + dyn_ob->get_d_uba() * dt;

	     dyn_ob->set_bba(temp_bba);
	     dyn_ob->set_bma(temp_bma);
	     dyn_ob->set_uma(temp_uma);
	     dyn_ob->set_uba(temp_uba);

	     accept_step = dyn_ob->update_velocities();

	     attempts++;
	     total_attempts += 1;
	  }
	  // if (attempts > 1) {
	  //   printf("NaN avoiding code: (onebound) At time t=%g, took %d attempts to timestep without NaNs\n", t, attempts);
	  // }
	}
      }

    if (current_state == BOTHBOUND) {
      while (t < runtime or run_indefinite) { // loop as long as it is bothbound
        if (am_debugging_time) printf("\n==== t = %8g/%8g ====\n", t, runtime);
        double near_unbinding_prob = dyn_bb->get_near_unbinding_rate()*dt;
        double far_unbinding_prob = dyn_bb->get_far_unbinding_rate()*dt;
	double roll = rand->rand();
	while (roll == 0) roll = rand->rand();
	if (am_debugging_rates and roll < 1e-8) {
	  near_unbinding_prob_printing_average = (near_unbinding_prob_printing_average*unbinding_prob_printing_n + near_unbinding_prob);
	  near_unbinding_prob_printing_average /= (unbinding_prob_printing_n + 1);
	  unbinding_prob_printing_n++;

	  printf("BB near unbinding probability: %g\n", near_unbinding_prob_printing_average);
	}
	bool unbind_near = roll < near_unbinding_prob;
	bool unbind_far = roll < far_unbinding_prob;
	if (unbind_near && unbind_far) {
	  if (debug_stepping) printf("both MTBDs want to fall off!\n");
	  if (iter % 2 == 0) unbind_far = false;
	  else unbind_near = false;
	}
	if (unbind_near and not frozen_in_bothbound) { // switch to farbound
	  dyn_ob = new Dynein_onebound(dyn_bb, rand, FARBOUND);
	  if (am_debugging_state_transitions) printf("Transitioning from bothbound to farbound\n");
	  if (am_debugging_state_transitions) printf("just unbound b/c unbinding probability was: %g, roll was: %g, boltzmann factor: %g\n",
                                                     near_unbinding_prob, roll, exp(-(dyn_ob->get_PE()-dyn_bb->get_PE())/kb/T));
	  delete dyn_bb;
	  dyn_bb = NULL;
	  current_state = FARBOUND;
	  job(dyn_ob, current_state, job_msg, job_data, iter);
	  t += dt;
	  iter++;
	  // rebinding_immune_until = t + REBINDING_IMMUNITY_TIME;
	  break;
	}
	else if (unbind_far and not frozen_in_bothbound) { // switch to nearbound
	  dyn_ob = new Dynein_onebound(dyn_bb, rand, NEARBOUND);
	  if (am_debugging_state_transitions) printf("Transitioning from bothbound to nearbound\n");
	  if (am_debugging_state_transitions) printf("just unbound b/c unbinding probability was: %g, roll as: %g, boltzmann factor: %g\n",
                                                     far_unbinding_prob, roll, exp(-(dyn_ob->get_PE()-dyn_bb->get_PE())/kb/T));
	  delete dyn_bb;
	  dyn_bb = NULL;
	  current_state = NEARBOUND;
	  job(dyn_ob, current_state, job_msg, job_data, iter);
	  t += dt;
	  iter++;
	  // rebinding_immune_until = t + REBINDING_IMMUNITY_TIME;
	  break;
	}
	else { // move like normal
	  job(dyn_bb, BOTHBOUND, job_msg, job_data, iter);
	  t += dt;
	  iter++;

	  // double temp_nma = dyn_bb->get_nma() + dyn_bb->get_d_nma()*dt;
	  // double temp_fma = dyn_bb->get_fma() + dyn_bb->get_d_fma()*dt;
	  // dyn_bb->set_nma(temp_nma);
	  // dyn_bb->set_fma(temp_fma);

	  // dyn_bb->update_velocities();

	  double old_nma = dyn_bb->get_nma();
	  double old_fma = dyn_bb->get_fma();

	  bool accept_step = false;
	  int attempts = 0;

	  const long long max_attempts = 1e6;
	  while(!accept_step){
	    if (attempts > max_attempts) {
	      printf("Over %lld attempts needed to avoid a NaN state in bothbound at time %g, something must be wrong. Exiting.\n",
                     max_attempts, t);
	      fprintf(stderr, "Over %lld attempts needed to avoid a NaN state at time %g, something must be wrong. Exiting.\n",
                      max_attempts, t);
	      if (am_only_writing_on_crash) on_crash_write_movie_buffer();
	      exit(1);
	    }
	    // if (attempts > 0 and attempts % 100 == 0) printf("Taking %g rerolls to avoid a NaN velocity at time %g\n", (double) attempts, t);
	    if(attempts > 0){
	      dyn_bb->set_nma(old_nma);
	      dyn_bb->set_fma(old_fma);
	      dyn_bb->update_velocities();
	     }

	    double temp_nma = dyn_bb->get_nma() + dyn_bb->get_d_nma() * dt;
	    double temp_fma = dyn_bb->get_fma() + dyn_bb->get_d_fma() * dt;

	    dyn_bb->set_nma(temp_nma);
	    dyn_bb->set_fma(temp_fma);

	    accept_step = dyn_bb->update_velocities();
	    attempts++;
	    total_attempts += 1;
	  }
	  // if (attempts > 1) {
	  //   printf("NaN avoiding code: (bothbound) At time t=%g, took %d attempts to timestep without NaNs\n", t, attempts);
	  // }
	}
      }
    }
    if (current_state == UNBOUND) {
      job(NULL, UNBOUND, job_msg, job_data, iter);
      goto end_simulation;
    }
  }

  printf("Simulation exited successfully.\n");
  printf("Executed %f NaN retries, or %g retries per step.\n", total_attempts, total_attempts / t * dt);

 end_simulation:
  delete rand;
  if (dyn_bb == NULL) delete dyn_ob;
  else delete dyn_bb;
}
Exemplo n.º 28
0
 double myrand () { return gen.rand(); }
Exemplo n.º 29
0
	const double operator()(const double & ignore)
	{
		return GlobalMT.rand();
	}
int TissueCell::TakeStep(RealType dt, RealType v0, RealType mob, RealType t_relax, RealType noise, RealType box_size, MTRand& rng, bool eq){
		int rtn = 0;
		// Handle invalid arguments
		if (mob < 0){ throw std::invalid_argument("mob < 0"); }
		if (t_relax < 0){ throw std::invalid_argument("t_relax < 0"); }
		if (noise < 0){ throw std::invalid_argument("noise < 0"); }

		//RealType ffffx = this->Fx;
		//RealType ffffy = this->Fy;
		//RealType xxxxx = this->x;
		//RealType yyyyy = this->y;
		//RealType aaaangle = this->angle;

		RealType dxF = (mob * Fx) * dt;
		RealType dxV = (std::cos(this->angle) * v0) * dt;
		RealType dx = dxF + dxV;
		RealType dyF = (mob * Fy) * dt;
		RealType dyV = (std::sin(this->angle) * v0) * dt;
		RealType dy = dyF + dyV;


		RealType vmag = sqrt(dx * dx + dy * dy); 

		RealType dtheta = 0;
		// arcsin of a cross product of two normalized vecors will give the deflection in theta.
		RealType step_noise = (rng.rand() - .5) * noise;
		if (vmag != 0){
			try{
				dtheta = (dt / t_relax) * std::asin( (std::cos(angle) * dy - std::sin(angle) * dx) / vmag);
				if (isnan(dtheta)){
					throw (std::cos(angle) * dy - std::sin(angle) * dx) / vmag;
				}
			}
			catch(RealType arcarg){
				std::cout << "Caught bad arctan." <<std::endl;
				if (arcarg >= 1 && arcarg <= 1.00001){
					dtheta = (dt / t_relax) * 3.141592865358979 / 2.0;
				}
				else if (arcarg <=-1 && arcarg >=-1.00001){
					dtheta = - (dt / t_relax) * 3.141592865358979 / 2.0;
				}
				else{
					throw std::domain_error("Arctangent argument outside of allowed extended domain from floating point arithmetic");
				}
			}

		}
		this->angle += step_noise;

#ifndef FORCE_WARN_OFF
		if (vmag > 10){
			std::cout << "WARNING: Assuming Req of 1: Single step is on the order of Req; vmag = " << vmag <<". Check your timestep and interaction parameters." << std::endl;
		}
#endif

		this->x += dx;
		this->y += dy;

		// =========================================================================================
		// Apply periodic topology:

		// Map x and y [0, box_size) periodically
		// e.g. box_size = 10.0, sends 10.0 -> 0.0
		// For a non-equilibration step:
		if (!eq){
			if (this->x >= box_size){ this->x -= box_size ;} 		
			if (this->y >= box_size){ this->y -= box_size; } 
			// e.g. box_size = 10.0, then -10.0 -> ceil(1) -> 0 and  -10.1 -> ceil(1.01) -> 9.99
			if (this->x < 0){ this->x += box_size; }  
			if (this->y < 0){ this->y += box_size; }
		}

		// For an equilibration step:
		if (eq){
			RealType beforex = this->x;
			RealType beforey = this->y;
			this->x = fmod(fmod(this->x, box_size) + box_size, box_size);
			this->y = fmod(fmod(this->y, box_size) + box_size, box_size);

			if (beforex != this->x or beforey != this->y){
				rtn = 1;
			}
		}

		RealType twoPi = 2.0 * 3.141592865358979;
		if (!(this->angle + dtheta >= 0)){
			this->angle += twoPi;
		}
		if (!(this->angle + dtheta < twoPi)){
			this->angle -= twoPi;
		}

		this->angle += dtheta;
		// Assertions to match the above definitions
		// Furthermore: Do not allow a particle to step more than a box width.
		//  (angle can rotate artibrarily)
		assert(fmod( 0 + twoPi, twoPi) == 0);
		assert(this->x < box_size);
		assert(this->x >= 0);
		assert(this->y < box_size);
		assert(this->y >= 0);
		if (!(this-> angle < twoPi)){
			std::cout << "Current angle is " << this->angle << " which is apparently larger than or equal to " << twoPi << std::endl;
			assert(this-> angle < twoPi);
		}
		if (!(this-> angle >= 0)){
			std::cout << "Current angle is " << this->angle << " which is apparently smaller than 0." << std::endl;
			assert(this->angle >= 0);
		}

		// Clear the old forces;
		this->Fx = 0;
		this->Fy = 0;
		
		return rtn;
}