Exemplo n.º 1
0
void AwtDesktopProperties::GetNonClientParameters() {
    //
    // general window properties
    //
    NONCLIENTMETRICS    ncmetrics;

    // Fix for 6944516: specify correct size for ncmetrics on WIN2K/XP
    // Microsoft recommend to subtract the size of  'iPaddedBorderWidth' field
    // when running on XP. However this can't be referenced at compile time
    // with the older SDK, so there use 'lfMessageFont' plus its size.
    if (!IS_WINVISTA) {
#if defined(_MSC_VER) && (_MSC_VER >= 1600)
        ncmetrics.cbSize = offsetof(NONCLIENTMETRICS, iPaddedBorderWidth);
#else
        ncmetrics.cbSize = offsetof(NONCLIENTMETRICS,lfMessageFont) + sizeof(LOGFONT);
#endif
    } else {
        ncmetrics.cbSize = sizeof(ncmetrics);
    }
    VERIFY( SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncmetrics.cbSize, &ncmetrics, FALSE) );

    float invScaleX;
    float invScaleY;
    getInvScale(invScaleX, invScaleY);

    SetFontProperty(TEXT("win.frame.captionFont"), ncmetrics.lfCaptionFont, invScaleY);
    SetIntegerProperty(TEXT("win.frame.captionHeight"), rescale(ncmetrics.iCaptionHeight, invScaleY));
    SetIntegerProperty(TEXT("win.frame.captionButtonWidth"), rescale(ncmetrics.iCaptionWidth, invScaleX));
    SetIntegerProperty(TEXT("win.frame.captionButtonHeight"), rescale(ncmetrics.iCaptionHeight, invScaleY));
    SetFontProperty(TEXT("win.frame.smallCaptionFont"), ncmetrics.lfSmCaptionFont, invScaleY);
    SetIntegerProperty(TEXT("win.frame.smallCaptionHeight"), rescale(ncmetrics.iSmCaptionHeight, invScaleY));
    SetIntegerProperty(TEXT("win.frame.smallCaptionButtonWidth"), rescale(ncmetrics.iSmCaptionWidth, invScaleX));
    SetIntegerProperty(TEXT("win.frame.smallCaptionButtonHeight"), rescale(ncmetrics.iSmCaptionHeight, invScaleY));
    SetIntegerProperty(TEXT("win.frame.sizingBorderWidth"), rescale(ncmetrics.iBorderWidth, invScaleX));

    // menu properties
    SetFontProperty(TEXT("win.menu.font"), ncmetrics.lfMenuFont, invScaleY);
    SetIntegerProperty(TEXT("win.menu.height"), rescale(ncmetrics.iMenuHeight, invScaleY));
    SetIntegerProperty(TEXT("win.menu.buttonWidth"), rescale(ncmetrics.iMenuWidth, invScaleX));

    // scrollbar properties
    SetIntegerProperty(TEXT("win.scrollbar.width"), rescale(ncmetrics.iScrollWidth, invScaleX));
    SetIntegerProperty(TEXT("win.scrollbar.height"), rescale(ncmetrics.iScrollHeight, invScaleY));

    // status bar and tooltip properties
    SetFontProperty(TEXT("win.status.font"), ncmetrics.lfStatusFont, invScaleY);
    SetFontProperty(TEXT("win.tooltip.font"), ncmetrics.lfStatusFont, invScaleY);

    // message box properties
    SetFontProperty(TEXT("win.messagebox.font"), ncmetrics.lfMessageFont, invScaleY);
}
Exemplo n.º 2
0
// examples macro
void 
etauAfterFit_novbf(bool scaled = true, bool log = true)
{
  // defining the common canvas, axes pad styles
  SetStyle();

  // open example histogram file
  TFile* exampleFile = new TFile("eleTau_sm.root");

  //load example histograms
  TH1F* data = (TH1F*)exampleFile->Get("eleTau_SM0/data_obs");
  if(data) {InitHist(data, "#bf{m_{vis} [GeV]}", "#bf{Events}"); InitData(data);} else{std::cout << "can't find hitogram " << "eleTau_SM0/data_obs" << std::endl;}

  TH1F* Fakes =  refill((TH1F*)exampleFile->Get("eleTau_SM0/QCD"))              ; InitHist(Fakes, "", "", kMagenta-10, 1001);                   
  TH1F* EWK1  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/W"  ))              ; InitHist(EWK1 , "", "", kRed    + 2, 1001);
  TH1F* EWK2  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZJ" ))              ; InitHist(EWK2 , "", "", kRed    + 2, 1001);
  TH1F* EWK3  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZL" ))              ; InitHist(EWK3 , "", "", kRed    + 2, 1001);
  TH1F* EWK   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/VV" ))              ; InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar =  refill((TH1F*)exampleFile->Get("eleTau_SM0/TT" ))              ; InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZTT"))              ; InitHist(Ztt  , "", "", kOrange - 4, 1001);
  TH1F* ggH   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/SM120" ))           ; InitSignal(ggH); ggH ->Scale(10*16.63*0.071*16.083/ggH ->Integral());
  TH1F* qqH   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/VBF120"))           ; InitSignal(qqH); qqH ->Scale(10*1.269*0.071* 1.105/qqH ->Integral());
 
  if(scaled){
    rescale(Fakes, 2); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
    rescale(EWK3 , 5); 
    rescale(EWK  , 7); 
    rescale(ttbar, 6); 
    rescale(Ztt  , 1);
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
  }
  if(log){
    qqH  ->Add(ggH  );
    Fakes->Add(qqH  );
    EWK1 ->Add(Fakes);
    EWK2 ->Add(EWK1 );
    EWK3 ->Add(EWK2 );
    EWK  ->Add(EWK3 );
    ttbar->Add(EWK  );
    Ztt  ->Add(ttbar);
  }
  else{
    EWK1 ->Add(Fakes);
    EWK2 ->Add(EWK1 );
    EWK3 ->Add(EWK2 );
    EWK  ->Add(EWK3 );
    ttbar->Add(EWK  );
    Ztt  ->Add(ttbar);
    ggH  ->Add(Ztt  );
    qqH  ->Add(ggH  );
  }
  // define canvas
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){
    canv->SetLogy(1);
    data->SetMinimum(5.0);
    data->SetMaximum(500000.);
  }
  else{
    data->SetMaximum(4000.);
  }
  data->SetNdivisions(505);
  data->Draw("e");

  if(log){
    Ztt->Draw("same");
    ttbar->Draw("same");
    EWK->Draw("same");
    Fakes->Draw("same");
    qqH->Draw("same");
  }
  else{
    qqH->Draw("same");
    Ztt->Draw("same");
    ttbar->Draw("same");
    EWK->Draw("same");
    Fakes->Draw("same");
  }
  data->Draw("esame");
  canv->RedrawAxis();

  CMSPrelim("#tau_{e}#tau_{h}", 0.45, 0.75);
  
  TLegend* leg = new TLegend(0.45, 0.45, 0.9, 0.75);
  SetLegendStyle(leg);
  leg->AddEntry(qqH  , "(10x) H#rightarrow#tau#tau" , "L" );
  leg->AddEntry(data , "Observed"                , "LP");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"    , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                , "F" );
  leg->AddEntry(EWK  , "Electroweak"             , "F" );
  leg->AddEntry(Fakes, "QCD"                     , "F" );
  leg->Draw();

  TPaveText* mssm  = new TPaveText(0.78, 0.70, 0.90, 0.74, "NDC");
  mssm->SetBorderSize(   0 );
  mssm->SetFillStyle(    0 );
  mssm->SetTextAlign(   12 );
  mssm->SetTextSize ( 0.04 );
  mssm->SetTextColor(    1 );
  mssm->SetTextFont (   62 );
  mssm->AddText("m_{H}=120");
  mssm->Draw();

  if(log){
    if(scaled) canv->Print("etau_rescaled_novbf_LOG.pdf"); else canv->Print("etau_unscaled_novbf_LOG.pdf");
    if(scaled) canv->Print("etau_rescaled_novbf_LOG.png"); else canv->Print("etau_unscaled_novbf_LOG.png");
  }
  else{
    if(scaled) canv->Print("etau_rescaled_novbf.pdf"); else canv->Print("etau_unscaled_novbf.pdf");
    if(scaled) canv->Print("etau_rescaled_novbf.png"); else canv->Print("etau_unscaled_novbf.png");
  }
}
Exemplo n.º 3
0
Window::Window(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Window)
    , calc_thread(new QThread(this))
    , calculator(new Calculator())
{
    calculator->moveToThread(calc_thread);
    calc_thread->start();

    ui->setupUi(this);

    {
        auto font = ui->plot->font();
        font.setPointSize(18);
        ui->plot->setFont(font);
        ui->plot->xAxis->setTickLabelFont(font);
        ui->plot->yAxis->setTickLabelFont(font);
        ui->plot->yAxis2->setTickLabelFont(font);
        font.setItalic(true);
        ui->plot->xAxis->setLabelFont(font);
        ui->plot->yAxis->setLabelFont(font);
        ui->plot->yAxis2->setLabelFont(font);
    }
    ui->plot->addGraph();
    ui->plot->addGraph(ui->plot->xAxis, ui->plot->yAxis2);
    ui->plot->yAxis2->setVisible(true);
    ui->plot->xAxis->setLabel("t");
    ui->plot->yAxis->setLabel("U");
    ui->plot->yAxis2->setLabel("I");
    connect(ui->plot->yAxis, static_cast<void(QCPAxis::*)(const QCPRange &, const QCPRange &)>(&QCPAxis::rangeChanged),  [this] (const QCPRange &newRange, const QCPRange &oldRange)
    {
        double scale_coef = ui->plot->yAxis2->range().size() / oldRange.size();

        double d_size = newRange.size() / oldRange.size();
        double d_center = (newRange.center() - oldRange.center()) * scale_coef;

        double new_size = ui->plot->yAxis2->range().size() * d_size;
        double new_center = ui->plot->yAxis2->range().center() + d_center;

        ui->plot->yAxis2->setRange(new_center - new_size/2, new_center + new_size/2);
    });

    for (int i=2; i < 5; i++)
    {
        ui->plot->addGraph();
    }
    ui->plot->addGraph(ui->plot->xAxis, ui->plot->yAxis2);

    ui->plot->graph(1)->setPen(QPen(QColor("blue")));
    ui->plot->graph(1)->setPen(QPen(QColor("red")));
    ui->plot->xAxis->setAutoTickCount(ui->x_axis_density->value());

    ui->plot->graph(2)->setPen(QPen(QColor("green")));
    ui->plot->graph(3)->setPen(QPen(QColor("green")));

    ui->plot->graph(4)->setPen(QPen(QBrush(QColor("lime")), 2));
    ui->plot->graph(5)->setPen(QPen(QBrush(QColor("orange")), 2));

    ui->plot->setInteraction(QCP::iRangeDrag);
    ui->plot->setInteraction(QCP::iRangeZoom);

    connect(this, SIGNAL(beginCalc()), calculator, SLOT(start()));
    connect(calculator, SIGNAL(progress(int,int)), this, SLOT(onProgress(int,int)));
    connect(calculator, SIGNAL(done()), this, SLOT(onDone()));
    connect(ui->btnRescale, SIGNAL(released()), this, SLOT(rescale()));
    connect(ui->allow_save_to_file, &QCheckBox::toggled, ui->output_filename, &QLineEdit::setEnabled);
    connect(ui->allow_save_to_file, &QCheckBox::toggled, calculator, &Calculator::setAllowOutToFile);

    connect(ui->slider_double, &DoubleSlider::valueChanged, this, &Window::onDoubleSliderMoved);
    connect(ui->slider_double, &DoubleSlider::altValueChanged, this, &Window::onDoubleSliderAltMoved);

    connect(ui->chck_dispersion_select, &QCheckBox::toggled, this, [this] (bool checked) {
        ui->chck_range_select->blockSignals(true);
        ui->chck_range_select->setChecked(false);
        ui->chck_range_select->blockSignals(false);

        if (checked)
        {
            select_from = ui->spin_dispersion_from;
            select_to = ui->spin_dispersion_to;
            ui->slider_double->show();
        }
        else
        {
            ui->slider_double->hide();
        }
    });

    connect(ui->chck_range_select, &QCheckBox::toggled, this, [this] (bool checked) {
        ui->chck_dispersion_select->blockSignals(true);
        ui->chck_dispersion_select->setChecked(false);
        ui->chck_dispersion_select->blockSignals(false);

        if (checked)
        {
            select_from = ui->spin_from;
            select_to = ui->spin_to;
            ui->slider_double->show();
        }
        else
        {
            ui->slider_double->hide();
        }
    });

    ui->chck_dispersion_select->setChecked(true);

    ui->allow_save_to_file->setChecked(false);
    ui->btnRescale->setIcon(qApp->style()->standardIcon(QStyle::SP_BrowserReload));
    ui->progressBar->hide();
}
Exemplo n.º 4
0
void 
HBB_LEP_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 4.8 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile);
  TH1F* bkgBBB  = refill((TH1F*)input->Get(TString::Format("%s/bkgBBB"   , directory)), "bkgBBB"); InitHist(bkgBBB, "", "", kMagenta-10, 1001);;
