Hugonweb | Programming Syntax Tips

Bash

# To loop over a sequence of numbers (including both endpoints!!)
for i in $(seq 1 8); do
  echo $i
done

# To extract all of the image filenames used in a .tex file:
grep includegraphics talk.tex | sed 's/.*{//' | sed 's/}.*//'

C++

Some Favorite Headers/Macros:

#include <string>
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tuple/tuple.hpp>

#include <TH1F.h>

#define foreach BOOST_FOREACH

//Defines method of std::string that appends any type :-)
#define appendAny(a) append(boost::lexical_cast<std::string>(a))

STL: Getting the index an iterator is pointing to:

std::distance(vec.begin(), it);

In C/C++, the boolean value of the int 0 is false. All other int\'s are true.


D

Favorite imports:

import std.stdio: writeln, write;    //easy printing
import std.math;                     //so that ^^ exponentiation works!
import std.typecons: tuple, Tuple;   //Tuple is type, tuple is easy builder

Array Usage:

double[] x = [0,1,2,3,4,5,6];
double[] y;
y.length = x.length;
y[] = x[]*x[]*5.34; //array operations!
foreach(ref ele; x)
{
  ele *= 3.6/ele;
}
writeln(x);

Tuple usage:

Tuple!(int,double) silly()
{
  return tuple(5,6.7);
}

Tuple!(int,double) s1 = silly();
auto s2 = silly();
writeln(s1[0]);
writeln(s2[1]);

Python

My Favorite ISO Time Format in Python:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')

Number of seconds since epoch (in UTC):

int(time.time())

To Fit numpy data with scikit learn:

import numpy
from sklearn.linear_model import LinearRegression

x = numpy.array([0.2,4.7,9.8,12.3])
y = numpy.array([4.3,89.3,500.6,2346.0])

nTerms = 1 # nTerms is the number of different terms you want in the fit
xForFit = numpy.zeros((x.size,nTerms))
xForFit[:,0] = numpy.power(x,2) #1st Term

fitter = LinearRegression()
fitter.fit(xForFit,y)
xPred = numpy.linspace(0.1,12.3,num=200)
xPredToFit = numpy.zeros((xPred.size,nTerms))
xPredToFit[:,0] = numpy.power(xPred,2) #1st Term

yPred = fitter.predict(xPredToFit)

coef = fitter.coef_
const = fitter.intercept_
print("const: "+str(const))
print("coefs: "+str(coef))

## Can use this for generic polynomial of order nOrder
nOrder = 2
fitter.fit(numpy.vander(x,nOrder+1),y)
yPred2 = fitter.predict(numpy.vander(xPred,nOrder+1))
coef = fitter.coef_
const = fitter.intercept_
print("Using numpy.vander:")
print("const: "+str(const))
print("coefs: "+str(coef))

SCons

To print the construction environment:

print env.Dump()

ROOT

TSkim

To redraw the axis lines after all histograms are plotted:

canvas->RedrawAxis(); //or the pad containing the histogram

Some nice helper functions for ROOT:

#include "TH1F.h"
#include "TMath.h"
#include "TStyle.h"

template <class histOrGraph> //Useful on decendents of TH1 or TGraph
void setHistTitles(histOrGraph* hist, TString xtitle, TString ytitle)
{
        hist->GetXaxis()->SetTitle(xtitle);
        hist->GetYaxis()->SetTitle(ytitle);
};

void setStyle(void)
{
  gStyle->SetLineWidth(2);
  gStyle->SetHistLineWidth(2);
  gStyle->SetFrameLineWidth(2);
  gStyle->SetLegendFillColor(kWhite);
  gStyle->SetLegendFont(42);
  gStyle->SetMarkerSize(1.2);
  gStyle->SetMarkerStyle(20);

  //gStyle->SetLabelSize(0.040,"X");
  //gStyle->SetLabelSize(0.040,"Y");

  gStyle->SetLabelFont(42,"X");
  gStyle->SetLabelFont(42,"Y");

  gStyle->SetTitleFont(42);
  gStyle->SetTitleFont(42,"X");
  gStyle->SetTitleFont(42,"Y");

  //gStyle->SetLabelOffset(1.40,"X");
  //gStyle->SetLabelOffset(1.40,"Y");

  //gStyle->SetTitleSize(0.045,"X");
  //gStyle->SetTitleSize(0.045,"Y");

  //gStyle->SetTitleOffset(1.2,"X");
  //gStyle->SetTitleOffset(1.2,"Y");

  //gStyle->SetTextSize(0.055);
  gStyle->SetTextFont(42);

  gStyle->SetOptStat(0);
};

