Esempio n. 1
0
void plot_diff_xsec()
{
  TF1* fXsec = new TF1("fXsec", "diff_xsec(x)", 1, 0);
  fXsec->SetLineWidth(3);
  fXsec->SetTitle("#nu_{#mu}-e differential cross section (E_{#nu} = 2 GeV)");
  fXsec->Draw();
  fXsec->GetXaxis()->SetTitle("cos#theta");
  fXsec->GetXaxis()->CenterTitle();
  fXsec->GetYaxis()->SetTitle("d#sigma/dcos#theta (cm^{-2})");
  fXsec->GetYaxis()->CenterTitle();
  fXsec->GetYaxis()->SetTitleOffset(1.4);
  gPad->SetLogy(1);
  
  double totXsec = fXsec->Integral(0,1);
  for(int i = 0; i < 100; i++)
  {
    cout << fXsec->Integral(0.01*i,1)/totXsec << endl;
  }
  cout << totXsec << " " << fXsec->Integral(.99,1) << endl;
  
  ROOT::Math::GSLIntegrator ig(1.E-6,1.E-6,1000); 
  ROOT::Math::WrappedTF1 wf(*fXsec);
  ig.SetFunction(wf);
  cout << ig.Integral(.9,1) << endl;
  
  //~ TCanvas* c2 = new TCanvas("c2");
  //~ TF1* fCXsec = new TF1("fCXsec", "cumul_xsec(x)", 0, 90);
  //~ fCXsec->Draw();
  //~ cout << cumul_xsec(45) << endl;
}
Esempio n. 2
0
int main(int argc, char** argv)
{
  if (argc != 3) {
    std::cerr << argv[0] << " [gold file] [test file]" << std::endl;
    return 1;
  }
  
  trance::Tree gold;
  trance::Tree test;

  trance::Evalb       evalb;
  trance::EvalbScorer scorer;
  
  utils::compress_istream ig(argv[1]);
  utils::compress_istream it(argv[2]);
  
  for (;;) {
    ig >> gold;
    it >> test;

    if (! ig || ! it) break;
    
    scorer.assign(gold);
    evalb += scorer(test);
  }
  
  if (ig || it)
    throw std::runtime_error("# of trees does not match");

  std::cout << "scor: " << evalb() << " match: " << evalb.match_ << " gold: " << evalb.gold_ << " test: " << evalb.test_<< std::endl;
}
Esempio n. 3
0
double LEP2sigmaMu::computeThValue() 
{ 
    Mw = SM.Mw(); 
    GammaZ = SM.Gamma_Z();

    if (!checkSMparams(s, Mw, GammaZ)) {
        ml_cache = m_l(SM.MU);
        
        if (!flag[ISR])
            SMresult_cache = sigma_NoISR_l();
        else {
            ROOT::Math::Functor1D wf(this, &LEP2sigmaMu::Integrand_sigmaWithISR_l);
            ROOT::Math::Integrator ig(wf, ROOT::Math::IntegrationOneDim::kADAPTIVESINGULAR);
            ig.SetAbsTolerance(1.E-14); // desired absolute error
            ig.SetRelTolerance(1.E-4); // desired relative error
            SMresult_cache = ig.Integral(0.0, 1.0-0.85*0.85); // interval
            /* check
             MathMore library is required to use kADAPTIVESINGULAR. */
            //std::cout << ig.Options().Integrator() << std::endl;
            //std::cout << ig.Options().AbsTolerance() << std::endl;
            //std::cout << ig.Options().RelTolerance() << std::endl;
            //std::cout << SMresult_cache << " +- " << ig.Error() << std::endl;
            // results: 6.8e-9 -- 2.2e-8
        }
        
        if (flag[WeakBox]) {
            ROOT::Math::Functor1D wf_box(this, &LEP2sigmaMu::Integrand_dsigmaBox_l);
            ROOT::Math::Integrator ig_box(wf_box, ROOT::Math::IntegrationOneDim::kADAPTIVESINGULAR);
            ig_box.SetAbsTolerance(1.E-17); // desired absolute error
            ig_box.SetRelTolerance(1.E-4); // desired relative error
            double sigma_box = ig_box.Integral(-1.0, 1.0); // interval
            SMresult_cache += sigma_box;
            //std::cout << sigma_box << " +- " << ig_box.Error() << std::endl;
            // results: 3.5e-12 -- +2.9e-10
        }
    }
    double sigma_mu = SMresult_cache;
    
    #ifdef LEP2TEST
    sigma_mu = myTEST.sigmaMuTEST(sqrt_s)/SM.GeVminus2_to_nb/1000.0;
    #endif 
    
    if ( checkLEP2NP() && !bSigmaForAFB ) {
        double obliqueShat = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueShat();
        double obliqueThat = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueThat();
        double obliqueUhat = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueUhat();
        double obliqueV = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueV();
        double obliqueW = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueW();
        double obliqueX = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueX();
        double obliqueY = (dynamic_cast<const NPSTUVWXY*> (&SM))->obliqueY();
        double ObParam[7] = {obliqueShat, obliqueThat, obliqueUhat,
                             obliqueV, obliqueW, obliqueX, obliqueY};
        sigma_mu += myLEP2oblique.sigma_l_LEP2_NP(StandardModel::MU, s, ml_cache, ObParam);
    }

    return ( sigma_mu*SM.GeVminus2_to_nb*1000.0 );
}
Esempio n. 4
0
static int innards(int iconlabel, const char *istr, int itype,
		   const char* fmt, va_list ap,
		   const char *b0, const char *b1, const char *b2)
{
    Fl_Window window(3*BORDER_W+ICON_W+INPUT_W, 3*BORDER_H+ICON_H+BUTTON_H);

    // This keeps the icon from resizing.
    Fl_Group ig(BORDER_W, BORDER_H, ICON_W, ICON_H);

    Fl_Box icon(0, 0, ICON_W, ICON_H);
    if (iconlabel==0) {
	icon.image(information_pix);
	window.label(_("Information"));
    }	
    else if (iconlabel==1) {
	icon.image(warning_pix);
	window.label(_("Warning"));
    }
    else { 
	icon.image(information_pix);
	window.label(_("Question"));
    }	
    ig.end();

    Fl_Box message(2*BORDER_W+ICON_W, 0, INPUT_W, 2*BORDER_H+ICON_H);
    message.set_flag(FL_ALIGN_LEFT|FL_ALIGN_INSIDE|FL_ALIGN_WRAP);
    message.style(fl_message_style);

    if (input) {delete input; input = 0;}
    if (istr)
    {
        input = new Fl_Input(2*BORDER_W+ICON_W, 0, INPUT_W, 0);
        input->h(input->text_size()+10);
        input->y(BORDER_H+ICON_H-input->h());
        message.h(input->y());
        input->type(itype);
        input->value(istr);
        window.focus(input);
    }

    window.resizable(message);
    //  w->size_range(window.w(), window.h(), 0, window.h());

    char buffer[1024] = {0};
    if (!strcmp(fmt,"%s"))
    {
        message.label(va_arg(ap, const char*));
    }
Esempio n. 5
0
void  testIntegPerf(double x1, double x2, int n = 100000){


   std::cout << "\n\n***************************************************************\n";
   std::cout << "Test integration performances in interval [ " << x1 << " , " << x2 << " ]\n\n";

  TStopwatch timer;

  double dx = (x2-x1)/double(n);

  //ROOT::Math::Functor1D<ROOT::Math::IGenFunction> f1(& TMath::BreitWigner);
  ROOT::Math::WrappedFunction<> f1(func);

  timer.Start();
  ROOT::Math::Integrator ig(f1 );
  double s1 = 0.0;
  nc = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s1+= ig.Integral(x1,x);
  }
  timer.Stop();
  std::cout << "Time using ROOT::Math::Integrator        :\t" << timer.RealTime() << std::endl;
  std::cout << "Number of function calls = " << nc/n << std::endl;
  int pr = std::cout.precision(18);  std::cout << s1 << std::endl;  std::cout.precision(pr);



  //TF1 *fBW = new TF1("fBW","TMath::BreitWigner(x)",x1, x2);  //  this is faster but cannot measure number of function calls
  TF1 *fBW = new TF1("fBW",func2,x1, x2,0);

  timer.Start();
  nc = 0;
  double s2 = 0;
  for (int i = 0; i < n; ++i) {
     double x = x1 + dx*i;
     s2+= fBW->Integral(x1,x );
  }
  timer.Stop();
  std::cout << "Time using TF1::Integral :\t\t\t" << timer.RealTime() << std::endl;
  std::cout << "Number of function calls = " << nc/n << std::endl;
  pr = std::cout.precision(18);  std::cout << s1 << std::endl;  std::cout.precision(pr);


}
Esempio n. 6
0
  // to generate the iwts again, and return to Fortran 
  int get_iwts(Mesh &mesh, MEField<> *iwts, int *regridScheme) {

    // generate integration weights
    Integrate ig(mesh);

    // Clear weights
    ig.clearWeights(iwts);

    // Add weights to meshes before poles
    // so all the weights are on user data points
    if (*regridScheme == ESMC_REGRID_SCHEME_FULL3D) {
        for (UInt i = 1; i <= 7; ++i)
          ig.AddPoleWeights(mesh,i,iwts);
    }


    // Add in other none-pole weights
    // (and do cross processor sum)
    ig.intWeights(iwts);

    return 1;
  }