#ifdef MSSM
  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A+H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (23314.3*0.879 + 21999.3*0.877)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (31087.9*0.879 + 29317.8*0.877)/1000.; }
 //  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A+H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (6211.6*0.89 + 5145.0*0.85)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (8282.7*0.89 + 6867.8*0.85)/1000.; }
  TH1F* bbH  = refill((TH1F*)input->Get(TString::Format("%s/bbH160"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale(bbHScale);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)bkgBBB->Clone("ref");

  double unscaled[7];
  unscaled[0] = bkgBBB ->Integral();
#ifdef MSSM
  unscaled[1] = bbH ->Integral();
  unscaled[2] = 0;
#endif

  if(scaled){
    rescale(bkgBBB,   1);
#ifdef MSSM 
    rescale(bbH,   2);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-bkgBBB", "", 3, 0, 3);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (bkgBBB  ->Integral()/unscaled[0]-1.) : 0.);
#ifdef MSSM
  scales[1] = new TH1F("scales-bbH"  , "", 3, 0, 3);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbH  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-NONE" , "", 3, 0, 3);
  scales[2]->SetBinContent(3, 0.);
#endif

  if(!log){
#ifdef MSSM
    bbH  ->Add(bkgBBB);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(bkgBBB, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)bkgBBB ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif
  }
  else{  
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif  
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
 
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif


#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.94, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
  leg->AddEntry(data,   "observed"                       , "LP");
  leg->AddEntry(bkgBBB, "bkgBBB"                      , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(bkgBBB);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) bkgBBB->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{bkgBBB}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  bkgBBB  ->Write("bkgBBB"  );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Exemplo n.º 5
0
event_t *
be_file_playaudio(const char *url, media_pipe_t *mp,
		  char *errbuf, size_t errlen, int hold)
{
  AVFormatContext *fctx;
  AVIOContext *avio;
  AVCodecContext *ctx;
  AVPacket pkt;
  media_format_t *fw;
  int i, r, si;
  media_buf_t *mb = NULL;
  media_queue_t *mq;
  event_ts_t *ets;
  int64_t ts, pts4seek = 0;
  media_codec_t *cw;
  event_t *e;
  int lost_focus = 0;

  mp_set_playstatus_by_hold(mp, hold, NULL);

  if((avio = fa_libav_open(url, 32768, errbuf, errlen)) == NULL)
    return NULL;


  // First we need to check for a few other formats
#if ENABLE_LIBOPENSPC || ENABLE_LIBGME

  uint8_t pb[128];
  size_t psiz;
  
  psiz = avio_read(avio, pb, sizeof(pb));
  if(psiz < sizeof(pb)) {
    fa_libav_close(avio);
    snprintf(errbuf, errlen, "Fill too small");
    return NULL;
  }

#if ENABLE_LIBGME
  if(*gme_identify_header(pb))
    return fa_gme_playfile(mp, avio, errbuf, errlen, hold);
#endif

#if ENABLE_LIBOPENSPC
  if(!memcmp(pb, "SNES-SPC700 Sound File Data", 27))
    return openspc_play(mp, avio, errbuf, errlen);
#endif

#endif

  if((fctx = fa_libav_open_format(avio, url, errbuf, errlen)) == NULL) {
    fa_libav_close(avio);
    return NULL;
  }

  TRACE(TRACE_DEBUG, "Audio", "Starting playback of %s", url);

  mp_set_play_caps(mp, MP_PLAY_CAPS_SEEK | MP_PLAY_CAPS_PAUSE);

  mp->mp_audio.mq_stream = -1;
  mp->mp_video.mq_stream = -1;

  fw = media_format_create(fctx);

  cw = NULL;
  for(i = 0; i < fctx->nb_streams; i++) {
    ctx = fctx->streams[i]->codec;

    if(ctx->codec_type != AVMEDIA_TYPE_AUDIO)
      continue;

    cw = media_codec_create(ctx->codec_id, 0, fw, ctx, NULL, mp);
    mp->mp_audio.mq_stream = i;
    break;
  }
  
  if(cw == NULL) {
    media_format_deref(fw);
    snprintf(errbuf, errlen, "Unable to open codec");
    return NULL;
  }

  mp_become_primary(mp);
  mq = &mp->mp_audio;

  while(1) {

    /**
     * Need to fetch a new packet ?
     */
    if(mb == NULL) {

      if((r = av_read_frame(fctx, &pkt)) < 0) {

	while((e = mp_wait_for_empty_queues(mp, 0)) != NULL) {
	  if(event_is_type(e, EVENT_PLAYQUEUE_JUMP) ||
	     event_is_action(e, ACTION_PREV_TRACK) ||
	     event_is_action(e, ACTION_NEXT_TRACK) ||
	     event_is_action(e, ACTION_STOP)) {
	    mp_flush(mp, 0);
	    break;
	  }
	  event_release(e);
	}
	if(e == NULL)
	  e = event_create_type(EVENT_EOF);
	break;
      }

      si = pkt.stream_index;

      if(si == mp->mp_audio.mq_stream) {
	/* Current audio stream */
	mb = media_buf_alloc();
	mb->mb_data_type = MB_AUDIO;

      } else {
	/* Check event queue ? */
	av_free_packet(&pkt);
	continue;
      }


      mb->mb_pts      = rescale(fctx, pkt.pts,      si);
      mb->mb_dts      = rescale(fctx, pkt.dts,      si);
      mb->mb_duration = rescale(fctx, pkt.duration, si);

      mb->mb_cw = media_codec_ref(cw);

      /* Move the data pointers from ffmpeg's packet */

      mb->mb_stream = pkt.stream_index;

      av_dup_packet(&pkt);

      mb->mb_data = pkt.data;
      pkt.data = NULL;

      mb->mb_size = pkt.size;
      pkt.size = 0;

      if(mb->mb_pts != AV_NOPTS_VALUE) {
	if(fctx->start_time == AV_NOPTS_VALUE)
	  mb->mb_time = mb->mb_pts;
	else
	  mb->mb_time = mb->mb_pts - fctx->start_time;
	pts4seek = mb->mb_time;
      } else
	mb->mb_time = AV_NOPTS_VALUE;


      av_free_packet(&pkt);
    }

    /*
     * Try to send the buffer.  If mb_enqueue() returns something we
     * catched an event instead of enqueueing the buffer. In this case
     * 'mb' will be left untouched.
     */

    if((e = mb_enqueue_with_events(mp, mq, mb)) == NULL) {
      mb = NULL; /* Enqueue succeeded */
      continue;
    }      

    if(event_is_type(e, EVENT_PLAYQUEUE_JUMP)) {

      mp_flush(mp, 0);
      break;

    } else if(event_is_type(e, EVENT_SEEK)) {

      ets = (event_ts_t *)e;
      ts = ets->pts + fctx->start_time;
      if(ts < fctx->start_time)
	ts = fctx->start_time;
      av_seek_frame(fctx, -1, ts, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);
      
    } else if(event_is_action(e, ACTION_SEEK_FAST_BACKWARD)) {

      av_seek_frame(fctx, -1, pts4seek - 60000000, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SEEK_BACKWARD)) {

      av_seek_frame(fctx, -1, pts4seek - 15000000, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SEEK_FAST_FORWARD)) {

      av_seek_frame(fctx, -1, pts4seek + 60000000, 0);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SEEK_FORWARD)) {

      av_seek_frame(fctx, -1, pts4seek + 15000000, 0);
      seekflush(mp, &mb);
#if 0
    } else if(event_is_action(e, ACTION_RESTART_TRACK)) {

      av_seek_frame(fctx, -1, 0, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);
#endif
    } else if(event_is_action(e, ACTION_PLAYPAUSE) ||
	      event_is_action(e, ACTION_PLAY) ||
	      event_is_action(e, ACTION_PAUSE)) {

      hold = action_update_hold_by_event(hold, e);
      mp_send_cmd_head(mp, mq, hold ? MB_CTRL_PAUSE : MB_CTRL_PLAY);
      lost_focus = 0;
      mp_set_playstatus_by_hold(mp, hold, NULL);

    } else if(event_is_type(e, EVENT_MP_NO_LONGER_PRIMARY)) {

      hold = 1;
      lost_focus = 1;
      mp_send_cmd_head(mp, mq, MB_CTRL_PAUSE);
      mp_set_playstatus_by_hold(mp, hold, e->e_payload);

    } else if(event_is_type(e, EVENT_MP_IS_PRIMARY)) {

      if(lost_focus) {
	hold = 0;
	lost_focus = 0;
	mp_send_cmd_head(mp, mq, MB_CTRL_PLAY);
	mp_set_playstatus_by_hold(mp, hold, NULL);
      }

    } else if(event_is_type(e, EVENT_INTERNAL_PAUSE)) {

      hold = 1;
      lost_focus = 0;
      mp_send_cmd_head(mp, mq, MB_CTRL_PAUSE);
      mp_set_playstatus_by_hold(mp, hold, e->e_payload);

    } else if(event_is_action(e, ACTION_PREV_TRACK) ||
	      event_is_action(e, ACTION_NEXT_TRACK) ||
	      event_is_action(e, ACTION_STOP)) {
      mp_flush(mp, 0);
      break;
    }
    event_release(e);
  }

  if(mb != NULL)
    media_buf_free(mb);

  media_codec_deref(cw);
  media_format_deref(fw);

  if(hold) { 
    // If we were paused, release playback again.
    mp_send_cmd(mp, mq, MB_CTRL_PLAY);
    mp_set_playstatus_by_hold(mp, 0, NULL);
  }

  return e;
}
Exemplo n.º 6
0
int bound_prim_user(int boundstage, FTYPE prim[][N2M][N3M][NPR])
{
  int i, j, k, pl;
  struct of_geom geom,rgeom;
  FTYPE vcon[NDIM]; // coordinate basis vcon
#if(WHICHVEL==VEL3)
  int failreturn;
#endif
  int ri, rj, rk; // reference i,j,k
  FTYPE prescale[NPR];







  ///////////////////////////
  //
  // X1 inner OUTFLOW/FIXEDOUTFLOW
  //
  ///////////////////////////

  if (mycpupos[1] == 0) {
    if((BCtype[X1DN]==OUTFLOW)||(BCtype[X1DN]==FIXEDOUTFLOW)){
      /* inner r boundary condition: u, just copy */
      LOOPN2 LOOPN3{
#if(EXTRAP==0)
	ri=0;
	rj=j;
	rk=k;
	LOOPBOUND1IN PBOUNDLOOP(pl) prim[i][j][k][pl] = prim[ri][rj][rk][pl];
#elif(EXTRAP==1)

	ri=0;
	rj=j;
	rk=k;
	LOOPBOUND1IN{
	  for(pl=RHO;pl<=UU;pl++){
	    prim[i][j][k][pl] = prim[ri][rj][rk][pl] * gdet[ri][rj][rk][CENT]/gdet[i][j][k][CENT] ;
	  }
	  pl=U1;	    // treat U1 as special
	  prim[i][j][k][pl] = prim[ri][rj][rk][pl] * (1. - (i-ri)*dx[1]) ;
	  for(pl=U2;pl<=U3;pl++){
	    prim[i][j][k][pl] = prim[ri][rj][rk][pl] * (1. + (i-ri)*dx[1]) ;
	  }
	  pl=B1; // treat B1 special
	  prim[i][j][k][pl] = prim[ri][rj][rk][pl] * gdet[ri][rj][rk][CENT]/gdet[i][j][k][CENT] ;
	  for(pl=B2;pl<=B3;pl++){
	    prim[i][j][k][pl] = prim[ri][rj][rk][pl] * (1. + (i-ri)*dx[1]) ;
	  }
	}
#elif(EXTRAP==2)
	ri=0;
	rj=j;
	rk=k;
	get_geometry(ri, rj, rk, CENT, &rgeom);
	rescale(1,1,prim[ri][rj][rk],&rgeom,prescale);
	LOOPBOUND1IN{
	  // set guess
	  PBOUNDLOOP(pl) prim[i][j][k][pl]=prim[ri][rj][k][pl];
	  get_geometry(i, j, k, CENT, &geom);	    
	  rescale(-1,1,prim[i][j][k],&geom,prescale);
	}
#endif
	LOOPBOUND1IN{
#if(WHICHVEL==VEL4)
	  get_geometry(i, j, k, CENT, &geom);
	  inflow_check_4vel(1,prim[i][j][k],&geom, 0) ;
#elif(WHICHVEL==VEL3)
	  get_geometry(i, j, k, CENT, &geom);
	  inflow_check_3vel(1,prim[i][j][k],&geom, 0) ;
	  // projection may not preserve u^t to be real and rho>rhoscal u>uuscal
#if(JONCHECKS)
	  if(jonchecks){
	    //fixup1zone(prim[i][j][k],&geom,0);
	    failreturn=check_pr(prim[i][j][k],prim[i][j][k],&geom,-3);
	    if(failreturn){
	      dualfprintf(fail_file,"Bad boundary zone, couldn't fix: i=%d j=%d k=%d\n",startpos[1]+i,startpos[2]+j,startpos[3]+k);
	      if (fail(FAIL_BCFIX) >= 1) return (1);
	    }
	  }
#endif
#elif(WHICHVEL==VELREL4)
	  get_geometry(i,j,k,CENT,&geom) ;
	  inflow_check_rel4vel(1,prim[i][j][k],&geom,0) ;
	  if(limit_gamma(GAMMAMAX,prim[i][j][k],&geom,0)>=1)
	    FAILSTATEMENT("bounds.c:bound_prim()", "limit_gamma()", 1);
#endif	
	}
      }// end 2 3
    }// end if correct bound type

  }// end if mycpupos[1]==0
void setMotion(const int y1, const int y2)
{
	setMotors(rescale(y1), rescale(y2));
}
int main(int argc, char **argv)
{

	// instantiate a model manager:
	ModelManager manager("test SuperPixel Road Segmenter");

	// Instantiate our various ModelComponents:

	nub::soft_ref<InputFrameSeries> ifs(new InputFrameSeries(manager));
	manager.addSubComponent(ifs);

	nub::soft_ref<OutputFrameSeries> ofs(new OutputFrameSeries(manager));
	manager.addSubComponent(ofs);

	manager.exportOptions(MC_RECURSE);

	// Parse command-line:
	if (manager.parseCommandLine(argc, argv, "[pyr_size] [angle] [min_size]", 0, 4) == false) return(1);


	// let's do it!
	manager.start();




	bool keepGoing = true; uint index = 0;
	rutz::shared_ptr<SuperPixelRoadSegmenter>sprs (new SuperPixelRoadSegmenter());

	Timer timer(1000000); float time = 0.0;
	while(keepGoing)
	{
		ifs->updateNext();
		Image<PixRGB<byte> > ima = ifs->readRGB();

		if(!ima.initialized()) { keepGoing = false; }
		else
		{

			//char buffer[200];

			uint w = ima.getWidth();
			uint h = ima.getHeight();


			LINFO("B4 rescale: imaW %d imaH %d",ima.getWidth(),ima.getHeight());
			if(w > 320 ||w/h != 320/240||1){
				LINFO("rescale input to 320/240");
				ima = rescale(ima,320,240);
				w = ima.getWidth();
				h = ima.getHeight();
			}

			LINFO("After scale,imaW %d imaH %d",ima.getWidth(),ima.getHeight());
			LINFO("W %d H %d",w,h);

			Image<PixRGB<byte> > dispIma(w*4, h*4, NO_INIT);

			timer.reset();
			time = timer.get()/1000.0F;
			sprs->updateImage(ima);
			LINFO("Total time for one frame: %f", timer.get()/1000.0F - time);time = timer.get()/1000.0F;
			
			Image<PixRGB<byte> > outputIma = sprs->getOutputImage();
			LINFO("outputIma,imaW %d imaH %d",outputIma.getWidth(),outputIma.getHeight());
			time = timer.get()/1000.0F;
			inplacePaste(dispIma, outputIma, Point2D<int>(0, 0));
			inplacePaste(dispIma, ima, Point2D<int>(0, 0));
			Image<PixRGB<byte> > fanIma = sprs->getFanImg();
			inplacePaste(dispIma, fanIma, Point2D<int>(0, h));


			LINFO("Compute Road Region time: %f", timer.get()/1000.0F - time);time = timer.get()/1000.0F;



			ofs->writeRGB(dispIma, "SuperPixel Road Segmenter");
			ofs->updateNext();
			Raster::waitForKey();

		}
		index++;
	}
	Raster::waitForKey();


	return 0;
}
void 
HTT_TT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("tauTau_1jet"      )){ category_extra = "1 jet";             }
  if(std::string(directory) == std::string("tauTau_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("tauTau_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("tauTau_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau,  19.8 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary, #sqrt{s} = 8 TeV, L = 19.8 fb^{-1}, H #rightarrow #tau #tau";}
#endif

  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"   , directory)), "QCD"); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"     , directory)), "W"  ); InitHist(EWK1 , "", "", kRed    + 2, 1001);
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"    , directory)), "ZJ" ); InitHist(EWK2 , "", "", kRed    + 2, 1001);
//TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"    , directory)), "ZL" ); InitHist(EWK3 , "", "", kRed    + 2, 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"    , directory)), "VV" ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"    , directory)), "TT" ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  // float ggHScale = 1., bbHScale = 1.;
//   ggHScale = ($MSSM_SIGNAL_ggH_xseff_A + $MSSM_SIGNAL_ggH_xseff_hH);
//   bbHScale = ($MSSM_SIGNAL_bbH_xseff_A + $MSSM_SIGNAL_bbH_xseff_hH);
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA", directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB); //ggH ->Scale(ggHScale);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA", directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB); //bbH ->Scale(bbHScale);
#else
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125", directory)), "qqH"); InitSignal(qqH); qqH ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125" , directory)), "VH" ); InitSignal(VH ); VH  ->Scale(SIGNAL_SCALE);
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
//ref->Add(EWK3 );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
//unscaled[1]+= EWK3 ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif

  if(scaled){
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
  //rescale(EWK3 , 5);
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
					      //+EWK3 ->Integral()
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif

  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
//EWK3 ->Add(EWK2 );
//EWK  ->Add(EWK3 );
  EWK  ->Add(EWK2 );
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(500)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
    ggH  ->Draw("histsame");
  }
  else{
    ggH  ->Draw("histsame");
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("#tau_{h}#tau_{h}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=$MA GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=$TANB");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("m^{h}_{max}");
  scen->Draw();
#endif
  
#ifdef MSSM
  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.88);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.88);
  SetLegendStyle(leg);
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + SM125 GeV signal"    , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=120, tan#beta=10)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Ztt);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+0.5);
  rat1->SetMinimum(-0.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);

  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "pre" : "post", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
  output->Close();
}
Exemplo n.º 10
0
event_t *
be_file_playaudio(const char *url, media_pipe_t *mp,
		  char *errbuf, size_t errlen, int hold, const char *mimetype)
{
  AVFormatContext *fctx;
  AVCodecContext *ctx;
  AVPacket pkt;
  media_format_t *fw;
  int i, r, si;
  media_buf_t *mb = NULL;
  media_queue_t *mq;
  event_ts_t *ets;
  int64_t ts, seekbase = 0;
  media_codec_t *cw;
  event_t *e;
  int registered_play = 0;

  mp_set_playstatus_by_hold(mp, hold, NULL);

  fa_handle_t *fh = fa_open_ex(url, errbuf, errlen, FA_BUFFERED_SMALL, NULL);
  if(fh == NULL)
    return NULL;

  // First we need to check for a few other formats
#if ENABLE_LIBGME

  uint8_t pb[128];
  size_t psiz;
  
  psiz = fa_read(fh, pb, sizeof(pb));
  if(psiz < sizeof(pb)) {
    fa_close(fh);
    snprintf(errbuf, errlen, "Fill too small");
    return NULL;
  }

#if ENABLE_LIBGME
  if(*gme_identify_header(pb))
    return fa_gme_playfile(mp, fh, errbuf, errlen, hold, url);
#endif

#endif

  
  AVIOContext *avio = fa_libav_reopen(fh);

  if(avio == NULL) {
    fa_close(fh);
    return NULL;
  }

  if((fctx = fa_libav_open_format(avio, url, 
				  errbuf, errlen, mimetype)) == NULL) {
    fa_libav_close(avio);
    return NULL;
  }

  TRACE(TRACE_DEBUG, "Audio", "Starting playback of %s", url);

  mp_configure(mp, MP_PLAY_CAPS_SEEK | MP_PLAY_CAPS_PAUSE,
	       MP_BUFFER_SHALLOW);

  mp->mp_audio.mq_stream = -1;
  mp->mp_video.mq_stream = -1;

  fw = media_format_create(fctx);

  cw = NULL;
  for(i = 0; i < fctx->nb_streams; i++) {
    ctx = fctx->streams[i]->codec;

    if(ctx->codec_type != AVMEDIA_TYPE_AUDIO)
      continue;

    cw = media_codec_create(ctx->codec_id, 0, fw, ctx, NULL, mp);
    mp->mp_audio.mq_stream = i;
    break;
  }
  
  if(cw == NULL) {
    media_format_deref(fw);
    snprintf(errbuf, errlen, "Unable to open codec");
    return NULL;
  }

  mp_become_primary(mp);
  mq = &mp->mp_audio;

  while(1) {

    /**
     * Need to fetch a new packet ?
     */
    if(mb == NULL) {
      
      mp->mp_eof = 0;
      r = av_read_frame(fctx, &pkt);
      if(r == AVERROR(EAGAIN))
	continue;
      
      if(r == AVERROR_EOF || r == AVERROR(EIO)) {
	mb = MB_SPECIAL_EOF;
	mp->mp_eof = 1;
	continue;
      }
      
      if(r != 0) {
	char msg[100];
	fa_ffmpeg_error_to_txt(r, msg, sizeof(msg));
	TRACE(TRACE_ERROR, "Audio", "Playback error: %s", msg);

	while((e = mp_wait_for_empty_queues(mp)) != NULL) {
	  if(event_is_type(e, EVENT_PLAYQUEUE_JUMP) ||
	     event_is_action(e, ACTION_SKIP_BACKWARD) ||
	     event_is_action(e, ACTION_SKIP_FORWARD) ||
	     event_is_action(e, ACTION_STOP)) {
	    mp_flush(mp, 0);
	    break;
	  }
	  event_release(e);
	}
	if(e == NULL)
	  e = event_create_type(EVENT_EOF);
	break;
      }

      si = pkt.stream_index;

      if(si != mp->mp_audio.mq_stream) {
	av_free_packet(&pkt);
	continue;
      }



      mb = media_buf_alloc_unlocked(mp, pkt.size);
      mb->mb_data_type = MB_AUDIO;

      mb->mb_pts      = rescale(fctx, pkt.pts,      si);
      mb->mb_dts      = rescale(fctx, pkt.dts,      si);
      mb->mb_duration = rescale(fctx, pkt.duration, si);

      mb->mb_cw = media_codec_ref(cw);

      /* Move the data pointers from ffmpeg's packet */

      mb->mb_stream = pkt.stream_index;

      memcpy(mb->mb_data, pkt.data, pkt.size);

      if(mb->mb_pts != AV_NOPTS_VALUE) {
	if(fctx->start_time == AV_NOPTS_VALUE)
	  mb->mb_time = mb->mb_pts;
	else
	  mb->mb_time = mb->mb_pts - fctx->start_time;
      } else
	mb->mb_time = AV_NOPTS_VALUE;

      mb->mb_send_pts = 1;

      av_free_packet(&pkt);
    }

    /*
     * Try to send the buffer.  If mb_enqueue() returns something we
     * catched an event instead of enqueueing the buffer. In this case
     * 'mb' will be left untouched.
     */

    if(mb == MB_SPECIAL_EOF) {
      // We have reached EOF, drain queues
      e = mp_wait_for_empty_queues(mp);
      
      if(e == NULL) {
	e = event_create_type(EVENT_EOF);
	break;
      }

    } else if((e = mb_enqueue_with_events(mp, mq, mb)) == NULL) {
      mb = NULL; /* Enqueue succeeded */
      continue;
    }      

    if(event_is_type(e, EVENT_PLAYQUEUE_JUMP)) {

      mp_flush(mp, 0);
      break;

    } else if(event_is_type(e, EVENT_CURRENT_PTS)) {

      ets = (event_ts_t *)e;
      seekbase = ets->ts;

      if(registered_play == 0) {
	if(ets->ts - fctx->start_time > METADB_AUDIO_PLAY_THRESHOLD) {
	  registered_play = 1;
	  metadb_register_play(url, 1, CONTENT_AUDIO);
	}
      }

    } else if(event_is_type(e, EVENT_SEEK)) {

      ets = (event_ts_t *)e;
      ts = ets->ts + fctx->start_time;
      if(ts < fctx->start_time)
	ts = fctx->start_time;
      av_seek_frame(fctx, -1, ts, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);
      
    } else if(event_is_action(e, ACTION_SEEK_FAST_BACKWARD)) {

      av_seek_frame(fctx, -1, seekbase - 60000000, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SEEK_BACKWARD)) {

      av_seek_frame(fctx, -1, seekbase - 15000000, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SEEK_FAST_FORWARD)) {

      av_seek_frame(fctx, -1, seekbase + 60000000, 0);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SEEK_FORWARD)) {

      av_seek_frame(fctx, -1, seekbase + 15000000, 0);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_PLAYPAUSE) ||
	      event_is_action(e, ACTION_PLAY) ||
	      event_is_action(e, ACTION_PAUSE)) {

      hold = action_update_hold_by_event(hold, e);
      mp_send_cmd_head(mp, mq, hold ? MB_CTRL_PAUSE : MB_CTRL_PLAY);
      mp_set_playstatus_by_hold(mp, hold, NULL);

    } else if(event_is_type(e, EVENT_INTERNAL_PAUSE)) {

      hold = 1;
      mp_send_cmd_head(mp, mq, MB_CTRL_PAUSE);
      mp_set_playstatus_by_hold(mp, hold, e->e_payload);

    } else if(event_is_action(e, ACTION_SKIP_BACKWARD)) {

      if(seekbase < 1500000)
	goto skip;

      av_seek_frame(fctx, -1, 0, AVSEEK_FLAG_BACKWARD);
      seekflush(mp, &mb);

    } else if(event_is_action(e, ACTION_SKIP_FORWARD) ||
	      event_is_action(e, ACTION_STOP)) {
    skip:
      mp_flush(mp, 0);
      break;
    }
    event_release(e);
  }

  if(mb != NULL && mb != MB_SPECIAL_EOF)
    media_buf_free_unlocked(mp, mb);

  media_codec_deref(cw);
  media_format_deref(fw);

  if(hold) { 
    // If we were paused, release playback again.
    mp_send_cmd(mp, mq, MB_CTRL_PLAY);
    mp_set_playstatus_by_hold(mp, 0, NULL);
  }

  return e;
}
Exemplo n.º 11
0
void
predict_acdc(MACROBLOCK * pMBs,
             uint32 x, uint32 y, uint32 mb_width,
             uint32 block,
             int16 qcoeff[64],
             uint32 current_quant,
             int32 iDcScaler, int16 predictors[8], xint * slice)
{
    int16  *left, *top, *diag, *current;

    int32   left_quant = current_quant;
    int32   top_quant = current_quant;

    const int16 *pLeft = default_acdc_values;
    const int16 *pTop = default_acdc_values;
    const int16 *pDiag = default_acdc_values;

    xint    index = x + y * mb_width;   // current macroblock
    xint    slice_idx = index + y + mb_width + 2;
    xint   *acpred_direction = &pMBs[index].acpred_directions[block];
    xint    i;

    left = top = diag = current = 0;

    // grab left,top and diag macroblocks

    // left macroblock
    if ((slice[slice_idx - 1] == slice[slice_idx]) &&
        (pMBs[index - 1].mode == MODE_INTRA
         || pMBs[index - 1].mode == MODE_INTRA_Q))
    {
        left = pMBs[index - 1].pred_values[0];
        left_quant = pMBs[index - 1].quant;
        //DEBUGI("LEFT", *(left+MBPRED_SIZE));
    }

    // top macroblock
    if ((slice[slice_idx - mb_width - 1] == slice[slice_idx])
        && (pMBs[index - mb_width].mode == MODE_INTRA
            || pMBs[index - mb_width].mode == MODE_INTRA_Q))
    {
        top = pMBs[index - mb_width].pred_values[0];
        top_quant = pMBs[index - mb_width].quant;
    }

    // diag macroblock
    if ((slice[slice_idx - 2 - mb_width] == slice[slice_idx]) &&
        (pMBs[index - 1 - mb_width].mode == MODE_INTRA ||
         pMBs[index - 1 - mb_width].mode == MODE_INTRA_Q))
    {
        diag = pMBs[index - 1 - mb_width].pred_values[0];
    }

    current = pMBs[index].pred_values[0];

    // now grab pLeft, pTop, pDiag _blocks_

    switch (block)
    {
    case 0:
        if (left)
            pLeft = left + MBPRED_SIZE;
        if (top)
            pTop = top + (MBPRED_SIZE << 1);
        if (diag)
            pDiag = diag + 3 * MBPRED_SIZE;
        break;

    case 1:
        pLeft = current;
        left_quant = current_quant;
        if (top)
        {
            pTop = top + 3 * MBPRED_SIZE;
            pDiag = top + (MBPRED_SIZE << 1);
        }
        break;

    case 2:
        if (left)
        {
            pLeft = left + 3 * MBPRED_SIZE;
            pDiag = left + MBPRED_SIZE;
        }
        pTop = current;
        top_quant = current_quant;
        break;

    case 3:
        pLeft = current + (MBPRED_SIZE << 1);
        left_quant = current_quant;
        pTop = current + MBPRED_SIZE;
        top_quant = current_quant;
        pDiag = current;
        break;

    case 4:
        if (left)
            pLeft = left + (MBPRED_SIZE << 2);
        if (top)
            pTop = top + (MBPRED_SIZE << 2);
        if (diag)
            pDiag = diag + (MBPRED_SIZE << 2);
        break;

    case 5:
        if (left)
            pLeft = left + 5 * MBPRED_SIZE;
        if (top)
            pTop = top + 5 * MBPRED_SIZE;
        if (diag)
            pDiag = diag + 5 * MBPRED_SIZE;
        break;
    }

    //      determine ac prediction direction & ac/dc predictor
    //      place rescaled ac/dc predictions into predictors[] for later use

    if (ABS(pLeft[0] - pDiag[0]) < ABS(pDiag[0] - pTop[0]))
    {
        *acpred_direction = 1;  // vertical
        predictors[0] = DIV_DIV(pTop[0], (int16) iDcScaler);
        for (i = 1; i < 8; i++)
        {
            predictors[i] = rescale(top_quant, current_quant, pTop[i]);
        }
    }
    else
    {
        *acpred_direction = 2;  // horizontal
        predictors[0] = DIV_DIV(pLeft[0], (int16) iDcScaler);
        for (i = 1; i < 8; i++)
        {
            predictors[i] =
                rescale(left_quant, current_quant, pLeft[i + 7]);
        }
    }
}
Exemplo n.º 12
0
void ChartWidget::setMaxY(int y)
{
    maxY = y;
    rescale();
    repaint();
}
Exemplo n.º 13
0
void ChartWidget::setMaxX(int x)
{
    maxX = x;
    rescale();
    repaint();
}
Exemplo n.º 14
0
void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID,
    LPCTSTR propName, float invScale) {
        HGDIOBJ font = GetStockObject(fontID);
    if (font != NULL && SelectObject(dc, font) != NULL) {
        int length = GetTextFace(dc, 0, NULL);

        if (length > 0) {
            LPTSTR face = new TCHAR[length];

            if (GetTextFace(dc, length, face) > 0) {
                TEXTMETRIC metrics;

                if (GetTextMetrics(dc, &metrics) > 0) {
                    jstring fontName = NULL;
                    if (!wcscmp(face, L"MS Shell Dlg")) {
                        // MS Shell Dlg is an indirect font name, find the
                        // real face name from the registry.
                        LPTSTR shellDialogFace = resolveShellDialogFont();
                        if (shellDialogFace != NULL) {
                            fontName = JNU_NewStringPlatform(GetEnv(),
                                                             shellDialogFace);
                            free(shellDialogFace);
                        }
                        else {
                            // Couldn't determine mapping for MS Shell Dlg,
                            // fall back to Microsoft Sans Serif
                            fontName = JNU_NewStringPlatform(GetEnv(),
                                                    L"Microsoft Sans Serif");
                        }
                    }
                    else {
                        fontName = JNU_NewStringPlatform(GetEnv(), face);
                    }
                    if (fontName == NULL) {
                        delete[] face;
                        throw std::bad_alloc();
                    }

                    jint pointSize = rescale(metrics.tmHeight -
                                     metrics.tmInternalLeading, invScale);
                    jint style = java_awt_Font_PLAIN;

                    if (metrics.tmWeight >= FW_BOLD) {
                        style =  java_awt_Font_BOLD;
                    }
                    if (metrics.tmItalic ) {
                        style |= java_awt_Font_ITALIC;
                    }

                    jstring key = JNU_NewStringPlatform(GetEnv(), propName);
                    if (key == NULL) {
                        GetEnv()->DeleteLocalRef(fontName);
                        delete[] face;
                        throw std::bad_alloc();
                    }
                    GetEnv()->CallVoidMethod(self,
                              AwtDesktopProperties::setFontPropertyID,
                              key, fontName, style, pointSize);
                    GetEnv()->DeleteLocalRef(key);
                    GetEnv()->DeleteLocalRef(fontName);
                }
            }
            delete[] face;
        }
    }
}
/// Main Program
int main(int argc, char *argv[])
{
	CmdLine cmd;

    std::string combine;
    ParamDisparity p; // Parameters for adaptive weights
    cmd.add( make_option('R',p.radius) );
    cmd.add( make_option(0,p.gammaCol,"gcol") );
    cmd.add( make_option(0,p.gammaPos,"gpos") );
	cmd.add( make_option('c', combine) );

	try {
		cmd.process(argc, argv);
	} catch(std::string str) {
		std::cerr << "Error: " << str << std::endl<<std::endl;
        argc = 1; // To display usage
	}
	if(argc!=5 && argc!=7) {
		usage(argv[0]);
		return 1;
	}

    // Load images
    Image im1 = loadImage(argv[1]);
    Image im2;
    if(argc>5)
        im2 = loadImage(argv[5]);

	int x,y;
	if(! ((std::istringstream(argv[2])>>x).eof() &&
		  (std::istringstream(argv[3])>>y).eof())) {
        std::cerr << "Error reading x or y" << std::endl;
        return 1;
	}

	int disp=0;
	if(argc>6 && !((std::istringstream(argv[6])>>disp).eof()) ) {
        std::cerr << "Error reading disparity" << std::endl;
        return 1;
	}

    Comb* comb=0;
    if(cmd.used('c') && im2.channels()!=0) {
        if(combine == "left")
            comb = new Comb(left);
        else if(combine == "max")
            comb = new Comb(max);
        else if(combine == "min")
            comb = new Comb(min);
        else if(combine == "mult")
            comb = new Comb(mult);
        else if(combine == "plus")
            comb = new Comb(plus);
        else {
            std::cerr << "Unrecognized option for weights combination "
                      << "(should be left,max,min,mult or plus)" << std::endl;
            return 1;
        }
    }

    Image w = show_weights(im1, im2, x, y, x+disp, comb,
                           p.radius, p.gammaCol, p.gammaPos);
    rescale(w);
    if(io_png_write_f32(argv[4], &w(0,0), w.width(), w.height(), 1) != 0) {
        std::cerr << "Unable to write file " << argv[4] << std::endl;
        return 1;
    }

	return 0;
}
Exemplo n.º 16
0
int main(const int argc, const char **argv)
{

  MYLOGVERB = LOG_INFO;
  mgr = new ModelManager("Test ObjRec");

  if (mgr->parseCommandLine(
        (const int)argc, (const char**)argv, "<vdb file> <server ip>", 2, 2) == false)
    return 1;

  mgr->start();

  // catch signals and redirect them to terminate for clean exit:
  signal(SIGHUP, terminateProc); signal(SIGINT, terminateProc);
  signal(SIGQUIT, terminateProc); signal(SIGTERM, terminateProc);
  signal(SIGALRM, terminateProc);

  //get command line options
  const char *vdbFile = mgr->getExtraArg(0).c_str();
  const char *server_ip = mgr->getExtraArg(1).c_str();
  bool train = false;

  LINFO("Loading db from %s\n", vdbFile);
  //vdb.loadFrom(std::string(vdbFile));

  xwin  = new XWinManaged(Dims(256,256),
      -1, -1, "ILab Robot Head Demo");


   labelServer =
    nv2_label_server_create(9930,
        server_ip,
        9931);

  nv2_label_server_set_verbosity(labelServer,1); //allow warnings


  int send_interval = 1;

  while(!terminate)
  {

    Point2D clickLoc = xwin->getLastMouseClick();
    if (clickLoc.isValid())
      train = !train;

    struct nv2_image_patch p;
    const enum nv2_image_patch_result res =
      nv2_label_server_get_current_patch(labelServer, &p);

    std::string objName;
    if (res == NV2_IMAGE_PATCH_END)
    {
      fprintf(stdout, "ok, quitting\n");
      break;
    }
    else if (res == NV2_IMAGE_PATCH_NONE)
    {
      usleep(10000);
      continue;
    }
    else if (res == NV2_IMAGE_PATCH_VALID &&
        p.type == NV2_PIXEL_TYPE_RGB24)
    {
      Image<PixRGB<byte> > img(p.width, p.height, NO_INIT);
      memcpy(img.getArrayPtr(), p.data, p.width*p.height*3);

      Image<PixRGB<byte> > inputImg = rescale(img, 256, 256);

      std::string objName = matchObject(inputImg);

      Image<PixRGB<byte> > disp(320, 240, ZEROS);

      xwin->drawImage(inputImg);

      if (objName == "nomatch")
      {
        if (train)
        {
          printf("Is this %s\n", objName.c_str());
          std::string tmp;
          std::getline(std::cin, tmp);
          if (tmp == "exit") break;
          if (tmp == "no")
          {
            printf("Can you tell me what this is?\n");
            std::getline(std::cin, objName);

            rutz::shared_ptr<VisualObject>
              vo(new VisualObject(objName.c_str(), "NULL", inputImg,
                    Point2D(-1,-1),
                    std::vector<double>(),
                    std::vector< rutz::shared_ptr<Keypoint> >(),
                    USECOLOR));
            vdb.addObject(vo);
            vdb.saveTo(vdbFile);
          }
        }
      } else {
        printf("Object is %s\n", objName.c_str());
        struct nv2_patch_label l;
        l.protocol_version = NV2_LABEL_PROTOCOL_VERSION;
        l.patch_id = p.id;
        snprintf(l.source, sizeof(l.source), "%s",
            "ObjRec");
        snprintf(l.name, sizeof(l.name), "%s", // (%ux%u #%u)",
            objName.c_str());
        //(unsigned int) p.width,
        //(unsigned int) p.height,
        //(unsigned int) p.id);
        snprintf(l.extra_info, sizeof(l.extra_info),
            "auxiliary information");

        if (l.patch_id % send_interval == 0)
        {
          nv2_label_server_send_label(labelServer, &l);

          fprintf(stdout, "sent label '%s (%s)'\n",
              l.name, l.extra_info);
        }
        else
        {
          fprintf(stdout, "DROPPED label '%s (%s)'\n",
              l.name, l.extra_info);
        }
      }

      nv2_image_patch_destroy(&p);
    }

  }
  nv2_label_server_destroy(labelServer);

}
Exemplo n.º 17
0
void
repaint (ppm_t *p, ppm_t *a)
{
  int         x, y;
  int         tx = 0, ty = 0;
  ppm_t       tmp = {0, 0, NULL};
  ppm_t       atmp = {0, 0, NULL};
  int         r, g, b, h, i, j, on, sn;
  int         num_brushes, maxbrushwidth, maxbrushheight;
  guchar      back[3] = {0, 0, 0};
  ppm_t      *brushes, *shadows;
  ppm_t      *brush, *shadow = NULL;
  double     *brushes_sum;
  int         cx, cy, maxdist;
  double      scale, relief, startangle, anglespan, density, bgamma;
  int         max_progress;
  ppm_t       paper_ppm = {0, 0, NULL};
  ppm_t       dirmap = {0, 0, NULL};
  ppm_t       sizmap = {0, 0, NULL};
  int        *xpos = NULL, *ypos = NULL;
  int         progstep;
  static int  running = 0;

  int dropshadow = pcvals.general_drop_shadow;
  int shadowblur = pcvals.general_shadow_blur;

  if (running)
    return;
  running++;

  runningvals = pcvals;

  /* Shouldn't be necessary, but... */
  if (img_has_alpha)
    if ((p->width != a->width) || (p->height != a->height))
      {
        g_printerr ("Huh? Image size != alpha size?\n");
        return;
      }

  num_brushes = runningvals.orient_num * runningvals.size_num;
  startangle = runningvals.orient_first;
  anglespan = runningvals.orient_last;

  density = runningvals.brush_density;

  if (runningvals.place_type == PLACEMENT_TYPE_EVEN_DIST)
    density /= 3.0;

  bgamma = runningvals.brushgamma;

  brushes = g_malloc (num_brushes * sizeof (ppm_t));
  brushes_sum = g_malloc (num_brushes * sizeof (double));

  if (dropshadow)
    shadows = g_malloc (num_brushes * sizeof (ppm_t));
  else
    shadows = NULL;

  brushes[0].col = NULL;
  brush_get_selected (&brushes[0]);

  resize (&brushes[0],
          brushes[0].width,
          brushes[0].height * pow (10, runningvals.brush_aspect));
  scale = runningvals.size_last / MAX (brushes[0].width, brushes[0].height);

  if (bgamma != 1.0)
    ppm_apply_gamma (&brushes[0], 1.0 / bgamma, 1,1,1);

  resize (&brushes[0], brushes[0].width * scale, brushes[0].height * scale);
  i = 1 + sqrt (brushes[0].width  * brushes[0].width +
                brushes[0].height * brushes[0].height);
  ppm_pad (&brushes[0], i-brushes[0].width, i-brushes[0].width,
           i - brushes[0].height, i - brushes[0].height, back);

  for (i = 1; i < num_brushes; i++)
    {
      brushes[i].col = NULL;
      ppm_copy (&brushes[0], &brushes[i]);
    }

    for (i = 0; i < runningvals.size_num; i++)
      {
      double sv;
      if (runningvals.size_num > 1)
        sv = i / (runningvals.size_num - 1.0);
      else sv = 1.0;
      for (j = 0; j < runningvals.orient_num; j++)
        {
          h = j + i * runningvals.orient_num;
          free_rotate (&brushes[h],
                       startangle + j * anglespan / runningvals.orient_num);
          rescale (&brushes[h],
                   ( sv      * runningvals.size_first +
                    (1.0-sv) * runningvals.size_last    ) / runningvals.size_last);
          autocrop (&brushes[h],1);
        }
    }

  /* Brush-debugging */
#if 0
  for (i = 0; i < num_brushes; i++)
    {
      char tmp[1000];
      g_snprintf (tmp, sizeof (tmp), "/tmp/_brush%03d.ppm", i);
      ppm_save (&brushes[i], tmp);
    }
#endif

  for (i = 0; i < num_brushes; i++)
    {
      if (!runningvals.color_brushes)
        prepare_brush (&brushes[i]);
      brushes_sum[i] = sum_brush (&brushes[i]);
    }

  brush = &brushes[0];

  maxbrushwidth = maxbrushheight = 0;
  for (i = 0; i < num_brushes; i++)
    {
      if (brushes[i].width > maxbrushwidth)
        maxbrushwidth = brushes[i].width;
      if (brushes[i].height > maxbrushheight)
        maxbrushheight = brushes[i].height;
    }

  for (i = 0; i < num_brushes; i++)
    {
      int xp, yp;
      guchar blk[3] = {0, 0, 0};

      xp = maxbrushwidth - brushes[i].width;
      yp = maxbrushheight - brushes[i].height;
      if (xp || yp)
        ppm_pad (&brushes[i], xp / 2, xp - xp / 2, yp / 2, yp - yp / 2, blk);
    }

  if (dropshadow)
    {
      for (i = 0; i < num_brushes; i++)
        {
          shadows[i].col = NULL;
          ppm_copy (&brushes[i], &shadows[i]);
          ppm_apply_gamma (&shadows[i], 0, 1,1,0);
          ppm_pad (&shadows[i], shadowblur*2, shadowblur*2,
                   shadowblur*2, shadowblur*2, back);
          for (j = 0; j < shadowblur; j++)
            blur (&shadows[i], 2, 2);
#if 0
          autocrop (&shadows[i],1);
#endif
        }
#if 0
      maxbrushwidth += shadowdepth*3;
      maxbrushheight += shadowdepth*3;
#endif
    }

  /* For extra annoying debugging :-) */
#if 0
  ppm_save (brushes, "/tmp/__brush.ppm");
  if (shadows) ppm_save (shadows, "/tmp/__shadow.ppm");
  system ("xv /tmp/__brush.ppm & xv /tmp/__shadow.ppm & ");
#endif

  if (runningvals.general_paint_edges)
    {
      edgepad (p, maxbrushwidth, maxbrushwidth,
               maxbrushheight, maxbrushheight);
      if (img_has_alpha)
        edgepad (a, maxbrushwidth, maxbrushwidth,
                 maxbrushheight, maxbrushheight);
    }

  if (img_has_alpha)
    {
    /* Initially fully transparent */
      if (runningvals.general_background_type == BG_TYPE_TRANSPARENT)
        {
          guchar tmpcol[3] = {255, 255, 255};

          ppm_new (&atmp, a->width, a->height);
          fill (&atmp, tmpcol);
        }
      else
        {
          ppm_copy (a, &atmp);
        }
    }

  if (runningvals.general_background_type == BG_TYPE_SOLID)
    {
      guchar tmpcol[3];

      ppm_new (&tmp, p->width, p->height);
      gimp_rgb_get_uchar (&runningvals.color,
                          &tmpcol[0], &tmpcol[1], &tmpcol[2]);
      fill (&tmp, tmpcol);
    }
  else if (runningvals.general_background_type == BG_TYPE_KEEP_ORIGINAL)
    {
      ppm_copy (p, &tmp);
    }
  else
    {
      int dx, dy;

      ppm_new (&tmp, p->width, p->height);
      ppm_load (runningvals.selected_paper, &paper_ppm);

      if (runningvals.paper_scale != 100.0)
        {
          scale = runningvals.paper_scale / 100.0;
          resize (&paper_ppm, paper_ppm.width * scale, paper_ppm.height * scale);
        }

      if (runningvals.paper_invert)
        ppm_apply_gamma (&paper_ppm, -1.0, 1, 1, 1);

      dx = runningvals.general_paint_edges ? paper_ppm.width - maxbrushwidth : 0;
      dy = runningvals.general_paint_edges ? paper_ppm.height - maxbrushheight : 0;

      for (y = 0; y < tmp.height; y++)
        {
          int lx;
          int ry = (y + dy) % paper_ppm.height;

          for (x = 0; x < tmp.width; x+=lx)
            {
              int rx = (x + dx) % paper_ppm.width;

              lx = MIN (tmp.width - x, paper_ppm.width - rx);

              memcpy (&tmp.col[y * tmp.width * 3 + x * 3],
                      &paper_ppm.col[ry * paper_ppm.width * 3 + rx * 3],
                      3 * lx);
            }
        }
    }

  cx = p->width / 2;
  cy = p->height / 2;
  maxdist = sqrt (cx * cx + cy * cy);

  switch (runningvals.orient_type)
    {
    case ORIENTATION_VALUE:
      ppm_new (&dirmap, p->width, p->height);
      for (y = 0; y < dirmap.height; y++)
        {
          guchar *dstrow = &dirmap.col[y * dirmap.width * 3];
          guchar *srcrow = &p->col[y * p->width * 3];
          for (x = 0; x < dirmap.width; x++)
            {
              dstrow[x * 3] =
                (srcrow[x * 3] + srcrow[x * 3 + 1] + srcrow[x * 3 + 2]) / 3;
            }
        }
      break;

    case ORIENTATION_RADIUS:
      ppm_new (&dirmap, p->width, p->height);
      for (y = 0; y < dirmap.height; y++)
        {
          guchar *dstrow = &dirmap.col[y * dirmap.width * 3];
          double ysqr = (cy - y) * (cy - y);

          for (x = 0; x < dirmap.width; x++)
            {
              dstrow[x*3] = sqrt ((cx - x) * (cx - x) + ysqr) * 255 / maxdist;
            }
        }
      break;

    case ORIENTATION_RADIAL:
      ppm_new (&dirmap, p->width, p->height);
      for (y = 0; y < dirmap.height; y++)
        {
          guchar *dstrow = &dirmap.col[y * dirmap.width * 3];

          for (x = 0; x < dirmap.width; x++)
            {
              dstrow[x * 3] = (G_PI + atan2 (cy - y, cx - x)) *
                              255.0 / (G_PI * 2);
            }
        }
      break;

    case ORIENTATION_FLOWING:
      ppm_new (&dirmap, p->width / 6 + 5, p->height / 6 + 5);
      mkgrayplasma (&dirmap, 15);
      blur (&dirmap, 2, 2);
      blur (&dirmap, 2, 2);
      resize (&dirmap, p->width, p->height);
      blur (&dirmap, 2, 2);
      if (runningvals.general_paint_edges)
        edgepad (&dirmap, maxbrushwidth, maxbrushheight,
                 maxbrushwidth, maxbrushheight);
      break;

    case ORIENTATION_HUE:
      ppm_new (&dirmap, p->width, p->height);
      for (y = 0; y < dirmap.height; y++)
        {
          guchar *dstrow = &dirmap.col[y * dirmap.width * 3];
          guchar *srcrow = &p->col[y * p->width * 3];

          for (x = 0; x < dirmap.width; x++)
            {
              dstrow[x * 3] = get_hue (&srcrow[x * 3]);
            }
        }
      break;

    case ORIENTATION_ADAPTIVE:
      {
        guchar tmpcol[3] = {0, 0, 0};

        ppm_new (&dirmap, p->width, p->height);
        fill (&dirmap, tmpcol);
      }
      break;

    case ORIENTATION_MANUAL:
      ppm_new (&dirmap, p->width-maxbrushwidth*2, p->height-maxbrushheight*2);
      for (y = 0; y < dirmap.height; y++)
        {
          guchar *dstrow = &dirmap.col[y * dirmap.width * 3];
          double tmpy = y / (double)dirmap.height;
          for (x = 0; x < dirmap.width; x++)
            {
              dstrow[x * 3] = get_pixel_value(90 -
                                              get_direction(x /
                                                            (double)dirmap.width,
                                                            tmpy, 1));
            }
        }
      edgepad (&dirmap,
               maxbrushwidth, maxbrushwidth,
               maxbrushheight, maxbrushheight);
    break;
  }

  if (runningvals.size_type == SIZE_TYPE_VALUE)
    {
      ppm_new (&sizmap, p->width, p->height);
      for (y = 0; y < sizmap.height; y++)
        {
          guchar *dstrow = &sizmap.col[y * sizmap.width * 3];
          guchar *srcrow = &p->col[y * p->width * 3];

          for (x = 0; x < sizmap.width; x++)
            {
              dstrow[x * 3] =
                (srcrow[x * 3] + srcrow[x * 3 + 1] + srcrow[x * 3 + 2]) / 3;
            }
        }
    }
  else if (runningvals.size_type == SIZE_TYPE_RADIUS)
    {
      ppm_new (&sizmap, p->width, p->height);
      for (y = 0; y < sizmap.height; y++)
        {
          guchar *dstrow = &sizmap.col[y * sizmap.width * 3];
          double ysqr = (cy - y) * (cy - y);

          for (x = 0; x < sizmap.width; x++)
            {
              dstrow[x * 3] =
                sqrt ((cx - x) * (cx - x) + ysqr) * 255 / maxdist;
            }
        }
    }
  else if (runningvals.size_type == SIZE_TYPE_RADIAL)
    {
      ppm_new (&sizmap, p->width, p->height);
      for (y = 0; y < sizmap.height; y++)
        {
          guchar *dstrow = &sizmap.col[y * sizmap.width * 3];

          for (x = 0; x < sizmap.width; x++)
            {
              dstrow[x * 3] = (G_PI + atan2 (cy - y, cx - x)) *
                              255.0 / (G_PI * 2);
            }
        }
    }
  else if (runningvals.size_type == SIZE_TYPE_FLOWING)
    {
      ppm_new (&sizmap, p->width / 6 + 5, p->height / 6 + 5);
      mkgrayplasma (&sizmap, 15);
      blur (&sizmap, 2, 2);
      blur (&sizmap, 2, 2);
      resize (&sizmap, p->width, p->height);
      blur (&sizmap, 2, 2);
      if (runningvals.general_paint_edges)
        edgepad (&sizmap,
                 maxbrushwidth, maxbrushheight,
                 maxbrushwidth, maxbrushheight);
    }
  else if (runningvals.size_type == SIZE_TYPE_HUE)
    {
      ppm_new (&sizmap, p->width, p->height);
      for (y = 0; y < sizmap.height; y++)
        {
          guchar *dstrow = &sizmap.col[y * sizmap.width * 3];
          guchar *srcrow = &p->col[y * p->width * 3];

          for (x = 0; x < sizmap.width; x++)
            {
              dstrow[ x * 3] = get_hue (&srcrow[x * 3]);
            }
        }
    }
  else if (runningvals.size_type == SIZE_TYPE_ADAPTIVE)
    {
      guchar tmpcol[3] = {0, 0, 0};

      ppm_new (&sizmap, p->width, p->height);
      fill (&sizmap, tmpcol);
    }
  else if (runningvals.size_type == SIZE_TYPE_MANUAL)
    {
      ppm_new (&sizmap,
               p->width-maxbrushwidth * 2,
               p->height-maxbrushheight * 2);

      for (y = 0; y < sizmap.height; y++)
        {
          guchar *dstrow = &sizmap.col[y * sizmap.width * 3];
          double tmpy = y / (double)sizmap.height;

          for (x = 0; x < sizmap.width; x++)
            {
              dstrow[x * 3] = 255 * (1.0 - get_siz_from_pcvals (x / (double)sizmap.width, tmpy));
            }
        }
      edgepad (&sizmap,
               maxbrushwidth, maxbrushwidth,
               maxbrushheight, maxbrushheight);
    }
#if 0
  ppm_save(&sizmap, "/tmp/_sizmap.ppm");
#endif
  if (runningvals.place_type == PLACEMENT_TYPE_RANDOM)
    {
      i = tmp.width * tmp.height / (maxbrushwidth * maxbrushheight);
      i *= density;
    }
  else if (runningvals.place_type == PLACEMENT_TYPE_EVEN_DIST)
    {
      i = (int)(tmp.width * density / maxbrushwidth) *
          (int)(tmp.height * density / maxbrushheight);
#if 0
    g_printerr("i=%d\n", i);
#endif
    }

  if (i < 1)
    i = 1;

  max_progress = i;
  progstep = max_progress / 30;
  if (progstep < 10)
    progstep = 10;

  if (runningvals.place_type == PLACEMENT_TYPE_EVEN_DIST)
    {
      int j;

      xpos = g_new (int, i);
      ypos = g_new (int, i);
      for (j = 0; j < i; j++)
        {
          int factor = (int)(tmp.width * density / maxbrushwidth + 0.5);

          if (factor < 1)
            factor = 1;
          xpos[j] = maxbrushwidth/2 + (j % factor) * maxbrushwidth / density;
          ypos[j] = maxbrushheight/2 + (j / factor) * maxbrushheight / density;
        }
      for (j = 0; j < i; j++)
        {
          int a, b;

          a = g_rand_int_range (random_generator, 0, i);
          b = xpos[j]; xpos[j] = xpos[a]; xpos[a] = b;
          b = ypos[j]; ypos[j] = ypos[a]; ypos[a] = b;
        }
    }
Exemplo n.º 18
0
task main()
{
	disableDiagnosticsDisplay();

	while(true) {
		getJoystickSettings(joystick);  // Update Buttons and Joysticks
  	wait1Msec(10);

		/*--------------------------
		controller one
		-------------------------*/
		/*-------------------------
		maping
		---------------------------
		up =
		down =
		left = strafe left
		right = strafe right
		joystick left = left motors
		joystick right = right motors
		A = catcher down
		B =	catcher up
		X =
		Y =
		L1 =
		L2 =
		R1 =
		R2 =
		---------------------------*/

		// If lift is too high slower the driver motors
		if(nMotorEncoder[liftRight] < GOVLIMIT) {
			GOVERNOR = 1;
		} else {
		  GOVERNOR = 2;
		}

		// Drive the robot from joystick 1
		if((abs(joystick.joy1_y1) >= deadZone) || (abs(joystick.joy1_y2) >= deadZone)) {
			setMotion(joystick.joy1_y1 / GOVERNOR, joystick.joy1_y2 / GOVERNOR);
		}
		/*else if(joystick.joy1_TopHat == 6) {
			strafe(50);
		}
		else if(joystick.joy1_TopHat == 2){
			strafe(-50);
		}*/
		else if(joy1Btn(JOY_BUTTON_LT)) {
		  strafe(-50);
		}
	  else if(joy1Btn(JOY_BUTTON_RT)) {
	  	strafe(50);
		}
	  else {
		  stopMotors();
		}

		if(joy1Btn(JOY_BUTTON_RB))
		{
		int iCRate = servoChangeRate[goalCapture];	// Save change rate
		servoChangeRate[goalCapture] = 0; 					// Max Speed
		servo[goalCapture] = CATCHDOWN;					// Set servo position
		wait1Msec(20);
		servoChangeRate[goalCapture] = iCRate;			// Reset the servo
		}
		else if(joy1Btn(JOY_BUTTON_LB))
		{
		int iCRate = servoChangeRate[goalCapture];	// Save change rate
		servoChangeRate[goalCapture] = 0; 					// Max Speed
		servo[goalCapture] = CATCHUP;					// Set servo position
		wait1Msec(20);
		servoChangeRate[goalCapture] = iCRate;			// Reset the servo
	}

	/*--------------------------
	controller two
	-------------------------*/
	/*-------------------------
	maping
	---------------------------
	up =
	down =
	left =
	right =
	joystick left =
	joystick right =
	A =
	B =
	X =
	Y =
	LB = big backward
	LT = big forward
	RB = small backward
	RT = small forward
	---------------------------*/
		// Raise/lower the lift
		if(abs(joystick.joy2_y2) > deadZone) {
			stopLiftTask(); //first, ensure that robot is not already moving the lift
			if((joystick.joy2_y2 <= 0) && TSreadState(LTOUCH)) {
				lift(0);// if touch sensor is active and driver says go down, stop the lift (don't burn out motor)
				nMotorEncoder[liftMotor] = 0; //The lift is down, so set lift encoder to 0
				} else {//If touch is NOT active or driver says go up
				lift(rescale(joystick.joy2_y2)); //Raise lift at a rescaled value of the joystick
			}
			} else { //No controls?
			lift(0); //Stop lift motors.
		}
		// Set the lift to preset heights
		/*if(joy2Btn(JOY_BUTTON_A)) {
			liftHeight(35);
		} else if(joy2Btn(JOY_BUTTON_B)) {
			liftHeight(65);
		}	else if(joy2Btn(JOY_BUTTON_Y)) {
			liftHeight(95);
		} else if(joy2Btn(JOY_BUTTON_X)) {
			liftHeight(115);
		} else if(joy2Btn(JOY_BUTTON_RT)) {
			liftHeight(0);
			nMotorEncoder[liftRight] = 0;
		}*/

		// Run the spinner to pick up balls
		if((abs(joystick.joy2_y1)) >= deadZone) {
			spin(rescale(joystick.joy2_y1));
		} else {
			spin(0);
		}
	}
}
Exemplo n.º 19
0
uint8_t editNumber(S32MMSValCb_t* s32, uint8_t aY)
{
    // aY is the current yPos from were the edit was triggered
    /**
     * calculate the rectangle height on the display: 
     *    fontheight + 1 pix on top + 1 pix at bottom + 2*2 pix for the frame 
     */
    int32_t valBackup = s32->m_val; // backup the old value
    uint8_t fontHeight = FONTHEIGHT(EDITFONT);
    // re-use aY
    aY = (aY < LCDHEIGHT/2 - 9 ? aY+11: aY - 25);

    // maximum size, for a scaled long: "-2123456.789" + 1 leading blank + 0x00 = 14
    char valBuf[14]; 
    // put this in a block to release memory after calculation
    { 
        // get the biggest absolute value to calculate longest
        // possible string
        uint32_t min = (s32->m_min < 0) ? -s32->m_min : s32->m_min;
        uint32_t max = (s32->m_max < 0) ? -s32->m_max : s32->m_max;
        valBuf[0] = ' '; // leading blank
        valBuf[1] = '-'; // prepend minus-sign
        valBuf[2] = '.'; // prepend decimal point
        ltoa( (max > min ? max : min), valBuf+2, 10);
        //        maxDigits = strlen(valBuf+2);
    }

    uint8_t textLength = lcdBufPuts(AT_RAM, valBuf, &EDITFONT, 0, 0, LA_CHARWIDTHONLY); 
    
    uint8_t x = (LCDWIDTH - textLength - 8) / 2;     
    drawEditFrame(x, aY, textLength, fontHeight);
    x += 4;
    aY += 4;
    uint8_t endX = x + textLength;
    uint8_t clearLength = textLength;
    uint8_t key = 0;
    uint8_t accel = 1;
    int32_t step = 1;

    CallbackFunctor_t cb = s32->m_callback;

    // call the callback if exists
    if (cb)
        cb(CT_ENTRY, s32); 

    do
    {
        /** 
         * procedure: - clear rectangle
         *              write value to string
         *              length = (write string to ldcBuffer, width_only)
         *              clear area of (width x length)
         *              paint rectangle
         *              write string to lcdbuffer(last digit inverse)
         *              display buffer
         *              read key
         *                if (enter) update & return
         *                if (back) return
         *                if (accel) inc-value <<= 2;
         *                   else inc-value = 1; 
         *                if (up) increase
         *                if (down) decrease
         */
        
        lcdBufFillRect(x, aY, clearLength, fontHeight+1, COL_WHITE);
        // write current value
        ltoa(s32->m_val, valBuf, 10);

        if (s32->m_scale)
            rescale(s32->m_scale, valBuf);

        // get size in pixels
        textLength = lcdBufPuts(AT_RAM, valBuf, &EDITFONT, 0, 0, LA_CHARWIDTHONLY);
        uint8_t xt = endX - textLength;

        lcdBufPuts(AT_RAM, valBuf, &EDITFONT, xt, aY, COL_BLACK);
        //        lcdBufPuts(AT_RAM, valBuf, &EDITFONT, endX - textLength, aY, COL_BLACK);

        uint8_t iconMask = BT_BACK|BT_ENTER;
        if (s32->m_val > s32->m_min) 
            iconMask |= BT_MINUS;
        if (s32->m_val < s32->m_max) 
            iconMask |= BT_PLUS;

        setIcons(IT_EDIT, iconMask);
        lcdUpdate(1);

        key = pollButtons(BT_ALL, BF_ACCEL|BF_DELAY); 

        if (key & BF_ACCEL)
        {
            if (accel == 10)
            {
                accel = 1;
                if (step < (s32->m_max/8))
                    step *= 8;
            }
            else
                ++accel;
        }
        else
        {
            accel = 1;
            step = 1;
        }

        switch (key & 0xF0) // clean code
        {
            case BT_BACK: 
            case BT_ENTER:
                break;

            case BT_PLUS: 
                s32->m_val += step;
                if (s32->m_val > s32->m_max)
                    s32->m_val = s32->m_max;
                break;
            case BT_MINUS: 
                s32->m_val -= step; 
                if (s32->m_val < s32->m_min)
                    s32->m_val = s32->m_min;
                break;
        } // switch key
        
        // call the callback if exists
        if (cb)
            cb((CT_CHANGE | (key & 0xF0)), s32); 
    } while (! (key & (BT_BACK | BT_ENTER)) );

    if (key & BT_BACK) // restore old value if BT_BACK was pressed
        s32->m_val = valBackup;
    if (cb)
        cb((CT_RETURN | (key & 0xF0)), s32);     
    return key & 0xF0; // return pure key
} // editNumber (s32 ..)
Exemplo n.º 20
0
//
// Bottom right corner indicators: Flight mode, Battery, Logger
//
void MapWindow::DrawFlightMode(LKSurface& Surface, const RECT& rc)
{
  static bool flip= true;
  static PixelSize loggerIconSize,mmIconSize, batteryIconSize;
  static POINT loggerPoint, mmPoint, batteryPoint;
  static PixelSize loggerNewSize, mmNewSize, batteryNewSize;
  static int vsepar;

  LKIcon* ptmpBitmap = NULL;

  if (DoInit[MDI_DRAWFLIGHTMODE]) {
      DoInit[MDI_DRAWFLIGHTMODE]=false;

      ptmpBitmap=&hLogger;
      loggerIconSize = ptmpBitmap->GetSize();

      ptmpBitmap=&hMM0;;
      mmIconSize = ptmpBitmap->GetSize();

      ptmpBitmap=&hBattery12;;
      batteryIconSize = ptmpBitmap->GetSize();

      //
      // determine if we can rescale. Preference is to keep standard rescale.
      //
      vsepar=NIBLSCALE(1);
      #define HSEPAR NIBLSCALE(1)  // right border and items separator

      use_rescale=1; // IBLSCALING
      int minvsize= vsepar + rescale(mmIconSize.cy) + rescale(batteryIconSize.cy)+vsepar;
      if (minvsize > BottomSize) {
          use_rescale=0; // NO SCALING
          minvsize= vsepar + rescale(mmIconSize.cy) + rescale(batteryIconSize.cy)+vsepar;
          if (minvsize >= BottomSize) {
              vsepar=0; // minimize interlines
              minvsize= rescale(mmIconSize.cy) + rescale(batteryIconSize.cy);
              LKASSERT(minvsize>0);
              if (minvsize<=1) minvsize=BottomSize; // recover impossible error
              newscale=BottomSize/(double)minvsize;
              use_rescale=2;
          } else {
              // using unscaled bitmaps the BottomSize is taller than minvsize;
              // lets see if we can enlarge them a bit. We cannot exceed the BB_ICONSIZE
              newscale=BottomSize/(double)minvsize;
              use_rescale=2;
              int minhsize= rescale(batteryIconSize.cx) + HSEPAR + rescale(loggerIconSize.cx) + HSEPAR;
              if (minhsize > (NIBLSCALE(26)+1)) { // BB_ICONSIZE! with tolerance 1
                  for (; newscale>1; newscale-=0.1) {
                      minhsize= rescale(batteryIconSize.cx) + HSEPAR + rescale(loggerIconSize.cx) + HSEPAR;
                      if (minhsize<= (NIBLSCALE(26)+1)) break;
                  }
                  if (newscale <= 1) use_rescale=0; // give up, keep small bitmaps
              }
          }

      }


      //
      // precalculate positions and sizes
      //

      loggerPoint.x=rc.right-rescale(loggerIconSize.cx)-HSEPAR;
      // center the logger icon in respect of battery icon which is bigger
      loggerPoint.y=rc.bottom - BottomSize + rescale((batteryIconSize.cy-loggerIconSize.cy)/2) + vsepar;
      loggerNewSize.cx= rescale(loggerIconSize.cx);
      loggerNewSize.cy= rescale(loggerIconSize.cy);

      batteryPoint.x= loggerPoint.x - rescale(batteryIconSize.cx) - HSEPAR;
      batteryPoint.y= rc.bottom - BottomSize + vsepar;
      batteryNewSize.cx= rescale(batteryIconSize.cx);
      batteryNewSize.cy= rescale(batteryIconSize.cy);

      mmPoint.x= rc.right - rescale(mmIconSize.cx) - HSEPAR;
      mmPoint.x-=   (mmPoint.x - batteryPoint.x)/2;
      mmPoint.y= rc.bottom - rescale(mmIconSize.cy)- vsepar;
      mmNewSize.cx= rescale(mmIconSize.cx);
      mmNewSize.cy= rescale(mmIconSize.cy);

      // fine tuning for vertical spacing between items
      int interline=  mmPoint.y - (batteryPoint.y+rescale(batteryIconSize.cy));
      if (interline>4) {
          loggerPoint.y += (interline/4);
          batteryPoint.y += (interline/4);
          mmPoint.y -= (interline/4);
      }

  } // endof doinit


  //
  // Logger indicator
  //
  flip = !flip;

  if (DisableAutoLogger) {
      ptmpBitmap = &hLoggerDisabled;
  } else {
      if (LoggerActive) {
          ptmpBitmap = &hLogger;
      } else {
          if (flip)
              ptmpBitmap = &hLoggerOff;
          else
              ptmpBitmap = &hLoggerDisabled;
      }
  }
  #ifdef DITHER
  if ( (!DisableAutoLogger && (LoggerActive || !flip)) && ptmpBitmap)
  #else
  if (ptmpBitmap)
  #endif
      ptmpBitmap->Draw(Surface, loggerPoint.x, loggerPoint.y, loggerNewSize.cx, loggerNewSize.cy);

  //
  // Big icon
  //

  if (!IsMultiMapNoMain() && mode.Is(Mode::MODE_CIRCLING)) {
      ptmpBitmap = &hClimb;
  } else {
      //short i=Get_Current_Multimap_Type()-1;
      short i=ModeType[LKMODE_MAP]-1;
      if (i<0) i=0;
      if (!IsMultiMap()) {
          switch(i) {
              case 0:
                  ptmpBitmap = &hIMM0;
                  break;
              case 1:
                  ptmpBitmap = &hIMM1;
                  break;
              case 2:
                  ptmpBitmap = &hIMM2;
                  break;
              case 3:
                  ptmpBitmap = &hIMM3;
                  break;
              case 4:
                  ptmpBitmap = &hIMM4;
                  break;
              case 5:
                  ptmpBitmap = &hIMM5;
                  break;
              case 6:
                  ptmpBitmap = &hIMM6;
                  break;
              case 7:
                  ptmpBitmap = &hIMM7;
                  break;
              case 8:
                  ptmpBitmap = &hIMM8;
                  break;
              default:
                  ptmpBitmap = &hIMM0;
                  break;
         }
      } else {
          switch(i) {
              case 0:
                  ptmpBitmap = &hMM0;
                  break;
              case 1:
                  ptmpBitmap = &hMM1;
                  break;
              case 2:
                  ptmpBitmap = &hMM2;
                  break;
              case 3:
                  ptmpBitmap = &hMM3;
                  break;
              case 4:
                  ptmpBitmap = &hMM4;
                  break;
              case 5:
                  ptmpBitmap = &hMM5;
                  break;
              case 6:
                  ptmpBitmap = &hMM6;
                  break;
              case 7:
                  ptmpBitmap = &hMM7;
                  break;
              case 8:
                  ptmpBitmap = &hMM8;
                  break;
              default:
                  ptmpBitmap = &hMM0;
                  break;
         }
      }
  }

  if(ptmpBitmap ) {
      ptmpBitmap->Draw(Surface, mmPoint.x, mmPoint.y, mmNewSize.cx,mmNewSize.cy);
  }

  //
  // Battery indicator
  //

  #if TESTBENCH && !defined(KOBO)
  // Battery test in Simmode will be available in testbench mode only
  if (!HaveBatteryInfo && SIMMODE && !(QUICKDRAW)) {
      PDABatteryPercent-=1;
      if (PDABatteryPercent<0) {
          PDABatteryPercent=100;
      }
  }
  #else
  // If we are not in testbench, no matter simmode is active we shall represent the real battery (as in v5).
  // Exception: PC version.
  #if (WINDOWSPC>0)
  if (!SIMMODE) return;
  #else
  if (!HaveBatteryInfo) return;
  #endif
  #endif

  if ((PDABatteryPercent==0 || PDABatteryPercent>100) && PDABatteryStatus==Battery::ONLINE && PDABatteryFlag!=Battery::CHARGING) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_BatteryFullC; else
#endif
	ptmpBitmap = &hBatteryFullC;
	goto _drawbattery;
  }

  if (PDABatteryPercent<=6) {
	if (flip) return;
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery12; else
#endif
	ptmpBitmap = &hBattery12;
	goto _drawbattery;
  }

  if (PDABatteryPercent<=12) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery12; else
#endif
	ptmpBitmap = &hBattery12;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=24) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery24; else