// outIntHIst needs to have the same binning as inHist
void makeIntegralPlot(TH1F* inHist, TH1F* outIntHist, bool useWidth)
{
  unsigned nBins = inHist->GetNbinsX();
  for(unsigned i=0; i< nBins+2; i++)
  {
    float tmpBin = 0.0;
    for(unsigned j = i; j < (nBins+2);j++)
        tmpBin += inHist->GetBinContent(j);
    outIntHist->SetBinContent(i,tmpBin);
  }
  if(useWidth)
    outIntHist->Scale(1.0/float(inHist->Integral(0,nBins+1)),"width");
  else
    outIntHist->Scale(1.0/float(inHist->Integral(0,nBins+1)));
};

float* makeLogBinningArray(unsigned nBins, float min, float max)
{

  float* array = new float[nBins+1];

  float base = pow(max/min,1.0/nBins);

  float tmpTerm = min;

  for(unsigned i = 0; i < nBins+1; i++)
  {
        array[i] = tmpTerm;
        tmpTerm *= base;

  }
  return array;
};

float* makeLinBinningArray(unsigned nBins, float min, float max)
{

  float* array = new float[nBins+1];

  float base = (max-min)/(float)nBins;

  float tmpTerm = min;

  for(unsigned i = 0; i < nBins+1; i++)
  {
        array[i] = tmpTerm;
        tmpTerm += base;

  }
  return array;
};

Useful Python function for use with pyROOT:

import ROOT as root
from ROOT import gStyle as gStyle
#from ROOT import RooRealVar, RooGaussian, RooArgList, RooDataHist
import re

def fit2DResHist(hist,color):
  histName = hist.GetName()
  hist.FitSlicesY()
  outMeanHist = root.gDirectory.Get(histName+"_1")
  outSigmaHist = root.gDirectory.Get(histName+"_2")

  outMeanHist.SetName(histName+"FitMean")
  outSigmaHist.SetName(histName+"FitSigma")
  outMeanHist.GetXaxis().SetTitle(hist.GetXaxis().GetTitle())
  outSigmaHist.GetXaxis().SetTitle(hist.GetXaxis().GetTitle())
  outMeanHist.GetYaxis().SetTitle(hist.GetYaxis().GetTitle())
  outSigmaHist.GetYaxis().SetTitle(hist.GetYaxis().GetTitle())

  outSigOverMeanHist = outSigmaHist.Clone(histName+"FitSigmaOverMean")
  outSigOverMeanHist.Divide(outMeanHist)

  outMeanHist.SetMarkerColor(color)
  outMeanHist.SetLineColor(color)
  outSigmaHist.SetMarkerColor(color)
  outSigmaHist.SetLineColor(color)
  outSigOverMeanHist.SetMarkerColor(color)
  outSigOverMeanHist.SetLineColor(color)

  outMeanHist.SetTitle("")
  outSigmaHist.SetTitle("")
  outSigOverMeanHist.SetTitle("")

  return outMeanHist, outSigmaHist, outSigOverMeanHist

