def flagLowStatPoints_noLargeErrorCheck(graph, debug): #stick all the indices of the bad points in this vector points = [] #loop on all data points of the graph nPoints = graph.GetN() for iPoint in xrange(0, nPoints): dataPointX = Double(0) dataPointY = Double(0) error = Double(0) errorX = graph.GetErrorX(iPoint) errorY = graph.GetErrorY(iPoint) graph.GetPoint(iPoint, dataPointX, dataPointY) ##eliminate and flag NaN points (better if numpy module installed) if isnan(dataPointY): dataPointY = 0.000001 #if dataPointY < 0.000001 : #dataPointY = 0.000001 points.append(iPoint) ##flag points where the error is zero (this means that there was just one entry in the histogram) if errorY < 0.00000001: points.append(iPoint) if debug == True: print "DEBUG: List of bad points for plot", graph.GetName(), ":" print points return points
def _integral(self, graph, x_lo, x_hi): """ Return integral of TGraph from x_lo to x_hi. This is done by using triangles. Note that TGraph::Integral() does not return the integral of the TGraph, but the area of the polygon spanned by the TGraph. """ integral = 0. for point in range(0, graph.GetN()): # Check if we are in the range requested by the user if point < x_lo: continue if point >= x_hi: break # Use ROOT::Double() for x_n, y_n and x_n+1, y_n+1 x_n1 = Double() y_n1 = Double() x_n2 = Double() y_n2 = Double() graph.GetPoint(int(point), x_n1, y_n1) graph.GetPoint(int(point) + 1, x_n2, y_n2) # Calculate new integral segment and add it to old one integral += 1. / 2 * (y_n2 + y_n1) * (x_n2 - x_n1) return integral
def plotEtaPhiForDeltaPhiOne(self): canvas = TCanvas("cEtaPhiDeltaPhiOne", "Eta Phi For DPhi 1", 1200, 1200) graph = self.fileHandler.getGraph('graphs/averageEnergyDeltaPhi1') halfbinwidth = L1_PHI_BIN / 2. hist = TH2D('hEtaPhiDeltaPhi1', "#eta#phi of #Delta#phi=1 evts.", 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 289, -math.pi - halfbinwidth, math.pi + halfbinwidth) x = Double(0) y = Double(0) for i in range(0, graph.GetN()): graph.GetPoint(i, x, y) hist.Fill(x, y) hist.SetStats(0) hist.GetXaxis().SetRangeUser(-1, 1) hist.SetTitle(hist.GetTitle() + ';#eta;#phi;Entries') setupAxes(hist) hist.Draw('colz') canvas.Update() setupPalette(hist) label = self.drawLabel() canvas.Update() self.storeCanvas(canvas, 'etaPhiForDeltaPhiOne') canvas.SaveAs('plots/etaPhiForDeltaPhiOne.pdf') return canvas, hist, label
def __drawGraph__(self, graph): ## Takes care of drawing a graph # Also takes care of calculating axis ranges, etc. if self.combineStatsAndSyst and graph in self.systematicsGraphs.values( ): return drawOption = self.optionsDict[graph].upper() title = graph.GetTitle() if title: legendOption = '' if any(x in drawOption for x in ['L', '0']): legendOption += 'L' if any(x in drawOption for x in ['2', '3', '4', '5']): legendOption += 'F' if any(x in drawOption for x in ['P']): legendOption += 'P' self.legendElements.append( LegendElement(graph, title, legendOption)) if not self.firstDrawnObject: self.firstDrawnObject = self.xVariable.createHistogram() self.firstDrawnObject.Draw() if graph.GetN() > 0: from ROOT import Double xMin, xMax, yMin, yMax = (Double(), Double(), Double(), Double()) graph.ComputeRange(xMin, yMin, xMax, yMax) if self.minimum > yMin: self.minimum = yMin if self.maximum < yMax: self.maximum = yMax graph.Draw(drawOption)
def tau_from_L_curve(unfoldingObject): ''' Get best tau via l curve method Not tested ''' lCurve = TGraph() logTauX = TSpline3() logTauY = TSpline3() iBest = unfoldingObject.ScanLcurve(500, 0., 0., lCurve, logTauX, logTauY) # Additional info, plots t = Double(0) x = Double(0) y = Double(0) logTauX.GetKnot(iBest, t, x) logTauY.GetKnot(iBest, t, y) bestLcurve = Graph(1) bestLcurve.SetPoint(1, x, y) lCurve.SetMarkerColor(600) lCurve.SetMarkerSize(1) lCurve.SetMarkerStyle(5) # lCurve.Draw("AP"); bestLcurve.markercolor = 'red' # bestLcurve.Draw("*"); return unfoldingObject.GetTau()
def rescaleJetPlot(plot): #loop on all data points nPoints = plot.GetN() # print "old:",plot.GetName(), nPoints #create another TGraph newPlot = TGraphErrors() for i in xrange(0, nPoints): dataPointX = Double(0) dataPointY = Double(0) error = Double(0) plot.GetPoint(i, dataPointX, dataPointY) #if numpy.isnan(dataPointY) : dataPointY = 0.000001 if dataPointY < 0.000001: dataPointY = 0.000001 errorX = plot.GetErrorX(i) errorY = plot.GetErrorY(i) newPlot.SetPoint(i, dataPointX / 1000., dataPointY) newPlot.SetPointError(i, errorX / 1000., errorY) # print "new:", newPlot.GetName(), newPlot.GetN() return newPlot
def extendLastGoodBin_2011(graph, warn): #loop on all data points of the graph nPoints = graph.GetN() #it should not happen that the first bin is bad, but just in case we keep it obvious lastGoodBin = -999 lastGoodError = -999 for iPoint in xrange(0, nPoints): dataPointX = Double(0) dataPointY = Double(0) error = Double(0) errorX = graph.GetErrorX(iPoint) errorY = graph.GetErrorY(iPoint) graph.GetPoint(iPoint, dataPointX, dataPointY) #HACK: this is rather arbitrary! if dataPointY > 2. or errorY > 0.1: if warn: print "WARNING in JESUncertainty_RatioUtils::extendLastGoodBin: " print "found bad point for graph:", graph.GetName( ), "at point: ", iPoint, ", X:", dataPointX, "Y:", dataPointY print "extending previous point:", lastGoodBin newDataPointY = lastGoodBin newErrorY = lastGoodError graph.SetPoint(iPoint, dataPointX, newDataPointY) graph.SetPointError(iPoint, errorX, newErrorY) else: lastGoodBin = dataPointY lastGoodError = errorY
def correctIncompleteShowers(self, limits): """ Arguments: -> fname: Name of the root file where the incomplete energy per layer distributions are stored. -> hnames: Name of the histograms to be corrected. -> weights: weights to correct the incomplete showers -> limits: limits on the x axis where the correction should stop being applied """ h, corr_graphs = ([] for _ in range(2)) for ireg in range(self.nsr): h.append([]) corr_graphs.append([]) for iw in range(self.ndiscrintervals_): h[ireg].append(self.f_.Get(self.hn_bckg[ireg][iw])) corr_graphs[ireg].append(TGraph(h[ireg][iw].GetNbinsX())) for ireg in range(self.nsr): graphs = RootHistograms(h[ireg]).toGraph() assert len(graphs) == self.ndiscrintervals_ for iw in range(self.ndiscrintervals_): for j in range(graphs[iw].GetN()): x, y = Double(0.), Double(0.) #pass by reference graphs[iw].GetPoint(j, x, y) if x < limits[ireg] and self.weights_[ireg][iw][j] != 0: corr_graphs[ireg][iw].SetPoint( j, x, y / self.weights_[ireg][iw][j]) else: corr_graphs[ireg][iw].SetPoint(j, x, y) return corr_graphs
def grrScale(gr1, scale): x1 = Double() x_ = Double() x1e = Double() y1 = Double() y1e = Double() y = [] ex = [] ey = [] NC = gr1.GetN() x = [0 for i in range(NC)] for ii in range(NC): x1e = gr1.GetErrorX(ii) y1e = gr1.GetErrorY(ii) gr1.GetPoint(ii, x_, y1) x1 = x_ * 1.0 x[ii] = x1 y.append(y1 * scale) ex.append(x1e) ey.append(y1e * scale) gr = Graph(NC) for x0, y0, x0e, y0e, i in zip(x, y, ex, ey, range(NC)): gr.SetPoint(i, x0, y0) gr.SetPointError(i, x0e, x0e, y0e, y0e) return gr
def get_integrals_and_errors(condor_dir,channel,dataset,histogram,threshold,minimum,maximum): out = [] inputFile = TFile("condor/"+condor_dir+"/"+dataset+".root") Histogram = inputFile.Get("OSUAnalysis/"+channel+"/"+histogram).Clone() Histogram.SetDirectory(0) inputFile.Close() thresholdBin = Histogram.FindBin (threshold) if Histogram.GetXaxis().GetBinLowEdge(thresholdBin) - threshold > 0.00001: print "WARNING: your threshold value ("+str(threshold)+") is not on a bin edge" print "the edge of its bin is " + str(Histogram.GetXaxis().GetBinLowEdge(thresholdBin)) minimumBin = Histogram.FindBin (minimum) if Histogram.GetXaxis().GetBinLowEdge(minimumBin) - minimum > 0.00001: print "WARNING: your minimum value ("+str(minimum)+") is not on a bin edge" print "the edge of its bin is " + str(Histogram.GetXaxis().GetBinLowEdge(minimumBin)) maximumBin = Histogram.FindBin (maximum) if Histogram.GetXaxis().GetBinLowEdge(maximumBin) - maximum > 0.00001: print "WARNING: your maximum value ("+str(maximum)+") is not on a bin edge" print "the edge of its bin is " + str(Histogram.GetXaxis().GetBinLowEdge(maximumBin)) isolatedIntegral = Double(0) isolatedIntegralError = Double(0) isolatedIntegral = Histogram.IntegralAndError(0,thresholdBin,isolatedIntegralError) out.append(isolatedIntegral) out.append(isolatedIntegralError) nonIsolatedIntegral = Double(0) nonIsolatedIntegralError = Double(0) nonIsolatedIntegral = Histogram.IntegralAndError(minimumBin,maximumBin,nonIsolatedIntegralError) out.append(nonIsolatedIntegral) out.append(nonIsolatedIntegralError) return out
def getRateInPb (self, seed): if seed not in numerator[self._label]: print "ETM" + seed + " not found in results!" return self._denominatorHist = TH1D ("total", "", 1, -0.5, 0.5) self._numeratorHist = TH1D ("pass", "", 1, -0.5, 0.5) self._denominatorHist.SetBinContent (1, self._denominator) self._denominatorHist.SetBinError (1, math.sqrt (self._denominator)) self._numeratorHist.SetBinContent (1, numerator[self._label][seed]) self._numeratorHist.SetBinError (1, math.sqrt (numerator[self._label][seed])) self._rateGraph = TGraphAsymmErrors (self._numeratorHist, self._denominatorHist) x = Double (0.0) y = Double (0.0) self._rateGraph.GetPoint (0, x, y) eLow = self._rateGraph.GetErrorYlow (0) eHigh = self._rateGraph.GetErrorYhigh (0) y *= self._crossSectionInPb eLow *= self._crossSectionInPb eHigh *= self._crossSectionInPb return (y, eLow, eHigh)
def makeErrorGraph(graph): '''Make graphs of the low and high error of a given graph.''' N = graph.GetN() graphElow = TGraph(N) graphEup = TGraph(N) graphElow.SetName(graph.GetName() + "_graphElow") graphEup.SetName(graph.GetName() + "_graphEup") graphElow.SetTitle(graph.GetTitle() + " low error") graphEup.SetTitle(graph.GetTitle() + " high error") for i in xrange(0, N): x, y = Double(), Double() graph.GetPoint(i, x, y) graphElow.SetPoint(i, x, graph.GetErrorYlow(i)) graphEup.SetPoint(i, x, graph.GetErrorYhigh(i)) graphElow.SetLineWidth(graph.GetLineWidth()) graphEup.SetLineWidth(graph.GetLineWidth()) graphElow.SetLineColor(graph.GetLineColor()) graphEup.SetLineColor(graph.GetLineColor()) graphElow.SetLineStyle(graph.GetLineStyle()) graphEup.SetLineStyle(graph.GetLineStyle()) graphElow.SetMarkerSize(graph.GetMarkerSize()) graphEup.SetMarkerSize(graph.GetMarkerSize()) graphElow.SetMarkerColor(graph.GetMarkerColor()) graphEup.SetMarkerColor(graph.GetMarkerColor()) graphElow.SetMarkerStyle(graph.GetMarkerStyle()) graphEup.SetMarkerStyle(graph.GetMarkerStyle()) return [graphElow, graphEup]
def ScaleGraphY(graph, factor): '''Scales the y values of a graph with the factor in the argument''' for i in range(graph.GetN()): x, y = Double(0), Double(0) graph.GetPoint(i, x, y) y *= factor graph.SetPoint(i, x, y)
def generate(self, add_particle): #electron polar angle theta and energy E theta = -1. E = 0. while theta < 0. or theta > pi or E**2 < self.me**2: #values of the x and y from the cross section x = Double(0) y = Double(0) self.eq.GetRandom2(x, y) #electron angle and energy theta = math.sqrt(x * y * self.s / ((1. - y) * self.Ee**2)) E = self.Ee * (1. - y) #tree output with generator kinematics self.out.gen_x = x self.out.gen_y = y self.out.gen_Q2 = x * y * self.s self.out.gen_theta = theta self.out.gen_E = E #uniform azimuthal angle phi = 2. * TMath.Pi() * self.rand.Rndm() self.out.gen_phi = phi #put the electron to the event el = add_particle(electron(E, theta, phi)) el.pxyze_prec = 9
def getHistoContentInJson(histo): xBins={} histoName=histo.GetName() xaxisName = re.split("_",histoName)[0] yaxisName = re.split("_",histoName)[1] #if (histo.GetYaxis().GetNbins()==1): if (histo.GetYaxis().GetNbins()==1): print "this is a 1D histo" #for i in range(0,histo.GetXaxis().GetNbins()+1): for i in range(0,histo.GetN()): print 'i is', i x = Double(999) x_hi = 999 x_low = 999 y = Double(999) y_hi = 999 y_low = 999 histo.GetPoint(i,x,y) x_hi = x+ histo.GetErrorXhigh(i) x_low = x - histo.GetErrorXlow(i) y_hi = histo.GetErrorYhigh(i) y_low = histo.GetErrorYlow(i) xBinValue=xaxisName+":["+str(x_low)+","+str(x_hi)+"]" print 'xBinValue is', xBinValue xBins[xBinValue]=getValueError(y, max(y_low,y_hi)) return xBins
def get_bins_errors(binned, include_overflow=False): """Get a list of bin content and bin centers of a TH1 or TGraph. Args: binned: The TH1 or TGraph object Returns: A list of (x, y, y_err) values """ points = [] if isinstance(binned, TGraph): x = Double() y = Double() for i in range(binned.GetN()): binned.GetPoint(i, x, y) points.append((float(x), float(y), binned.GetErrorYhigh(i))) elif isinstance(binned, TH1): offset = 1 if include_overflow else 0 points = [(binned.GetBinCenter(i + 1), binned.GetBinContent(i + 1), binned.GetBinError(i + 1)) for i in range(0 - offset, binned.GetNbinsX() + offset)] else: raise RuntimeError('Unsupported object: {0}'.format(type(binned))) return points
def makeCoordinatePlot(self, source): c = TCanvas(source, source, 1200, 1200) graphDt = self.fileHandler.getGraph('graphs/L1MuonPresent_' + source) histAll = TH2D('hEtaPhi' + source, ";#eta_{L1};#phi_{L1};#", 30, -15 * L1_ETA_BIN, 15 * L1_ETA_BIN, 144, -math.pi, math.pi) fillGraphIn2DHist(graphDt, histAll) ### ''' Temporary stuff to check the eta coordinates in the graphs ''' x = Double(0) y = Double(0) listeDt = [] for i in range(0, graphDt.GetN()): graphDt.GetPoint(i, x, y) listeDt.append(float(x)) histAll.SetStats(0) histAll.Draw('colz') c.Update() setupAxes(histAll) label = self.drawLabel() c.Update() return c, histAll, label
def plcLimit(obs_, poi_, model, ws, data, CL=0.95, verbose=False): # obs : observable variable or RooArgSet of observables # poi : parameter of interest or RooArgSet of parameters # model : RooAbsPdf of model to consider including any constraints # data : RooAbsData of the data # CL : confidence level for interval # returns a dictionary with the upper and lower limits for the first/only # parameter in poi_ as well as the interval object and status flag obs = RooArgSet(obs_) obs.setName('observables') poi = RooArgSet(poi_) poi.setName('poi') poi.setAttribAll('Constant', False) nuis = model.getParameters(obs) nuis.remove(poi) nuis.remove(nuis.selectByAttrib('Constant', True)) nuis.setName('nuisance') if verbose: print 'observables' obs.Print('v') print 'parameters of interest' poi.Print('v') print 'nuisance parameters' nuis.Print('v') mc = RooStats.ModelConfig('mc') mc.SetWorkspace(ws) mc.SetPdf(model) mc.SetObservables(obs) mc.SetParametersOfInterest(poi) mc.SetNuisanceParameters(nuis) plc = RooStats.ProfileLikelihoodCalculator(data, mc) plc.SetConfidenceLevel(CL) interval = plc.GetInterval() upperLimit = Double(999.) lowerLimit = Double(0.) Limits = {} paramIter = poi.createIterator() param = paramIter.Next() while param: ok = interval.FindLimits(param, lowerLimit, upperLimit) Limits[param.GetName()] = { 'ok': ok, 'upper': float(upperLimit), 'lower': float(lowerLimit) } param = paramIter.Next() if verbose: print '%.0f%% CL limits' % (interval.ConfidenceLevel() * 100) print Limits Limits['interval'] = interval return Limits
def w_lowHighMTRatio( var, anaDir, comp, weights, cut, weight, lowMTMax, highMTMin, highMTMax, chargeRequirement, treeName = None): cutWithChargeReq = ' && '.join([cut, chargeRequirement]) max = 5000 mt = shape(var, anaDir, comp, weights, max, 0, max, cutWithChargeReq, weight, None, None, treeName = treeName) mt_low = mt.Integral(True, 0, lowMTMax) mt_high = mt.Integral(True, highMTMin, highMTMax) mt_ratio = mt_low / mt_high print 'W MT ratio, mt ranges', lowMTMax, highMTMin, highMTMax error_low = Double(0.) error_high = Double(0.) mt_low_jan = mt.weighted.IntegralAndError(1, mt.weighted.FindBin(lowMTMax)-1, error_low) mt_high_jan = mt.weighted.IntegralAndError(mt.weighted.FindBin(highMTMin), mt.weighted.FindBin(highMTMax), error_high) print mt.weighted.FindBin(lowMTMax)-1, mt.weighted.FindBin(highMTMin), mt.weighted.FindBin(highMTMax) if mt_high > 0. and mt_low > 0.: print 'MT ratio', mt_ratio, '+-', math.sqrt(error_low**2/mt_low**2 + error_high**2/mt_high**2) * mt_ratio # print 'MT ratio', mt_low_jan/mt_high_jan, '+-', math.sqrt(error_low**2/mt_low**2 + error_high**2/mt_high**2) * mt_ratio print 'Integrals: low', mt_low, '+-', error_low, 'high', mt_high, '+-', error_high # print 'Integrals: low', mt_low_jan, '+-', error_low, 'high', mt_high_jan, '+-', error_high print 'Relative errors: low', error_low/mt_low, 'high', error_high/mt_high print 'TOTAL RELATIVE ERROR:', math.sqrt(error_low**2/mt_low**2 + error_high**2/mt_high**2), '\n' return mt_ratio
def getGraph(self,graphname,filesToProcess = -1): rootfile = TFile(self.getFile(0),'READ') graphname = self.getFullPlotPath(graphname) try: graph = rootfile.Get(graphname) nTotal = 0 counter = graph.GetN() except AttributeError: if self.DEBUG: commandLine.warning('Could not get graph %s' % graphname) return None #Check whether a number of result files to process is given fileRange = filesToProcess if (filesToProcess != -1) else len(self.fileNameList) #Then check that we don't try process more files than available fileRange = min(len(self.fileNameList), fileRange ) for i in range(0,fileRange): rootfile = TFile(self.getFile(i),'READ') g = rootfile.Get(graphname) nTotal += g.GetN() commandLine.output('getGraph(%s) found %d points to process' % (graphname,nTotal)) for i in range(1,fileRange): rootfile = TFile(self.getFile(i),'READ') g2 = rootfile.Get(graphname) x = Double(0) y = Double(0) for j in range(0,g2.GetN()): counter += 1 if (counter % 10000 == 0): commandLine.printProgress(counter,nTotal) g2.GetPoint(j,x,y) graph.SetPoint(graph.GetN(),x,y) commandLine.printProgress(counter,nTotal) return graph
def fixpar(massmin, massmax, masspeak, range_signal): par_fix1 = Double(massmax-massmin) par_fix2 = Double(massmax+massmin) par_fix3 = Double(massmax*massmax*massmax-massmin*massmin*massmin) par_fix4 = Double(masspeak) par_fix5 = Double(range_signal) return par_fix1, par_fix2, par_fix3, par_fix4, par_fix5
def draw_l_shape( l_shape, best_tau, x_value, y_value, channel, variable ): total = l_shape.GetN() x_values = [] y_values = [] add_x = x_values.append add_y = y_values.append for i in range( 0, total ): x = Double( 0 ) y = Double( 0 ) l_shape.GetPoint( i, x, y ) add_x( x ) add_y( y ) plt.figure( figsize = ( 16, 16 ), dpi = 200, facecolor = 'white' ) plt.plot( x_values, y_values ) plt.xlabel( r'log10($\chi^2$)', fontsize = 40 ) plt.ylabel( 'log10(curvature)', fontsize = 40 ) ax = plt.axes() ax.annotate( r"$\tau = %.3g$" % best_tau, xy = ( x_value, y_value ), xycoords = 'data', xytext = ( 0.3, 0.3 ), textcoords = 'figure fraction', arrowprops = dict( arrowstyle = "fancy,head_length=0.4,head_width=0.4,tail_width=0.4", connectionstyle = "arc3" ), size = 40, ) if use_data: plt.savefig( 'plots/tau_from_L_shape_%s_channel_%s_DATA.png' % ( channel, variable ) ) else: plt.savefig( 'plots/tau_from_L_shape_%s_channel_%s_MC.png' % ( channel, variable ) )
def profile(self, parameter_name, bins=21, bound=2, args=None, subtract_min=False): if self.__gMinuit is None: raise MinimizerROOTTMinuitException("Need to perform a fit before calling profile()!") MAX_ITERATIONS = 6000 _error_code = Long(0) _minuit_id = Long(self.parameter_names.index(parameter_name) + 1) _par_min = Double(0) _par_err = Double(0) self.__gMinuit.GetParameter(_minuit_id - 1, _par_min, _par_err) _x = np.linspace(start=_par_min - bound * _par_err, stop=_par_min + bound * _par_err, num=bins, endpoint=True) self.__gMinuit.mnexcm("FIX", arr('d', [_minuit_id]), 1, _error_code) _y = np.zeros(bins) for i in range(bins): self.__gMinuit.mnexcm("SET PAR", arr('d', [_minuit_id, Double(_x[i])]), 2, _error_code) self.__gMinuit.mnexcm("MIGRAD", arr('d', [MAX_ITERATIONS, self.tolerance]), 2, _error_code) _y[i] = self.get_fit_info("fcn") self.__gMinuit.mnexcm("RELEASE", arr('d', [_minuit_id]), 1, _error_code) self._migrad() self.__gMinuit.mnexcm("SET PAR", arr('d', [_minuit_id, Double(_par_min)]), 2, _error_code) return np.asarray((_x, _y))
def normalize(self): """ Normalize S-curves. First point is at y=1., last point is at y=0. """ # List to store normalize graps graphs_normalized = [] for graph in self._scurves: # Last point of TGraph needed for normalization x_N = Double() y_N = Double() graph.GetPoint(graph.GetN() - 1, x_N, y_N) # Need arrays for TGraph constructor a_pts = array('d', range(0, graph.GetN())) a_nrm = array('d', []) for point in a_pts: # Use ROOT::Double() for x_n, y_n x_n1 = Double() y_n1 = Double() graph.GetPoint(int(point), x_n1, y_n1) # Normalize to 1 and invert a_nrm.append(-safe_divide(y_n1, y_N)) graphs_normalized.append(TGraph(len(a_pts), a_pts, a_nrm)) # Overwrite class member list self._scurves = graphs_normalized
def properTime(particle, vertex, fitter): tau = Double(-999999 / SystemOfUnits.picosecond) if vertex: error = Double(0.) chi2 = Double(0.) fitter.fit(vertex, particle, tau, error, chi2) return tau / SystemOfUnits.picosecond
def correctIncompleteShowers(fname, hnames, weights, limits): """ Arguments: -> fname: Name of the root file where the incomplete energy per layer distributions are stored. -> hnames: Name of the histograms to be corrected. -> weights: weights to correct the incomplete showers -> limits: limits on the x axis where the correction should stop being applied """ assert len(hnames) == len(weights) fIn = TFile.Open(fname) h = [] for i in hnames: h.append(fIn.Get(i)) correctedGraphs = [TGraph(h[i].GetNbinsX()) for i in range(len(h))] g = RootHistograms(h).toGraph() g = RootGraphs(g) ilim = -1 for it,ig in enumerate(g.getObjects()): if ilim%3 == 0: ilim += 1 for j in range(ig.GetN()): x, y = Double(0.), Double(0.) #pass by reference ig.GetPoint(j,x,y) if x <= limits[ilim] and weights[it][j] != 0: correctedGraphs[it].SetPoint(j, x, y/weights[it][j]) else: correctedGraphs[it].SetPoint(j, x, y) return correctedGraphs
def getVariationGraph(graph): varGraph = graph.Clone() for iPoint in xrange(0, graph.GetN()): # Retrieve points graphPointX = Double(0) graphPointY = Double(0) graphErrorX = graph.GetErrorX(iPoint) graphErrorY = graph.GetErrorY(iPoint) graph.GetPoint(iPoint, graphPointX, graphPointY) newPoint = Double(0) newPoint = fabs(1 - graphPointY) newPointErrorX = graphErrorX newPointErrorY = graphErrorY #set the point in the new plot varGraph.SetPoint(iPoint, graphPointX, newPoint) varGraph.SetPointError(iPoint, newPointErrorX, newPointErrorY) return varGraph
def addHistToTGraphPoisson(self, h, g, w=1.): for i in range(0, g.GetN()): # shifted by +1, i.e. over/underflow err = h.GetBinError(i + 1) y = h.GetBinContent(i + 1) binWidth = h.GetBinWidth(i + 1) # From https://twiki.cern.ch/twiki/bin/view/CMS/PoissonErrorBars alpha = 1. - 0.6827 n = int( round(y * binWidth / w)) # Round is necessary due to, well, rounding errors l = Math.gamma_quantile(alpha / 2., n, 1.) if n != 0. else 0. u = Math.gamma_quantile_c(alpha, n + 1, 1) if n != 0. else 0. g.SetPointEYlow( i, math.sqrt(((n - l) / binWidth * w)**2 + g.GetErrorYlow(i)**2)) g.SetPointEYhigh( i, math.sqrt(((u - n) / binWidth * w)**2 + g.GetErrorYhigh(i)**2)) gx = Double(0.) gy = Double(0.) g.GetPoint(i, gx, gy) g.SetPoint(i, gx, y + gy)
def shiftAlongX(tGraph, numberOfGraphs, index): for binNumber in xrange(tGraph.GetN()): x = Double(-1) y = Double(-1) tGraph.GetPoint(binNumber, x, y) shift = (tGraph.GetErrorXhigh(binNumber)) / (numberOfGraphs + 1) x = x + shift * index tGraph.SetPoint(binNumber, x, y)
def test1MinuitFit(self): """Test minuit callback and fit""" # setup minuit and callback gMinuit = TMinuit(5) gMinuit.SetPrintLevel(-1) # quiet gMinuit.SetGraphicsMode(ROOT.kFALSE) gMinuit.SetFCN(fcn) arglist = array('d', 10 * [0.]) ierflg = Long() arglist[0] = 1 gMinuit.mnexcm("SET ERR", arglist, 1, ierflg) # set starting values and step sizes for parameters vstart = array('d', [3, 1, 0.1, 0.01]) step = array('d', [0.1, 0.1, 0.01, 0.001]) gMinuit.mnparm(0, "a1", vstart[0], step[0], 0, 0, ierflg) gMinuit.mnparm(1, "a2", vstart[1], step[1], 0, 0, ierflg) gMinuit.mnparm(2, "a3", vstart[2], step[2], 0, 0, ierflg) gMinuit.mnparm(3, "a4", vstart[3], step[3], 0, 0, ierflg) # now ready for minimization step arglist[0] = 500 arglist[1] = 1. gMinuit.mnexcm("MIGRAD", arglist, 2, ierflg) # verify results amin, edm, errdef = Double(), Double(), Double() nvpar, nparx, icstat = Long(), Long(), Long() gMinuit.mnstat(amin, edm, errdef, nvpar, nparx, icstat) # gMinuit.mnprin( 3, amin ) self.assertEqual(nvpar, 4) self.assertEqual(nparx, 4) # success means that full covariance matrix is available (icstat==3) self.assertEqual(icstat, 3) # check results (somewhat debatable ... ) par, err = Double(), Double() gMinuit.GetParameter(0, par, err) self.assertEqual(round(par - 2.15, 2), 0.) self.assertEqual(round(err - 0.10, 2), 0.) gMinuit.GetParameter(1, par, err) self.assertEqual(round(par - 0.81, 2), 0.) self.assertEqual(round(err - 0.25, 2), 0.) gMinuit.GetParameter(2, par, err) self.assertEqual(round(par - 0.17, 2), 0.) self.assertEqual(round(err - 0.40, 2), 0.) gMinuit.GetParameter(3, par, err) self.assertEqual(round(par - 0.10, 2), 0.) self.assertEqual(round(err - 0.16, 2), 0.)