Exemplo n.º 1
0
void FluxBoundary::operator ()(const double dt) {
	Operator::resume_timer();
	BOOST_FOREACH(Species *s, all_species) {
		Molecules& mols = s->mols;
		boost::poisson_distribution<> p_dist(dt*rate);
		boost::variate_generator<base_generator_type&, boost::poisson_distribution<> > poisson(generator, p_dist);
		const unsigned int n = poisson();
		for (int i = 0; i < n; ++i) {
			mols.add_molecule(p + uni1()*t1 + uni2()*t2);
		}
	}
Exemplo n.º 2
0
double upperErrorZero()
{
  double cumprob=0.0;
  double step=0.0001;
  double i_step=0.0;
  while (cumprob<0.68)
  {
    i_step+=step;
    cumprob+=0.5*(poisson(0, i_step)+poisson(0, i_step-step))*step;
  }
  return i_step;
}
Exemplo n.º 3
0
double lowerError(unsigned int i)
{
  double max=log(poisson(i,double(i)));
  double step=pow(double(i), 0.5)/1000.0;
  double diff=0.0;
  double i_step=double(i);
  while(diff<0.5)
  {
    i_step-=step;
    diff=max-log(poisson(i, i_step));
  }
  double i_report=i_step+0.5*step;
  return i-i_report;
}
Exemplo n.º 4
0
void MixMod::CalcMat()
{
int i,j;


 for(j=0;j<k;j++)
  {
   for(i=0;i<n;i++)
   {
     switch (dens)
     {
     case 0: // normal density
      {
     xf[i][j]=normal (x[i][0],t[j],x[i][3]);
      break;
      }
     case 1:  // poisson density
      {
      xf[i][j]=poisson(x[i][0],t[j]*x[i][2]);
      break;
      }
     case 2: // binomial density
      {
      xf[i][j]=binomial (x[i][0],x[i][2],t[j]);
      break;
      }
    }  // end of switch
   }  // end of i-loop
  } // end if j-loop
             //
 }
Exemplo n.º 5
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    if (nrhs < 1)
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs",
                          "Two inputs required.");
    double *lambda = mxGetPr(prhs[0]);;
    double *outputPr;
    int nSamp = 1;
    std::mt19937 mt; // Mersenne Twister generator
    
    if (mxGetNumberOfElements(prhs[0]) == 1) {
        // Single lambda, multiple samples
        // Output is the same size as samples
        std::poisson_distribution<> poisson(*lambda);
        if (nrhs < 2){
            plhs[0] = mxCreateDoubleScalar(poisson(mt));
        }
        else{
            int ndim = mxGetNumberOfElements(prhs[1]);
            int totProd = 1;
            mwSize *dimSize = (mwSize*)mxCalloc(ndim, sizeof(mwSize));
            double *dims = (double*)mxGetData(prhs[1]);
            for (int ii = 0; ii < ndim; ii++){
                dimSize[ii] = (mwSize)dims[ii];
                totProd *= dims[ii];
            }
            
            plhs[0] = mxCreateNumericArray(ndim, dimSize, mxDOUBLE_CLASS, mxREAL);
            outputPr = mxGetPr(plhs[0]);
            
            for (int ii = 0; ii < totProd; ii++){
                outputPr[ii] = poisson(mt);
            }
            mxFree(dimSize);
        }
    }
    else{
        // Lambda matrix, output is the same size as lambda
        const mwSize* dims = mxGetDimensions(prhs[0]);
        int ndim = mxGetNumberOfDimensions(prhs[0]);
        plhs[0] = mxCreateNumericArray(ndim, dims, mxDOUBLE_CLASS, mxREAL);
        outputPr = mxGetPr(plhs[0]);
        for (int ii=0; ii<mxGetNumberOfElements(prhs[0]); ii++) {
            std::poisson_distribution<> poisson(lambda[ii]);
            outputPr[ii] = poisson(mt);
        }
    }
}
int main() {
    
    double lambda; scanf("%lf", &lambda);
    int k; scanf("%d", &k);
    printf("%.3lf\n", poisson(lambda, k));
    
    return 0;
}
Exemplo n.º 7
0
int RAIDProcess::msgDelay() {
	RAIDProcessState *myState = (RAIDProcessState*) getState();
	double ldelay;

	// Hard coded for now... add to ssl later
	sourcedist = UNIFORM;
	first = 1;
	second = 2;

	switch (sourcedist) {
	case UNIFORM: {
		Uniform uniform(first, second, myState->getGen());
		ldelay = uniform();
		break;
	}
	case NORMAL: {
		Normal normal(first, second, myState->getGen());
		ldelay = normal();
		break;
	}
	case BINOMIAL: {
		Binomial binomial((int) first, second, myState->getGen());
		ldelay = binomial();
		break;
	}
	case POISSON: {
		Poisson poisson(first, myState->getGen());
		ldelay = poisson();
		break;
	}
	case EXPONENTIAL: {
		NegativeExpntl expo(first, myState->getGen());
		ldelay = expo();
		break;
	}
	case FIXED:
		ldelay = (int) first;
		break;
	default:
		ldelay = 0;
		cerr << "Improper Distribution for a Source Object!!!" << "\n";
		break;
	}
	return ((int) ldelay);

}
Exemplo n.º 8
0
vector<unsigned long> simulator::drawNumberEvents_tauLeap(double timestep)
{
	/// Draws the number of events during a tau-leap
	/// for every event
	
	vector<unsigned long> res;
	
	// New infection event
	res.push_back(poisson(eventRate_infection()*timestep));
	
	// Migrations through the E[k]
	for(int i=0; i<_nE; i++) res.push_back(poisson(eventRate_latencyProgress(i)*timestep));
	
	// Migrations through the I[k]
	for(int i=0; i<_nI; i++) res.push_back(poisson(eventRate_infectiousProgress(i)*timestep));

	return res;
}
Exemplo n.º 9
0
void Simulation_running::on_entry()
{
    /*****************************/
    //auto seed = chrono::high_resolution_clock::now().time_since_epoch().count();

    //mt19937 mt_rand(seed);
    auto dice_rand = std::bind(std::uniform_int_distribution<int>(1,9999),
                               mt19937(seed));

    mt19937 nrg;
    poisson_distribution<int> poisson(4.9);

    /*****************************/

    std::cout << "Simulation_running on_entry()\n";
    std::cout<<"State: "<<state_to_text(
                 m_state_machine_controller.m_current_state->get_state())<<std::endl;
    bool flag = false;
    auto sim_run_thread = sim_running_thread(m_state_machine_controller);

    while (!flag) // Infinite loop producing random numbers every "poisson" time
    {
        flag = check_me2(m_state_machine_controller);

        int job = dice_rand();
        int sth = random_disp();

        std::cout<<"DA FAQ "<<flag<<" - - - Random Disp Number: "<<sth<<" - - - Random Job: "<<job<<std::endl;
        std::cout<<"Job sending"<<std::endl;
        vDisp.at(sth)->add_job_q(job);
        vDisp.at(sth)->schedule_event(Events::DISP_JOB);


        std::this_thread::sleep_for(std::chrono::seconds(poisson(nrg)));
        //std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    }

    //sim_run_thread.get();


    //std::cout<<"State: "<<state_to_text(m_state_machine_controller.m_previous_state)<<std::endl;
}
Exemplo n.º 10
0
void test_2_run(int level, Float& e1, Float& e2, Float& e3) {
	const st dim = 2;
	// new shape--------------------
	Shape2D shape;
	Shape2D cir;
	//CreatCircle(cir, 2.1, 2.1, 0.8, 359);
	Float x1 = -0.5, y1 = -0.5, x2 = 0.5, y2 = 0.5;
	CreatCube(shape, x1, y1, x2, y2);
	// define unit length
	Float UL = 1.0;
	// build grid ------------------
	Domain_<Float, Float, dim> domain(&shape, UL, level, level + 1);
	//domain.adaptive().adapt_shape_boundary(cir);
	domain.build();
	//domain.new_data(4,0,0,0); // idx = 3 used for exact
	//domain.set_val(3,exact_fun_2);
	Poisson_<Float, Float, dim> poisson(&domain);
	poisson.set_beta(coe_set_b);
	poisson.set_f(f_fun_2);
	// set exact
	domain.set_val(0, exact_fun_2);
	// boundary condition
	Poisson_<Float, Float, dim>::BoundaryCondition bc;
	//bc.set_default_1_bc(exact_fun_2);
	poisson.set_boundary_condition(0, 0, poisson.phi_idx(), &bc);
	poisson.set_boundary_condition(0, 1, poisson.phi_idx(), &bc);
	poisson.set_boundary_condition(0, 2, poisson.phi_idx(), &bc);
	poisson.set_boundary_condition(0, 3, poisson.phi_idx(), &bc);
	std::cout << "solve -----------\n";
	poisson.solve();
	cout << "end solve -------\n";
	e1 = error_1(domain, 2, 0);
	e2 = error_2(domain, 2, 0);
	e3 = error_i(domain, 2, 0);
	//cout << "error 1  " << e1 << "\n";
	//cout << "error 2  " << e2 << "\n";
	//cout << "error 3  " << e3 << "\n";
	// show ================================
	GnuplotActor::list_spActor lga;
	lga.push_back(
			GnuplotActor::LeafNodesContour(domain.grid(), poisson.phi_idx()));
	lga.push_back(
			GnuplotActor::GhostNodesContours(domain.ghost(),
					poisson.phi_idx()));
	lga.push_back(GnuplotActor::Shape(shape, 0));
	Gnuplot gp;
	gp.set_equal_ratio();
	//gp.set_xrange(2.0,3.0);
	//gp.set_yrange(1.5,2.5);
	//gp.set_cbrange(-2.0, 2.0);
	gp.plot(lga);
	//delete shape
}
int
AGDataAndStatistics::getPoissonsNumberOfChildren(SUMOReal mean) {
    SUMOReal alea = RandHelper::rand();
    SUMOReal cumul = 0;
    for (int nbr = 0; nbr < LIMIT_CHILDREN_NUMBER; ++nbr) {
        cumul += poisson(mean, nbr);
        if (cumul > alea) {
            return nbr;
        }
    }
    return LIMIT_CHILDREN_NUMBER;
}
Exemplo n.º 12
0
double MixMod::loglike1(double alphab,double *d)
{
double value,s,ad,sp;
std::vector<double> td(k);
std::vector<double> pd(k);
int i,j,l,ii;
double * s1t;
//if (longmode) s1t = new double [nnlong];
//else s1t = new double [nn];
s1t = (double *) R_alloc(n, sizeof(double));
l=k-1;
   sp=0.;
   for(i=0;i<l;i++)
   {
    pd[i]=p[i]+alphab*d[i];
    sp=sp+pd[i]; 
   }
   pd[l]=1.-sp;
   ii=l;
   for(i=0;i<k;i++)
  {
   td[i]=t[i]+alphab*d[ii];
   ii++;
  }
   sp=0.;
   for(j=0;j<k;j++)
   { 
     
     sp=sp+pd[j];
   }

    for(i=0;i<n;i++)
   {
    s=0.;
       for(j=0;j<k;j++)
      {
       ad=poisson(x[i][0],td[j]);
       s=s+pd[j]*ad;
      }
     s1t[i]=s;
  }


value=0.;
 for(i=0;i<n;i++)
 {
 value=value+x[i][1]*g(s1t[i]);
 }

 return value;


}
Exemplo n.º 13
0
int main( int argc, char** argv ){
	srand( time( 0 ) );
	
	int number_of_VNs;
	float arrival_rate;
	int average_lifetime;
	int schedule_window;
	int min_windows_wait;
	int max_windows_wait;
	
	sscanf( argv[1], "%d", &number_of_VNs );
	sscanf( argv[2], "%f", &arrival_rate );
	sscanf( argv[3], "%d", &average_lifetime );
	sscanf( argv[4], "%d", &schedule_window );
	sscanf( argv[5], "%d", &min_windows_wait );
	sscanf( argv[6], "%d", &max_windows_wait );
	
	FILE *out;
	
	out = fopen( "events/events.evt", "w" );
	if( !out ){
		printf( "Error in file generate_events.cpp, function main: Could not open file events/events.evt\n" );
		exit(-1);
	}
	
	int clock = 0;
	int last_event_time = 0;
	
	//this code generates the arrive departure and expire network events
	for( int i = 0; i< number_of_VNs; ++i ){
		int arrival_time = poisson( arrival_rate );
		int life_time = exponential( average_lifetime );
		
		clock = clock + arrival_time;
		
		int expire_time = ( clock-( clock % schedule_window )) + schedule_window * uniform( min_windows_wait, max_windows_wait );
		
		int departure_time = clock + life_time;
		
		last_event_time = ( last_event_time > expire_time ) ? last_event_time : clock;
		
		fprintf( out, "%d A %d\n", i, clock );
		fprintf( out, "%d D %d\n", i, departure_time );
		fprintf( out, "%d E %d\n", i, expire_time );
	}
	//this code generates the schedule events
	last_event_time = last_event_time + schedule_window;
	for( int i = schedule_window; i < last_event_time; i += schedule_window )
		fprintf( out,  "-1 S %d\n", i );
	
	fclose( out);
}
Exemplo n.º 14
0
int main(int argc, char *argv[]) {
    Image<byte> I;
    Image<float> Vx, Vy;
    if (!load(I, argc > 1 ? argv[1] : srcPath("salon.png"))) {
        cout << "Echec de lecture d'image" << endl;
        return 1;
    }

    openWindow(I.width(), I.height());
    display(I);
    click();
    cout << "Contraste simple" << endl;
    affiche(I);
    gradient(I, Vx, Vy);
    click();
    cout << "Dérivée selon x par la fonction gradient" <<endl;
    affiche(Vx);
    click();
    cout << "Dérivée selon y par la fonction gradient" <<endl;
    affiche(Vy);

    click();

    Image<float> F = dx(I);

    cout << "Dérivée selon x par la fonction dx" <<endl;

    affiche(F);

    click();

    Image<float> U= dy(I);
    cout << "Dérivée selon y par la fonction dy" <<endl;

    affiche(U);

    click();

    masque(I,F,U);

    Image<float> z = poisson(F,U);
    cout << "Image reconstruite par poisson" <<endl;

    affiche(z);

    endGraphics();
    return 0;
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
    if (argc < 4) {
        printf("gen-poisson seed lambda num\n");
        printf("  The results to to stdout\n");
        exit(1);
    }

    do_seed(argv[1]);

    double lambda=atof(argv[2]);
    long num=atol(argv[3]);

    for (long i=0; i<num; i++) {
        long pval = poisson(lambda);
        printf("%ld\n", pval);
    }
}
Exemplo n.º 16
0
void linear::alpha_inv_cp2(const kind::f alpha,
			   const FT dt,
			   const kind::f alpha0 ) {

  VectorXd al  = field_to_vctr( alpha );
  VectorXd cp = field_to_vctr( kind::CHEMPOT ) ;

  VectorXd alal3  = - al.array() * ( 1 - al.array() * al.array() ); // - al + al^3

  VectorXd lapl= 2*( alal3 - cp );

  poisson( lapl , al );

  vctr_to_field( al , alpha);

  return;

}
Exemplo n.º 17
0
void linear::chempot_inv(const kind::f alpha,
			 const FT dt,
			 const kind::f alpha0 ) {

  const FT D=0.04;

  VectorXd al  = field_to_vctr( alpha  );
  VectorXd al0  = field_to_vctr( alpha0 );

  VectorXd diff = (1.0/ ( D * dt ) ) * ( al - al0) ;

  VectorXd cp( diff.size() );

  poisson( diff , cp );

  vctr_to_field( cp , kind::CHEMPOT );

  return;

}
Exemplo n.º 18
0
void initializeNodeInfo(staInfo sta[], apInfo* ap){
	int i, j;

	for(i=0; i<gSpec.numSta; i++){
		for(j=0; j<BUFFER_SIZE; j++){
			sta[i].buffer[j].lengthMsdu = 0;
			sta[i].buffer[j].timeStamp = 0.0;
			/*if(sta[i].sumFrameLengthInBuffer>(gSpec.bufferSizeByte*1000)){
				sta[i].waitFrameLength = sta[i].buffer[i].lengthMsdu;
				sta[i].sumFrameLengthInBuffer -= sta[i].buffer[i].lengthMsdu;
				sta[i].buffer[i].lengthMsdu = 0;
				sta[i].buffer[i].timeStamp = 0.0;
				break;
			}*/
		}
		sta[i].buffer[0].lengthMsdu = traffic(true);
		sta[i].sumFrameLengthInBuffer = sta[i].buffer[0].lengthMsdu;
		sta[i].waitFrameLength = traffic(true);
		sta[i].backoffCount = rand() % (gStd.cwMin + 1);
		sta[i].cw = gStd.cwMin;
		sta[i].retryCount = 0;
		sta[i].numTxFrame = 0;
		sta[i].numCollFrame = 0;
		sta[i].numLostFrame = 0;
		sta[i].numSuccFrame = 0;
		sta[i].numPrimFrame = 0;
		sta[i].byteSuccFrame = 0;
		sta[i].fCollNow = false;
		sta[i].afterColl = 0;
		sta[i].fSuccNow = false;
		sta[i].afterSucc = 0;
		sta[i].fTx = false;
		//sta[i].sumFrameLengthInBuffer = 0;
		sta[i].sumDelay = 0.0;
		sta[i].x = (double)(rand() % 1000 + 1) / 10;
		sta[i].y = (double)(rand() % 1000 + 1) / 10;
		sta[i].txPower = 20.0;   //dBm
		sta[i].antennaGain = 2.0;   //dBi
		sta[i].timeNextFrame = poisson(true);
	}

	for(i=0; i<BUFFER_SIZE; i++){
		ap->buffer[i].lengthMsdu = 0;
		ap->buffer[i].timeStamp = 0.0;
		/*if(ap->sumFrameLengthInBuffer>(gSpec.bufferSizeByte*1000)){
			ap->waitFrameLength = ap->buffer[i].lengthMsdu;
			ap->sumFrameLengthInBuffer -= ap->buffer[i].lengthMsdu;
			ap->buffer[i].lengthMsdu = 0;
			ap->buffer[i].timeStamp = 0.0;
			break;
		}*/
	}
	ap->buffer[0].lengthMsdu = traffic(false);
	ap->sumFrameLengthInBuffer = ap->buffer[0].lengthMsdu;
	ap->waitFrameLength = traffic(false);
	ap->backoffCount = rand() % (gStd.cwMin + 1);
	ap->cw = gStd.cwMin;
	ap->retryCount = 0;
	ap->numTxFrame = 0;
	ap->numCollFrame = 0;
	ap->numLostFrame = 0;
	ap->numSuccFrame = 0;
	ap->numPrimFrame = 0;
	ap->byteSuccFrame = 0;
	ap->fCollNow = false;
	ap->afterColl = 0;
	ap->fSuccNow = false;
	ap->afterSucc = 0;
	ap->fTx = false;
	//ap->sumFrameLengthInBuffer = 0;
	ap->sumDelay = 0.0;
	ap->x = 0.0;
	ap->y = 0.0;
	ap->txPower = 20.0;
	ap->antennaGain = 2.0;
	ap->timeNextFrame = poisson(false);
}
Exemplo n.º 19
0
/* Define a function to simulate a server.
 * This function processes the sent packet according to the server script,
 * creates a reply packet and pushes the reply packet onto the event queue
 */
int simulate_server(
    sockaddr_u *serv_addr,		/* Address of the server */
    struct interface *inter,		/* Interface on which the reply should
					   be inserted */
    struct pkt *rpkt			/* Packet sent to the server that
					   needs to be processed. */
)
{
    struct pkt xpkt;	       /* Packet to be transmitted back
				  to the client */
    struct recvbuf rbuf;       /* Buffer for the received packet */
    Event *e;		       /* Packet receive event */
    server_info *server;       /* Pointer to the server being simulated */
    script_info *curr_script;  /* Current script being processed */
    int i;
    double d1, d2, d3;	       /* Delays while the packet is enroute */
    double t1, t2, t3, t4;     /* The four timestamps in the packet */

    memset(&xpkt, 0, sizeof(xpkt));
    memset(&rbuf, 0, sizeof(rbuf));

    /* Search for the server with the desired address */
    server = NULL;
    for (i = 0; i < simulation.num_of_servers; ++i) {
	fprintf(stderr,"Checking address: %s\n", stoa(simulation.servers[i].addr));
	if (memcmp(simulation.servers[i].addr, serv_addr, 
		   sizeof(*serv_addr)) == 0) { 
	    server = &simulation.servers[i];
	    break;
	}
    }

    fprintf(stderr, "Received packet for: %s\n", stoa(serv_addr));
    if (server == NULL)
	abortsim("Server with specified address not found!!!");
    
    /* Get the current script for the server */
    curr_script = server->curr_script;

    /* Create a server reply packet. 
     * Masquerade the reply as a stratum-1 server with a GPS clock
     */
    xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING, NTP_VERSION,
                                     MODE_SERVER);
    xpkt.stratum = STRATUM_TO_PKT(((u_char)1));
    memcpy(&xpkt.refid, "GPS", 4);
    xpkt.ppoll = rpkt->ppoll;
    xpkt.precision = rpkt->precision;
    xpkt.rootdelay = 0;
    xpkt.rootdisp = 0;

    /* TIMESTAMP CALCULATIONS
	    t1				 t4
	     \				/
	  d1  \			       / d3
	       \		      /
	       t2 ----------------- t3
			 d2
    */
    /* Compute the delays */
    d1 = poisson(curr_script->prop_delay, curr_script->jitter);
    d2 = poisson(curr_script->proc_delay, 0);
    d3 = poisson(curr_script->prop_delay, curr_script->jitter);

    /* Note: In the transmitted packet: 
     * 1. t1 and t4 are times in the client according to the local clock.
     * 2. t2 and t3 are server times according to the simulated server.
     * Compute t1, t2, t3 and t4
     * Note: This function is called at time t1. 
     */

    LFPTOD(&rpkt->xmt, t1);
    t2 = server->server_time + d1;
    t3 = server->server_time + d1 + d2;
    t4 = t1 + d1 + d2 + d3;

    /* Save the timestamps */
    xpkt.org = rpkt->xmt;     
    DTOLFP(t2, &xpkt.rec);
    DTOLFP(t3, &xpkt.xmt);
    xpkt.reftime = xpkt.xmt;



    /* Ok, we are done with the packet. Now initialize the receive buffer for
     * the packet.
     */
    rbuf.receiver = receive;   /* Function to call to process the packet */
    rbuf.recv_length = LEN_PKT_NOMAC;
    rbuf.recv_pkt = xpkt;
    rbuf.used = 1;

    memcpy(&rbuf.srcadr, serv_addr, sizeof(rbuf.srcadr));
    memcpy(&rbuf.recv_srcadr, serv_addr, sizeof(rbuf.recv_srcadr));
    if ((rbuf.dstadr = malloc(sizeof(*rbuf.dstadr))) == NULL)
	abortsim("malloc failed in simulate_server");
    memcpy(rbuf.dstadr, inter, sizeof(*rbuf.dstadr));
    /* rbuf.link = NULL; */

    /* Create a packet event and insert it onto the event_queue at the 
     * arrival time (t4) of the packet at the client 
     */
    e = event(t4, PACKET);
    e->rcv_buf = rbuf;
    enqueue(event_queue, e);
    

    /* Check if the time of the script has expired. If yes, delete the script.
     * If not, re-enqueue the script onto the server script queue 
     */
    if (curr_script->duration > simulation.sim_time && 
	!empty(server->script)) {
	printf("Hello\n");
	/* 
	 * For some reason freeing up the curr_script memory kills the
	 * simulation. Further debugging is needed to determine why.
	 * free_node(curr_script);
	 */
	curr_script = dequeue(server->script);
    }

    return (0);
}
Exemplo n.º 20
0
arma::mat ung_ssm::sample_model(const unsigned int predict_type,
  const unsigned int nsim) {
  
  arma::cube alpha(m, n, nsim);
  std::normal_distribution<> normal(0.0, 1.0);
  
  for (unsigned int i = 0; i < nsim; i++) {
    
    alpha.slice(i).col(0) = a1;
    
    for (unsigned int t = 0; t < (n - 1); t++) {
      arma::vec uk(k);
      for(unsigned int j = 0; j < k; j++) {
        uk(j) = normal(engine);
      }
      alpha.slice(i).col(t + 1) =
        C.col(t * Ctv) + T.slice(t * Ttv) * alpha.slice(i).col(t) +
        R.slice(t * Rtv) * uk;
    }
  }
  if (predict_type < 3) {
    
    arma::cube y(1, n, nsim);
    
    switch(distribution) {
    case 0:
      y.zeros();
      break;
    case 1:
      for (unsigned int i = 0; i < nsim; i++) {
        for (unsigned int t = 0; t < n; t++) {
          y(0, t, i) = std::exp(xbeta(t) + D(t * Dtv) +
            arma::as_scalar(Z.col(t * Ztv).t() * alpha.slice(i).col(t)));
        }
      }
      break;
    case 2:
      for (unsigned int i = 0; i < nsim; i++) {
        for (unsigned int t = 0; t < n; t++) {
          double tmp = std::exp(xbeta(t) + D(t * Dtv) +
            arma::as_scalar(Z.col(t * Ztv).t() * alpha.slice(i).col(t)));
          y(0, t, i) = tmp / (1.0 + tmp);
        }
      }
      break;
    case 3:
      for (unsigned int i = 0; i < nsim; i++) {
        for (unsigned int t = 0; t < n; t++) {
          y(0, t, i) = std::exp(xbeta(t) + D(t * Dtv) +
            arma::as_scalar(Z.col(t * Ztv).t() * alpha.slice(i).col(t)));
        }
      }
      break;
    }
    
    if (predict_type == 1) {
      
      switch(distribution) {
      case 0:
        break;
      case 1:
        for (unsigned int i = 0; i < nsim; i++) {
          for (unsigned int t = 0; t < n; t++) {
            std::poisson_distribution<> poisson(u(t) * y(0, t, i));
            if ((u(t) * y(0, t, i)) < poisson.max()) {
              y(0, t, i) = poisson(engine);
            } else {
              y(0, t, i) = std::numeric_limits<double>::quiet_NaN();
            }
          }
        }
        break;
      case 2:
        for (unsigned int i = 0; i < nsim; i++) {
          for (unsigned int t = 0; t < n; t++) {
            std::binomial_distribution<> binomial(u(t), y(0, t, i));
            y(0, t, i) = binomial(engine);
          }
        }
        break;
      case 3:
        for (unsigned int i = 0; i < nsim; i++) {
          for (unsigned int t = 0; t < n; t++) {
            std::negative_binomial_distribution<>
            negative_binomial(phi, phi / (phi + u(t) * y(0, t, i)));
            y(0, t, i) = negative_binomial(engine);
          }
        }
        break;
      }
    }
    return y;
  }
  return alpha;
}
Exemplo n.º 21
0
int init_fld(Mode *fld) {
	int i;
	double dr = Params->dr;
	double r,lr;
	

	istart = NG;
	iend = NR+NG;
	
	fld->m = Params->m;
	
// #ifdef OPENMP
//         #pragma omp parallel private(i,r,lr) shared(fld)
//         #pragma omp for schedule(static)
// #endif
	for(i=0;i<NTOT;i++) {
		lr = (Params->rmin) + (.5 + i -NG ) * dr;
		fld->lr[i] = lr;
#ifdef LOG10
		fld->r[i] = pow(10,lr);
#else
		fld->r[i] = exp(lr);
#endif
		r = fld->r[i];
		Params->hor[i] = (Params->h)*pow(r,Params->indfl);

		
		bfld->sig[i] = (Params->sig0)*pow(r,Params->indsig);
		
		bfld->omk[i] = (Params->om0)*pow(r,Params->q);
		bfld->dlomk[i] = (Params->q);
		
		
		Params->c2[i] = (Params->hor[i])*
							(Params->hor[i])*r*r*(bfld->omk[i])*(bfld->omk[i]);
		
		Params->nus[i] = (Params->alpha_s)*(Params->hor[i])*(Params->hor[i])*(bfld->omk[i])*r*r;
		Params->nub[i] = (Params->alpha_b)*(Params->hor[i])*(Params->hor[i])*(bfld->omk[i])*r*r;

#ifdef PRESSURECORRECTION		
		bfld->omk[i] *= sqrt( 1 + (Params->hor[i])*(Params->hor[i])*(Params->indsig));
		
 		bfld->dlomk[i] += 
 				(1-pow((Params->om0)*pow(r,Params->q)/(bfld->omk[i]),2))*(Params->indfl);
#endif			
		bfld->v[i] = r * (bfld->omk[i]);
		bfld->u[i] = 0;
		bfld->dru[i] = 0;
		fld->u[i] = 0;
		fld->v[i] = 0;
		fld->sig[i] = 0;
#ifdef SELFGRAV
		fld->phi_sg[i] = 0;
		fld->gr_sg[i] = 0;
		fld->gp_sg[i] = 0;
#endif

/* Non power law density and sound speed profiles */
// 
// 		bfld->sig[i] = (Params->sig0)* (1 - pow(exp(Params->rmin)/r,10))*sqrt(exp(Params->rmin)/r);
// 		Params->c2[i] = .05*.05 * (1- exp(Params->rmin)/r)*(exp(Params->rmin)/r);

	}
	Params->indnus = 2 *(Params->indfl) + Params->q + 2;
	Params->indnub = 2 *(Params->indfl) + Params->q + 2;
	
	calc_cmax(fld);

#ifdef RESTART
	printf("Reading restart file...\n");
	int restart_status = restart(fld);	
	if (restart_status == -1) return -1;
#else


#ifndef INFINITE
	user_ic(fld);
#endif

/* Set B.C */	
/* Grab the inner and outer b.c's from the initialized profile. */

	u_in_bc = 0; // I*(bfld->v[istart])*.1 * cexp(I*0);
	u_out_bc =  I*(bfld->v[iend-1])*.1 * cexp(I*0);
	
	v_in_bc = 0; //.5*(bfld->v[istart])*.1* cexp(I*0);
	v_out_bc = .5*(bfld->v[iend-1])*.1 * cexp(I*0);
	
//	s_in_bc = fld->sig[istart];
	s_in_bc = 0;
	s_out_bc = fld->sig[iend-1];
//	s_out_bc = fld->sig[iend-1];
	

#endif
#ifdef COMPANION	
	init_cstar(fld);
#endif
#ifdef INDIRECT	
	init_CentralStar(fld);
	output_CentralStar(Params->t0,0);
#endif
#ifdef SELFGRAV
	printf("Initializing self gravity\n");
	init_poisson(fld->m,fld->r);
	printf("Solving for self gravity based on i.c \n");
	poisson(fld);
	output_selfgrav(fld);

#ifdef SGCORRECTION	
	for(i=0;i<NR;i++) {
		bfld->omk[i+istart] = sqrt((bfld->omk[i+istart])*(bfld->omk[i+istart]) 
										- (bfld->gr_sg[i] / (fld->r[i+istart])));
		bfld->v[i+istart] = (bfld->omk[i+istart])*(fld->r[i+istart]);
	}
	for(i=1;i<NTOT-1;i++) {
		if (i == 1) {
			bfld->dlomk[i] = (log(bfld->omk[i+1]) - log(bfld->omk[i]))/(Params->dr);
		}
		else {
			bfld->dlomk[i] = (log(bfld->omk[i]) - log(bfld->omk[i-1]))/(Params->dr);
		}
	}
	bfld->dlomk[0] = bfld->dlomk[1];
	bfld->omk[0] = bfld->omk[1] - (bfld->dlomk[0])*(Params->dr);
	bfld->dlomk[NTOT-1] = bfld->dlomk[NTOT-2];
	bfld->omk[NTOT-1] =  bfld->omk[NTOT-2] + (bfld->dlomk[NTOT-1])*(Params->dr);
#endif
#endif	


	return 0;
}
Exemplo n.º 22
0
// The function gradcg is overloaded to avoid trouble with
// variable length arrays that the strict CRAN policy does not
// allow
void MixMod::gradcg(std::vector<double> gradq,std::vector<double> p1,
                    std::vector<double>t1)
{
//int nump;
int i,j,ii;
double s,b;
double **pij, **xft;
double *s1t;
/*if (longmode) {
   pij = new double *[kk];
   xft = new double *[kk];
   for (i=0;i<kk;i++) {xft[i]=new double[nnlong];
                      pij[i] = new double [nnlong];}
   s1t = new double[nnlong];}
else {   
   pij = new double *[kk];
   xft = new double *[kk];
   for (i=0;i<kk;i++) {xft[i]=new double[nn];
                      pij[i] = new double [nn];}
   s1t = new double[nn];}
   */
//new
   pij = (double **) R_alloc(k, sizeof(double *));
   xft =(double **) R_alloc(k, sizeof(double *));
   for (i=0;i<k;i++) {xft[i]=(double *) R_alloc(n, sizeof(double));
                      pij[i] = (double *) R_alloc(n, sizeof(double));}
   s1t = (double *) R_alloc(n, sizeof(double));


int l;


// Number of mixing weights
l=k-1;


// Number of parameters in the model
//nump=2*k-1;

// temporary matrix of function values
  for(i=0;i<n;i++)
   {
    s=0.;
       for(j=0;j<k;j++)
      {
       xft[i][j]=poisson(x[i][0],t1[j]);
       s=s+p1[j]*xft[i][j];
      }
     s1t[i]=s;
  }

  /* Computation of Q�(theta,theta�) 
	   which gives the score of the complete 
	   data likelihood */


// E-Step  Posteriori expectation of component membership
  
   for(i=0;i<n;i++)
   {
       for(j=0;j<k;j++)
      {
       xft[i][j]=poisson(x[i][0],t1[j]);
       pij[i][j]=0.;
       if(s1[i] > 1.E-12)
       pij[i][j]=p1[j]*xft[i][j]/s1t[i];
      } 
   }
 

   // Gradient of LogL()

// First part: The k-1 mixing weights using the constraint that sum p_j =1

       l=k-1;
       for(j=0;j<l;j++)
       {
        s=0.;
        for(i=0;i<n;i++)
	{
                         
         b=xft[i][j]-xft[i][l]; // Contribution of the last component to the gradient
         if(s1t[i] > 1.E-12) s=s+x[i][1]*b/s1t[i];
	}  
	gradq[j]=s;
       }
      
       // Second part: Population parameters 
       ii=l;
        for(j=0;j<k;j++)
       {
        s=0.;
        for(i=0;i<n;i++)
       {
       b=0.;
       if(fabs(t1[j]) > 1.E-10)  b=(x[i][0]-t1[j])/t1[j];
       s=s+x[i][1]*pij[i][j]*b;
   
       }
     
        gradq[ii]=s;
        ii++;
     }
}
Exemplo n.º 23
0
void createPseudoDataFunc(double luminosity, const std::string decayChannel, TString specifier){
  // specifier="NoDistort" for closure test; "topPtUp", "topPtDown", "ttbarMassUp", "ttbarMassDown" or "data" for shape distortions; "1000" for Zprime
  // "verbose": set detail level of output ( 0: no output, 1: std output 2: output for debugging )
  int verbose=0;
  // "smear": say if you want to do a poisson smearing for each bin or just a combination for the different samples 
  bool smear=false;
  // "dataFile": absolute path of data file, used to define plots of interest
  TString dataFile= "";
  if(decayChannel.compare("electron")==0) dataFile="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/elecDiffXSecData2012ABCDAll.root";
  else                                    dataFile="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/muonDiffXSecData2012ABCDAll.root";
  // "useReweightedTop": use parton level reweighted ttbar signal file in pseudo data?
  bool useReweightedTop = (specifier.Contains("NoDistort")) ? false : true;
  // "zprime": include additional Zprime in pseudo data?
  bool zprime=specifier.Contains("1000") ? true : false;
  // naming for outputfile, constructed within macro
  TString outNameExtension="";

  // check input parameter validity
  // type of closure test
  if(!(specifier.Contains("NoDistort")||specifier.Contains("1000")||specifier.Contains("data")||specifier.Contains("topPtUp")||specifier.Contains("topPtDown")||specifier.Contains("ttbarMassUp")||specifier.Contains("ttbarMassDown")||specifier.Contains("topMass161p5")||specifier.Contains("topMass163p5")||specifier.Contains("topMass166p5")||specifier.Contains("topMass169p5")||specifier.Contains("topMass175p5")||specifier.Contains("topMass178p5")||specifier.Contains("topMass181p5")||specifier.Contains("topMass184p5"))){
    std::cout << "ERROR: invalid input specifier=" << specifier << std::endl;
    std::cout << "supported are: specifier=NoDistort,1000,data,topPtUp,topPtDown,ttbarMassUp,ttbarMassDown,topMass161p5,topMass163p5,topMass166p5,topMass169p5,topMass175p5,topMass178p5,topMass181p5,topMass184p5" << std::endl;
    exit(0);
  }
  // decay channel
  if(!(decayChannel.compare("electron")==0||decayChannel.compare("muon")==0)){
    std::cout << "ERROR: invalid input decayChannel=" << decayChannel << std::endl;
    std::cout << "supported are: decayChannel=muon,electron" << std::endl;
    exit(0);
  }
  

  //  ---
  //     create container for histos and files
  //  ---
  std::map<unsigned int, TFile*> files_;
  std::map< TString, std::map <unsigned int, TH1F*> > histo_;
  std::map< TString, std::map <unsigned int, TH2F*> > histo2_;

  //  ---
  //     parton level reweighted top distribution
  //  ---
  // a) name and path of rootfile
  // path
  TString nameTtbarReweighted="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/";
  // subfolder for reweighting systematics
  if(specifier!="NoDistort"&&!specifier.Contains("p5")){
    nameTtbarReweighted+="ttbarReweight/";
    // SG reweighting test
    if(decayChannel.compare("electron")==0) nameTtbarReweighted+="elecDiffXSec";
    else                                    nameTtbarReweighted+="muonDiffXSec";
    nameTtbarReweighted+="SigSysDistort"+specifier+"Summer12PF.root";
  }
  else{
    // SG sample for corresponding top mass
    int sys=sysNo; // == "NoDistort"
    if(     specifier=="topMass161p5") sys=sysTopMassDown4;
    else if(specifier=="topMass163p5") sys=sysTopMassDown3;
    else if(specifier=="topMass166p5") sys=sysTopMassDown2;
    else if(specifier=="topMass169p5") sys=sysTopMassDown;
    else if(specifier=="topMass175p5") sys=sysTopMassUp;
    else if(specifier=="topMass178p5") sys=sysTopMassUp2;
    else if(specifier=="topMass181p5") sys=sysTopMassUp3;
    else if(specifier=="topMass184p5") sys=sysTopMassUp4;
    nameTtbarReweighted+=TopFilename(kSig, sys, decayChannel);
  }
  // BG
  TString nameTtbarBGReweighted=nameTtbarReweighted;
  nameTtbarBGReweighted.ReplaceAll("Sig","Bkg");
  if(useReweightedTop&&!specifier.Contains("p5")) outNameExtension+="Reweighted"+specifier;
  // b) get average weight for reweighted samples
  double avWeight=1;
  if(useReweightedTop && specifier!="NoDistort"&& !specifier.Contains("p5")){
    TFile* ttbarRewfile = new (TFile)(nameTtbarReweighted);
    TString weightPlot="eventWeightDileptonModelVariation/modelWeightSum";
    histo_["avWeight"][kSig] = (TH1F*)(ttbarRewfile->Get(weightPlot)->Clone());
    avWeight=histo_ ["avWeight"][kSig]->GetBinContent(2)/histo_ ["avWeight"][kSig]->GetBinContent(1);
    histo_["avWeight"].erase(kSig);
    TFile* sigfile = new (TFile)("/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"+TopFilename(kSig, sysNo, decayChannel));
    TString partonPlot="analyzeTopPartonLevelKinematics/ttbarMass";
    gROOT->cd();
    histo_["parton"   ][kSig] = (TH1F*)(sigfile     ->Get(partonPlot)->Clone());
    histo_["partonRew"][kSig] = (TH1F*)(ttbarRewfile->Get(partonPlot)->Clone());
    double avWeight2  = histo_["partonRew"][kSig]->Integral(0, histo_["partonRew"][kSig]->GetNbinsX()+1);
    avWeight2        /= histo_["parton"   ][kSig]->Integral(0, histo_["parton"   ][kSig]->GetNbinsX()+1);
    if(verbose>1){
      std::cout << "ratio unweighted/weighted" << std::endl;
      std::cout << avWeight  << " (from " << weightPlot << ")" << std::endl;
      std::cout << avWeight2 << TString(" (from entries in ")+partonPlot+" wrt /afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"+TopFilename(kSig, sysNo, decayChannel)+"): " << std::endl;
    }
  }

  //  ---
  //     Z prime 
  //  ---
  // xSec scaling (default value chosen for M1000W100: 5pb)
  double xSecSF=1.0;
  // path & naming
  TString zprimeMass =specifier;
  TString zprimeWidth=specifier;
  zprimeWidth.ReplaceAll("1000", "100");
  TString nameZprime="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/zprime/";
  if(decayChannel.compare("electron")==0) nameZprime+="elec";
  else                                    nameZprime+="muon";
  nameZprime+="DiffXSecZprimeM"+zprimeMass+"W"+zprimeWidth+"Summer12PF.root";
  // event weight wrt luminosity
  double zPrimeLumiWeight=1.;
  if     (zprimeMass=="1000") zPrimeLumiWeight=(xSecSF*5*luminosity)/104043;
  // naming of oututfile 
  TString xSecSFstr="";
  if      (xSecSF==0.5 ) xSecSFstr="x0p5";
  else if (xSecSF==0.25) xSecSFstr="x0p25";
  else if (xSecSF==0.1 ) xSecSFstr="x0p1";
  else if (xSecSF==0.03) xSecSFstr="x0p03";
  else if (xSecSF>1.   ) xSecSFstr="x"+getTStringFromDouble(xSecSF,0);
  if(zprime) outNameExtension="andM"+zprimeMass+"W"+zprimeWidth+xSecSFstr+"Zprime";
  // sample iteration limit
  int kLast  =kSAToptW;
  int kZprime=kLast+1;
  if(zprime) kLast=kZprime;

  if(zprime&&zPrimeLumiWeight==1){
    std::cout << "ERROR: chosen zprime weight is exactly 1!" << std::endl;
    exit(0);
  }
  
  // -------------------------
  // !!! choose luminosity !!!
  // -------------------------
  TString lum = getTStringFromInt(roundToInt(luminosity));
  // -----------------------------------------
  // !!! add all contributing samples here !!!
  // -----------------------------------------
  TString inputFolder = "/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/";
  // save all default top analysis samples in files_
  files_ = getStdTopAnalysisFiles(inputFolder, sysNo, dataFile, decayChannel);
  // remove combined file dor single Top & DiBoson
  if(files_.count(kSTop )>0)files_.erase(kSTop );
  if(files_.count(kDiBos)>0)files_.erase(kDiBos);
  // remove combined QCD file for electron channel
  if(decayChannel.compare("electron")==0&&files_.count(kQCD)>0) files_.erase(kQCD);
  // remove all QCD files to be consistent with later treatment
  if(files_.count(kQCD)>0) files_.erase(kQCD);
  if(decayChannel.compare("electron")==0){
    for(int sample = kQCDEM1; sample<=kQCDBCE3; sample++){
      if(files_.count(sample)>0) files_.erase(sample);
    }
  }
  // add zprime
  if(zprime) files_[kZprime]=new (TFile)(nameZprime);
  // exchange default ttbar files with the reweighted ones
  if(useReweightedTop){ 
    files_[kSig]=new (TFile)(nameTtbarReweighted  );
    files_[kBkg]=new (TFile)(nameTtbarBGReweighted);
  }

  //  -----------------------------------------
  //     get list of all plots to be considered
  //  -----------------------------------------
  std::vector<TString> plotList_;
  TString currentFolder ="";
  TString currentPlot   ="";
  if(verbose>0) std::cout << std::endl << "searching for all plots in file " << files_[kData]->GetName() << std::endl;
  // go to data file for getting plot names
  files_[kData]->cd();
  // loop objects in file
  TIter fileIterator(gDirectory->GetListOfKeys());
  if(verbose>2){
    std::cout << "looping objects in in ";
    gDirectory->pwd();
  }
  TKey *fileKey;
  int count=0;
  while( (fileKey = (TKey*)fileIterator()) ){
    ++count;
    if(verbose>2) std::cout << "folderObject #" << count;
    TObject *fileObject = fileKey->ReadObj(); 
    // check if object is a directory
    if(!(fileObject->InheritsFrom("TDirectory"))&&(verbose>2)) std::cout << " is no directory" << count << std::endl;
    if(fileObject->InheritsFrom("TDirectory")){
      currentFolder = (TString)fileObject->GetName();
      if(verbose>2) std::cout << " ("+currentFolder+")" << std::endl;
      // go to directory
      ((TDirectory*)fileObject)->cd();
      if(verbose>2){
	std::cout << "looping objects in in ";
	gDirectory->pwd();
      }
      TIter folderIterator(gDirectory->GetListOfKeys());
      TKey *folderKey;
      int count2=0;
      while( (folderKey = (TKey*)folderIterator()) ) {
	++count2;
	TObject *folderObject = folderKey->ReadObj(); 
	currentPlot = (TString)folderObject->GetName();
	if(verbose>2) std::cout << "plotObject #" << count2 << " ("+currentPlot+")" << std::endl;
	// check if object is a TH1 
	if(folderObject->InheritsFrom("TH1")){
	  if(verbose>2) std::cout << "inherits from TH1";
	  // check if TH2 and neglect because a simple 
	  // re-smearing is here not possible
	  if((folderObject->InheritsFrom("TH2"))&&(verbose>2)) std::cout << " and from TH2" << std::endl;
	  else{
	    if(verbose>2) std::cout << " and NOT from TH2" << std::endl;
	    // add to list of plots
	    if(verbose>2) std::cout << "will be added to list of output plots" << std::endl;
	    plotList_.push_back(currentFolder+"/"+currentPlot);
	  }
	}
      }
    }
  }
  // close data file after getting plot names
  files_[kData]->Close();
  // remove data file from list of considered files
  if(files_.count(kData )>0)files_.erase(kData );
  // print list of files considered
  if(verbose>0){
    std::cout << std::endl << "the following files will be considered: " << std::endl;
    // loop files
    for(int sample = kSig; sample<=kLast; sample++){
      // check existence of folder in all existing files
      if(files_.count(sample)>0){
	std::cout << files_[sample]->GetName() << std::endl;
      }
    }
  }
  // print out the name of all plots
  if(verbose>0){
    std::cout << std::endl << "list of all plots to be considered: " << std::endl;
    // loop list of plots
    for(unsigned int plot=0; plot<plotList_.size(); ++plot){
      std::cout << "\"" << plotList_[plot] << "\"" << std::endl;
    }
    std::cout << plotList_.size() << " plots in total" << std::endl;
  }
  // ---------------------------------------
  // !!! load all hists !!!
  // ---------------------------------------
  unsigned int N1Dplots=plotList_.size();
  int Nplots=0;
  if(verbose>0) std::cout << std::endl << "loading plots: " << std::endl;
  // a) for std analysis file (& reweighted ttbar)
  getAllPlots(files_, plotList_, histo_, histo2_, N1Dplots, Nplots, verbose-1);
  if(verbose>0){
    std::cout << Nplots << " plots loaded from " << plotList_.size();
    std::cout << " requested" << std::endl << "empty plots are not counted" << std::endl;
  }
  // b) for zprime
  if(zprime){ 
    for(unsigned int plot=0; plot<plotList_.size(); ++plot){
      histo_[plotList_[plot]][kZprime] = (TH1F*)(files_[kZprime]->Get(plotList_[plot]));
    }
  }

  // ---------------------------------------
  // !!! definition of output file(name) !!!
  // ---------------------------------------
  //TString outputfile="/afs/naf.desy.de/user/g/goerner/WGspace/RecentAnalysisRun8TeV_doubleKinFit/pseudodata/"+(TString)decayChannel+"PseudoData"+lum+"pb"+outNameExtension+"8TeV.root";
  TString outputfile="/afs/naf.desy.de/user/g/goerner/WGspace/RecentAnalysisRun8TeV_doubleKinFit/pseudodata/"+pseudoDataFileName(specifier, decayChannel);
  TFile* out = new TFile(outputfile, "recreate");
  if(verbose>0) std::cout << std::endl << "outputfile: " << outputfile << std::endl;
  poisson(histo_, plotList_, decayChannel, *out, luminosity, verbose, smear, useReweightedTop, avWeight, zprime, zPrimeLumiWeight);

  // free memory
  for(std::map< TString, std::map <unsigned int, TH1F*> >::iterator histo=histo_.begin(); histo!=histo_.end(); ++histo){
    for(std::map <unsigned int, TH1F*>::iterator histoSub=histo->second.begin(); histoSub!=histo->second.end(); ++histoSub){
      if(histoSub->second) delete histoSub->second;
    }
    histo->second.clear();
  }
  histo_ .clear();
  for(std::map< TString, std::map <unsigned int, TH2F*> >::iterator histo2=histo2_.begin(); histo2!=histo2_.end(); ++histo2){
    for(std::map <unsigned int, TH2F*>::iterator histo2Sub=histo2->second.begin(); histo2Sub!=histo2->second.end(); ++histo2Sub){
      if(histo2Sub->second) delete histo2Sub->second;      
    }
    histo2->second.clear();
  }
  histo2_ .clear();
  for(std::map<unsigned int, TFile*>::const_iterator file=files_.begin(); file!=files_.end(); ++file){
    if(file->second){
      file->second->Close();	  
      delete file->second;
    }
  }
  files_ .clear();
  out->Close();
  delete out;

}
int main(int argc, char *argv[]) {

	int socketFD, sockfd2;
	int rate = DEFAULT_INTERVAL;
	char msg[141];
	
	struct addrinfo hints;
	struct addrinfo *servinfo;
	
	struct timespec sleepTime = {0, 100};

	FILE *input = fopen("MMSposter.jpg", "rb");


	fseek(input, 0L, SEEK_END);
 	int size = ftell(input);
 	fseek(input, 0L, SEEK_SET);

	
	//Get sockets
	socketFD = socket(AF_INET, SOCK_DGRAM, 0);
	if (socket < 0){
		printf("Error: Could not get socket.");
		exit(1);
	}
	
	//Get connection info
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE;
	
	if (getaddrinfo("10.10.66.90", "56790", &hints, &servinfo) != 0 || servinfo == NULL) {
	    printf("Error: Could not find router.");
	    exit(1);
	}

	

	int count = 1;
	int i;
	double timestamp;
	int tail = size % 128;


	printf("%d\n", tail);

	int a[32];
	while(fread(&a, 32*sizeof(int), 1, input) && !feof(input)) {
		sleepTime.tv_nsec = poisson((float)R)*1000000;
		nanosleep(&sleepTime, NULL);
		
		memcpy(msg,a,128);
		msg[128] = '1';   // flow number
		memcpy(msg+129, &count, 4);
		timestamp = clock()/(double)CLOCKS_PER_SEC;

		memcpy(msg+133, &timestamp, 8);
		

		if (sendto(socketFD, msg, 141, 0, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
			printf("Sending failed!\n");
			exit(1);
		}
		
		count += 1;
	}



	if (tail != 0) {
		fread(&a, tail, 1, input);
		sleepTime.tv_nsec = poisson((float)R)*1000000;
		nanosleep(&sleepTime, NULL);
		int temp = INT_MAX;
		
		memcpy(msg, &a, tail);
		msg[128] = '1';   // flow number
		memcpy(msg+129, &temp, 4);

		memcpy(msg+133, &tail,4);
		memcpy(msg+137, &count,4);

		printf("%d\n",*(int *)(msg+133));
		printf("%d\n",*(int *)(msg+137));

		if (sendto(socketFD, msg, 141, 0, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
			printf("Sending failed!\n");
			exit(1);
		}

		printf("%d\n", tail);
		
	}

	fclose(input);
	
	return 0;
}
double flow_poster_prob_calc::best_hyp(flow_list *alter_hyp, flow_list *read_list, int cov, float vh, char *line_out)
{
    int num_hyp = alter_hyp->num_list();
    int best = -1;
    double bscore = 1e20;
    double sbscore = 1e20;
    int i, num_r = read_list->num_list();
    unsigned char *s;
    int *f;
    int len;
    if (num_hyp == 0) return 0.0;
    for (i = 0; i < num_hyp; i++) {
	int j;
	double prior;
	alter_hyp->get_list(i, s, f, len, prior);
	setRef(len, s, f);
	double score = 0.0;
    	unsigned char *s1;
    	int *f1;
    	int len1;
	if (debug) alter_hyp->output_hyp(i);
	for (j = 0; j < num_r; j++) {
	    double p1;
	    read_list->get_list(j, s1, f1, len1, p1);
	    double x = calc_post_prob(len1, s1, f1, (p1 >0.0)? 1:-1);
	    score += x;
	}
	score -= log10(prior)*10.0;

	if (score < bscore) {
	    sbscore = bscore;
	    bscore = score;
	    best = i;
	} else if (score < sbscore) {
	    sbscore  = score;
	}
    }
    if (debug) printf("best =%f  second=%f\n", bscore, sbscore);
    double ex =-(sbscore-bscore)/num_r/10.0;
    ex = pow(10.0, ex);
    if (num_r > cov) ex = ex*(cov+num_r);
    else ex = ex*cov;
    double xxx = poisson(num_r, ex);
    if (num_r > cov) xxx = xxx*cov/num_r;
    if (vh > 75.0 && (best == 0 || xxx < 1.0)) {
	best = 1;
	xxx = vh*2.0;
    }
    //xxx = -log10(xxx)*10.0;
    //printf("PPP=log odd p-value=%f %f %f %f %f\n", (float) (sbscore-bscore), (float) sbscore, (float) bscore, (float) xxx, (float) ex);
    
    int is_hotspot = 0;
    if (alter_hyp->is_indel()) {
 	is_hotspot =  check_is_hotspot(line_out);
    }
    if (best != 0) {
	//printf("PPP=Refe="); alter_hyp->output_hyp(0); 
    	//printf("PPP=Call="); alter_hyp->output_hyp(best);
	xxx = xxx*0.63;  // normalization
	output_line(xxx, line_out, is_hotspot);
    } else {
	//printf("PPP1=Refe="); alter_hyp->output_hyp(0);
	output_line(0.0, line_out, is_hotspot);
	xxx = 0.0;
	//fprintf(outp, "Bayesian_Score=0\n");
    }
    return xxx;
}
Exemplo n.º 26
0
void validation()
{
	msglvl[DBG] = SILENT;
	msglvl[INF] = VISUAL;
	msglvl[WRN] = VISUAL;
	msglvl[ERR] = VISUAL;
	msglvl[FAT] = VISUAL;

	TDirectory* oldDir = gDirectory; // remember old directory

	style();

	Int_t g4bin = (ng4bins/g4max+1); //==> g^4=1 ==> SSM !
	
	TString suffix = "";
	if(doTruth) suffix = "_truth";
	
	TString mctype  = (isMC11c) ? "mc11c" : "mc11a";
	
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_overallEWkF_noInAmpSigEWkF_noHighMbins_wthOfficialZP_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_mc11c_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_wthOfficialZP_fixedBWwidth_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_mc11c_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_treeLevelMass_Xmass2000.root";
	// TString fBGname = "plots/ZP_2dtemplates_"+mctype+"_33st_noKKtmplates_overallEWkF_noInAmpSigEWkF_noTruth_wthOfficialZP_fixedBWwidth_treeLevelMass_Xmass2000.root";

	TLegend* legR = new TLegend(0.15,0.75,0.35,0.85,NULL,"brNDC");
	legR->SetFillStyle(4000); //will be transparent
	legR->SetFillColor(0);
	legR->SetTextFont(42);
	TH1D* hDummy = new TH1D("","",1,0.,1.);
	hDummy->SetMarkerStyle(20);
	hDummy->SetMarkerSize(0.8);
	hDummy->SetMarkerColor(kBlack);
	if(!doResiduals) legR->AddEntry(hDummy,"#frac{template}{official}","lep");
	else             legR->AddEntry(hDummy,"#frac{template - official}{#sqrt{#delta^{2}template + #delta^{2}official}}","lep");
	
	TPaveText* ptxt = new TPaveText(0.145,0.35,0.245,0.55,"NDC");
	TText* txt;
	ptxt->SetTextSize(0.03);
	ptxt->SetBorderSize(0);
	ptxt->SetFillStyle(4000); //will be transparent
	ptxt->SetFillColor(0);
	ptxt->SetTextAlign(12);
	txt = ptxt->AddText("This range");
	txt = ptxt->AddText("is chopped");
	txt = ptxt->AddText("before the");
	txt = ptxt->AddText("template is");
	txt = ptxt->AddText("handed to");
	txt = ptxt->AddText("BAT (limit).");
	
	oldDir->cd();

	TString fBGname = "plots/validation/ZP_2dtemplates_mc11c_33st_noKKtmplates_wthOfficialZP_treeLevelMass_Xmass2000.root";
	TFile* fD = new TFile(fBGname,"READ");
	TH1D* hDY = NULL;
	if(doTruth) hDY = (TH1D*)fD->Get("hMass_DYmumu_truth")->Clone();
	else        hDY = (TH1D*)fD->Get("hMass_DYmumu")->Clone();
	hDY->SetLineColor(kMagenta-5);
	hDY->SetMarkerColor(kMagenta-5);

	oldDir->cd();

	TFile* fDYrozmin    = new TFile("plots/mass_plot_tables_3st.root","READ");
	TH1D* hDYrozmin = (TH1D*)fDYrozmin->Get("mass_log_dy")->Clone();
	hDYrozmin = (TH1D*)hGeV2TeV(hDYrozmin)->Clone();
	hDYrozmin = (TH1D*)hChopper(hDYrozmin,bins2chop)->Clone();
	oldDir->cd();
	TFile* f1dTemplates = new TFile("plots/ZpSignal_MM_MC11c_5points.root","READ");
	TObjArray* toarr1d = new TObjArray();
	toarr1d->Read("template");
	TMapTSP2TH1D h1dBrandeisTmpltMap;
	double Nflat = 399948;
	double sigmaflat = 4.3988E+07*nb2fb;
	double Lmcflat = Nflat/sigmaflat;
	double scale = luminosity/Lmcflat;
	TH1D* h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(0/*22*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1000",(TH1D*)resetErrors(h1dTmp)->Clone("1000")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(1/*28*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1250",(TH1D*)resetErrors(h1dTmp)->Clone("1250")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(2/*34*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1500",(TH1D*)resetErrors(h1dTmp)->Clone("1500")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(3/*40*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("1750",(TH1D*)resetErrors(h1dTmp)->Clone("1750")) );
	h1dTmp = NULL;
	h1dTmp = (TH1D*)((TObjArray*)toarr1d->At(4/*47*/))->Clone();
	h1dTmp->Scale(scale);
	h1dTmp = (TH1D*)hChopper(h1dTmp,bins2chop)->Clone();
	h1dTmp->Add(hDYrozmin);
	h1dBrandeisTmpltMap.insert( make_pair("2000",(TH1D*)resetErrors(h1dTmp)->Clone("2000")) );

	oldDir->cd();

	TMapTSP2TH1D h1Map;
	h1Map.insert( make_pair("1000o", (TH1D*)fD->Get("hMass_Zprime_SSM1000"+suffix)->Clone()) );
	h1Map.insert( make_pair("1000t", (TH1D*)fD->Get("hMass_Zprime_SSM1000_template"+suffix)->Clone()) );
	if(isMC11c)
	{
		h1Map.insert( make_pair("1250o", (TH1D*)fD->Get("hMass_Zprime_SSM1250"+suffix)->Clone()) );
		h1Map.insert( make_pair("1250t", (TH1D*)fD->Get("hMass_Zprime_SSM1250_template"+suffix)->Clone()) );
	}
	h1Map.insert( make_pair("1500o", (TH1D*)fD->Get("hMass_Zprime_SSM1500"+suffix)->Clone()) );
	h1Map.insert( make_pair("1500t", (TH1D*)fD->Get("hMass_Zprime_SSM1500_template"+suffix)->Clone()) );
	h1Map.insert( make_pair("1750o", (TH1D*)fD->Get("hMass_Zprime_SSM1750"+suffix)->Clone()) );
	h1Map.insert( make_pair("1750t", (TH1D*)fD->Get("hMass_Zprime_SSM1750_template"+suffix)->Clone()) );
	h1Map.insert( make_pair("2000o", (TH1D*)fD->Get("hMass_Zprime_SSM2000"+suffix)->Clone()) );
	h1Map.insert( make_pair("2000t", (TH1D*)fD->Get("hMass_Zprime_SSM2000_template"+suffix)->Clone()) );

	TMapTSP2TH1D h1rMap;
	h1rMap.insert( make_pair("1000", (TH1D*)fD->Get("hMass_Zprime_SSM1000"+suffix)->Clone()) );
	if(isMC11c) h1rMap.insert( make_pair("1250", (TH1D*)fD->Get("hMass_Zprime_SSM1250"+suffix)->Clone()) );
	h1rMap.insert( make_pair("1500", (TH1D*)fD->Get("hMass_Zprime_SSM1500"+suffix)->Clone()) );
	h1rMap.insert( make_pair("1750", (TH1D*)fD->Get("hMass_Zprime_SSM1750"+suffix)->Clone()) );
	h1rMap.insert( make_pair("2000", (TH1D*)fD->Get("hMass_Zprime_SSM2000"+suffix)->Clone()) );
	for(TMapTSP2TH1D::iterator it=h1rMap.begin() ; it!=h1rMap.end() ; ++it)
	{
		it->second->Reset();
		if(!doResiduals) it->second->Divide(h1Map[it->first+"o"],h1Map[it->first+"t"],1.,1.,"B");
		else             residuals(h1Map[it->first+"o"], h1Map[it->first+"t"], it->second);
		
		// for(Int_t i=0 ; i<=it->second->GetNbinsX()+1 ; i++) it->second->SetBinError(i,0);
		it->second->SetMarkerStyle(20);
		it->second->SetMarkerSize(0.5);
		it->second->GetXaxis()->SetLabelSize(0.073);
		it->second->GetYaxis()->SetLabelSize(0.073);
		it->second->GetXaxis()->SetTitleSize(0.073);
		it->second->GetYaxis()->SetTitleSize(0.073);
		it->second->SetTitleSize(0.075);
		it->second->GetYaxis()->SetTitleOffset(0.5);
		if(!doResiduals)
		{
			it->second->SetMinimum(0.2);
			it->second->SetMaximum(1.8);
		}
		else
		{
			it->second->SetMinimum(-5.);
			it->second->SetMaximum(+5.);
		}
		it->second->SetTitle("");
		if(!doResiduals) it->second->GetYaxis()->SetTitle("ratio");
		else             it->second->GetYaxis()->SetTitle("residuals");
	}

	TMapTSP2TGAE poissonGraphMap;
	TMapTSP2TLeg legMap;


	_INFO("");

	oldDir->cd();

	fD->cd();	
	TH1D* h1Template = (TH1D*)fD->Get("hMass_DYmumu"+suffix)->Clone();
	h1Template->Reset();
	TObjArray* toarr = new TObjArray();
	if(doTruth) toarr->Read("truth_template2d");
	else        toarr->Read("template2d");
	TH2D* h2SSM2000 = (TH2D*)((TObjArray*)toarr->At(0))->Clone("hMass"+suffix+"_Zprime_SSM2000_template2d");
	for(Int_t bin=1 ; bin<=h2SSM2000->GetNbinsX() ; bin++)
	{
		h1Template->SetBinContent(bin, h2SSM2000->GetBinContent(bin,g4bin));
		h1Template->SetBinError(bin, h2SSM2000->GetBinError(bin,g4bin));
	}
	h1Template->SetLineColor(kViolet);
	h1Template->SetLineWidth(1);
	h1Template->SetMarkerStyle(20);
	h1Template->SetMarkerSize(0.3);
	h1Template->SetMarkerColor(kViolet);
	// the functions
	h2Template = (TH2D*)h2SSM2000->Clone();
	vector<TF1*> vfunc;
	unsigned int nmllbins = h2Template->GetNbinsX();
	for(unsigned int mll=1 ; mll<=(nmllbins-bins2chop) ; mll++) // 1...(56-9 = 47)
	{
		TString mllname = (TString)_s(mll);
		TString mllval  = (TString)_s(h2Template->GetXaxis()->GetBinCenter(mll+bins2chop));
		
		TF1* f = new TF1("fNominal_mll"+mllname,fTH1toTF1,g4min,g4max,1);
		f->SetParameter(0,mll);
		f->SetParNames("mll");
		// f->SetLineColor(kBlue);
		// f->SetLineWidth(1);
		f->SetNpx(400);
		vfunc.push_back(f);
	}
	TGraph* graphDY = new TGraph();
	graphDY->SetMarkerStyle(25);
	graphDY->SetMarkerSize(0.6);
	graphDY->SetMarkerColor(kGreen+2);
	TGraph* graphSSM = new TGraph();
	graphSSM->SetMarkerStyle(24);
	graphSSM->SetMarkerSize(0.6);
	graphSSM->SetMarkerColor(kOrange+8);
	for(unsigned int i=0 ; i<vfunc.size() ; i++)
	{
		double DY = vfunc[i]->Eval(0.0);
		double SSM = vfunc[i]->Eval(1.0);
		graphDY->SetPoint(i,h2Template->GetXaxis()->GetBinCenter(bins2chop+i+1),DY);
		graphSSM->SetPoint(i,h2Template->GetXaxis()->GetBinCenter(bins2chop+i+1),SSM);
	}
	
	
	oldDir->cd();

	TObjArray* toarr1dTLV = new TObjArray();
	TMapTSP2TH1D h1dTlvTmpltMap;
	TFile* fT = NULL;
	TString fTname = "plots/validation/ZP_2dtemplates_mc11c_33st_noInterference_noKKtmplates_noOverallEWkF_wthOfficialZP_treeLevelMass_Xmass";
	
	fT = new TFile(fTname+"1000.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1000",(TH1D*)resetErrors(h1dTmp)->Clone("1000")) );
	fT = new TFile(fTname+"1250.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1250",(TH1D*)resetErrors(h1dTmp)->Clone("1250")) );
	fT = new TFile(fTname+"1500.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1500",(TH1D*)resetErrors(h1dTmp)->Clone("1500")) );
	fT = new TFile(fTname+"1750.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("1750",(TH1D*)resetErrors(h1dTmp)->Clone("1750")) );
	fT = new TFile(fTname+"2000.root","READ");
	toarr1dTLV->Read("template");
	h1dTmp = (TH1D*)((TObjArray*)toarr1dTLV->At(0))->Clone();
	h1dTmp->Add(hDY);
	h1dTlvTmpltMap.insert( make_pair("2000",(TH1D*)resetErrors(h1dTmp)->Clone("2000")) );

	oldDir->cd();
	
	
	for(TMapTSP2TH1D::iterator it=h1Map.begin() ; it!=h1Map.end() ; ++it)
	{
		if(it->first.Contains("o"))
		{
			TString name = it->first;
			name.ReplaceAll("o","");
			it->second->SetFillColor(kAzure-9);
			if(doTruth) it->second->SetTitle("m_{Z'} = "+name+" GeV (truth)");
			else        it->second->SetTitle("m_{Z'} = "+name+" GeV");
		}
		if(it->first.Contains("t"))
		{
			//TGraphAsymmErrors* poisson(TH1D* h)
			it->second->SetLineColor(kBlue);
			it->second->SetMarkerStyle(20);
			it->second->SetMarkerSize(0.4);
			it->second->SetMarkerColor(kBlue);
			it->second->SetLineWidth(1);
			
			TString name = it->first;
			name.ReplaceAll("t","");
			poissonGraphMap.insert( make_pair(name, (TGraphAsymmErrors*)poisson(it->second)->Clone()) );
			poissonGraphMap[name]->SetMarkerStyle(20);
			poissonGraphMap[name]->SetMarkerSize(0.3);
			poissonGraphMap[name]->SetMarkerColor(kBlue);
			poissonGraphMap[name]->SetLineWidth(1);
			poissonGraphMap[name]->SetLineColor(kBlue);
		}
	}	

	Double_t yLine = (!doResiduals) ? 1. : 0.;

	TLine* line = new TLine(0.07,yLine,3.,yLine);	
	line->SetLineColor(kRed);
	line->SetLineWidth(2);
	
	TMapTSP2TCNV cnvMap;
	cnvMap.insert( make_pair("1000", new TCanvas("1000","1000",600,550)) );
	if(isMC11c) cnvMap.insert( make_pair("1250", new TCanvas("1250","1250",600,550)) );
	cnvMap.insert( make_pair("1500", new TCanvas("1500","1500",600,550)) );
	cnvMap.insert( make_pair("1750", new TCanvas("1750","1750",600,550)) );
	cnvMap.insert( make_pair("2000", new TCanvas("2000","2000",600,550)) );
	for(TMapTSP2TCNV::iterator it=cnvMap.begin() ; it!=cnvMap.end() ; ++it)
	{
		_INFO("starting "+(string)it->first);
		if(it->first=="2000") legMap.insert( make_pair(it->first, new TLegend(0.35,0.55,0.83,0.84,NULL,"brNDC")) );
		else                  legMap.insert( make_pair(it->first, new TLegend(0.35,0.60,0.83,0.84,NULL,"brNDC")) );
		legMap[it->first]->SetFillStyle(4000); //will be transparent
		legMap[it->first]->SetFillColor(0);
		legMap[it->first]->SetTextFont(42);
		legMap[it->first]->AddEntry(h1Map[it->first+"o"],"Official Z'_{SSM}","F");
		legMap[it->first]->AddEntry(hDY,"Official DY#mu#mu","lep");
		legMap[it->first]->AddEntry(h1Map[it->first+"t"],"ME^{2} method: Template w/o couplings scale","lep");
		if(it->first=="2000")
		{
			legMap[it->first]->AddEntry(h1Template,"ME^{2} method: Template histogram at  #it{g=1} (SSM)","lep");
			legMap[it->first]->AddEntry(graphSSM,  "ME^{2} method: Template function  at  #it{g=1} (SSM)","p");
			legMap[it->first]->AddEntry(graphDY,   "ME^{2} method: Template function  at  #it{g=0} (DY)","p");
		}
		if(!doTruth)
		{
			h1dTlvTmpltMap[it->first]->SetLineColor(kCyan+2);
			h1dTlvTmpltMap[it->first]->SetMarkerColor(kCyan+2);
			h1dTlvTmpltMap[it->first]->SetMarkerStyle(5);
			h1dTlvTmpltMap[it->first]->SetMarkerSize(0.5);
			legMap[it->first]->AddEntry(h1dTlvTmpltMap[it->first],"ME^{2} method: DY+Template (no interference)","p");
		
			h1dBrandeisTmpltMap[it->first]->SetLineColor(kRed);
			h1dBrandeisTmpltMap[it->first]->SetMarkerColor(kRed);
			h1dBrandeisTmpltMap[it->first]->SetMarkerStyle(27);
			h1dBrandeisTmpltMap[it->first]->SetMarkerSize(0.5);
			legMap[it->first]->AddEntry(h1dBrandeisTmpltMap[it->first],"Flat Z' method: DY+Template (no interference)","p");
		}

		it->second->Divide(1,2);
		TVirtualPad* ph = it->second->cd(1);
		TVirtualPad* pr = it->second->cd(2);	
		ph->SetPad(0.00, 0.35, 1.00, 1.00);
		pr->SetPad(0.00, 0.00, 1.00, 0.35);
		ph->SetBottomMargin(0.012);
		pr->SetBottomMargin(0.20);
		pr->SetTopMargin(0.012);
		
		ph->cd();
		ph->Draw();
		ph->SetTicks(1,1);
		ph->SetLogy();
		ph->SetLogx();
		// h1Map[it->first+"o"]->SetMaximum( h1Map[it->first+"t"]->GetMaximum()*1.5 );
		// h1Map[it->first+"o"]->Draw();
		TH1D* hTmpNoErr = (TH1D*)resetErrors(h1Map[it->first+"o"])->Clone();
		hTmpNoErr->SetMaximum( h1Map[it->first+"t"]->GetMaximum()*1.5 );
		hTmpNoErr->SetLineStyle(1);
		hTmpNoErr->SetLineColor(kBlack);
		hTmpNoErr->SetFillColor(kAzure-9);
		hTmpNoErr->Draw();
		TH1D* hTmpErr = (TH1D*)ShiftLog(h1Map[it->first+"o"],0.2)->Clone();
		hTmpErr->SetFillStyle(4000); //will be transparent
		hTmpErr->SetFillColor(0);
		hTmpErr->DrawCopy("epx0SAMES");
		hDY->Draw("SAMES");
		h1Map[it->first+"t"]->Draw("epSAMES");
		//poissonGraphMap[it->first]->Draw("pSAMES");
		if(it->first=="2000")
		{
			graphDY->Draw("SAMESp");
			graphSSM->Draw("SAMESp");
			h1Template->Draw("epSAMES");
		}
		_INFO("");
		h1dTlvTmpltMap[it->first]->Draw("SAMESp");
		h1dBrandeisTmpltMap[it->first]->Draw("SAMESp");
		
		TLine* chopline = new TLine(0.12805,getYmin(h1Map[it->first+"o"]),0.12805,7.e5);
		chopline->SetLineStyle(2);
		chopline->SetLineColor(kBlack);
		chopline->Draw("SAMES");
		ptxt->Draw("SAMES");
		
		legMap[it->first]->Draw("SAMES");
		ph->RedrawAxis();
		ph->Update();

		_INFO("");

		pr->cd();
		pr->Draw();
		pr->SetTicks(1,1);
		pr->SetGridy();
		pr->SetLogx();
		h1rMap[it->first]->Draw("ep");
		line->Draw("SAMES");
		h1rMap[it->first]->Draw("epSAMES");
		legR->Draw("SAMES");
		pr->RedrawAxis();
		pr->Update();

		unsigned int savestate = 1;
		if(it->first=="1000")      savestate = 0;
		else if(it->first=="2000") savestate = 2;
		else                       savestate = 1;
		TString testType = (doResiduals) ? "_residuals" : "_ratio";
		mutype   = (doTruth)     ? "_truth"     : "_recon";
		savemultipdf(it->second, "plots/validation/validation"+mutype+testType+"_"+mctype+"_all.pdf", savestate);
		saveas(it->second, "plots/validation/validation"+mutype+testType+"_"+mctype+"_"+it->first);
		
		TCanvas* c = new TCanvas(it->first,"",600,400);
		c->cd();
		c->Draw();
		c->SetTicks(1,1);
		c->SetLogy();
		c->SetLogx();
		hTmpNoErr->Draw();
		hTmpErr->DrawCopy("epx0SAMES");
		hDY->Draw("SAMES");
		h1Map[it->first+"t"]->Draw("epSAMES");
		//poissonGraphMap[it->first]->Draw("pSAMES");
		if(it->first=="2000")
		{
			graphDY->Draw("SAMESp");
			graphSSM->Draw("SAMESp");
			h1Template->Draw("epSAMES");
		}
		h1dTlvTmpltMap[it->first]->Draw("SAMESp");
		h1dBrandeisTmpltMap[it->first]->Draw("SAMESp");
		legMap[it->first]->Draw("SAMES");
		chopline->Draw("SAMES");
		ptxt->Draw("SAMES");
		c->RedrawAxis();
		c->Update();
		saveas(c,"plots/validation/validation_"+it->first+"_"+mutype+testType);
		
		_INFO("done "+(string)it->first);
	}
}
Exemplo n.º 27
0
T& Random< T, G, I, F >::poisson(T &t, F mean) {
  return const_cast< T& >(poisson(const_cast< const T& >(t), mean));
                                                }