def fit2DResHistManual(hist,color):
  histName = hist.GetName()
  histSaveName = "slices_"+histName+".pdf"

  outMeanHist = hist.ProjectionX()
  outMeanHist.Clear()
  outMeanHist.Sumw2()
  outMeanHist.SetName(histName+"FitMean")
  outSigmaHist = outMeanHist.Clone(histName+"FitSigma")
  outRMSHist = outMeanHist.Clone(histName+"FitRMS")

  tmpCanvas = root.TCanvas("tmpCanvas"+histName)
  tmpCanvas.cd()
  nBins = hist.GetXaxis().GetNbins()
  for i in range(0,nBins+2):
    sliceHist = getXBinHist(hist,i)

    mean = sliceHist.GetMean()
    meanErr = sliceHist.GetMeanError()
    rms = sliceHist.GetRMS()
    rmsErr = sliceHist.GetRMSError()

    gaus = root.TF1("gaus","gaus");
    sliceHist.Fit(gaus,"WLME","",mean-2*rms,mean+2*rms)
    sliceHist.SetTitle("pt: "+str(hist.GetXaxis().GetBinCenter(i))+"   iBin: "+str(i))
    sliceHist.GetXaxis().SetRangeUser(-100,100)
    sliceHist.GetXaxis().SetRangeUser(-30,30) ##Temporary! Justin justin silly Silly
    sliceHist.Draw()

    # 1 is mean, 2 is sigma
    outMeanHist.SetBinContent(i,gaus.GetParameter(1))
    outMeanHist.SetBinError(i,gaus.GetParError(1))
    outSigmaHist.SetBinContent(i,gaus.GetParameter(2))
    outSigmaHist.SetBinError(i,gaus.GetParError(2))
    outRMSHist.SetBinContent(i,rms)
    outRMSHist.SetBinError(i,rmsErr)

    """
    outMeanHist.SetBinContent(i,mean)
    outMeanHist.SetBinError(i,meanErr)
    outSigmaHist.SetBinContent(i,rms)
    outSigmaHist.SetBinError(i,rmsErr)
    """

    """
    ptDiff = RooRealVar("ptDiff","pt - pt",hist.GetXaxis().GetXmin(), hist.GetXaxis().GetXmax())
    mean1 = RooRealVar("mean1","<pt-pt>",0.0)
    sigma1 = RooRealVar("sigma1","#sigma(pt-pt)",5.0)
    mean1.setConstant(False)
    sigma1.setConstant(False)

    frame1 = ptDiff.frame()

    gaus1 = RooGaussian("guas1","Guassian",ptDiff,mean1,sigma1)
    data = RooDataHist("data","Data",RooArgList(ptDiff),sliceHist)
    gaus1.fitTo(data)

    data.plotOn(frame1)
    gaus1.plotOn(frame1)

    outMeanHist.SetBinContent(i,mean1.GetVal())
    outMeanHist.SetBinError(i,mean1.GetError())
    outSigmaHist.SetBinContent(i,sigma1.GetVal())
    outSigmaHist.SetBinError(i,sigma1.GetError())

    frame1.SetTitle("pt: "+str(hist.GetXaxis().GetBinCenter(i))+"   iBin: "+str(i))
    frame1.GetXaxis().SetRangeUser(-100,100)
    frame1.Draw()
    """

    if(i == 0):
    tmpCanvas.SaveAs(histSaveName+"(")
    tmpCanvas.Clear()
    elif(i == nBins+1):
    tmpCanvas.SaveAs(histSaveName+")")
    tmpCanvas.Clear()
    else:
    tmpCanvas.SaveAs(histSaveName)
    tmpCanvas.Clear()

  outMeanHist.SetMarkerColor(color)
  outMeanHist.SetLineColor(color)
  outSigmaHist.SetMarkerColor(color)
  outSigmaHist.SetLineColor(color)
  outRMSHist.SetMarkerColor(color)
  outRMSHist.SetLineColor(color)
  outMeanHist.SetTitle("")
  outSigmaHist.SetTitle("")
  outRMSHist.SetTitle("")

  #outMeanHist.Print()
  #outSigmaHist.Print()
  #outRMSHist.Print()

  return outMeanHist, outSigmaHist, outRMSHist

def getXBinHist(inHist, xBin):
  outHist = inHist.ProjectionY()
  outHist.Clear()
  outHist.SetName(inHist.GetName()+"XSliceBin"+str(xBin))
  outHist.Sumw2()
  nBins = outHist.GetXaxis().GetNbins()
  for i in range(0,nBins+2):
    outHist.SetBinContent(i,inHist.GetBinContent(xBin,i))
    outHist.SetBinError(i,inHist.GetBinError(xBin,i))
  return outHist

