Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
makeQuickModel.py
Go to the documentation of this file.
1#!/usr/bin/env python
2#
3# A pyROOT script that allows one to
4# make quick measuremenst.
5#
6# This is a command-line script that
7# takes in signal and background values,
8# as well as potentially uncertainties on those
9# values, and returns a fitted signal value
10# and errors
11
12
13def main():
14 """ Create a simple model and run statistical tests
15
16 This script can be used to make simple statistical using histfactory.
17 It takes values for signal, background, and data as input, and
18 can optionally take uncertainties on signal or background.
19 The model is created and saved to an output ROOT file, and
20 the model can be fit if requested.
21
22 """
23
24 # Let's parse the input
25 # Define the command line options of the script:
26 import optparse
27 desc = " ".join(main.__doc__.split())
28
29 vers = "0.1"
30 parser = optparse.OptionParser( description = desc, version = vers, usage = "%prog [options]" )
31
32 parser.add_option( "-s", "--signal", dest = "signal",
33 action = "store", type = "float", default=None,
34 help = "Expected Signal" )
35
36 parser.add_option( "-b", "--background", dest = "background",
37 action = "store", type = "float", default=None,
38 help = "Expected Background" )
39
40 parser.add_option( "-d", "--data", dest = "data",
41 action = "store", type = "float", default=None,
42 help = "Measured data" )
43
44 parser.add_option( "--signal-uncertainty", dest = "signal_uncertainty",
45 action = "store", type = "float", default=None,
46 help = "Uncertainty on the signal rate, as a fraction. --signal-uncertainty=.05 means a 5% uncertainty." )
47
48 parser.add_option( "--background-uncertainty", dest = "background_uncertainty",
49 action = "store", type = "float", default=None,
50 help = "Uncertainty on the background rate, as a fraction, not a percentage. --background-uncertainty=.05 means a 5% uncertainty." )
51
52 parser.add_option( "--output-prefix", dest = "output_prefix",
53 action = "store", type = "string", default="Measurement",
54 help = "Prefix for output files when using export. Can include directories (ie 'MyDirectory/MyPrefix')" )
55
56 parser.add_option( "-e", "--export", dest = "export",
57 action = "store_true", default=False,
58 help = "Make output plots, graphs, and save the workspace." )
59
60 # Parse the command line options:
61 ( options, unknown ) = parser.parse_args()
62
63 # Make a log
64 # Set the format of the log messages:
65 FORMAT = 'Py:%(name)-25s %(levelname)-8s %(message)s'
66 import logging
67 logging.basicConfig( format = FORMAT )
68 # Create the logger object:
69 logger = logging.getLogger( "makeQuickMeasurement" )
70 # Set the following to DEBUG when debugging the scripts:
71 logger.setLevel( logging.INFO )
72
73 # So a small sanity check:
74 if len( unknown ):
75 logger.warning( "Options(s) not recognised: [" + ",".join( unknown ) + "]" )
76
77 # Ensure that all necessary input has been supplied
78 if options.signal == None:
79 logger.error( "You have to define a value for expacted signal (use --signal)" )
80 return 255
81
82 if options.background == None:
83 logger.error( "You have to define a value for expacted background (use --background)" )
84 return 255
85
86 if options.data == None:
87 logger.error( "You have to define a value for measured data (use --data)" )
88 return 255
89
90
91 # Okay, if all input is acceptable, we simply pass
92 # it to the MakeSimpleMeasurement function, which
93 # does the real work.
94
95 MakeSimpleMeasurement( signal_val=options.signal, background_val=options.background, data_val=options.data,
96 signal_uncertainty=options.signal_uncertainty, background_uncertainty=options.background_uncertainty,
97 Export=options.export, output_prefix=options.output_prefix)
98 return
99
100
101def MakeSimpleMeasurement( signal_val, background_val, data_val, signal_uncertainty=None, background_uncertainty=None,
102 Export=False, output_prefix="Measurement"):
103 """ Make a simple measurement using HistFactory
104
105 Take in simple values for signal, background data,
106 and potentially uncertainty on signal and background
107
108 """
109
110 try:
111 import ROOT
112 except ImportError:
113 print("It seems that pyROOT isn't properly configured")
114 return
115
116 # Create and name a measurement
117 # Set the Parameter of interest, and set several
118 # other parameters to be constant
119 meas = ROOT.RooStats.HistFactory.Measurement("meas", "meas")
120 meas.SetOutputFilePrefix( output_prefix )
121 meas.SetPOI( "SigXsecOverSM" )
122
123 # We don't include Lumi here,
124 # but since HistFactory gives it to
125 # us for free, we set it constant
126 # The values are just dummies
127
128 meas.SetLumi( 1.0 )
129 meas.SetLumiRelErr( 0.10 )
130 meas.AddConstantParam("Lumi")
131
132 # We set ExportOnly to false. This parameter
133 # defines what happens when we run MakeMeasurementAndModelFast
134 # If we DO run that function, we also want it to export.
135 meas.SetExportOnly( False )
136
137 # Create a channel and set
138 # the measured value of data
139 # (no external hist necessary for cut-and-count)
140 chan = ROOT.RooStats.HistFactory.Channel( "channel" )
141 chan.SetData( data_val )
142
143 # Create the signal sample and set it's value
144 signal = ROOT.RooStats.HistFactory.Sample( "signal" )
145 signal.SetNormalizeByTheory( False )
146 signal.SetValue( signal_val )
147 #signal.SetValue( 10 )
148
149 # Add the parameter of interest and a systematic
150 # Try to make intelligent choice of upper bound
151 import math
152 upper_bound = 3*math.ceil( (data_val - background_val) / signal_val )
153 upper_bound = max(upper_bound, 3)
154 signal.AddNormFactor( "SigXsecOverSM", 1, 0, upper_bound )
155
156 # If we have a signal uncertainty, add it too
157 if signal_uncertainty != None:
158 uncertainty_up = 1.0 + signal_uncertainty
159 uncertainty_down = 1.0 - signal_uncertainty
160 signal.AddOverallSys( "signal_uncertainty", uncertainty_down, uncertainty_up )
161
162 # Finally, add this sample to the channel
163 chan.AddSample( signal )
164
165 # Create a background sample
166 background = ROOT.RooStats.HistFactory.Sample( "background" )
167 background.SetNormalizeByTheory( False )
168 background.SetValue( background_val )
169
170 # If we have a background uncertainty, add it too
171 if background_uncertainty != None:
172 uncertainty_up = 1.0 + background_uncertainty
173 uncertainty_down = 1.0 - background_uncertainty
174 background.AddOverallSys( "background_uncertainty", uncertainty_down, uncertainty_up )
175
176 # Finally, add this sample to the channel
177 chan.AddSample( background )
178
179 # Add this channel to the measurement
180 # There is only this one channel, after all
181 meas.AddChannel( chan )
182
183 # Now, do the measurement
184 if Export:
185 workspace = ROOT.RooStats.HistFactory.MakeModelAndMeasurementFast( meas )
186 return workspace
187
188 else:
189 factory = ROOT.RooStats.HistFactory.HistoToWorkspaceFactoryFast()
190 workspace = factory.MakeCombinedModel( meas )
191 #workspace = ROOT.RooStats.HistFactory.HistoToWorkspaceFactoryFast.MakeCombinedModel( meas )
192 ROOT.RooStats.HistFactory.FitModel( workspace )
193
194 # At this point, we are done
195 return
196
197
198if __name__ == "__main__":
199 main()
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
main()
Create a simple model and run statistical tests
MakeSimpleMeasurement(signal_val, background_val, data_val, signal_uncertainty=None, background_uncertainty=None, Export=False, output_prefix="Measurement")
Make a simple measurement using HistFactory.