Exemplo n.º 28
0
void Gui::SetArm(const char* text)
{	
	//Initialize a surface used to hide a part of the screen wich is used later
	SDL_Surface* hide = NULL;
	hide=LoadImage("Images/hide.png");

	//The variables that the window is going to get

	double mean =0;//the mean of the arm
	double variance =0;//its variance
	char armType ='A';//its type

	//Initializing the texts
	Texts arm(0,150,_font,text,_textColor);	
	Texts instructions(0,250,_font2,"Choose a type of arm then click in the boxes and type the parameters",_textColor);
	//Initializing the buttons

	//Ok button to skip to the next window
	Buttons ok(361,500, "Images/ok1.png", "Images/ok2.png","Images/ok3.png");

	//Type zones for the mean and the variance
	TypeZone meanT(300,400,_font2,"Mean",_textColor);	
	TypeZone varianceT(600,400,_font2,"Variance",_textColor);
	

	//Radiobuttons to choose the type of arm (exponential, uniform real, uniform int, poisson, logNormal)
	RadioButtons exp(100,300,"Exponential",_font2,_textColor);
	RadioButtons unifr(exp.GetBox().x+exp.GetBox().w+20,300,"Uniform real",_font2,_textColor);
	RadioButtons unifi(unifr.GetBox().x+unifr.GetBox().w+20,300,"Uniform int",_font2,_textColor);
	RadioButtons poisson(unifi.GetBox().x+unifi.GetBox().w+20,300,"Poisson",_font2,_textColor);
	RadioButtons logNormal(poisson.GetBox().x+poisson.GetBox().w+20,300,"Log-normal",_font2,_textColor);

	//Calculate the x for centering them (width of the screen minus the sum the width of the buttons)

	int xCentered = ((*(_screen.GetScreen())).clip_rect.w-exp.GetBox().w-unifr.GetBox().w-unifi.GetBox().w-poisson.GetBox().w-logNormal.GetBox().w-80)/2;

	//Relocate the buttons

	exp.SetPosition(xCentered,exp.GetBox().y);
	unifr.SetPosition(exp.GetBox().x+exp.GetBox().w+20,unifr.GetBox().y);
	unifi.SetPosition(unifr.GetBox().x+unifr.GetBox().w+20,unifi.GetBox().y);
	poisson.SetPosition(unifi.GetBox().x+unifi.GetBox().w+20,poisson.GetBox().y);
	logNormal.SetPosition(poisson.GetBox().x+poisson.GetBox().w+20,logNormal.GetBox().y);

	//Display them all

	arm.DisplayCentered(_screen);
	instructions.DisplayCentered(_screen);
	//meanT.Display(_screen);

	
	
	ok.Show(_screen);
	exp.Show(_screen);
	unifr.Show(_screen);
	unifi.Show(_screen);
	poisson.Show(_screen);
	logNormal.Show(_screen);

	
	meanT.DisplayLeft(_screen,mean,_font2,_textColor);
	varianceT.DisplayRight(_screen,mean,_font2,_textColor);
	
	
	
		//Initialize the event structure
	SDL_Event event;

	//Initialization of the loop
	bool isChoiceCorrect= false;
	bool skip=false;
	while((skip==false)&&(_quit==false))
	{	//While there's an event to handle
		while( SDL_PollEvent( &event ) )
			{	
				//the buttons react to the user's actions 
				ok.HandleEvents(event);
				exp.HandleEvents(event);
				unifr.HandleEvents(event);
				unifi.HandleEvents(event);
				poisson.HandleEvents(event);
				logNormal.HandleEvents(event);

				meanT.HandleEvents(event,mean);
				
				
				//For some button we just need the mean to set the distribution so in this case we hide the variance
				if((exp.IsActive()==false)&&(poisson.IsActive()==false))
				{				
				varianceT.HandleEvents(event,variance);
				
				}
				//we check if one option was chosen
				isChoiceCorrect = (exp.IsActive()|| unifr.IsActive()||unifi.IsActive()||poisson.IsActive()||logNormal.IsActive());

				//If the user clicks on ok and made a choice 
				if((ok.HandleEvents(event)==false)&&(isChoiceCorrect))
				{
					//skip to the next window
				skip=true;
				}

				//If he clicks on ok and hasn't made a choice then change color of the text
				if((ok.HandleEvents(event)==false)&&(isChoiceCorrect==false))
				{
					SDL_Color red={240,0,0};
					exp.SetColor(red);
					unifr.SetColor(red);
					unifi.SetColor(red);
					poisson.SetColor(red);
					logNormal.SetColor(red);
				}
				
				//If the user has Xed out the window
				if( event.type == SDL_QUIT )
					{
					//Quit the program
					_quit = true;
					}
			}

	    //Display all
	    ok.Show(_screen);
		exp.Show(_screen);
		unifr.Show(_screen);
		unifi.Show(_screen);
		poisson.Show(_screen);
		logNormal.Show(_screen);
	
		meanT.DisplayLeft(_screen,mean, _font2,_textColor);
		
		
		//For some button we just need the mean to set the distribution so in this case we hide the variance
		if((exp.IsActive()==false)&&(poisson.IsActive()==false))
			{
			 varianceT.DisplayRight(_screen,variance, _font2,_textColor);	
			 
			}
		else
			{
			 ApplySurface(400,398,hide,_screen.GetScreen());
			}

		_screen.Display();
	}
	
	_screen.Clean("Images/background.png");

	//Then we save the parameters in the Gui's attributes

	//First we get the type of arm:
	if(exp.IsActive()){armType='A';}
	if(unifr.IsActive()){armType='B';}
	if(unifi.IsActive()){armType='C';}
	if(poisson.IsActive()){armType='D';}
	if(logNormal.IsActive()){armType='E';}

	std::vector<double> parameter;
	
	//Then acoording to the type of arms we calculate the parameters required
	switch(armType)
		{
		case 'A'://Exponential: we need the lambda

			_choices.push_back('A');//we save the type in _choices 

			
			parameter.push_back(1.0/(mean*1.0));
			_parameters.push_back(parameter);//and the parameters calculated using the mean and the variance in _parameters

			break;
		case 'B'://uniform real on [a,b]  we need a and b

			_choices.push_back('B');

			
			parameter.push_back((2.0*mean-sqrt(12.0*variance))/2.0);
			parameter.push_back((2.0*mean+sqrt(12.0*variance))/2.0);
			_parameters.push_back(parameter);
			break;


		case 'C':

			_choices.push_back('C');//uniform integer on [a,b] we need a and b

			
			parameter.push_back((2.0*mean -sqrt(12.0*variance+1.0)+1)/2.0);
			parameter.push_back((2.0*mean+sqrt(12.0*variance+1)-1)/2.0);
			_parameters.push_back(parameter);
			break;


		case 'D': //poisson we just need the mu wich equal to the mean

			_choices.push_back('D');

			
			parameter.push_back(mean);
			_parameters.push_back(parameter);
			break;

		default:

			_choices.push_back('E'); //log-normal we need mu and sigma square

			
			parameter.push_back(log(mean*1.0)-0.5*log(1.0+((variance*1.0)/(mean*mean*1.0))));
			parameter.push_back((2.0*mean+sqrt(12.0*variance+1.0)-1.0)/2.0);
			_parameters.push_back(parameter);
			break;		

		}


}
Exemplo n.º 29
0
void build_scv_correction_fit(int nreps, int ngenes, int mean_count, SCVInterpolator& true_to_est_scv_table)
{    
    setuplf();  
    
    vector<pair<double, double> > alpha_vs_scv;
   
    boost::mt19937 rng;
    vector<boost::random::negative_binomial_distribution<int, double> > nb_gens;
    
    vector<double> alpha_range;
    for(double a = 0.0002; a < 2.0; a += 0.0002)
    {
        alpha_range.push_back(a);
    }
    
    for (double a = 2; a < 100.0; a += 1)
    {
        alpha_range.push_back(a);
    }
    
    BOOST_FOREACH (double alpha, alpha_range)
    {
        double k = 1.0/alpha;
        double p = k / (k + mean_count);
        double r = (mean_count * p) / (1-p);

        //boost::random::negative_binomial_distribution<int, double> nb(r, p);
        
        boost::random::gamma_distribution<double> gamma(r, (1-p)/p);
        
        
        vector<double> scvs_for_alpha;
        vector<double> draws;
        for (size_t i = 0; i < ngenes; ++i)
        {
            LocusCountList locus_count("", nreps, 1, vector<string>(), vector<string>());
            for (size_t rep_idx = 0; rep_idx < nreps; ++rep_idx)
            {
                double gamma_draw = gamma(rng);
                if (gamma_draw == 0)
                {
                    locus_count.counts[rep_idx] = 0;
                    draws.push_back(0);
                }
                else
                {
                    boost::random::poisson_distribution<long, double> poisson(gamma_draw);
                    locus_count.counts[rep_idx] = poisson(rng);
                    draws.push_back(locus_count.counts[rep_idx]);
                    //fprintf(stderr, "%lg\t", locus_count.counts[rep_idx]);
                }
            }
            
            double mean = accumulate(locus_count.counts.begin(), locus_count.counts.end(), 0.0);
            if (mean == 0)
                continue;
            mean /= locus_count.counts.size();
            double var = 0.0;
            BOOST_FOREACH(double c,  locus_count.counts)
            {
                var += (c-mean)*(c-mean);
            }
            var /= locus_count.counts.size();
            var *= locus_count.counts.size() / (locus_count.counts.size() - 1);
            
            double scv = var / (mean*mean);
            scvs_for_alpha.push_back(scv);
            //fprintf(stderr, " : mean = %lg, var = %lg, scv = %lg\n", mean, var, scv);
            
            //fprintf(stderr, "\n");
        }
        
        double mean = accumulate(draws.begin(), draws.end(), 0.0);
        mean /= draws.size();
        double var = 0.0;
        BOOST_FOREACH(int c,  draws)
        {
            var += (c - mean)*(c-mean);
        }
void *threadfunction1(){

	int socketFD, sockfd2;
	int rate = DEFAULT_INTERVAL;
	char msg[141];
	double tstart, tend, ttime;
	
	struct addrinfo hints;
	struct addrinfo *servinfo;
	
	struct timespec sleepTime = {0, 100};//10000000
	
	
	//Get sockets
	socketFD = socket(AF_INET, SOCK_DGRAM, 0);
	if (socket < 0){
		printf("Error: Could not get socket.");
		exit(1);
	}
	
	//Get connection info
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;
	hints.ai_flags = AI_PASSIVE;
	
	if (getaddrinfo("10.10.66.90", "56790", &hints, &servinfo) != 0 || servinfo == NULL) {
	    printf("Error: Could not find router.");
	    exit(1);
	}


	

	int attempt = 0;
	int count = 1;
	int memory = count, temp = 0;
	int i;
	double timestamp; 
	while (numACK < NUM_PACKETS) {
        
		if (count==memory+WINDOW_SIZE || count == NUM_PACKETS) {
			count = numACK;
			memory = count;
			temp = indicator;
            
            
            tstart = (double)clock()/CLOCKS_PER_SEC;
            while (timePassed < TIME_OUT && indicator == temp) {
                tend = (double)clock()/CLOCKS_PER_SEC;

                timePassed = tend - tstart;
                //printf("%lf\n",TIME_OUT);
                //printf("Time passed : %lf\n",timePassed);
                //printf("insie while loop\n");
            }
            if (timePassed >= TIME_OUT)
            {
            	TIME_OUT *= 2;
            }
            
		}
		for (i=0; i<128; i++)
			msg[i] = '2';   // message content 
		msg[128] = '2';   // flow number
		memcpy(msg+129, &count, 4);

		timestamp = clock()/(double)CLOCKS_PER_SEC;
		memcpy(msg+133, &timestamp, 8);


		temp = indicator;
		//printf("%d\n",WINDOW_SIZE);

		if (sendto(socketFD, msg, 141, 0, servinfo->ai_addr, servinfo->ai_addrlen) < 0) {
			
			printf("Sending failed!\n");
			exit(1);
		}
        attempt += 1;
        if (attempt>=WINDOW_SIZE) {
            //printf("%f\n", (float)(numACK+(float)WINDOW_SIZE/10)/attempt);
        } else {
            //printf("%f\n", (float)(numACK)/attempt);
        }
        
		sleepTime.tv_nsec = poisson((float)R)*1000000;
		nanosleep(&sleepTime, NULL);
		count += 1;
        //printf("%d\n",numACK);
        if (numACK == NUM_PACKETS) {
            //printf("inside break\n");
            //printf("outside while\n");
            
            break;
        }
        
	}
}