def fitSlicesTopRooFit(hist):
  #mTopBest = 172.9
  mass = root.RooRealVar("mass","m_{jjj} of Top Candidate [GeV]",20,250)
  #mtParam = root.RooRealVar("mtParam","m_{t} Parameter",mTopBest);
  #wtParam = root.RooRealVar("wtParam","#Gamma_{t} Parameter",2.0);

  smearMeanParam = root.RooRealVar("smearMeanParam","m_{t} Smearing Mean",0.0);
  smearSigParam = root.RooRealVar("smearSigParam","m_{t} Smearing Sigma",0.5);

  smearMeanParam.setConstant(False);
  smearSigParam.setConstant(False);

  #bwPdf = root.RooBreitWigner("bwPdf","m_{t} Breit-Wigner Pdf",
  #                     mass,mtParam,wtParam);
  smearPdf = root.RooGaussian("smearPdf","m_{t} Smearing PDF",
                        mass,smearMeanParam,smearSigParam);
  #convPdf = root.RooFFTConvPdf("convPdf","m_{t} Convolution of BW with Gaussian",
  #                     mass,bwPdf,smearPdf);

  outMeanGraph = root.TGraphErrors()
  outSigGraph = root.TGraphErrors()
  if(hist.GetDimension()==1):

      mass = root.RooRealVar("mass","m_{jjj} of Top Candidate [GeV]",hist.GetXaxis().GetXmin(),hist.GetXaxis().GetXmax())
      smearMeanParam = root.RooRealVar("smearMeanParam","m_{t} Smearing Mean",0.0);
      smearSigParam = root.RooRealVar("smearSigParam","m_{t} Smearing Sigma",0.5);
      smearMeanParam.setConstant(False);
      smearSigParam.setConstant(False);
      smearPdf = root.RooGaussian("smearPdf","m_{t} Smearing PDF",
                        mass,smearMeanParam,smearSigParam);

      data = root.RooDataHist("data",
            "t Candidate m_{jjj} from Measured b-jet and Fit W-mass",
            root.RooArgList(mass),hist)

      smearPdf.fitTo(data)

      smearMean = smearMeanParam.getVal()
      smearMeanErr = smearMeanParam.getError()
      smearSig = smearSigParam.getVal()
      smearSigErr = smearSigParam.getError()
      return smearMean, smearMeanErr, smearSig, smearSigErr

  elif(hist.GetDimension()==2):
    iPoint=0;
    nBinsX = hist.GetXaxis().GetNbins()
    for iBinX in range(1,nBinsX+1):
      dataHist = getXBinHist(hist,iBinX);
      dataHist.Rebin(2)
      data = root.RooDataHist("data",
            "t Candidate m_{jjj} from Measured b-jet and Fit W-mass",
            root.RooArgList(mass),dataHist)

      print("justin bin: "+str(iBinX))
      dataHist.Print("v")
      data.Print("v")
      fitResult = convPdf.fitTo(data,root.RooFit.Save())

      smearMean = smearMeanParam.getVal()
      smearMeanErr = smearMeanParam.getError()
      smearSig = smearSigParam.getVal()
      smearSigErr = smearSigParam.getError()

      xPos = hist.GetXaxis().GetBinCenter(iBinX)
      xErr = hist.GetXaxis().GetBinWidth(iBinX)/2.0

      #should it be divided by mTopBest or xPos?
      smearSig = smearSig/xPos
      smearSigErr = smearSigErr/xPos
      smearMean = smearMean/xPos
      smearMeanErr = smearMeanErr/xPos
      """
      outMeanGraph.SetPoint(iPoint,xPos,dataHist.GetMean())
      outMeanGraph.SetPointError(iPoint,xErr,dataHist.GetMeanError())
      smearSig = dataHist.GetRMS()/mTopBest
      smearSigErr = dataHist.GetRMSError()/mTopBest
      """

      outMeanGraph.SetPoint(iPoint,xPos,smearMean)
      outMeanGraph.SetPointError(iPoint,xErr,smearMeanErr)
      outSigGraph.SetPoint(iPoint,xPos,smearSig)
      outSigGraph.SetPointError(iPoint,xErr,smearSigErr)

      iPoint = iPoint+1

  return outMeanGraph, outSigGraph

def divideYValByXVal(hist):
    nBinsX = hist.GetXaxis().GetNbins()
    for iBinX in range(1,nBinsX+1):
    binVal = hist.GetBinContent(iBinX)
    binErrVal = hist.GetBinError(iBinX)
    xVal = hist.GetXaxis().GetBinCenter(iBinX)
    hist.SetBinContent(iBinX,binVal/xVal)
    hist.SetBinError(iBinX,binErrVal/xVal)

def drawMVAHist(tfile, histToGetRE, meanOrsigmaString):
  """
   Draws a hist from the TMVA out file.  Must already have an active TCanvas
  """
  leg = root.TLegend(0.70,0.6,0.9,0.9)
  leg.SetFillColor(root.kWhite)
  leg.SetLineColor(root.kWhite)
  colors = [root.kBlack,root.kBlue+1,root.kRed+1,root.kBlue+1,root.kOrange+1]
  iColor = 0
  for dirName in tfile.GetListOfKeys():
   if(re.match(r"Method_.*",dirName.GetName())):
     for subDirName in dirName.ReadObj().GetListOfKeys():
       for histName in subDirName.ReadObj().GetListOfKeys():
    if(re.match(histToGetRE,histName.GetName())):
      hist = histName.ReadObj()
      #hist.GetXaxis().Rebin(2)
      hM, hS, hSOM = fit2DResHist(hist)
      hM.SetLineColor(colors[iColor % len(colors)])
      hM.SetMarkerColor(colors[iColor % len(colors)])
      hS.SetLineColor(colors[iColor % len(colors)])
      hS.SetMarkerColor(colors[iColor % len(colors)])
      hSOM.SetLineColor(colors[iColor % len(colors)])
      hSOM.SetMarkerColor(colors[iColor % len(colors)])
      tmpLegLabel = re.sub(r"MVA_","",histName.GetName())
      tmpLegLabel = re.sub(r"test.*","",tmpLegLabel)
      leg.AddEntry(hM,tmpLegLabel,"lep")
      divideYValByXVal(hS)

      if(iColor==0):
        if(meanOrsigmaString == "mean"):
        hM.SetTitle("")
        hM.GetYaxis().SetRangeUser(-10,10)
        hM.Draw()
        else:
        hS.SetTitle("")
        hS.GetYaxis().SetRangeUser(0.0,0.6)
        hS.Draw()
      else:
        if(meanOrsigmaString == "mean"):
        hM.Draw("same")
        else:
        hS.Draw("same")
      iColor += 1
  leg.Draw()
  leg.Print()
  print("made it to leg.Draw")