Esempio n. 7
0
	void Gl1_PolyhedraPhys::go(const shared_ptr<IPhys>& ip, const shared_ptr<Interaction>& i, const shared_ptr<Body>& b1, const shared_ptr<Body>& b2, bool wireFrame){
		if(!gluQuadric){ gluQuadric=gluNewQuadric(); if(!gluQuadric) throw runtime_error("Gl1_PolyhedraPhys::go unable to allocate new GLUquadric object (out of memory?)."); }
		PolyhedraPhys* np=static_cast<PolyhedraPhys*>(ip.get());
		shared_ptr<IGeom> ig(i->geom); if(!ig) return; // changed meanwhile?
		PolyhedraGeom* geom=YADE_CAST<PolyhedraGeom*>(ig.get());
		Real fnNorm=np->normalForce.dot(geom->normal);
		if((signFilter>0 && fnNorm<0) || (signFilter<0 && fnNorm>0)) return;
		int fnSign=fnNorm>0?1:-1;
		fnNorm=std::abs(fnNorm);
		Real radiusScale=1.;
		maxFn=max(fnNorm,maxFn);
		Real realMaxRadius;
		if(maxRadius<0){
			refRadius=min(0.03,refRadius);
			realMaxRadius=refRadius;
		}
		else realMaxRadius=maxRadius;
		Real radius=radiusScale*realMaxRadius*(fnNorm/maxFn); 
		if (radius<=0.) radius = 1E-8;
		Vector3r color=Shop::scalarOnColorScale(fnNorm*fnSign,-maxFn,maxFn);
		
		Vector3r p1=b1->state->pos, p2=b2->state->pos;
		Vector3r relPos;
		relPos=p2-p1;
		Real dist=relPos.norm();
				
		glDisable(GL_CULL_FACE); 
		glPushMatrix();
			glTranslatef(p1[0],p1[1],p1[2]);
			Quaternionr q(Quaternionr().setFromTwoVectors(Vector3r(0,0,1),relPos/dist /* normalized */));
			// using Transform with OpenGL: http://eigen.tuxfamily.org/dox/TutorialGeometry.html
			//glMultMatrixd(Eigen::Affine3d(q).data());
			glMultMatrix(Eigen::Transform<Real,3,Eigen::Affine>(q).data());
			glColor3v(color);
			gluCylinder(gluQuadric,radius,radius,dist,slices,stacks);
		glPopMatrix();
	}