#endif
	ptmpBitmap = &hBattery24;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=36) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery36; else
#endif
	ptmpBitmap = &hBattery36;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=48) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery48; else
#endif
	ptmpBitmap = &hBattery48;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=60) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery60; else
#endif
	ptmpBitmap = &hBattery60;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=72) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery72; else
#endif
	ptmpBitmap = &hBattery72;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=84) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery84; else
#endif
	ptmpBitmap = &hBattery84;
	goto _drawbattery;
  }
  if (PDABatteryPercent<=96) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_Battery96; else
#endif
	ptmpBitmap = &hBattery96;
	goto _drawbattery;
  }
  if (PDABatteryStatus==Battery::ONLINE) {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_BatteryFullC; else
#endif
	ptmpBitmap = &hBatteryFullC;
  } else {
#ifdef DITHER
        if (!INVERTCOLORS) ptmpBitmap = &hKB_BatteryFull; else
#endif
	ptmpBitmap = &hBatteryFull;
  }

_drawbattery:
    if(ptmpBitmap) {
        ptmpBitmap->Draw(Surface, batteryPoint.x, batteryPoint.y, batteryNewSize.cx, batteryNewSize.cy);
    }

}
bool D_PAD::GetBestAnchorPosition( VECTOR2I& aPos )
{
    SHAPE_POLY_SET poly;

    if( !buildCustomPadPolygon( &poly, ARC_LOW_DEF ) )
        return false;

    const int minSteps = 10;
    const int maxSteps = 50;

    int stepsX, stepsY;

    auto bbox = poly.BBox();

    if( bbox.GetWidth() < bbox.GetHeight() )
    {
        stepsX = minSteps;
        stepsY = minSteps * (double) bbox.GetHeight() / (double )(bbox.GetWidth() + 1);
    }
    else
    {
        stepsY = minSteps;
        stepsX = minSteps * (double) bbox.GetWidth() / (double )(bbox.GetHeight() + 1);
    }

    stepsX = std::max(minSteps, std::min( maxSteps, stepsX ) );
    stepsY = std::max(minSteps, std::min( maxSteps, stepsY ) );

    auto center = bbox.Centre();

    auto minDist = std::numeric_limits<int64_t>::max();
    int64_t minDistEdge;

    if( GetAnchorPadShape() == PAD_SHAPE_CIRCLE )
    {
        minDistEdge = GetSize().x;
    }
    else
    {
        minDistEdge = std::max( GetSize().x, GetSize().y );
    }

    OPT<VECTOR2I> bestAnchor( []()->OPT<VECTOR2I> { return NULLOPT; }() );

    for ( int y = 0; y < stepsY ; y++ )
    {
        for ( int x = 0; x < stepsX; x++ )
        {
            VECTOR2I p = bbox.GetPosition();
            p.x += rescale( x, bbox.GetWidth(), (stepsX - 1) );
            p.y += rescale( y, bbox.GetHeight(), (stepsY - 1) );

            if ( poly.Contains(p) )
            {

                auto dist = (center - p).EuclideanNorm();
                auto distEdge = poly.COutline(0).Distance( p, true );
                if ( distEdge >= minDistEdge )
                {
                    if ( dist < minDist )
                    {
                        bestAnchor = p;
                        minDist = dist;
                    }
                }
            }
        }
    }

    if ( bestAnchor )
    {
        aPos = *bestAnchor;
        return true;
    }

    return false;
}
Exemplo n.º 22
0
// ######################################################################
void DescriptorVec::buildRawDV()
{

  bool salientLocationWithinSubmaps = true;
  Point2D<int> objSalientLoc(-1,-1);  //the feature location

  const LevelSpec lspec = itsComplexChannel->getModelParamVal<LevelSpec>("LevelSpec");
  const int smlevel = lspec.mapLevel();

  int x=int(itsFoveaLoc.i / double(1 << smlevel) + 0.49);
  int y=int(itsFoveaLoc.j / double(1 << smlevel) + 0.49);

  int foveaW = int(itsFoveaSize.getVal().w() / double(1 << smlevel) + 0.49);
  int foveaH = int(itsFoveaSize.getVal().h() / double(1 << smlevel) + 0.49);

  int tl_x = x - (foveaW/2);
  int tl_y = y - (foveaH/2);

  Dims mapDims = itsComplexChannel->getSubmap(0).getDims();

  //Shift the fovea location so we dont go outside the image
  //Sift the fovea position if nessesary
  if (tl_x < 0) tl_x = 0; if (tl_y < 0) tl_y = 0;
  if (tl_x+foveaW > mapDims.w()) tl_x = mapDims.w() - foveaW;
  if (tl_y+foveaH > mapDims.h()) tl_y = mapDims.h() - foveaH;

  if (!salientLocationWithinSubmaps)
  {
    //Find the most salient location within the fovea
    Image<float> SMap = itsComplexChannel->getOutput();

    Image<float> tmp = SMap; //TODO need to resize to fovea
    //Find the max location within the fovea

    float maxVal; Point2D<int> maxLoc;
    findMax(tmp, maxLoc, maxVal);
    //convert back to original SMap cordinates
   // objSalientLoc.i=tl_x+maxLoc.i;
   // objSalientLoc.j=tl_y+maxLoc.j;
    objSalientLoc.i=x;
    objSalientLoc.j=y;
    itsAttentionLoc = objSalientLoc;
  }

  //Go through all the submaps building the DV
  itsFV.clear(); //clear the FV
  uint numSubmaps = itsComplexChannel->numSubmaps();
  for (uint i = 0; i < numSubmaps; i++)
  {
    //Image<float> submap = itsComplexChannel->getSubmap(i);
    Image<float> submap = itsComplexChannel->getRawCSmap(i);

    // resize submap to fixed scale if necessary:
    if (submap.getWidth() > mapDims.w())
      submap = downSize(submap, mapDims);
    else if (submap.getWidth() < mapDims.w())
      submap = rescale(submap, mapDims); //TODO convert to  quickInterpolate


    if (salientLocationWithinSubmaps) //get the location from the salient location within each submap
    {
      Image<float> tmp = submap;
      //get only the fovea region

      if (foveaW < tmp.getWidth()) //crop if our fovea is smaller
        tmp = crop(tmp, Point2D<int>(tl_x, tl_y), Dims(foveaW, foveaH));
     // tmp = maxNormalize(tmp, 0.0F, 10.0F, VCXNORM_MAXNORM);  //find salient locations

      //Find the max location within the fovea
      float maxVal; Point2D<int> maxLoc; findMax(tmp, maxLoc, maxVal);
      //LINFO("%i: Max val %f, loc(%i,%i)", i, maxVal, maxLoc.i, maxLoc.j);

      objSalientLoc.i=tl_x+maxLoc.i;
      objSalientLoc.j=tl_y+maxLoc.j;

    }

    if (objSalientLoc.i < 0) objSalientLoc.i = 0;
    if (objSalientLoc.j < 0) objSalientLoc.j = 0;

    if (objSalientLoc.i > submap.getWidth()-1) objSalientLoc.i = submap.getWidth()-1;
    if (objSalientLoc.j > submap.getHeight()-1) objSalientLoc.j = submap.getHeight()-1;



   // LINFO("Location from %i,%i: (%i,%i)", objSalientLoc.i, objSalientLoc.j,
    //    submap.getWidth(), submap.getHeight());
    float featureVal = submap.getVal(objSalientLoc.i,objSalientLoc.j);
    itsFV.push_back(featureVal);
 //   SHOWIMG(rescale(submap, 255, 255));

  }
}
Exemplo n.º 23
0
void GenEcho::step() {
	// Implement a simple sine oscillator
  //float deltaTime = engineGetSampleTime();
  float amp_out = 0.0;

  // handle the 3 switches for accumlating and mirror toggle
  // and probability distrobution selection
  is_accumulating = (int) params[ACCM_PARAM].value;
  is_mirroring = (int) params[MIRR_PARAM].value;
  dt = (DistType) params[PDST_PARAM].value;

  // read in cv vals for astp, dstp and bpts
  bpts_sig = 5.f * quadraticBipolar((inputs[BPTS_INPUT].value / 5.f) * params[BPTSCV_PARAM].value);
  astp_sig = quadraticBipolar((inputs[ASTP_INPUT].value / 5.f) * params[ASTPCV_PARAM].value);
  dstp_sig = quadraticBipolar((inputs[DSTP_INPUT].value / 5.f) * params[DSTPCV_PARAM].value);

  max_amp_step = rescale(params[ASTP_PARAM].value + (astp_sig / 4.f), 0.0, 1.0, 0.05, 0.3);
  max_dur_step = rescale(params[DSTP_PARAM].value + (dstp_sig / 4.f), 0.0, 1.0, 0.01, 0.3);

  sample_length = (int) (clamp(params[SLEN_PARAM].value, 0.1, 1.f) * MAX_SAMPLE_SIZE);

  bpt_spc = (unsigned int) params[BPTS_PARAM].value + 800;
  bpt_spc += (unsigned int) rescale(bpts_sig, -1.f, 1.f, 1.f, 200.f);
  num_bpts = sample_length / bpt_spc + 1;
 
  env_dur = bpt_spc / 2;

  // snap knob for selecting envelope for the grain
  int env_num = (int) clamp(roundf(params[ENVS_PARAM].value), 1.0f, 4.0f);

  if (env.et != (EnvType) env_num) {
    env.switchEnvType((EnvType) env_num);
  }

  // handle sample reset
  if (smpTrigger.process(params[TRIG_PARAM].value)
      || resetTrigger.process(inputs[RSET_INPUT].value / 2.f)) {
    for (unsigned int i=0; i<MAX_SAMPLE_SIZE; i++) sample[i] = _sample[i];
    for (unsigned int i=0; i<MAX_BPTS; i++) {
      mAmps[i] = 0.f;
      mDurs[i] = 1.f; 
    }
  }

  // handle sample trigger through gate 
  if (g2Trigger.process(inputs[GATE_INPUT].value / 2.f)) {

    // reset accumulated breakpoint vals
    for (unsigned int i=0; i<MAX_BPTS; i++) {
      mAmps[i] = 0.f;
      mDurs[i] = 1.f;
    }

    num_bpts = sample_length / bpt_spc;
    sampling = true;
    idx = 0;
    s_i = 0;
  }

  if (sampling) {
    if (s_i >= MAX_SAMPLE_SIZE - 50) {
      float x,y,p;
      x = sample[s_i-1];
      y = sample[0];
      p = 0.f;
      while (s_i < MAX_SAMPLE_SIZE) {
        sample[s_i] = (x * (1-p)) + (y * p);
        p += 1.f / 50.f;
        s_i++;
      }
      debug("Finished sampling");
      sampling = false;
    } else {
      sample[s_i] = inputs[WAV0_INPUT].value; 
      _sample[s_i] = sample[s_i];
      s_i++;
    } 
  }

  if (phase >= 1.0) {
    phase -= 1.0;

    amp = amp_next;
    index = (index + 1) % num_bpts;
    
    // adjust vals
    astp = max_amp_step * rg.my_rand(dt, randomNormal());
    dstp = max_dur_step * rg.my_rand(dt, randomNormal());

    if (is_mirroring) {
      mAmps[index] = mirror((is_accumulating ? mAmps[index] : 0.f) + astp, -1.0f, 1.0f); 
      mDurs[index] = mirror(mDurs[index] + (dstp), 0.5, 1.5);
    }
    else {
      mAmps[index] = wrap((is_accumulating ? mAmps[index] : 0.f) + astp, -1.0f, 1.0f); 
      mDurs[index] = wrap(mDurs[index] + dstp, 0.5, 1.5);
    }
  
    amp_next = mAmps[index];
    
    // step/adjust grain sample offsets 
    g_idx = g_idx_next;
    g_idx_next = 0.0;
  }

  // change amp in sample buffer
  sample[idx] = wrap(sample[idx] + (amp * env.get(g_idx)), -5.f, 5.f);
  amp_out = sample[idx];

  idx = (idx + 1) % sample_length;
  g_idx = fmod(g_idx + (1.f / (4.f * env_dur)), 1.f);
  g_idx_next = fmod(g_idx_next + (1.f / (4.f * env_dur)), 1.f);
  
  phase += 1.f / (mDurs[index] * bpt_spc);

  // get that amp OUT
  outputs[SINE_OUTPUT].value = amp_out;
}
Exemplo n.º 24
0
Decimal& Decimal::operator*=(Decimal rhs)
{
    Decimal orig = *this;
    rationalize();
    rhs.rationalize();

    // Rule out problematic smallest Decimal
    JEWEL_ASSERT (minimum() == Decimal(numeric_limits<int_type>::min(), 0));
    JEWEL_ASSERT (maximum() == Decimal(numeric_limits<int_type>::max(), 0));
    if (*this == minimum() || rhs == minimum())
    {
        JEWEL_ASSERT (*this == orig);
        JEWEL_THROW
        (   DecimalMultiplicationException,
            "Cannot multiply smallest possible "
            "Decimal safely."
        );
    }

    // Make absolute and remember signs
    bool const signs_differ =
    (   (m_intval < 0 && rhs.m_intval > 0) ||
        (m_intval > 0 && rhs.m_intval < 0)
    );
    if (m_intval < 0)
    {
        JEWEL_ASSERT
        (   !multiplication_is_unsafe(m_intval, static_cast<int_type>(-1))
        );
        m_intval *= -1;
    }
    if (rhs.m_intval < 0)
    {
        JEWEL_ASSERT
        (   !multiplication_is_unsafe(rhs.m_intval, static_cast<int_type>(-1))
        );
        rhs.m_intval *= -1;
    }

    // Do "unchecked multiply" if we can
    JEWEL_ASSERT (m_intval >= 0 && rhs.m_intval >= 0);    
    if (!multiplication_is_unsafe(m_intval, rhs.m_intval))
    {
        JEWEL_ASSERT (!addition_is_unsafe(m_places, rhs.m_places));
        m_intval *= rhs.m_intval;
        m_places += rhs.m_places;
        while (m_places > s_max_places)
        {
            JEWEL_ASSERT (m_places > 0);
            #ifndef NDEBUG
                int const check = rescale(m_places - 1);
                JEWEL_ASSERT (check == 0);
            #else
                rescale(m_places - 1);
            #endif
        }
        if (signs_differ)
        {
            JEWEL_ASSERT (m_intval != numeric_limits<int_type>::min());
            JEWEL_ASSERT
            (   !multiplication_is_unsafe
                (   m_intval,
                    static_cast<int_type>(-1)
                )
            );
            m_intval *= -1;
        }
        rationalize();
        return *this;
    }

    *this = orig;
    JEWEL_THROW(DecimalMultiplicationException, "Unsafe multiplication.");
    JEWEL_HARD_ASSERT (false);  // Execution should never reach here.
    return *this;    // Silence compiler re. return from non-void function.

}
Exemplo n.º 25
0
void
predict_acdc(MACROBLOCK * pMBs,
			 uint32_t x,
			 uint32_t y,
			 uint32_t mb_width,
			 uint32_t block,
			 int16_t qcoeff[64],
			 uint32_t current_quant,
			 int32_t iDcScaler,
			 int16_t predictors[8],
			 const int bound)