def makeResPlotFromMVATree(tfile,xname,yname,truename,cuts,doDivide):
  histName2D = "mvaResTmpHist"
  #tree = tfile.Get("TestTree")
  tree = tfile.Get("TrainTree")
  drawStr = ""
  if doDivide:
    drawStr = "("+yname+"-"+truename+")/"+truename+":"+xname
  else:
    drawStr = yname+"-"+truename+":"+xname
  drawStr += ">>"
  drawStr += histName2D
  print(drawStr)
  tree.Draw(drawStr,cuts)
  tmpHist = root.gDirectory.Get(histName2D)
  tmpM, tmpS, tmpSOM = fit2DResHist(tmpHist,root.kBlack)
  if(doDivide):
    tmpM.GetYaxis().SetRangeUser(-1,1)
    tmpS.GetYaxis().SetRangeUser(0,0.5)
  else:
    tmpM.GetYaxis().SetRangeUser(-50,50)
    tmpS.GetYaxis().SetRangeUser(0,100)
  tmpM.SetTitle("")
  tmpS.SetTitle("")
  return tmpM, tmpS



def setStyle():
  gStyle.SetCanvasColor(0)
  gStyle.SetCanvasBorderSize(10)
  gStyle.SetCanvasBorderMode(0)
  gStyle.SetCanvasDefH(700)
  gStyle.SetCanvasDefW(700)

  gStyle.SetPadColor       (0)
  gStyle.SetPadBorderSize  (10)
  gStyle.SetPadBorderMode  (0)
  gStyle.SetPadBottomMargin(0.13)
  gStyle.SetPadTopMargin   (0.08)
  gStyle.SetPadLeftMargin  (0.15)
  gStyle.SetPadRightMargin (0.05)
  gStyle.SetPadGridX       (0)
  gStyle.SetPadGridY       (0)
  gStyle.SetPadTickX       (1)
  gStyle.SetPadTickY       (1)

  gStyle.SetFrameFillStyle ( 0)
  gStyle.SetFrameFillColor ( 0)
  gStyle.SetFrameLineColor ( 1)
  gStyle.SetFrameLineStyle ( 0)
  gStyle.SetFrameLineWidth ( 1)
  gStyle.SetFrameBorderSize(10)
  gStyle.SetFrameBorderMode( 0)

  gStyle.SetNdivisions(505)

  gStyle.SetLineWidth(2)
  gStyle.SetHistLineWidth(2)
  gStyle.SetFrameLineWidth(2)
  gStyle.SetLegendFillColor(root.kWhite)
  gStyle.SetLegendFont(42)
  gStyle.SetMarkerSize(1.2)
  gStyle.SetMarkerStyle(20)

  gStyle.SetLabelSize(0.040,"X")
  gStyle.SetLabelSize(0.040,"Y")

  gStyle.SetLabelOffset(0.010,"X")
  gStyle.SetLabelOffset(0.010,"Y")

  gStyle.SetLabelFont(42,"X")
  gStyle.SetLabelFont(42,"Y")

  gStyle.SetTitleBorderSize(0)
  gStyle.SetTitleFont(42)
  gStyle.SetTitleFont(42,"X")
  gStyle.SetTitleFont(42,"Y")

  gStyle.SetTitleSize(0.045,"X")
  gStyle.SetTitleSize(0.045,"Y")

  gStyle.SetTitleOffset(1.4,"X")
  gStyle.SetTitleOffset(1.4,"Y")

  gStyle.SetTextSize(0.055)
  gStyle.SetTextFont(42)

  gStyle.SetOptStat(0)