Esempio n. 8
0
void  DrawCumulative(double x1, double x2, int n = 100){

   std::cout << "\n\n***************************************************************\n";
   std::cout << "Drawing cumulatives of BreitWigner in interval [ " << x1 << " , " << x2 << " ]\n\n";


   double dx = (x2-x1)/double(n);

   TH1D *cum0 = new TH1D("cum0", "", n, x1, x2); //exact cumulative
   for (int i = 1; i <= n; ++i) {
      double x = x1 + dx*i;
      cum0->SetBinContent(i, exactIntegral(x1, x));

   }

   // alternative method using ROOT::Math::Functor class
   ROOT::Math::Functor1D f1(& func);


   ROOT::Math::Integrator ig(f1, ROOT::Math::IntegrationOneDim::kADAPTIVE,1.E-12,1.E-12);

   TH1D *cum1 = new TH1D("cum1", "", n, x1, x2);
   for (int i = 1; i <= n; ++i) {
      double x = x1 + dx*i;
      cum1->SetBinContent(i, ig.Integral(x1,x));
   }


   TF1 *fBW = new TF1("fBW","TMath::BreitWigner(x, 0, 1)",x1, x2);


   TH1D *cum2 = new TH1D("cum2", "", n, x1, x2);
   for (int i = 1; i <= n; ++i) {
      double x = x1 + dx*i;
      cum2->SetBinContent(i, fBW->Integral(x1,x));
   }

   TH1D *cum10 = new TH1D("cum10", "", n, x1, x2); //difference between  1 and exact
   TH1D *cum20 = new TH1D("cum23", "", n, x1, x2); //difference between 2 and excact
   for (int i = 1; i <= n; ++i) {
      double delta  =  cum1->GetBinContent(i) - cum0->GetBinContent(i);
      double delta2 =  cum2->GetBinContent(i) - cum0->GetBinContent(i);
      //std::cout << " diff for " << x << " is " << delta << "  " << cum1->GetBinContent(i) << std::endl;
      cum10->SetBinContent(i, delta );
      cum10->SetBinError(i, std::numeric_limits<double>::epsilon() * cum1->GetBinContent(i) );
      cum20->SetBinContent(i, delta2 );
   }


   TCanvas *c1 = new TCanvas("c1","Integration example",20,10,800,500);
   c1->Divide(2,1);
   c1->Draw();

   cum0->SetLineColor(kBlack);
   cum0->SetTitle("BreitWigner - the cumulative");
   cum0->SetStats(0);
   cum1->SetLineStyle(2);
   cum2->SetLineStyle(3);
   cum1->SetLineColor(kBlue);
   cum2->SetLineColor(kRed);
   c1->cd(1);
   cum0->DrawCopy("h");
   cum1->DrawCopy("same");
   //cum2->DrawCopy("same");
   cum2->DrawCopy("same");

   c1->cd(2);
   cum10->SetTitle("Difference");
   cum10->SetStats(0);
   cum10->SetLineColor(kBlue);
   cum10->Draw("e0");
   cum20->SetLineColor(kRed);
   cum20->Draw("hsame");

   TLegend * l = new TLegend(0.11, 0.8, 0.7 ,0.89);
   l->AddEntry(cum10, "GSL integration - analytical ");
   l->AddEntry(cum20, "TF1::Integral  - analytical ");
   l->Draw();


   c1->Update();
   std::cout << "\n***************************************************************\n";


}
Esempio n. 9
0
void fitMKVoight(TH1 *h33 , Double_t low, Double_t high, Double_t p0, Double_t p1, Double_t p2, Double_t p3, Double_t initialPar, Double_t width, Double_t Gamma, Double_t factor, Int_t draw_opt){
  
  //double nEnt = h33->GetEntries();
  double nEnt = h33->GetMaximum();
  double in_par[8] = {100, initialPar, width , Gamma, p0, p1, p2}; //{A,mean,sigma,Gamma}
  TF1 *fitter = new TF1("fitter",myFuncBWG,low,high,8);
  fitter->SetParameters(&in_par[0]);
  fitter->SetParLimits(0,10,nEnt); fitter->SetParLimits(1,initialPar-width,initialPar+width);
  fitter->SetLineColor(kBlue);
  h33->Fit("fitter","REM+","same");
  //h33->Draw("E");
  TF1 *backFcn = new TF1("backFcn", "pol2",low,high);
  TF1 *signalFcn = new TF1("signalFcn", myVoight,low,high,4);
  signalFcn->SetLineColor(kBlue);
  signalFcn->SetLineWidth(2);
  Double_t par[8];
  fitter->GetParameters(par);
  backFcn->SetParameters(&par[4]);
  backFcn->SetLineStyle(2);
  backFcn->SetLineColor(6);
  backFcn->SetLineWidth(1);
  
  
  signalFcn->SetParameters(par);
  signalFcn->SetLineStyle(2);
  signalFcn->SetLineColor(4);
  signalFcn->SetLineWidth(1);
  // backFcn->Draw("same");
  //signalFcn->Draw("same");
  //Double_t Intg = abs(signalFcn->Integral(par[1]-factor*par[2],par[1]+factor*par[2]));
  ROOT::Math::GSLIntegrator ig(1.E-6,1.E-6,1000);
  ROOT::Math::WrappedTF1 wf(*fitter);
  ig.SetFunction(wf);
  double Intg = ig.Integral(par[1]-factor*par[2],par[1]+factor*par[2]);
  Double_t Intb = abs(backFcn->Integral(par[1]-factor*par[2],par[1]+factor*par[2]));
  
  
  Double_t binw = h33->GetBinWidth(1);
  Int_t yield = Intg/binw;
  Int_t bckgd = Intb/binw;
  //Double_t ratio = double(yield)/TMath::Sqrt(double(bckgd));
  Double_t ratio = double(yield)/double(yield+bckgd);
  
  cout << yield << "\t" << ratio << endl;
  TAxis *x=h33->GetXaxis();
  TAxis *y=h33->GetYaxis();
  
  Double_t startx=x->GetXmin()+0.45*(x->GetXmax()-x->GetXmin());
  /*
   Double_t starty0=0.5*h33->GetMaximum();
   Double_t starty1=0.56*h33->GetMaximum();
   Double_t starty2=0.62*h33->GetMaximum();
   Double_t starty3=0.68*h33->GetMaximum();
   Double_t starty4=0.74*h33->GetMaximum();
   Double_t starty5=0.8*h33->GetMaximum();
   */
  Double_t starty0=0.35*h33->GetMaximum();
  Double_t starty1=0.43*h33->GetMaximum();
  Double_t starty2=0.49*h33->GetMaximum();
  Double_t starty3=0.56*h33->GetMaximum();
  Double_t starty4=0.63*h33->GetMaximum();
  Double_t starty5=0.7*h33->GetMaximum();
  
  
  
  double meanError = fitter->GetParError(1);
  double sigmaError = fitter->GetParError(2);
  if (draw_opt ==1) {
    
    TLatex *sum = new TLatex(startx*0.93, starty5,Form("Yield: %i",yield));
    TLatex *sum12 = new TLatex(startx*0.93, starty4,Form("Background: %i",bckgd));
    TLatex *sum0=new TLatex(startx*0.93, starty3,Form("Range: #pm %2.1f #sigma",factor));
    TLatex *sum2=new TLatex(startx*0.93, starty2,Form("Mean: %4.4f #pm %.4f GeV",par[1], meanError));
    TLatex *sum3=new TLatex(startx*0.93, starty1,Form("#sigma: %5.4f #pm %.4f GeV",par[2], sigmaError));
    //TLatex *ra = new TLatex(startx*0.93, starty0,Form("#frac{S}{#sqrt{B}}= %.1f", ratio));
    TLatex *ra = new TLatex(startx*0.93, starty0,Form("#frac{S}{S+B} = %1.4f", ratio));
    
    
    sum->SetTextSize(0.04);
    sum->SetTextColor(kBlue);//2
    sum->Draw("same");
    sum12->SetTextSize(0.04);
    sum12->SetTextColor(kBlue);//6
    sum12->Draw("same");
    
    ra->SetTextSize(0.04);
    ra->SetTextColor(kBlue);//was black before;
    ra->Draw("same");
    
    
    sum0->SetTextSize(0.04);
    sum0->SetTextColor(kBlue);//2
    sum0->Draw("same");
    sum2->SetTextSize(0.04);
    sum2->SetTextColor(kBlue);//4
    sum2->Draw("same");
    sum3->SetTextSize(0.04);
    sum3->SetTextColor(kBlue);//4
    sum3->Draw("same");
    
    
  }
}
Esempio n. 10
0
void functor_demo(){
    cout<<endl<<"functor_demo :"<<endl;
    greater<int> ig;
    cout<<boolalpha<<ig(4,6)<<endl;
    cout<<greater<int>()(6,4)<<endl;
}
Esempio n. 11
0
	void Gl1_NormPhys::go(const shared_ptr<IPhys>& ip, const shared_ptr<Interaction>& i, const shared_ptr<Body>& b1, const shared_ptr<Body>& b2, bool wireFrame){
		if(!gluQuadric){ gluQuadric=gluNewQuadric(); if(!gluQuadric) throw runtime_error("Gl1_NormPhys::go unable to allocate new GLUquadric object (out of memory?)."); }
		NormPhys* np=static_cast<NormPhys*>(ip.get());
		shared_ptr<IGeom> ig(i->geom); if(!ig) return; // changed meanwhile?
		GenericSpheresContact* geom=YADE_CAST<GenericSpheresContact*>(ig.get());
		//if(!geom) cerr<<"Gl1_NormPhys: IGeom is not a GenericSpheresContact, but a "<<ig->getClassName()<<endl;
		Real fnNorm=np->normalForce.dot(geom->normal);
		if((signFilter>0 && fnNorm<0) || (signFilter<0 && fnNorm>0)) return;
		int fnSign=fnNorm>0?1:-1;
		fnNorm=abs(fnNorm);
		Real radiusScale=1.;
		// weak/strong fabric, only used if maxWeakFn is set
		if(!isnan(maxWeakFn)){
			if(fnNorm*fnSign<maxWeakFn){ // weak fabric
				if(weakFilter>0) return;
				radiusScale=weakScale;
			} else { // strong fabric
				if(weakFilter<0) return;
			}
		}

		maxFn=max(fnNorm,maxFn);
		Real realMaxRadius;
		if(maxRadius<0){
			if(geom->refR1>0) refRadius=min(geom->refR1,refRadius);
			if(geom->refR2>0) refRadius=min(geom->refR2,refRadius);
			realMaxRadius=refRadius;
		}
		else realMaxRadius=maxRadius;
		Real radius=radiusScale*realMaxRadius*(fnNorm/maxFn); // use logarithmic scale here?
		Vector3r color=Shop::scalarOnColorScale(fnNorm*fnSign,-maxFn,maxFn);
		# if 0
			// get endpoints from body positions
			Vector3r p1=b1->state->pos, p2=b2->state->pos;
			Vector3r relPos;
			if(scene->isPeriodic){
				relPos=p2+scene->cell->Hsize*i->cellDist.cast<Real>()-p1;
				p1=scene->cell->wrapShearedPt(p1);
				p2=p1+relPos;
			} else {
				relPos=p2-p1;
			}
			Real dist=relPos.norm();
		#else
			// get endpoints from geom
			// max(r,0) handles r<0 which is the case for "radius" of the facet in Dem3DofGeom_FacetSphere
			Vector3r cp=scene->isPeriodic? scene->cell->wrapShearedPt(geom->contactPoint) : geom->contactPoint;
			Vector3r p1=cp-max(geom->refR1,(Real)0.)*geom->normal;
			Vector3r p2=cp+max(geom->refR2,(Real)0.)*geom->normal;
			const Vector3r& dispScale=scene->renderer ? scene->renderer->dispScale : Vector3r::Ones(); 
			if(dispScale!=Vector3r::Ones()){
				// move p1 and p2 by the same amounts as particles themselves would be moved
				p1+=dispScale.cwiseProduct(Vector3r(b1->state->pos-b1->state->refPos));
				p2+=dispScale.cwiseProduct(Vector3r(b2->state->pos-b2->state->refPos));
			}
			Vector3r relPos=p2-p1;
			Real dist=relPos.norm(); //max(geom->refR1,0.)+max(geom->refR2,0.);
	#endif


	glDisable(GL_CULL_FACE); 
	glPushMatrix();
		glTranslatef(p1[0],p1[1],p1[2]);
		Quaternionr q(Quaternionr().setFromTwoVectors(Vector3r(0,0,1),relPos/dist /* normalized */));
		// using Transform with OpenGL: http://eigen.tuxfamily.org/dox/TutorialGeometry.html
		//glMultMatrixd(Eigen::Affine3d(q).data());
		glMultMatrix(Eigen::Transform<Real,3,Eigen::Affine>(q).data());
		glColor3v(color);
		gluCylinder(gluQuadric,radius,radius,dist,slices,stacks);
	glPopMatrix();
}
Esempio n. 12
0
// ------------------------------------------------------------
// calculates the text in the tabular
int TruthDiagram::calcDiagram()
{
  Lines.clear();
  Texts.clear();
  Arcs.clear();

  x1 = 0;  // no scroll bar
  x3 = x2;
  // get size of text using the screen-compatible metric
  QFontMetrics metrics(QucsSettings.font, 0);
  int tHeight = metrics.lineSpacing();
  QString Str;
  int colWidth=0, x=6, y;

  if(y2 < (41 + MIN_SCROLLBAR_SIZE))
    y2 = 41 + MIN_SCROLLBAR_SIZE;

  if(y2 < (tHeight + 8))
    y2 = tHeight + 8;
  y = y2 - tHeight - 6;

  // outer frame
  Lines.append(new Line(0, y2, x2, y2, QPen(Qt::black,0)));
  Lines.append(new Line(0, y2, 0, 0, QPen(Qt::black,0)));
  Lines.append(new Line(x2, y2, x2, 0, QPen(Qt::black,0)));
  Lines.append(new Line(0, 0, x2, 0, QPen(Qt::black,0)));
  Lines.append(new Line(0, y+2, x2, y+2, QPen(Qt::black,2)));

  if(xAxis.limit_min < 0.0)
    xAxis.limit_min = 0.0;

  Graph *firstGraph;

  QListIterator<Graph *> ig(Graphs);
  Graph *g = 0;
  if (ig.hasNext())
     g= ig.next();

  if(g == 0) {  // no variables specified in diagram ?
    Str = QObject::tr("no variables");
    colWidth = checkColumnWidth(Str, metrics, colWidth, x, y2);
    if(colWidth >= 0)
      Texts.append(new Text(x-4, y2-2, Str)); // independent variable
    return 0;
  }

  int NumAll=0;   // how many numbers per column
  int NumLeft=0;  // how many numbers could not be written

  char *py;
  int counting, invisibleCount=0;
  int startWriting, z;

  // any graph with data ?
  while(g->isEmpty()) {
    if (!ig.hasNext()) break; // no more graphs, exit loop
    g = ig.next(); // point to next graph
  }

  if(!g->isEmpty()) { // did we find a graph with data ?
    // ................................................
    NumAll = g->axis(0)->count * g->countY;  // number of values
    
    invisibleCount = NumAll - y/tHeight;
    if(invisibleCount <= 0)  xAxis.limit_min = 0.0;// height bigger than needed
    else {
      if(invisibleCount < int(xAxis.limit_min + 0.5))
	xAxis.limit_min = double(invisibleCount); // adjust limit of scroll bar
      NumLeft = invisibleCount - int(xAxis.limit_min + 0.5);
    }

    colWidth = 0;
    Texts.append(new Text(x-4, y2-2, Str)); // independent variable
    if(NumAll != 0) {
      z = metrics.width("1");
      colWidth = metrics.width("0");
      if(z > colWidth)  colWidth = z;
      colWidth += 2;
      counting = int(log(double(NumAll)) / log(2.0) + 0.9999); // number of bits
      
      if((x+colWidth*counting) >= x2) {    // enough space for text ?
	checkColumnWidth("0", metrics, 0, x2, y);
	goto funcEnd;
      }
      
      y = y2-tHeight-5;
      startWriting = x;
      for(z=int(xAxis.limit_min + 0.5); z<NumAll; z++) {
	if(y < tHeight) break;  // no room for more rows ?
	startWriting = x;
	for(int zi=counting-1; zi>=0; zi--) {
	  if(z & (1 << zi))  Str = "1";
	  else  Str = "0";
	  Texts.append(new Text( startWriting, y, Str));
	  startWriting += colWidth;
	}
	y -= tHeight;
      }
      x = startWriting + 15;
    }
    Lines.append(new Line(x-8, y2, x-8, 0, QPen(Qt::black,2)));  
  }  // of "if no data in graphs"
  

  int zi, digitWidth;
  firstGraph = g;
  // ................................................
  // all dependent variables
  foreach(Graph *g ,Graphs) {
    y = y2-tHeight-5;

    Str = g->Var;
    colWidth = checkColumnWidth(Str, metrics, 0, x, y2);
    if(colWidth < 0)  goto funcEnd;
    Texts.append(new Text(x, y2-2, Str));  // dependent variable


    startWriting = int(xAxis.limit_min + 0.5);  // when to reach visible area
    if(g->axis(0)) {

      if(sameDependencies(g, firstGraph)) {

        if(g->Var.right(2) != ".X") {  // not a digital variable ?
          double *pdy = g->cPointsY - 2;
          for(z = NumAll; z>0; z--) {
            pdy += 2;
            if(startWriting-- > 0) continue; // reached visible area ?
            if(y < tHeight) break;           // no room for more rows ?
            Str = QString::number(sqrt((*pdy)*(*pdy) + (*(pdy+1))*(*(pdy+1))));

            colWidth = checkColumnWidth(Str, metrics, colWidth, x, y);
            if(colWidth < 0)  goto funcEnd;

            Texts.append(new Text(x, y, Str));
            y -= tHeight;
          }
        }

        else {  // digital variable !!!
          py = (char*)g->cPointsY;
          counting = strlen((char*)py);    // count number of "bits"

          digitWidth = metrics.width("X") + 2;
          if((x+digitWidth*counting) >= x2) {    // enough space for "bit vector" ?
            checkColumnWidth("0", metrics, 0, x2, y);
            goto funcEnd;
          }

          for(z = NumAll; z>0; z--) {
            if(startWriting-- > 0) {   // reached visible area ?
              py += counting + 1;
              continue;
            }
            if(y < tHeight) break;    // no room for more rows ?

            zi = 0;
            while(*py) {
              Str = *(py++);
              Texts.append(new Text(x + zi, y, Str));
              zi += digitWidth;
            }
            py++;
            y -= tHeight;
          }

          digitWidth *= counting;
          if(colWidth < digitWidth)
            colWidth = digitWidth;
        }

      }  // of "if(sameDeps)"
      else {
        Str = QObject::tr("wrong dependency");
        colWidth = checkColumnWidth(Str, metrics, colWidth, x, y);
        if(colWidth < 0)  goto funcEnd;
        Texts.append(new Text(x, y, Str));
      }
    }
    else {   // no data in graph
      Str = QObject::tr("no data");
      colWidth = checkColumnWidth(Str, metrics, colWidth, x, y);
      if(colWidth < 0)  goto funcEnd;
      Texts.append(new Text(x, y, Str));
    }
    x += colWidth+15;
    if(g != Graphs.last())   // do not paint last line
      Lines.append(new Line(x-8, y2, x-8, 0, QPen(Qt::black,0)));
  }
Esempio n. 13
0
void genotype::read_vcf (string genofile, bool isgenoytpe) { 
    igzstream ig (genofile.c_str());
    string line;
	vector<snp> tmp;
	int j = 0 ;
	maxgpos = unordered_map<string, double> ();
	mingpos = unordered_map<string, double>();
	maxppos = unordered_map<string, double> ();
	minppos = unordered_map<string, double>();
	chrs = vector<string> ();
	double prevgpos ;
	double prevppos;
	string prevchr="";
    int size =  10000;
    int inc = 10000;
	
    int linenum = 0 ;
    bool setind = false;
    int numhap = 2;
    if (isgenotype)
        numhap = 1;
    while (std::getline (ig, line) ) {
        linenum ++;
        char c = line[0];
        if (c=='#') { 
            if (line.find ("CHROM")!=string::npos) {
                if (!givenind)  {
                    vector<string> toks;
                    functions::tokenize (line.c_str(), toks, " \t");
                    nind = toks.size() - 9 ;
                    nind *= numhap;
                    for (int i = 9 ; i < toks.size(); i++){
                        string id = toks[i];
                        indiv.push_back (ind(id,'U',"G"));
                        if (!isgenotype)
                            indiv.push_back (ind(id,'U',"G"));

                    }
                    setind = true;
                }
            }
        } else { 
            vector<string> toks;
            functions::tokenize (line.c_str(), toks, " \t");
            string id = toks[2];
            string chr = toks[0];
            double physpos =  atof(toks[1].c_str());
            double genpos = physpos*1.3/1e8;
            if (id.compare (".")==0) { 
                id = chr+":"+toks[1];
            }
            string ref = toks[3];
            string var = toks[4];
            string pass = toks[6];
            string desc = toks[7];
            string format = toks[8];
            if (pass.compare("PASS")!=0)
                continue;
            if (ref.compare (".")==0)
                continue;
            if (desc.compare (".") == 0 ) {
                cout << "Warning: No INFO field found. Assuming site is a SNP " << endl;
            }
            vector<string> tok1;
            functions::tokenize (desc.c_str(), tok1, ";");
            if (tok1[0].compare("SNP")!=0)
                continue;


            // Fill the snps
            if (chr.compare(prevchr)==0) {
                if (physpos >= prevppos){
                    prevgpos = genpos;
                    prevppos = physpos;
                } else {
                    cerr << "Invalid snps in  " << genofile <<" : Line " << linenum  << "\t Must have non-decreasing physical positions" << endl;
            //				exit (1);
                }
            } else {
                prevchr = chr;
                prevgpos = genpos;
                prevppos = physpos;
                if (snps.find(chr) != snps.end ()) {
                    cerr << "Invalid snps in "<< genofile << " : Line " << linenum << "\t SNPs on a chromosome must be consecutive" << endl;
                    exit (1);
                }
                chrs.push_back(chr);
                snps[chr] = vector<snp>();
//                snps[chr].reserve (size);
            }

/*            if (j==size){ 
                size += inc;
                snps[chr].reserve(size);
            }
            */

            if ( maxppos.find(chr) == maxppos.end()) {
                maxppos[chr] = physpos;
            } else if (physpos > maxppos[chr])
                maxppos[chr] = physpos;


            if ( minppos.find(chr) == minppos.end()) {
                minppos[chr] = physpos;
            } else if (physpos < minppos[chr])
                minppos[chr] = physpos;


            if ( maxgpos.find(chr) == maxgpos.end()) {
                maxgpos[chr] = genpos;
            } else if (genpos > maxgpos[chr])
                maxgpos[chr] = genpos;


            if ( mingpos.find(chr) == mingpos.end()) {
                mingpos[chr] = genpos;
            } else if (genpos < mingpos[chr])
                mingpos[chr] = genpos;

            // Fill in the genotypes
            tok1.resize (0);
            functions::tokenize (format.c_str(), tok1,":");
            int gind = -1;

            for (int i = 0 ; i < tok1.size(); i++){
                if (tok1[i].compare ("GT")==0) { 
                    gind = i;
                    break;
                }
            }
            if (gind == -1)
                continue;

            snps[chr].push_back (snp(id,chr,physpos,genpos,var,ref));
            vector<int> &gtype = snps[chr].back().gtype;
            j++;

            if (setind) {
                if (nind != numhap*(toks.size()-9)){
					cerr << "Bad genotype in " << genofile << ": Line "<< linenum  << endl;
					exit(1);
				}
            } else {
                nind = toks.size() - 9;
                nind *= numhap;
                setind = true;
            }

            gtype.resize(nind, 9);
            
            for (int i = 9, k = 0; i < toks.size(); i++, k++){ 
                tok1.resize(0);
                functions::tokenize(toks[i], tok1,",");
                if (isgenotype)  {
                    int a1 =  tok1[gind][0];
                    int a2 =  tok1[gind][2];
                    gtype[k] = (a1-48) + (a2-48);
                } else { 
                    int a1 =  tok1[gind][0];
                    int a2 =  tok1[gind][2];
                    gtype[2*k] = a1-48;
                    gtype[2*k+1] = a2-48;
                }
            }
            
        }
        if (j%10000==0) {
            io::println ("Read " + tostring (j) + " lines" ,0);
        }
    }
    nchr = chrs.size ();
    nsnps = j;
    
    if (io::debug >= 2 ) {
        cout << "genotype = " << to_string ();
    }

    ig.close ();

}
Esempio n. 14
0
    void learn(attributes_iterator_type attributes_from,
               attributes_iterator_type attributes_to,
               size_t attribute_dimension,
               classifications_iterator_type classifications_from)
    {
        size_t sample_size = attributes_to-attributes_from;
        classifications_iterator_type classifications_to = classifications_from + sample_size;
        // check for termination
        {
            size_t n_y0 = std::count(classifications_from,classifications_to,0);
            size_t n_y1 = sample_size - n_y0;
            if (n_y0 > ((double)sample_size)*termination_ratio ||
                    n_y1 > ((double)sample_size)*termination_ratio ||
                    sample_size < minimum_sample)
            {
                is_end_node = true;
                end_node_decision = n_y1 > n_y0;
                return;
            }
        }
        // decision the best decision
        {

            std::vector<std::pair<size_t,double> > decision_list;
            for (size_t index = 0;index < attribute_dimension;++index)
            {
                std::pair<attribute_type,attribute_type> range = get_value_range(attributes_from,attributes_to,index);
                double step = (range.first-range.second)/5.0;
                for (double value = range.second+step;value <= range.first-step;value += step)
                    decision_list.push_back(std::make_pair(index,value));
            }

            std::vector<double> ig(decision_list.size());
            for (size_t index = 0;index < decision_list.size();++index)
            {
                attribute_index = decision_list[index].first;
                param = decision_list[index].second;
                ig[index] = information_gain(attributes_from,attributes_to,classifications_from);
            }
            size_t best_decision_index = std::max_element(ig.begin(),ig.end())-ig.begin();

            attribute_index = decision_list[best_decision_index].first;
            param = decision_list[best_decision_index].second;
        }
        // split tree
        {
            std::vector<std::vector<attribute_type> > right_attributes;
            std::vector<std::vector<attribute_type> > left_attributes;
            std::vector<classification_type>		  right_classification;
            std::vector<classification_type>		  left_classification;
            right_attributes.reserve(sample_size);
            left_attributes.reserve(sample_size);
            right_classification.reserve(sample_size);
            left_classification.reserve(sample_size);

            for (size_t index = 0;index < sample_size;++index)
                if (attributes_from[index][attribute_index] > param)
                {
                    right_attributes.push_back(
                        std::vector<attribute_type>(
                            &(attributes_from[index][0]),&(attributes_from[index][0])+attribute_dimension));
                    right_classification.push_back(classifications_from[index]);
                }
                else
                {
                    left_attributes.push_back(
                        std::vector<attribute_type>(
                            &(attributes_from[index][0]),&(attributes_from[index][0])+attribute_dimension));
                    left_classification.push_back(classifications_from[index]);
                }

            right_tree.reset(new decision_tree(minimum_sample,termination_ratio));
            left_tree.reset(new decision_tree(minimum_sample,termination_ratio));
            right_tree->learn(right_attributes.begin(),right_attributes.end(),attribute_dimension,right_classification.begin());
            left_tree->learn(left_attributes.begin(),left_attributes.end(),attribute_dimension,left_classification.begin());
            is_end_node = false;
        }
    }