{
	const int mbpos = (y * mb_width) + x;
	int16_t *left, *top, *diag, *current;

	int32_t left_quant = current_quant;
	int32_t top_quant = current_quant;

	const int16_t *pLeft = default_acdc_values;
	const int16_t *pTop = default_acdc_values;
	const int16_t *pDiag = default_acdc_values;

	uint32_t index = x + y * mb_width;	/* current macroblock */
	int *acpred_direction = &pMBs[index].acpred_directions[block];
	uint32_t i;

	left = top = diag = current = NULL;

	/* grab left,top and diag macroblocks */

	/* left macroblock */

	if (x && mbpos >= bound + 1  &&
		(pMBs[index - 1].mode == MODE_INTRA ||
		 pMBs[index - 1].mode == MODE_INTRA_Q)) {

		left = (int16_t*)pMBs[index - 1].pred_values[0];
		left_quant = pMBs[index - 1].quant;
	}
	/* top macroblock */

	if (mbpos >= bound + (int)mb_width &&
		(pMBs[index - mb_width].mode == MODE_INTRA ||
		 pMBs[index - mb_width].mode == MODE_INTRA_Q)) {

		top = (int16_t*)pMBs[index - mb_width].pred_values[0];
		top_quant = pMBs[index - mb_width].quant;
	}
	/* diag macroblock */

	if (x && mbpos >= bound + (int)mb_width + 1 &&
		(pMBs[index - 1 - mb_width].mode == MODE_INTRA ||
		 pMBs[index - 1 - mb_width].mode == MODE_INTRA_Q)) {

		diag = (int16_t*)pMBs[index - 1 - mb_width].pred_values[0];
	}

	current = (int16_t*)pMBs[index].pred_values[0];

	/* now grab pLeft, pTop, pDiag _blocks_ */

	switch (block) {

	case 0:
		if (left)
			pLeft = left + MBPRED_SIZE;

		if (top)
			pTop = top + (MBPRED_SIZE << 1);

		if (diag)
			pDiag = diag + 3 * MBPRED_SIZE;

		break;

	case 1:
		pLeft = current;
		left_quant = current_quant;

		if (top) {
			pTop = top + 3 * MBPRED_SIZE;
			pDiag = top + (MBPRED_SIZE << 1);
		}
		break;

	case 2:
		if (left) {
			pLeft = left + 3 * MBPRED_SIZE;
			pDiag = left + MBPRED_SIZE;
		}

		pTop = current;
		top_quant = current_quant;

		break;

	case 3:
		pLeft = current + (MBPRED_SIZE << 1);
		left_quant = current_quant;

		pTop = current + MBPRED_SIZE;
		top_quant = current_quant;

		pDiag = current;

		break;

	case 4:
		if (left)
			pLeft = left + (MBPRED_SIZE << 2);
		if (top)
			pTop = top + (MBPRED_SIZE << 2);
		if (diag)
			pDiag = diag + (MBPRED_SIZE << 2);
		break;

	case 5:
		if (left)
			pLeft = left + 5 * MBPRED_SIZE;
		if (top)
			pTop = top + 5 * MBPRED_SIZE;
		if (diag)
			pDiag = diag + 5 * MBPRED_SIZE;
		break;
	}

	/* determine ac prediction direction & ac/dc predictor place rescaled ac/dc
	 * predictions into predictors[] for later use */
	if (abs(pLeft[0] - pDiag[0]) < abs(pDiag[0] - pTop[0])) {
		*acpred_direction = 1;	/* vertical */
		predictors[0] = DIV_DIV(pTop[0], iDcScaler);
		for (i = 1; i < 8; i++) {
			predictors[i] = rescale(top_quant, current_quant, pTop[i]);
		}
	} else {
		*acpred_direction = 2;	/* horizontal */
		predictors[0] = DIV_DIV(pLeft[0], iDcScaler);
		for (i = 1; i < 8; i++) {
			predictors[i] = rescale(left_quant, current_quant, pLeft[i + 7]);
		}
	}
}
Exemplo n.º 26
0
Decimal& Decimal::operator/=(Decimal rhs)
{
    // Record original dividend and divisor
    Decimal const orig = *this;

    rhs.rationalize();

    // Capture division by zero
    if (rhs.m_intval == 0)
    {
        JEWEL_ASSERT (*this == orig);
        JEWEL_THROW(DecimalDivisionByZeroException, "Division by zero.");
    }
    
    // To prevent complications
    if ( m_intval == numeric_limits<int_type>::min() ||
      rhs.m_intval == numeric_limits<int_type>::min() )
    {
        JEWEL_ASSERT (*this == orig);
        JEWEL_THROW
        (   DecimalDivisionException,
            "Smallest possible Decimal cannot "
            "feature in division operation."
        );
    }
    JEWEL_ASSERT (NumDigits::num_digits(rhs.m_intval) <= maximum_precision());
    if (NumDigits::num_digits(rhs.m_intval) == maximum_precision())
    {
        JEWEL_ASSERT (*this == orig);
        JEWEL_THROW
        (   DecimalDivisionException,
            "Dividend has a number of significant"
             "digits that is greater than or equal to the return value of "
            "Decimal::maximum_precision(); as a result, division cannot be "
            "performed safely."
        );
    }
    
    // Remember required sign of product
    bool const diff_signs =
    (   ( m_intval > 0 && rhs.m_intval < 0) ||
        ( m_intval < 0 && rhs.m_intval > 0)
    );

    // Make absolute
    JEWEL_ASSERT
    (   !multiplication_is_unsafe(m_intval, static_cast<int_type>(-1))
    );
    JEWEL_ASSERT
    (   !multiplication_is_unsafe(rhs.m_intval, static_cast<int_type>(-1))
    );
    if (m_intval < 0) m_intval *= -1;
    if (rhs.m_intval < 0) rhs.m_intval *= -1;

    // Rescale the dividend as high as we can
    while (m_places < rhs.m_places && rescale(m_places + 1) == 0)
    {
    }
    if (rhs.m_places > m_places)
    {
        // We can't rescale high enough to proceed, so reset and throw
        *this = orig;
        JEWEL_THROW(DecimalDivisionException, "Unsafe division.");
    }

    // Proceed with basic division algorithm
    JEWEL_ASSERT (m_places >= rhs.m_places);
    JEWEL_ASSERT (!subtraction_is_unsafe(m_places, rhs.m_places));
    m_places -= rhs.m_places;
    JEWEL_ASSERT (rhs.m_intval != 0);
    JEWEL_ASSERT (m_intval != numeric_limits<int_type>::min());
    JEWEL_ASSERT (!remainder_is_unsafe(m_intval, rhs.m_intval));
    int_type remainder = m_intval % rhs.m_intval;
    JEWEL_ASSERT (!division_is_unsafe(m_intval, rhs.m_intval));
    m_intval /= rhs.m_intval;

    // Deal with any remainder using "long division"
    while (remainder != 0 && rescale(m_places + 1) == 0)
    {
        JEWEL_ASSERT (!multiplication_is_unsafe(remainder, s_base));

        /*
         * Previously this commented-out section of code dealt
         * with the case where it was unsafe to multiply remainder
         * and s_base. However, this is now dealt with by the fact that
         * an exception is thrown if the number of significant digits
         * in the dividend is equal to Decimal::maximum_precision().
         * This makes for a more straightforward API, since the
         * below code caused loss of precision under difficult-to-explain
         * circumstances.
        if (multiplication_is_unsafe(remainder, s_base))
        {
            // Then we can't proceed with ordinary "long division" safely,
            // and need to "scale down" first

            bool add_rounding_right = false;
            if (rhs.m_intval % s_base >= s_rounding_threshold)
            {
                add_rounding_right = true;
            }
            rhs.m_intval /= s_base;
            if (add_rounding_right)
            {
                JEWEL_ASSERT (!addition_is_unsafe(rhs.m_intval,
                  JEWEL_NUMERIC_CAST<int_type>(1)));
                ++(rhs.m_intval);
            }

            // Redo the Decimal division on a "safe scale"
            Decimal lhs = orig;
            if (lhs.m_intval < 0) lhs.m_intval *= -1;
            JEWEL_ASSERT (rhs.m_intval >= 0);
            lhs /= rhs;
            bool add_rounding_left = false;
            if (lhs.m_intval % s_base >= s_rounding_threshold)
            {
                add_rounding_left = true;    
            }
            lhs.m_intval /= s_base;
            if (add_rounding_left)
            {
                JEWEL_ASSERT (!addition_is_unsafe(lhs.m_intval,
                  JEWEL_NUMERIC_CAST<int_type>(1)));
                ++(lhs.m_intval);
            }
            if (diff_signs) lhs.m_intval *= -1;
            *this = lhs;

            return *this;
        }
        */

        // It's safe to proceed with ordinary "long division"
        JEWEL_ASSERT (!multiplication_is_unsafe(remainder, s_base));
        remainder *= s_base;

        JEWEL_ASSERT (rhs.m_intval > 0);
        JEWEL_ASSERT (!remainder_is_unsafe(remainder, rhs.m_intval));
        int_type const temp_remainder = remainder % rhs.m_intval;
        JEWEL_ASSERT (!division_is_unsafe(remainder, rhs.m_intval));
        m_intval += remainder / rhs.m_intval;
        remainder = temp_remainder;
    }

    // Do rounding if required
    JEWEL_ASSERT (rhs.m_intval >= remainder);
    JEWEL_ASSERT (!subtraction_is_unsafe(rhs.m_intval, remainder));
    if (rhs.m_intval - remainder <= remainder)
    {
        // If the required rounding would be unsafe, we throw
        if (addition_is_unsafe(m_intval, JEWEL_NUMERIC_CAST<int_type>(1)))
        {
            *this = orig;
            JEWEL_THROW(DecimalDivisionException, "Unsafe division.");
        }
        // Do the rounding, it's safe
        ++m_intval;
    }

    // Put the correct sign
    JEWEL_ASSERT (m_intval >= 0);
    JEWEL_ASSERT
    (   !multiplication_is_unsafe(m_intval, static_cast<int_type>(-1))
    );
    if (diff_signs) m_intval *= -1;
    rationalize();
    return *this;
}
void 
//HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_mt_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("muTau_0jet_low"             )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("muTau_0jet_medium"          )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("muTau_0jet_high"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("muTau_1jet_medium"          )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("muTau_1jet_high_lowhiggs"   )){ category = "#mu#tau_{h}";                          }
  if(std::string(directory) == std::string("muTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("muTau_1jet_high_mediumhiggs")){ category = "#mu#tau_{h}";                          }
  if(std::string(directory) == std::string("muTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("muTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("muTau_vbf"                  )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("muTau_vbf_loose"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("muTau_vbf_tight"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("muTau_nobtag"               )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag"               )){ category_extra = "no b-tag";                        }
  if(std::string(directory) == std::string("muTau_btag"                 )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_btag"                 )){ category_extra = "b-tag";                           }
  if(std::string(directory) == std::string("muTau_nobtag_low"           )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("muTau_nobtag_low"           )){ category_extra2 = "low"; }
  if(std::string(directory) == std::string("muTau_nobtag_medium"        )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("muTau_nobtag_medium"        )){ category_extra2 = "medium"; }
  if(std::string(directory) == std::string("muTau_nobtag_high"          )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("muTau_nobtag_high"          )){ category_extra2 = "high"; }
  if(std::string(directory) == std::string("muTau_btag_low"             )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("muTau_btag_low"             )){ category_extra2 = "low"; }
  if(std::string(directory) == std::string("muTau_btag_high"            )){ category = "#mu#tau_{h}";          }
  if(std::string(directory) == std::string("muTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("muTau_btag_high"            )){ category_extra2 = "high"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
 
  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK3 , "", "", TColor::GetColor(222,90,106), 1001);
#else
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
#endif
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK  , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
  TH1F* ggH_SM125= refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125"  , directory)), "ggH_SM125"); InitHist(ggH_SM125, "", "", kGreen+2, 1001);
  TH1F* qqH_SM125= refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125"  , directory)), "qqH_SM125"); InitHist(qqH_SM125, "", "", kGreen+2, 1001);
  TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125"   , directory)), "VH_SM125" ); InitHist(VH_SM125, "", "", kGreen+2, 1001);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK3 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK3 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif


  if(scaled){

/*  Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
  EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
  EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
  EWK3 = refill(shape_histos(EWK3, datacard, "ZL"), "ZL");
#else
  //  EWK2 = refill(shape_histos(EWK2, datacard, "ZLL"), "ZLL");
#endif
  EWK = refill(shape_histos(EWK, datacard, "VV"), "VV");
  ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
  Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
#ifdef EXTRA_SAMPLES
    rescale(EWK3 , 5);
#endif 
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK3 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

#ifdef MSSM
  qqH_SM125->Add(ggH_SM125);
  VH_SM125->Add(qqH_SM125);
  Fakes->Add(VH_SM125);
#endif
  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  EWK3 ->Add(EWK2 );
  EWK  ->Add(EWK3 );
#else
  EWK  ->Add(EWK2 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
#ifdef MSSM
    VH_SM125->Draw("histsame");
#endif   
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
#ifdef MSSM
    VH_SM125->Draw("histsame");
#endif   
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{#mu}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{mod+} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "Electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
#ifdef MSSM
  leg->AddEntry(VH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
 
  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
  ggH_SM125->Write("ggH_SM125");
  qqH_SM125->Write("qqH_SM125");
  VH_SM125 ->Write("VH_SM125");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Exemplo n.º 28
0
Image<T> rescale(const Image<T>& src, const int width, const int height,
                 RescaleType ftype)
{
  return rescale(src, Dims(width, height), ftype);
}
Exemplo n.º 29
0
//! Adjust the plot axes scales
void QwtPlotRescaler::rescale() const
{
    const QSize size = canvas()->contentsRect().size();
    rescale( size, size );
}
QwtAbstractScale::QwtAbstractScale()
{
    d_data = new PrivateData;
    rescale(0.0, 100.0);
}