setStyle()

def makeWeightHist(f1,canvas,leg):
  firstHist = True
  canvas.cd()
  canvas.SetLogy()
  colorsList = [1,2,3,4,5,6,7,8]
  nColors = len(colorsList)
  iDir = 0
  leg.Clear()
  leg.SetFillColor(0)
  leg.SetLineColor(0)
  tmpList = []
  for dirName in f1.GetListOfKeys():
    tmpList.append(dirName)
  tmpList.reverse()
  for dirName in tmpList:
    print(dirName.GetName())
    if(re.search(r"data",dirName.GetName())):
    continue
    directory = dirName.ReadObj()
    for histKey in directory.GetListOfKeys():
      if(histKey.GetName()=="hWeight"):
        hist = histKey.ReadObj()
    hist.UseCurrentStyle()
    hist.SetLineColor(colorsList[iDir % nColors])
    hist.SetMarkerColor(colorsList[iDir % nColors])
    allIntegral = hist.Integral(0,hist.GetNbinsX()+1)
    integral = hist.Integral()
    if integral > 0.0:
      print("Fraction Outside of bounds: %f" % (allIntegral/integral-1.0))
      #hist.Scale(1.0/allIntegral)
      hist.Scale(1.0/integral)
    else:
      leg.AddEntry(hist,dirName.GetName(),"lep")
    if(firstHist):
      firstHist=False
      hist.GetYaxis().SetTitle("Fraction of Events")
      hist.GetXaxis().SetTitle("Event Weight")
      #hist.GetXaxis().SetRangeUser(0.0,1.0)
      hist.Draw()
    else:
      hist.Draw("same")
    iDir += 1
  leg.Draw("same")

class DataMCStack:
  def __init__(self, mcHistList, dataHist, canvas, xtitle, ytitle="Events", drawStack=True,nDivX=7):
    nBinsX = dataHist.GetNbinsX()
    self.nBinsX = nBinsX
    for mcHist in mcHistList:
      assert(nBinsX == mcHist.GetNbinsX())

    # Make MC Stack/sumHist
    self.stack = root.THStack()
    self.mcSumHist = dataHist.Clone("mcSumHist"+dataHist.GetName())
    self.mcSumHist.Reset()
    for mcHist in mcHistList:
      self.mcSumHist.Add(mcHist)
      self.stack.Add(mcHist)

    # Make Pull Hist
    self.pullHist = dataHist.Clone("pullHist"+dataHist.GetName())
    self.pullHist.Reset()
    for i in range(1,self.pullHist.GetNbinsX()):
      nData = dataHist.GetBinContent(i)
      nMC = self.mcSumHist.GetBinContent(i)
      error = dataHist.GetBinContent(i)
      pull = 0.0
      if error != 0.0:
        pull = (nData -nMC)/error
      self.pullHist.SetBinContent(i,pull)
      #print("nData: %f, nMC: %f, error: %f, pull: %f" % (nData,nMC,error,pull))

    #Setup Canvas
    canvas.cd()
    pad1 = root.TPad("pad1"+dataHist.GetName(),"",0.02,0.30,0.98,0.98,0)
    pad2 = root.TPad("pad2"+dataHist.GetName(),"",0.02,0.01,0.98,0.29,0)

    pad1.SetBottomMargin(0.005);
    pad2.SetTopMargin   (0.005);
    pad2.SetBottomMargin(0.33);
    """
    pad1.SetBottomMargin(0.01);
    pad2.SetTopMargin   (0.3);
    pad2.SetBottomMargin(0.33);
    """

    pad1.Draw() # Projections pad
    pad2.Draw() # Residuals   pad

    pad1Width = pad1.XtoPixel(pad1.GetX2())
    pad1Height = pad1.YtoPixel(pad1.GetY1())
    pad2Height = pad2.YtoPixel(pad2.GetY1())
    #pad1ToPad2FontScalingFactor = float(pad1Width)/pad2Height
    pad1ToPad2FontScalingFactor = float(pad1Height)/pad2Height

    # Main Pad
    pad1.cd();
    if drawStack:
      self.stack.Draw("histo b")
      self.stack.GetXaxis().SetTitle("")
      self.stack.GetXaxis().SetLabelSize(0)
      self.stack.GetYaxis().SetTitle(ytitle)
      self.stack.GetYaxis().SetLabelSize(0.050)
      self.stack.GetYaxis().SetTitleSize(0.055)
      self.stack.GetXaxis().SetNdivisions(nDivX)
      self.stack.Draw("histo b")
    else:
      self.mcSumHist.SetFillColor(856)
      self.mcSumHist.SetLineColor(856)
      self.mcSumHist.SetMarkerColor(856)
      self.mcSumHist.SetFillStyle(1001)
      self.mcSumHist.GetXaxis().SetTitle("")
      self.mcSumHist.GetXaxis().SetLabelSize(0)
      self.mcSumHist.GetYaxis().SetTitle(ytitle)
      self.mcSumHist.GetYaxis().SetLabelSize(0.050)
      self.mcSumHist.GetYaxis().SetTitleSize(0.055)
      self.mcSumHist.GetXaxis().SetNdivisions(nDivX)
      self.mcSumHist.Draw("histo b")
    dataHist.Draw("pe same")

    # Pulls Pad
    pad2.cd()
    self.pullHist.SetTitle("")
    self.pullHist.GetXaxis().SetTitle(xtitle)
    self.pullHist.GetXaxis().CenterTitle(1)
    self.pullHist.GetXaxis().SetNdivisions(nDivX)
    self.pullHist.GetXaxis().SetTitleSize(0.055*pad1ToPad2FontScalingFactor)
    self.pullHist.GetXaxis().SetLabelSize(0.050*pad1ToPad2FontScalingFactor)
    self.pullHist.GetYaxis().SetTitle("#frac{Data-MC}{Error}")
    self.pullHist.GetYaxis().SetTitleSize(0.040*pad1ToPad2FontScalingFactor)
    self.pullHist.GetYaxis().SetLabelSize(0.040*pad1ToPad2FontScalingFactor)
    self.pullHist.GetYaxis().CenterTitle(1)
    self.pullHist.GetYaxis().SetTitleOffset(0.70)
    self.pullHist.SetFillColor(856)
    self.pullHist.SetFillStyle(1001)
    self.pullHist.Draw("histo b")
    pad2.Update()
    pad2.GetFrame().DrawClone()

    canvas.cd()

RooFit

RooAbsPdf::fitTo returns a NULL pointer by default, you must include Save() in the options to actually get the RooFitResult* from it.

For error bands of a fit look at: http://root.cern.ch/root/html/tutorials/roofit/rf610_visualerror.C.html

The key thing is:

RooAbsPdf::plotOn(RooPlot* frame, 
VisualizeError(RooFitResult rslt, unsigned nSigmas, bool symetricAndUncorrelated), 
FillColor(kBlue-9));

It is a bit difficult to add a weight to a RooDataSet. This is the easiest way I\'ve found:

     # For dataset containing xVar:

     # construct the weight (making sure the total num events stays the same)                            
      weightVar = root.RooRealVar("weight","weight",1)
      weightVar.setVal( whatever_the_weight_is )                                   

      # the set containing the observable and the weight
      datasetWeightArgSet = root.RooArgSet(xVar, Weight)                                             

      # constructing the dataset with a weight                                                            
      dataset.addColumn( Weight )
      datasetWeight = root.RooDataSet(dataset.GetName() + "_withWeights",                                       
                                            "Weighted "+dataset.GetTitle(),
                                            datasetWeightArgSet,                               
                                            root.RooFit.Import(dataset),
                                            root.RooFit.WeightVar(weight)                                 
                                            )                               

VIM

This vim script is helpful for turning a histogram declaration line into a definition, in C++, and for turning a python definition into a copy to self.

" Packages
set nocompatible              " be iMproved, required for vundle
filetype off                  " required for vundle
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
Plugin 'mhinz/vim-signify'
Plugin 'vim-scripts/SearchComplete'
Plugin 'bling/vim-airline'
Plugin 'altercation/vim-colors-solarized'
call vundle#end()            " required
filetype plugin indent on    " required
" Config Packages
" enable airline always:
set laststatus=2
let g:airline#extensions#tabline#enabled = 1
let g:airline_left_sep=''
let g:airline_right_sep=''
let g:airline_section_warning=''
" for signify
let g:signify_vcs_list = [ 'git', 'bzr', 'svn' ]
" for solarized
syntax enable
set background=light
colorscheme solarized

" Personal Settings, Macros, and functions
:set foldenable
:set foldmethod=syntax
:set expandtab
:set tabstop=4
:set shiftwidth=4
:set t_Co=16
command Spell setlocal spell spelllang=en_us
autocmd BufRead *.tex :Spell
autocmd BufRead *.bib :Spell
command PdfLatex !mkdir -p build; rubber --pdf --into build %; cp build/*.pdf .
map <F4> :PdfLatex<CR>
command RunCurrentFile !./%
map <F5> :RunCurrentFile<CR>
command Scons !scons -j2
map <F6> :Scons<CR>
command Scramb !scram b -j2
map <F7> :Scramb<CR>

function! InitHist()
python << EOF
import vim
import re
import copy
#tmpLine = copy.deepcopy(vim.current.line)
tmpLine = vim.current.line
matchObj = re.search(r"TH.*\*",tmpLine)
if (not matchObj):
  print("Error: InitHist: TH* not found on current line")
else:
  typeStr = re.sub(r" ",r"",tmpLine[matchObj.start():matchObj.end()])
  typeStr = re.sub(r"\*",r"",typeStr)
  typeStr = re.sub(r"\t",r"",typeStr)

  varStr = tmpLine[matchObj.end():]
  varStr = re.sub(r";",r"",varStr)
  varStr = re.sub(r" ",r"",varStr)
  varStr = re.sub(r"\t",r"",varStr)

  indentationStr = tmpLine[:matchObj.start()]

  outLine = indentationStr+ varStr + " = new " + typeStr
  outLine += '("'+varStr+'", "'+varStr+'", );'
  vim.current.line = outLine
  print(outLine)

  vim.command("put =''")

  vim.current.line = indentationStr+'setHistTitles('+varStr+',"","");'

EOF
endfunction
command Hist call InitHist()

function! AddVarToSelf()
python << EOF
import vim
import re
import copy
#tmpLine = copy.deepcopy(vim.current.line)
tmpLine = vim.current.line
matchObj = re.search(r"([\s]*)([\w]+)[\s]*=.*",tmpLine)
if (not matchObj):
  print("Error: AddVarToSelf: <variable> = * not found on current line")
else:
  indentationStr = matchObj.group(1)
  varStr = matchObj.group(2)

  outLine = indentationStr + "self." + varStr + " = " + varStr
  vim.current.line = outLine

EOF
endfunction
command VarToSelf call AddVarToSelf()

GDB

To use GDB to find a segfault:

  1. Compile your program with debugging enabled (gcc option: -g)
  2. Make sure the kernel gives you the whole core-dump: ulimit -c unlimited
  3. Run the program like normal, and let it crash
  4. run gdb <program> <coredump>
  5. Type \'bt\' to get the line numbers right before the segfault

CVS

To add a new tag

cvs tag -R <tagname>

the -R means recursive. This will tag everything in or below the current directory. Remember that CVS does no version control of tags!

Starting a branch is just like tagging, do it before committing or changing anything:

cvs tag -b <branchname>

Now the code must have the \"Sticky Tag\" of the branch set. To update code to be using a Sticky Tag, run:

cvs update -r <branchname>

To get rid of all Sticky Tags, run:

cvs update -A

To see what Sticky Tags are in use, run:

cvs status

SVN

Always create branches and tags on the server, it is much faster:

svn copy ^/notes/HIG-13-007/trunk ^/notes/HIG-13-007/branches/mass110160PixelLumi -m "creating branch from trunk r206450 named mass110160PixelLumi"

The carat stands in for the url of your remote repository.


Git

Convert bzr repo to Git:

sudo apt-get install bzr-fastimport
cd <bzr repository dir>  # backup first!
git init
bzr fast-export --plain . | git fast-import
git checkout -f master
# will say that you are already on master
rm -r .bzr*
git commit -a

Git does not push tags by default!

git push --tags

AutoTools

bin_PROGRAMS = hello
hello_SOURCES = main.cc

CMake

CMake seems a lot simpler than Autotools.

You just have to write a CMakeLists.txt:

cmake_minimum_required (VERSION 2.8.11)
project (HELLO)

# Find Boost library >= 1.36.0 and get info for program_options library
find_package(Boost 1.36.0 COMPONENTS program_options)
if(NOT Boost_FOUND)
  # Exit if boost not found
  message(FATAL_ERROR "Boost Required!")
endif()
include_directories(${Boost_INCLUDE_DIRS}) #add include dirs for all builds

# create static library
add_library(silly sillylib.cc)
# create executable
add_executable (hello main.cc)
# make sure "hello" links "libsilly"
target_link_libraries(hello silly)
# make sure "hello" links to Boost libraries found above
target_link_libraries(hello ${Boost_LIBRARIES})

The first time you run it, you must type cmake CMakeLists.txt and then make. After that, you only have to ever type make, because the Makefile checks and rebuilds itself from the CMakeLists.txt automatically.