diff --git a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/CMakeLists.txt b/AtlasTest/DatabaseTest/AthenaPoolMultiTest/CMakeLists.txt index a7fb457b335839975438997baec4ee4949dd90ba..7654abe0716eb8109608a4bf6b841d7ab7f8f78c 100644 --- a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/CMakeLists.txt +++ b/AtlasTest/DatabaseTest/AthenaPoolMultiTest/CMakeLists.txt @@ -47,12 +47,6 @@ athenapoolmultitest_run_test( AthenaPoolMultiTestEventNoSplit EventNoSplit_jo athenapoolmultitest_run_test( AthenaPoolMultiTestPropagate DecisionPropagation_jo post_check_p DEPENDS AthenaPoolMultiTestEventSplitDecision ) -athenapoolmultitest_run_test( AthenaPoolMultiTestStreamSelect CheckStreamSelector_jo - post_check_ss - DEPENDS AthenaPoolMultiTestEventSplitDecision ) -athenapoolmultitest_run_test( AthenaPoolMultiTestPropagateSelect CheckStreamPropagate_jo - post_check_ss - DEPENDS AthenaPoolMultiTestPropagate ) #athenapoolmultitest_run_test( AthenaPoolMultiTestCheckNull CheckNull_jo # post_check_cn # DEPENDS AthenaPoolMultiTestEventSplit ) diff --git a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/AthenaPoolMultiTestPropagateSelect.ref b/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/AthenaPoolMultiTestPropagateSelect.ref deleted file mode 100644 index f3b45fbf61d1f2b7f7e7b9f4a5231e876bdfb7d8..0000000000000000000000000000000000000000 --- a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/AthenaPoolMultiTestPropagateSelect.ref +++ /dev/null @@ -1,281 +0,0 @@ -ReadData INFO in initialize() -EventSelector.S... DEBUG Property update for OutputLevel : new value = 2 -EventSelector.S... DEBUG ... postInitialize -EventSelector INFO EventSelection with query -AthenaEventLoopMgr INFO Setup EventSelector service EventSelector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 0 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1.2 y = -2.3 z = 226.6 detector = DummyHitDetector -ReadData INFO Hit x = 4.4 y = -8.0 z = 94.7 detector = DummyHitDetector -ReadData INFO Hit x = 7.6 y = -13.7 z = 70.2 detector = DummyHitDetector -ReadData INFO Hit x = 10.8 y = -19.3 z = 59.9 detector = DummyHitDetector -ReadData INFO Hit x = 14.0 y = -25.0 z = 54.2 detector = DummyHitDetector -ReadData INFO Hit x = 17.2 y = -30.7 z = 50.6 detector = DummyHitDetector -ReadData INFO Hit x = 20.4 y = -36.4 z = 48.1 detector = DummyHitDetector -ReadData INFO Hit x = 23.7 y = -42.0 z = 46.3 detector = DummyHitDetector -ReadData INFO Hit x = 26.9 y = -47.7 z = 44.9 detector = DummyHitDetector -ReadData INFO Hit x = 30.1 y = -53.4 z = 43.8 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 3 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 4 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 5 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 6 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 2 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 6 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 601.2 y = -2.3 z = -373.3 detector = DummyHitDetector -ReadData INFO Hit x = 604.4 y = -8.0 z = -505.2 detector = DummyHitDetector -ReadData INFO Hit x = 607.6 y = -13.7 z = -529.7 detector = DummyHitDetector -ReadData INFO Hit x = 610.8 y = -19.3 z = -540.0 detector = DummyHitDetector -ReadData INFO Hit x = 614.0 y = -25.0 z = -545.7 detector = DummyHitDetector -ReadData INFO Hit x = 617.2 y = -30.7 z = -549.3 detector = DummyHitDetector -ReadData INFO Hit x = 620.4 y = -36.4 z = -551.8 detector = DummyHitDetector -ReadData INFO Hit x = 623.7 y = -42.0 z = -553.6 detector = DummyHitDetector -ReadData INFO Hit x = 626.9 y = -47.7 z = -555.0 detector = DummyHitDetector -ReadData INFO Hit x = 630.1 y = -53.4 z = -556.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 2 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 8 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 2 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 9 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 3 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 9 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 901.2 y = -2.3 z = -673.3 detector = DummyHitDetector -ReadData INFO Hit x = 904.4 y = -8.0 z = -805.2 detector = DummyHitDetector -ReadData INFO Hit x = 907.6 y = -13.7 z = -829.7 detector = DummyHitDetector -ReadData INFO Hit x = 910.8 y = -19.3 z = -840.0 detector = DummyHitDetector -ReadData INFO Hit x = 914.0 y = -25.0 z = -845.7 detector = DummyHitDetector -ReadData INFO Hit x = 917.2 y = -30.7 z = -849.3 detector = DummyHitDetector -ReadData INFO Hit x = 920.4 y = -36.4 z = -851.8 detector = DummyHitDetector -ReadData INFO Hit x = 923.7 y = -42.0 z = -853.6 detector = DummyHitDetector -ReadData INFO Hit x = 926.9 y = -47.7 z = -855.0 detector = DummyHitDetector -ReadData INFO Hit x = 930.1 y = -53.4 z = -856.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 3 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 11 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 3 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 12 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 4 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 12 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1201.2 y = -2.3 z = -973.3 detector = DummyHitDetector -ReadData INFO Hit x = 1204.4 y = -8.0 z = -1105.2 detector = DummyHitDetector -ReadData INFO Hit x = 1207.6 y = -13.7 z = -1129.7 detector = DummyHitDetector -ReadData INFO Hit x = 1210.8 y = -19.3 z = -1140.0 detector = DummyHitDetector -ReadData INFO Hit x = 1214.0 y = -25.0 z = -1145.7 detector = DummyHitDetector -ReadData INFO Hit x = 1217.2 y = -30.7 z = -1149.3 detector = DummyHitDetector -ReadData INFO Hit x = 1220.4 y = -36.4 z = -1151.8 detector = DummyHitDetector -ReadData INFO Hit x = 1223.7 y = -42.0 z = -1153.6 detector = DummyHitDetector -ReadData INFO Hit x = 1226.9 y = -47.7 z = -1155.0 detector = DummyHitDetector -ReadData INFO Hit x = 1230.1 y = -53.4 z = -1156.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 4 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 14 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 4 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 15 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 5 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 15 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1501.2 y = -2.3 z = -1273.3 detector = DummyHitDetector -ReadData INFO Hit x = 1504.4 y = -8.0 z = -1405.2 detector = DummyHitDetector -ReadData INFO Hit x = 1507.6 y = -13.7 z = -1429.7 detector = DummyHitDetector -ReadData INFO Hit x = 1510.8 y = -19.3 z = -1440.0 detector = DummyHitDetector -ReadData INFO Hit x = 1514.0 y = -25.0 z = -1445.7 detector = DummyHitDetector -ReadData INFO Hit x = 1517.2 y = -30.7 z = -1449.3 detector = DummyHitDetector -ReadData INFO Hit x = 1520.4 y = -36.4 z = -1451.8 detector = DummyHitDetector -ReadData INFO Hit x = 1523.7 y = -42.0 z = -1453.6 detector = DummyHitDetector -ReadData INFO Hit x = 1526.9 y = -47.7 z = -1455.0 detector = DummyHitDetector -ReadData INFO Hit x = 1530.1 y = -53.4 z = -1456.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 6 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 16 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1601.2 y = -2.3 z = -1373.3 detector = DummyHitDetector -ReadData INFO Hit x = 1604.4 y = -8.0 z = -1505.2 detector = DummyHitDetector -ReadData INFO Hit x = 1607.6 y = -13.7 z = -1529.7 detector = DummyHitDetector -ReadData INFO Hit x = 1610.8 y = -19.3 z = -1540.0 detector = DummyHitDetector -ReadData INFO Hit x = 1614.0 y = -25.0 z = -1545.7 detector = DummyHitDetector -ReadData INFO Hit x = 1617.2 y = -30.7 z = -1549.3 detector = DummyHitDetector -ReadData INFO Hit x = 1620.4 y = -36.4 z = -1551.8 detector = DummyHitDetector -ReadData INFO Hit x = 1623.7 y = -42.0 z = -1553.6 detector = DummyHitDetector -ReadData INFO Hit x = 1626.9 y = -47.7 z = -1555.0 detector = DummyHitDetector -ReadData INFO Hit x = 1630.1 y = -53.4 z = -1556.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 6 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 18 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 7 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAllP -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 18 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1801.2 y = -2.3 z = -1573.3 detector = DummyHitDetector -ReadData INFO Hit x = 1804.4 y = -8.0 z = -1705.2 detector = DummyHitDetector -ReadData INFO Hit x = 1807.6 y = -13.7 z = -1729.7 detector = DummyHitDetector -ReadData INFO Hit x = 1810.8 y = -19.3 z = -1740.0 detector = DummyHitDetector -ReadData INFO Hit x = 1814.0 y = -25.0 z = -1745.7 detector = DummyHitDetector -ReadData INFO Hit x = 1817.2 y = -30.7 z = -1749.3 detector = DummyHitDetector -ReadData INFO Hit x = 1820.4 y = -36.4 z = -1751.8 detector = DummyHitDetector -ReadData INFO Hit x = 1823.7 y = -42.0 z = -1753.6 detector = DummyHitDetector -ReadData INFO Hit x = 1826.9 y = -47.7 z = -1755.0 detector = DummyHitDetector -ReadData INFO Hit x = 1830.1 y = -53.4 z = -1756.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 7 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector INFO skipping event 20 -EventSelector INFO Disconnecting input sourceID: B3D760F4-F874-B44B-AED4-78DE0A73D140 -ReadData INFO in finalize() diff --git a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/AthenaPoolMultiTestStreamSelect.ref b/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/AthenaPoolMultiTestStreamSelect.ref deleted file mode 100644 index 467cfa0fbdd7363044ed89c41194cd4443a76fa4..0000000000000000000000000000000000000000 --- a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/AthenaPoolMultiTestStreamSelect.ref +++ /dev/null @@ -1,458 +0,0 @@ -ReadData INFO in initialize() -EventSelector.S... DEBUG Property update for OutputLevel : new value = 2 -EventSelector.S... DEBUG Property update for OutputLevel : new value = 2 -EventSelector.S... DEBUG Property update for OutputLevel : new value = 2 -EventSelector.S... DEBUG ... postInitialize -EventSelector.S... DEBUG ... postInitialize -EventSelector.S... DEBUG ... postInitialize -EventSelector INFO EventSelection with query -AthenaEventLoopMgr INFO Setup EventSelector service EventSelector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 0 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1.2 y = -2.3 z = 226.6 detector = DummyHitDetector -ReadData INFO Hit x = 4.4 y = -8.0 z = 94.7 detector = DummyHitDetector -ReadData INFO Hit x = 7.6 y = -13.7 z = 70.2 detector = DummyHitDetector -ReadData INFO Hit x = 10.8 y = -19.3 z = 59.9 detector = DummyHitDetector -ReadData INFO Hit x = 14.0 y = -25.0 z = 54.2 detector = DummyHitDetector -ReadData INFO Hit x = 17.2 y = -30.7 z = 50.6 detector = DummyHitDetector -ReadData INFO Hit x = 20.4 y = -36.4 z = 48.1 detector = DummyHitDetector -ReadData INFO Hit x = 23.7 y = -42.0 z = 46.3 detector = DummyHitDetector -ReadData INFO Hit x = 26.9 y = -47.7 z = 44.9 detector = DummyHitDetector -ReadData INFO Hit x = 30.1 y = -53.4 z = 43.8 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 3 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 4 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 5 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 1 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 6 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 6 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 601.2 y = -2.3 z = -373.3 detector = DummyHitDetector -ReadData INFO Hit x = 604.4 y = -8.0 z = -505.2 detector = DummyHitDetector -ReadData INFO Hit x = 607.6 y = -13.7 z = -529.7 detector = DummyHitDetector -ReadData INFO Hit x = 610.8 y = -19.3 z = -540.0 detector = DummyHitDetector -ReadData INFO Hit x = 614.0 y = -25.0 z = -545.7 detector = DummyHitDetector -ReadData INFO Hit x = 617.2 y = -30.7 z = -549.3 detector = DummyHitDetector -ReadData INFO Hit x = 620.4 y = -36.4 z = -551.8 detector = DummyHitDetector -ReadData INFO Hit x = 623.7 y = -42.0 z = -553.6 detector = DummyHitDetector -ReadData INFO Hit x = 626.9 y = -47.7 z = -555.0 detector = DummyHitDetector -ReadData INFO Hit x = 630.1 y = -53.4 z = -556.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 2 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 2 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 8 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 2 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 2 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 9 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 3 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 3 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 9 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 901.2 y = -2.3 z = -673.3 detector = DummyHitDetector -ReadData INFO Hit x = 904.4 y = -8.0 z = -805.2 detector = DummyHitDetector -ReadData INFO Hit x = 907.6 y = -13.7 z = -829.7 detector = DummyHitDetector -ReadData INFO Hit x = 910.8 y = -19.3 z = -840.0 detector = DummyHitDetector -ReadData INFO Hit x = 914.0 y = -25.0 z = -845.7 detector = DummyHitDetector -ReadData INFO Hit x = 917.2 y = -30.7 z = -849.3 detector = DummyHitDetector -ReadData INFO Hit x = 920.4 y = -36.4 z = -851.8 detector = DummyHitDetector -ReadData INFO Hit x = 923.7 y = -42.0 z = -853.6 detector = DummyHitDetector -ReadData INFO Hit x = 926.9 y = -47.7 z = -855.0 detector = DummyHitDetector -ReadData INFO Hit x = 930.1 y = -53.4 z = -856.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 3 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 3 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 11 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 3 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 3 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 12 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 4 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 4 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 12 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1201.2 y = -2.3 z = -973.3 detector = DummyHitDetector -ReadData INFO Hit x = 1204.4 y = -8.0 z = -1105.2 detector = DummyHitDetector -ReadData INFO Hit x = 1207.6 y = -13.7 z = -1129.7 detector = DummyHitDetector -ReadData INFO Hit x = 1210.8 y = -19.3 z = -1140.0 detector = DummyHitDetector -ReadData INFO Hit x = 1214.0 y = -25.0 z = -1145.7 detector = DummyHitDetector -ReadData INFO Hit x = 1217.2 y = -30.7 z = -1149.3 detector = DummyHitDetector -ReadData INFO Hit x = 1220.4 y = -36.4 z = -1151.8 detector = DummyHitDetector -ReadData INFO Hit x = 1223.7 y = -42.0 z = -1153.6 detector = DummyHitDetector -ReadData INFO Hit x = 1226.9 y = -47.7 z = -1155.0 detector = DummyHitDetector -ReadData INFO Hit x = 1230.1 y = -53.4 z = -1156.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 4 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 4 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 14 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 4 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 4 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 15 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 5 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 5 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 15 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1501.2 y = -2.3 z = -1273.3 detector = DummyHitDetector -ReadData INFO Hit x = 1504.4 y = -8.0 z = -1405.2 detector = DummyHitDetector -ReadData INFO Hit x = 1507.6 y = -13.7 z = -1429.7 detector = DummyHitDetector -ReadData INFO Hit x = 1510.8 y = -19.3 z = -1440.0 detector = DummyHitDetector -ReadData INFO Hit x = 1514.0 y = -25.0 z = -1445.7 detector = DummyHitDetector -ReadData INFO Hit x = 1517.2 y = -30.7 z = -1449.3 detector = DummyHitDetector -ReadData INFO Hit x = 1520.4 y = -36.4 z = -1451.8 detector = DummyHitDetector -ReadData INFO Hit x = 1523.7 y = -42.0 z = -1453.6 detector = DummyHitDetector -ReadData INFO Hit x = 1526.9 y = -47.7 z = -1455.0 detector = DummyHitDetector -ReadData INFO Hit x = 1530.1 y = -53.4 z = -1456.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 6 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 6 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 16 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1601.2 y = -2.3 z = -1373.3 detector = DummyHitDetector -ReadData INFO Hit x = 1604.4 y = -8.0 z = -1505.2 detector = DummyHitDetector -ReadData INFO Hit x = 1607.6 y = -13.7 z = -1529.7 detector = DummyHitDetector -ReadData INFO Hit x = 1610.8 y = -19.3 z = -1540.0 detector = DummyHitDetector -ReadData INFO Hit x = 1614.0 y = -25.0 z = -1545.7 detector = DummyHitDetector -ReadData INFO Hit x = 1617.2 y = -30.7 z = -1549.3 detector = DummyHitDetector -ReadData INFO Hit x = 1620.4 y = -36.4 z = -1551.8 detector = DummyHitDetector -ReadData INFO Hit x = 1623.7 y = -42.0 z = -1553.6 detector = DummyHitDetector -ReadData INFO Hit x = 1626.9 y = -47.7 z = -1555.0 detector = DummyHitDetector -ReadData INFO Hit x = 1630.1 y = -53.4 z = -1556.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 6 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 6 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 18 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 7 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Accepting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 7 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -ReadData INFO EventStreamInfo: Number of events = 20 -ReadData INFO EventStreamInfo: ItemList: -ReadData INFO CLID = 2101, key = McEventInfo -ReadData INFO CLID = 9102, key = MyHits -ReadData INFO CLID = 1287802, key = ExcludeTestTrigMap -ReadData INFO CLID = 1287802, key = MultiTestTrigMap -ReadData INFO CLID = 38853911, key = EventInfoAux. -ReadData INFO CLID = 45903698, key = EventInfo -ReadData INFO CLID = 222376821, key = StreamAll2 -ReadData INFO EventType: Event type: sim/data - is sim , testbeam/atlas - is atlas , calib/physics - is physics -ReadData INFO TagInfo: -ReadData INFO EventInfo event: 18 run: 0 -ReadData INFO Get Smart data ptr 1 -ReadData INFO Could not find ExampleTrackContainer/MyTracks -ReadData INFO Hit x = 1801.2 y = -2.3 z = -1573.3 detector = DummyHitDetector -ReadData INFO Hit x = 1804.4 y = -8.0 z = -1705.2 detector = DummyHitDetector -ReadData INFO Hit x = 1807.6 y = -13.7 z = -1729.7 detector = DummyHitDetector -ReadData INFO Hit x = 1810.8 y = -19.3 z = -1740.0 detector = DummyHitDetector -ReadData INFO Hit x = 1814.0 y = -25.0 z = -1745.7 detector = DummyHitDetector -ReadData INFO Hit x = 1817.2 y = -30.7 z = -1749.3 detector = DummyHitDetector -ReadData INFO Hit x = 1820.4 y = -36.4 z = -1751.8 detector = DummyHitDetector -ReadData INFO Hit x = 1823.7 y = -42.0 z = -1753.6 detector = DummyHitDetector -ReadData INFO Hit x = 1826.9 y = -47.7 z = -1755.0 detector = DummyHitDetector -ReadData INFO Hit x = 1830.1 y = -53.4 z = -1756.1 detector = DummyHitDetector -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector1: For [Stream1] cutflow events = 7 -EventSelector INFO Request skipping event from: EventSelector.Selector1 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... DEBUG Rejecting event -EventSelector.S... DEBUG EventSelector.Selector2: For [Stream1] cutflow events = 7 -EventSelector INFO Request skipping event from: EventSelector.Selector2 -EventSelector.S... INFO StreamSelectorTool::postNext -EventSelector.S... DEBUG Found attribute list -EventSelector.S... ERROR Stream decision for [StreamX] does not exist in input -EventSelector.S... DEBUG EventSelector.SelectorX: For [StreamX] cutflow events = 0 -EventSelector INFO skipping event 20 -EventSelector INFO Disconnecting input sourceID: 0E8E08EE-13D0-BF40-BB78-56E53AEBF449 -ReadData INFO in finalize() diff --git a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/CheckStreamPropagate_jo.py b/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/CheckStreamPropagate_jo.py deleted file mode 100755 index af0ad699fb914bb5395e55d7f98bdb30d23924f7..0000000000000000000000000000000000000000 --- a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/CheckStreamPropagate_jo.py +++ /dev/null @@ -1,71 +0,0 @@ -## @file CheckExplicit_jo.py -## @brief TopOptions (but dependent SplittableData_jo.py, EventSplit_jo.py): -## Checks that the root collection is readable with the EventSelector -## @author Jack Cranshaw (Jack.Cranshaw@cern.ch) -## $Id: CheckExplicit_jo.py,v 1.9 2009-05-20 13:34:21 cranshaw Exp $ -############################################################### -# -# Job options file -# -#============================================================== - -#-------------------------------------------------------------- -# Event related parameters -#-------------------------------------------------------------- -from AthenaCommon.AlgSequence import AthSequencer -topSequence = AthSequencer("AthAlgSeq") -athRegSeq = AthSequencer("AthRegSeq") - -from AthenaCommon.AppMgr import theApp - -from AthenaCommon.AppMgr import ServiceMgr as svcMgr - -theApp.EvtMax = 200000 - -#-------------------------------------------------------------- -# Load POOL support -#-------------------------------------------------------------- -include( "AthenaPoolExampleConverter/AthenaPoolExampleConverter_jobOption.py" ) -include( "AthenaPoolTestAthenaPool/AthenaPoolTestAthenaPool_joboptions.py" ) -#-------------------------------------------------------------- -#--- Read portion ----- -#-------------------------------------------------------------- -import AthenaPoolCnvSvc.ReadAthenaPool - -from PoolSvc.PoolSvcConf import PoolSvc -svcMgr += PoolSvc() -PoolSvc = svcMgr.PoolSvc -PoolSvc.ReadCatalog = ["xmlcatalog_file:EventSplit.xml"] - -EventSelector = svcMgr.EventSelector -EventSelector.InputCollections = [ "AthenaPoolMultiTest_Propagate.root" ]; - -# Include the StreamSelectorTool -from EventBookkeeperTools.EventBookkeeperToolsConf import StreamSelectorTool -# Select existing Stream1 -selector1 = StreamSelectorTool("Selector1") -selector1.AcceptStreams = ["Stream1"] -selector1.OutputLevel = DEBUG -svcMgr.EventSelector.HelperTools += [selector1] - -#-------------------------------------------------------------- -# Configure the filters -#-------------------------------------------------------------- -from AthenaPoolExampleAlgorithms.AthenaPoolExampleAlgorithmsConf import AthPoolEx__ReadData - -topSequence += AthPoolEx__ReadData("ReadData") -#from AthenaPoolMultiTest.AthenaPoolMultiTestConf import EventTagReader - -from AthenaPoolMultiTest.AthenaPoolMultiTestConf import * - -#-------------------------------------------------------------- -# Set output level threshold (2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL) -#-------------------------------------------------------------- -svcMgr.MessageSvc.infoLimit = 5000 -svcMgr.MessageSvc.debugLimit = 5000 -svcMgr.MessageSvc.OutputLevel = INFO -#============================================================== -# -# End of job options file -# -############################################################### diff --git a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/CheckStreamSelector_jo.py b/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/CheckStreamSelector_jo.py deleted file mode 100755 index 170cd50a12bac06b18e798590e400bc9c6b4e776..0000000000000000000000000000000000000000 --- a/AtlasTest/DatabaseTest/AthenaPoolMultiTest/share/CheckStreamSelector_jo.py +++ /dev/null @@ -1,91 +0,0 @@ -## @file CheckExplicit_jo.py -## @brief TopOptions (but dependent SplittableData_jo.py, EventSplit_jo.py): -## Checks that the root collection is readable with the EventSelector -## @author Jack Cranshaw (Jack.Cranshaw@cern.ch) -## $Id: CheckExplicit_jo.py,v 1.9 2009-05-20 13:34:21 cranshaw Exp $ -############################################################### -# -# Job options file -# -#============================================================== - -#-------------------------------------------------------------- -# Event related parameters -#-------------------------------------------------------------- -from AthenaCommon.AlgSequence import AthSequencer -topSequence = AthSequencer("AthAlgSeq") -athRegSeq = AthSequencer("AthRegSeq") - -from AthenaCommon.AppMgr import theApp - -from AthenaCommon.AppMgr import ServiceMgr as svcMgr - -theApp.EvtMax = 200000 - -#-------------------------------------------------------------- -# Load POOL support -#-------------------------------------------------------------- -include( "AthenaPoolExampleConverter/AthenaPoolExampleConverter_jobOption.py" ) -include( "AthenaPoolTestAthenaPool/AthenaPoolTestAthenaPool_joboptions.py" ) -#-------------------------------------------------------------- -#--- Read portion ----- -#-------------------------------------------------------------- -import AthenaPoolCnvSvc.ReadAthenaPool - -from PoolSvc.PoolSvcConf import PoolSvc -svcMgr += PoolSvc() -PoolSvc = svcMgr.PoolSvc -PoolSvc.ReadCatalog = ["xmlcatalog_file:EventSplit.xml"] - -EventSelector = svcMgr.EventSelector -EventSelector.InputCollections = [ "AthenaPoolMultiTest_StreamAll2.root" ]; - -# Include the StreamSelectorTool -from EventBookkeeperTools.EventBookkeeperToolsConf import StreamSelectorTool -# Select existing Stream1 -selector1 = StreamSelectorTool("Selector1") -selector1.AcceptStreams = ["Stream1"] -selector1.OutputLevel = DEBUG -svcMgr.EventSelector.HelperTools += [selector1] - -# Select existing Stream1, but use a separate CutFlowSvc -# Create the CutFlowSvc instance(s) -from EventBookkeeperTools.EventBookkeeperToolsConf import CutFlowSvc -cfs = CfgMgr.CutFlowSvc("SS_CutFlowSvc") -svcMgr += cfs -cfs.InputStream = "StreamAll" -cfs.OutputCollName = "StreamSelect" -# -selector2 = StreamSelectorTool("Selector2") -selector2.AcceptStreams = ["Stream1"] -selector2.CutFlowSvc = cfs -selector2.OutputLevel = DEBUG -svcMgr.EventSelector.HelperTools += [selector2] - -# Select non-existing StreamX -selectorx = StreamSelectorTool("SelectorX") -selectorx.AcceptStreams = ["StreamX"] -selectorx.OutputLevel = DEBUG -svcMgr.EventSelector.HelperTools += [selectorx] - -#-------------------------------------------------------------- -# Configure the filters -#-------------------------------------------------------------- -from AthenaPoolExampleAlgorithms.AthenaPoolExampleAlgorithmsConf import AthPoolEx__ReadData - -topSequence += AthPoolEx__ReadData("ReadData") -#from AthenaPoolMultiTest.AthenaPoolMultiTestConf import EventTagReader - -from AthenaPoolMultiTest.AthenaPoolMultiTestConf import * - -#-------------------------------------------------------------- -# Set output level threshold (2=DEBUG, 3=INFO, 4=WARNING, 5=ERROR, 6=FATAL) -#-------------------------------------------------------------- -svcMgr.MessageSvc.infoLimit = 5000 -svcMgr.MessageSvc.debugLimit = 5000 -svcMgr.MessageSvc.OutputLevel = INFO -#============================================================== -# -# End of job options file -# -############################################################### diff --git a/Calorimeter/CaloRec/src/CaloClusterMomentsMaker.cxx b/Calorimeter/CaloRec/src/CaloClusterMomentsMaker.cxx index 2f3dbf5ff1eab7f1f74f41681ccdff2d8544200a..5c679d82e58c506c0e4c76db932c49fea9ee2a8a 100644 --- a/Calorimeter/CaloRec/src/CaloClusterMomentsMaker.cxx +++ b/Calorimeter/CaloRec/src/CaloClusterMomentsMaker.cxx @@ -26,9 +26,10 @@ #include "CaloGeoHelpers/CaloPhiRange.h" #include "CaloIdentifier/CaloCell_ID.h" #include "AthAllocators/ArenaPoolSTLAllocator.h" -//#include "CxxUtils/unordered_set.h" -#include "CLHEP/Geometry/Point3D.h" -#include "CLHEP/Geometry/Vector3D.h" + +#include "GeoPrimitives/GeoPrimitives.h" +#include "GeoPrimitives/GeoPrimitivesHelpers.h" + #include "CLHEP/Units/SystemOfUnits.h" #include "CxxUtils/prefetch.h" #include <Eigen/Dense> @@ -38,9 +39,6 @@ #include <limits> #include <sstream> - -using HepGeom::Vector3D; -using HepGeom::Point3D; using CLHEP::deg; using CLHEP::cm; @@ -529,7 +527,7 @@ CaloClusterMomentsMaker::execute(const EventContext& ctx, xc/=w; yc/=w; zc/=w; - Point3D<double> showerCenter(xc,yc,zc); + Amg::Vector3D showerCenter(xc,yc,zc); w=0; @@ -538,8 +536,8 @@ CaloClusterMomentsMaker::execute(const EventContext& ctx, // shower axis is just the vector pointing from the IP to the shower center // in case there are less than 3 cells in the cluster - Vector3D<double> showerAxis(xc,yc,zc); - showerAxis.setMag(1); + Amg::Vector3D showerAxis(xc,yc,zc); + Amg::setMag(showerAxis,1.0); // otherwise the principal direction with the largest absolute // eigenvalue will be used unless it's angle w.r.t. the vector pointing @@ -563,17 +561,8 @@ CaloClusterMomentsMaker::execute(const EventContext& ctx, C(2,2) += e2*(ci.z-zc)*(ci.z-zc); w += e2; } - - //Symmetrize matrix (Eigen has not symmetric matrix class) - C(0,1)=C(1,0); - C(0,2)=C(2,0); - C(1,2)=C(2,1); C/=w; - - //HepSymMatrix S(C); - //HepMatrix U = diagonalize(&S); - Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigensolver(C); if (eigensolver.info() != Eigen::Success) { msg(MSG::WARNING) << "Failed to compute Eigenvalues -> Can't determine shower axis" << endmsg; @@ -589,26 +578,24 @@ CaloClusterMomentsMaker::execute(const EventContext& ctx, if ( !( std::abs(S[0]) < epsilon || std::abs(S[1]) < epsilon || std::abs(S[2]) < epsilon ) ) { - Vector3D<double> prAxis(showerAxis); + Amg::Vector3D prAxis(showerAxis); int iEigen = -1; for (i=0;i<3;i++) { - if ( S[i] != 0 ) { - Vector3D<double> tmpAxis = Vector3D<double>(U(0,i),U(1,i),U(2,i)); + Amg::Vector3D tmpAxis=U.col(i); + + // calculate the angle + double tmpAngle=Amg::angle(tmpAxis,showerAxis); - // calculate the angle - - double tmpAngle = tmpAxis.angle(showerAxis); - if ( tmpAngle > 90*deg ) { - tmpAngle = 180*deg - tmpAngle; - tmpAxis = -tmpAxis; - } + if ( tmpAngle > 90*deg ) { + tmpAngle = 180*deg - tmpAngle; + tmpAxis = -tmpAxis; + } - if ( iEigen == -1 || tmpAngle < angle ) { - iEigen = i; - angle = tmpAngle; - prAxis = tmpAxis; - } + if ( iEigen == -1 || tmpAngle < angle ) { + iEigen = i; + angle = tmpAngle; + prAxis = tmpAxis; } }//end for loop @@ -620,28 +607,32 @@ CaloClusterMomentsMaker::execute(const EventContext& ctx, // check the angle - if ( angle < m_maxAxisAngle ) + if ( angle < m_maxAxisAngle ) { showerAxis = prAxis; + } else - ATH_MSG_DEBUG("principal Direction (" << prAxis.x() << ", " - << prAxis.y() << ", " << prAxis.z() << ") deviates more than " + ATH_MSG_DEBUG("principal Direction (" << prAxis[Amg::x] << ", " + << prAxis[Amg::y] << ", " << prAxis[Amg::z] << ") deviates more than " << m_maxAxisAngle*(1./deg) - << " deg from IP-to-ClusterCenter-axis (" << showerAxis.x() << ", " - << showerAxis.y() << ", " << showerAxis.z() << ")"); - }//end if !S[i]==0 - }// end else got Eigenvalues + << " deg from IP-to-ClusterCenter-axis (" << showerAxis[Amg::x] << ", " + << showerAxis[Amg::y] << ", " << showerAxis[Amg::z] << ")"); + }//end if fabs(S)<epsilon + else { + ATH_MSG_DEBUG("Eigenvalues close to 0, do not use principal axis"); + } + }//end got eigenvalues } //end if ncell>2 - ATH_MSG_DEBUG("Shower Axis = (" << showerAxis.x() << ", " - << showerAxis.y() << ", " << showerAxis.z() << ")"); + ATH_MSG_DEBUG("Shower Axis = (" << showerAxis[Amg::x] << ", " + << showerAxis[Amg::y] << ", " << showerAxis[Amg::z] << ")"); + // calculate radial distance from and the longitudinal distance // along the shower axis for each cell. The cluster center is // at r=0 and lambda=0 - for(i=0;i<ncell;i++) { - CaloClusterMomentsMaker_detail::cellinfo& ci = cellinfo[i]; - Point3D<double> currentCell(ci.x,ci.y,ci.z); + for (auto& ci : cellinfo) { + const Amg::Vector3D currentCell(ci.x,ci.y,ci.z); // calculate distance from shower axis r ci.r = ((currentCell-showerCenter).cross(showerAxis)).mag(); // calculate distance from shower center along shower axis @@ -654,11 +645,11 @@ CaloClusterMomentsMaker::execute(const EventContext& ctx, double commonNorm = 0; double phi0 = ncell > 0 ? cellinfo[0].phi : 0; - for(i=0;i<ncell;i++) { - const CaloClusterMomentsMaker_detail::cellinfo& ci = cellinfo[i]; + for(unsigned i=0;i<ncell;i++) { + const CaloClusterMomentsMaker_detail::cellinfo& ci = cellinfo[i]; // loop over all valid moments commonNorm += ci.energy; - for(size_t iMoment = 0, size = m_validMoments.size(); + for(size_t iMoment = 0, size = m_validMoments.size(); iMoment != size; ++ iMoment) { diff --git a/Event/EventBookkeeperTools/src/StreamSelectorTool.cxx b/Event/EventBookkeeperTools/src/StreamSelectorTool.cxx deleted file mode 100644 index 04cf7c636959913c7dab538d1ae0d12e40c97c5a..0000000000000000000000000000000000000000 --- a/Event/EventBookkeeperTools/src/StreamSelectorTool.cxx +++ /dev/null @@ -1,124 +0,0 @@ -/* - Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration -*/ - -/** @file StreamSelectorTool.cxx - * @brief This file contains the implementation for the StreamSelectorTool class. - * $Id: StreamSelectorTool.cxx,v 1.5 2009-03-17 09:44:46 cranshaw Exp $ - **/ -#include <algorithm> - -#include "GaudiKernel/ServiceHandle.h" -#include "StoreGate/StoreGateSvc.h" - -#include "StreamSelectorTool.h" -#include "PersistentDataModel/AthenaAttributeList.h" -#include "xAODCutFlow/CutBookkeeperContainer.h" - -//___________________________________________________________________________ -StreamSelectorTool::StreamSelectorTool(const std::string& type, const std::string& name, const IInterface* parent) : - AthAlgTool(type, name, parent), - m_cutflow("CutFlowSvc/CutFlowSvc",name) -{ - declareInterface<IAthenaSelectorTool>(this); - declareProperty("CutFlowSvc", m_cutflow, - "handle to the ICutFlowSvc instance this filtering algorithm" - " will use for building the flow of cuts."); - declareProperty("AcceptStreams",m_streamName,"Name of stream to be used as a ACCEPT, defaluts to ALL"); - declareProperty("VetoStreams",m_unstreamName,"Name of stream to be used as a VETO, defaluts to ALL"); -} -//___________________________________________________________________________ -StreamSelectorTool::~StreamSelectorTool() { -} - -//__________________________________________________________________________ -StatusCode StreamSelectorTool::postInitialize() { - ATH_MSG_DEBUG("... postInitialize"); - - ATH_CHECK(m_cutflow.retrieve()); - m_cutid = m_cutflow->registerFilter(this->name(),"Stream selection"); - if (0 == m_cutid) { - ATH_MSG_WARNING("Unable to register filter tool"); - } - - return StatusCode::SUCCESS; -} -//__________________________________________________________________________ -StatusCode StreamSelectorTool::postNext() const { - ATH_MSG_INFO("StreamSelectorTool::postNext"); - - StatusCode retc = StatusCode::SUCCESS; - - // if default, just return immediately - //if (m_streamName.size()>0 && m_streamName[0]=="ALL") return retc; - - // Use attribute list to filter on selected stream - const DataHandle<AthenaAttributeList> attrList; - StatusCode sc = evtStore()->retrieve(attrList,m_attrListKey); - if (sc.isSuccess()) { - ATH_MSG_DEBUG("Found attribute list"); - // fill the input bookkeeper - float weight = (*attrList)["EventWeight"].data<float>(); - // Search for stream name in attribute list, and check flag - for (auto sel = m_streamName.begin(); sel != m_streamName.end(); ++sel) { - // check veto - if ( attrList->specification().exists(*sel) ) { - bool dec(false); - bool veto(false); - // First check for vetoes - for (auto ivet = m_unstreamName.begin(); ivet != m_unstreamName.end(); ++ivet) { - try { - if ((*attrList)[*ivet].data<bool>()) { - ATH_MSG_DEBUG("Stream " << *ivet << " vetoed event"); - veto=true; - break; - } - } - catch (...) { - ATH_MSG_WARNING("Unable to access " << m_streamName << " decision"); - } - } - // if not vetoed, then look for accept - if (!veto) { - try { - dec = (*attrList)[*sel].data<bool>(); - } - catch (...) { - ATH_MSG_WARNING("Unable to access " << m_streamName << " decision"); - } - } else { - // exit loop as reject if already vetoed - retc = StatusCode::RECOVERABLE; - break; - } - // if not vetoed and decision found in attribute list - if (dec!=true) { - // Rejecting event - retc = StatusCode::RECOVERABLE; - ATH_MSG_DEBUG("Rejecting event"); - } else { - // Accepting event - ATH_MSG_DEBUG("Accepting event"); - m_cutflow->addEvent(m_cutid,weight); - } - } else { - ATH_MSG_ERROR("Stream decision for " << m_streamName << " does not exist in input"); - } - } - - uint64_t nAcceptedEvents = m_cutflow->getNAcceptedEvents(m_cutid); - if (nAcceptedEvents != std::numeric_limits<uint64_t>::max()) { - ATH_MSG_DEBUG(name() << ": For " << m_streamName << " cutflow events = " << nAcceptedEvents); - } - } - else { - ATH_MSG_WARNING("Could not find attribute list for " << m_attrListKey); - ATH_MSG_ERROR("Cannot do attributelist bookkeeping"); - } - return retc; -} -//__________________________________________________________________________ -StatusCode StreamSelectorTool::preNext() const { - return(StatusCode::SUCCESS); -} -//__________________________________________________________________________ diff --git a/Event/EventBookkeeperTools/src/StreamSelectorTool.h b/Event/EventBookkeeperTools/src/StreamSelectorTool.h deleted file mode 100644 index cc254b570fd6900c4624579ce05000efe5074392..0000000000000000000000000000000000000000 --- a/Event/EventBookkeeperTools/src/StreamSelectorTool.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef STREAMSELECTORTOOL_H -#define STREAMSELECTORTOOL_H - -/** @file StreamSelectorTool.h - * @brief This file contains the class definition for the StreamSelectorTool class. - * $Id: StreamSelectorTool.h,v 1.1 2008-12-10 21:28:11 gemmeren Exp $ - **/ - -#include "GaudiKernel/ServiceHandle.h" -#include "AthenaKernel/IAthenaSelectorTool.h" -#include "AthenaKernel/ICutFlowSvc.h" -#include "AthenaBaseComps/AthAlgTool.h" - -#include <string> - -/** @class StreamSelectorTool - * @brief This class provides an example for reading with a ISelectorTool to veto events on AttributeList. - **/ -class StreamSelectorTool : public AthAlgTool, virtual public IAthenaSelectorTool { -public: // Constructor and Destructor - /// Standard Service Constructor - StreamSelectorTool(const std::string& type, const std::string& name, const IInterface* parent); - /// Destructor - virtual ~StreamSelectorTool(); - -public: - /// IAthenaSelectorTool Interface method implementations: - virtual StatusCode initialize(); - virtual StatusCode postInitialize(); - virtual StatusCode preNext() const; - virtual StatusCode postNext() const; - virtual StatusCode preFinalize(); - virtual StatusCode finalize(); -private: - StringProperty m_attrListKey{this,"AttributeListKey","Input","Key for attribute list input to be used"}; - //StringArrayProperty m_streamName{this,"SelectedStreams","ALL","Name of stream to be used as a ACCEPT, defaluts to ALL"}; - //StringArrayProperty m_unstreamName{this,"DeselectedStreams","ALL","Name of stream to be used as a VETO, defaluts to ALL"}; - std::vector<std::string> m_streamName; - std::vector<std::string> m_unstreamName; - - ServiceHandle<ICutFlowSvc> m_cutflow; - CutIdentifier m_cutid; -}; - -inline StatusCode StreamSelectorTool::initialize() {return StatusCode::SUCCESS;} -inline StatusCode StreamSelectorTool::preFinalize() {return StatusCode::SUCCESS;} -inline StatusCode StreamSelectorTool::finalize() {return StatusCode::SUCCESS;} - -#endif diff --git a/Event/EventBookkeeperTools/src/components/EventBookkeeperTools_entries.cxx b/Event/EventBookkeeperTools/src/components/EventBookkeeperTools_entries.cxx index b7db38a32ec98559f760b6c3ece96e57462184b6..a2bb0fb8664b2a275a48e00ed6f5212bbc04db6a 100644 --- a/Event/EventBookkeeperTools/src/components/EventBookkeeperTools_entries.cxx +++ b/Event/EventBookkeeperTools/src/components/EventBookkeeperTools_entries.cxx @@ -5,7 +5,6 @@ #include "../CutFlowSvc.h" #include "../EventCounterAlg.h" #include "../SkimDecisionMultiFilter.h" -#include "../StreamSelectorTool.h" #include "../TestFilterReentrantAlg.h" DECLARE_COMPONENT( AllExecutedEventsCounterAlg ) @@ -14,5 +13,4 @@ DECLARE_COMPONENT( BookkeeperTool ) DECLARE_COMPONENT( CutFlowSvc ) DECLARE_COMPONENT( EventCounterAlg ) DECLARE_COMPONENT( SkimDecisionMultiFilter ) -DECLARE_COMPONENT( StreamSelectorTool ) DECLARE_COMPONENT( TestFilterReentrantAlg ) diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/CMakeLists.txt b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/CMakeLists.txt index 9d568ba0a74c2e88e9e25df5b91ca1753f3ac1fb..1a8fd7212e75859d7909ebd4377d99b0a6891be1 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopDataPreparation ) @@ -7,9 +6,8 @@ find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopDataPreparation _cintDictSource - ROOT_HEADERS TopDataPreparation/SampleXsection.h - TopDataPreparation/SampleXsectionSvc.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopDataPreparation Root/*.cxx Root/*.h Root/*.icc diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/LinkDef.h index 287a5ea504c181aded18fee120700fe53278c8bf..a28d094e3236ac5164b5dfb388e12279addd5d50 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/LinkDef.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifdef __CINT__ #pragma extra_include "TopDataPreparation/SampleXsection.h"; diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SamplePDF.cxx b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SamplePDF.cxx index 8536dec6b3f4b2ebc25b7ca59d5674d6455400aa..551b7f53d517bb5072b1a0636e0e13d246e7b563 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SamplePDF.cxx +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SamplePDF.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include <fstream> #include <sstream> @@ -12,28 +12,30 @@ using namespace std; -SamplePDF &SamplePDF::operator=(const SamplePDF &xs) -{ - if (this!=&xs) { - m_PDFs=xs.m_PDFs; +SamplePDF& SamplePDF::operator = (const SamplePDF& xs) { + if (this != &xs) { + m_PDFs = xs.m_PDFs; } return *this; } -bool SamplePDF::readFromFile(const char *fName) -{ +bool SamplePDF::readFromFile(const char* fName) { ifstream in(fName); - if (!in) {cerr << "SamplePDF::readFromFile : issue with " << fName << endl; return false;} - for( ; !in.eof() ; ) { + if (!in) { + cerr << "SamplePDF::readFromFile : issue with " << fName << endl; + return false; + } + + for (; !in.eof(); ) { string line; - if (!getline(in,line)) break; - if (!line.empty() && line[0]!='#') { + if (!getline(in, line)) break; + if (!line.empty() && line[0] != '#') { istringstream istr(line); - int dsid, PDFid=-1; + int dsid, PDFid = -1; istr >> dsid >> PDFid; //cout << dsid << "\t" << PDFid << endl; - setSample(dsid,PDFid); + setSample(dsid, PDFid); } } @@ -41,21 +43,21 @@ bool SamplePDF::readFromFile(const char *fName) return true; } -void SamplePDF::setSample(const int dsid, const int PDFid) -{ - if (dsid<0) return; - map<int, int >::const_iterator it=m_PDFs.find(dsid); - if (it!=m_PDFs.end()) { - cerr << "ERROR!! SamplePDF::setSample: duplicate entry ! DSID= " << dsid <<endl; - //cerr << "ERROR!! SamplePDF::setSample: xSect=" << xSect << "\told xSect=" << it->second.first <<endl; +void SamplePDF::setSample(const int dsid, const int PDFid) { + if (dsid < 0) return; + + map<int, int >::const_iterator it = m_PDFs.find(dsid); + if (it != m_PDFs.end()) { + cerr << "ERROR!! SamplePDF::setSample: duplicate entry ! DSID= " << dsid << endl; + //cerr << "ERROR!! SamplePDF::setSample: xSect=" << xSect << "\told xSect=" << it->second.first + // <<endl; } - m_PDFs[dsid]=PDFid; + m_PDFs[dsid] = PDFid; } +int SamplePDF::getPDFid(const int dsid) const { + map<int, int >::const_iterator it = m_PDFs.find(dsid); + if (it != m_PDFs.end()) return it->second; -int SamplePDF::getPDFid(const int dsid) const -{ - map<int,int >::const_iterator it=m_PDFs.find(dsid); - if (it!=m_PDFs.end()) return it->second; return unknown; } diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsection.cxx b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsection.cxx index 92c97f4ca9e704601af6a85d091abf0cb30e8398..f7a15ec031efbbc3f11a138f7589d849abb84cd8 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsection.cxx +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsection.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include <fstream> #include <sstream> @@ -12,64 +12,57 @@ using namespace std; -SampleXsection &SampleXsection::operator=(const SampleXsection &xs) -{ - if (this!=&xs) { - m_Xsects=xs.m_Xsects; - m_Uncert=xs.m_Uncert; +SampleXsection& SampleXsection::operator = (const SampleXsection& xs) { + if (this != &xs) { + m_Xsects = xs.m_Xsects; + m_Uncert = xs.m_Uncert; } return *this; } -bool SampleXsection::readFromFile(const char *fName) -{ +bool SampleXsection::readFromFile(const char* fName) { ifstream in(fName); + if (!in) return false; - for( ; !in.eof() ; ) { + for (; !in.eof(); ) { string line; - if (!getline(in,line)) break; - if (!line.empty() && line[0]!='#') { + if (!getline(in, line)) break; + if (!line.empty() && line[0] != '#') { istringstream istr(line); - int dsid=-1; - double xSect,kFact,xSectDw,xSectUp; + int dsid = -1; + double xSect, kFact, xSectDw, xSectUp; string s_shower, s_xSectDw, s_xSectUp; showering shower; istr >> dsid >> xSect >> kFact >> s_shower >> s_xSectDw >> s_xSectUp; - if(!s_shower.empty() && s_shower[0]!='#') { - if (s_shower=="pythia") shower=pythia; - else if (s_shower=="herwig") shower=herwig; - else if (s_shower=="sherpa") shower=sherpa; - else if (s_shower=="sherpa21") shower=sherpa21; - else if (s_shower=="pythia8") shower=pythia8; - else if (s_shower=="herwigpp") shower=herwigpp; - else { - cerr << "ERROR!! TopDataPreparation::SampleXsection::readFromFile: unknown showering (which is needed for btagging SF!!!) : " << s_shower << " for DSID= " << dsid <<endl; - shower=unknown; - } - //cout << "INFO SampleXsection::readFromFile: showering : " << s_shower << " -> " << shower << " for DSIS= " <<dsid <<endl; - - if(!s_xSectDw.empty() && s_xSectDw[0]!='#') { + if (!s_shower.empty() && s_shower[0] != '#') { + shower = stringToShower(s_shower); + if (shower == showering::unknown) { + cerr << + "ERROR!! TopDataPreparation::SampleXsection::readFromFile: unknown showering (which is needed for btagging SF!!!) : " + << s_shower << " for DSID= " << dsid << endl; + } + + if (!s_xSectDw.empty() && s_xSectDw[0] != '#') { xSectDw = atof(s_xSectDw.c_str()); - if(!s_xSectUp.empty()){ + if (!s_xSectUp.empty()) { xSectUp = atof(s_xSectUp.c_str()); - }else{ - cerr << "ERROR!! SampleXsection::readFromFile: xSectDw of "<<dsid<<" is defined ( "<<s_xSectDw<<" ), but not xSectUp" <<endl; - xSectUp=-1.; - } - //cout << " xSectDw= " << xSectDw << "\txSectUp= " << xSectUp << endl; - } - else { - xSectDw=-1.; - xSectUp=-1.; + } else { + cerr << "ERROR!! SampleXsection::readFromFile: xSectDw of " << dsid << " is defined ( " << s_xSectDw << + " ), but not xSectUp" << endl; + xSectUp = -1.; + } + } else { + xSectDw = -1.; + xSectUp = -1.; } }// !s_showering.empty() - else{ - xSectDw=-1.; - xSectUp=-1.; - shower = unknown; + else { + xSectDw = -1.; + xSectUp = -1.; + shower = unknown; } - setSample(dsid,xSect,kFact,shower,xSectDw,xSectUp); + setSample(dsid, xSect, kFact, shower, xSectDw, xSectUp); } } @@ -77,95 +70,149 @@ bool SampleXsection::readFromFile(const char *fName) return true; } -void SampleXsection::setSample(const int dsid,const double xSect,const double kFact, const showering shower, const double xSectDw, const double xSectUp) -{ - if (dsid<0) return; - map<int,pair<double,double> >::const_iterator it=m_Xsects.find(dsid); - if (it!=m_Xsects.end()) { - cerr << "ERROR!! SampleXsection::setSample: duplicate entry ! DSID= " << dsid <<endl; - //cerr << "ERROR!! SampleXsection::setSample: xSect=" << xSect << "\told xSect=" << it->second.first <<endl; +void SampleXsection::setSample(const int dsid, const double xSect, const double kFact, const showering shower, + const double xSectDw, const double xSectUp) { + if (dsid < 0) return; + + map<int, pair<double, double> >::const_iterator it = m_Xsects.find(dsid); + if (it != m_Xsects.end()) { + cerr << "ERROR!! SampleXsection::setSample: duplicate entry ! DSID= " << dsid << endl; + //cerr << "ERROR!! SampleXsection::setSample: xSect=" << xSect << "\told xSect=" << + // it->second.first <<endl; } - m_Xsects[dsid]=pair<double,double>(xSect,kFact); - m_Uncert[dsid]=pair<double,double>(xSectDw,xSectUp); - m_Showering[dsid]=shower; + m_Xsects[dsid] = pair<double, double>(xSect, kFact); + m_Uncert[dsid] = pair<double, double>(xSectDw, xSectUp); + m_Showering[dsid] = shower; } -double SampleXsection::getRawXsection(const int dsid) const -{ - map<int,pair<double,double> >::const_iterator it=m_Xsects.find(dsid); - if (it!=m_Xsects.end()) return it->second.first; +double SampleXsection::getRawXsection(const int dsid) const { + map<int, pair<double, double> >::const_iterator it = m_Xsects.find(dsid); + if (it != m_Xsects.end()) return it->second.first; + return -1; } -double SampleXsection::getKfactor(const int dsid) const -{ - map<int,pair<double,double> >::const_iterator it=m_Xsects.find(dsid); - if (it!=m_Xsects.end()) return it->second.second; +double SampleXsection::getKfactor(const int dsid) const { + map<int, pair<double, double> >::const_iterator it = m_Xsects.find(dsid); + if (it != m_Xsects.end()) return it->second.second; + return -1; } -double SampleXsection::getXsection(const int dsid) const -{ - map<int,pair<double,double> >::const_iterator it=m_Xsects.find(dsid); - if (it!=m_Xsects.end()) return (it->second.first)*(it->second.second); +double SampleXsection::getXsection(const int dsid) const { + map<int, pair<double, double> >::const_iterator it = m_Xsects.find(dsid); + if (it != m_Xsects.end()) return (it->second.first) * (it->second.second); + return -1; } -double SampleXsection::getXsectionDown(const int dsid) const -{ - map<int,pair<double,double> >::const_iterator it=m_Uncert.find(dsid); - if (it!=m_Uncert.end()) return it->second.first; +double SampleXsection::getXsectionDown(const int dsid) const { + map<int, pair<double, double> >::const_iterator it = m_Uncert.find(dsid); + if (it != m_Uncert.end()) return it->second.first; + return -1; } -double SampleXsection::getXsectionUp(const int dsid) const -{ - map<int,pair<double,double> >::const_iterator it=m_Uncert.find(dsid); - if (it!=m_Uncert.end()) return it->second.second; +double SampleXsection::getXsectionUp(const int dsid) const { + map<int, pair<double, double> >::const_iterator it = m_Uncert.find(dsid); + if (it != m_Uncert.end()) return it->second.second; + return -1; } -pair<double,double> SampleXsection::getXsectionDownUp(const int dsid) const -{ - map<int,pair<double,double> >::const_iterator it=m_Uncert.find(dsid); - if (it!=m_Uncert.end()) return it->second; - pair<double,double> temp=pair<double,double>(-1,-1); +pair<double, double> SampleXsection::getXsectionDownUp(const int dsid) const { + map<int, pair<double, double> >::const_iterator it = m_Uncert.find(dsid); + if (it != m_Uncert.end()) return it->second; + + pair<double, double> temp = pair<double, double>(-1, -1); return temp; } -SampleXsection::showering SampleXsection::getShowering(const int dsid) const -{ - map<int,showering >::const_iterator it=m_Showering.find(dsid); - if (it!=m_Showering.end()) return it->second; +SampleXsection::showering SampleXsection::getShowering(const int dsid) const { + map<int, showering >::const_iterator it = m_Showering.find(dsid); + if (it != m_Showering.end()) { + + showering shower = it->second; + // apply the translation of set + shower = applyTranslation(shower); + + return shower; + } + return unknown; } -int SampleXsection::getShoweringIndex(const int dsid) const +std::string SampleXsection::getShoweringString(const int dsid) const { - - // A.Knue: labelling taken from here: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/BTagCalib2015#Pre_Recommendations_for_MC15_Bas + return showerToString(getShowering(dsid)); +} + +int SampleXsection::getShoweringIndex(const int dsid) const { + // A.Knue: labelling taken from here: + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/BTagCalib2015#Pre_Recommendations_for_MC15_Bas showering shower = getShowering(dsid); - if(shower == showering::pythia) - return 0; - else if (shower == showering::herwigpp || shower == showering::herwig)// use the herwig++ maps for the few fortran herwig samples we may have + if (shower == showering::pythia) return 0; + else if (shower == showering::herwigpp || shower == showering::herwig) // use the herwig++ maps for the few fortran + // herwig samples we may have return 1; - else if (shower == showering::pythia8) - return 2; - else if (shower == showering::sherpa) - return 3; - else if (shower == showering::sherpa21) - return 4; - else{ - - std::cout << "===========================================================================================================================================" << std::endl; - std::cout << "ERROR:TopDataPreparation: The DSID " << dsid << " does not have a showering algorithm defined!!! This is needed for MC/MC SF!!! ---> EXIT." << std::endl; + else if (shower == showering::pythia8) return 2; + else if (shower == showering::sherpa) return 3; + else if (shower == showering::sherpa21) return 4; + else if (shower == showering::amcatnlopythia8) return 5; + else if (shower == showering::herwigpp713) return 6; + else if (shower == showering::sherpa228) return 7; + else { + std::cout << + "===========================================================================================================================================" + << std::endl; + std::cout << "ERROR:TopDataPreparation: The DSID " << dsid << + " does not have a showering algorithm defined!!! This is needed for MC/MC SF!!! ---> EXIT." << std::endl; std::cout << "\t" << std::endl; exit(1); - } - + return 0; +} + +SampleXsection::showering SampleXsection::applyTranslation(const SampleXsection::showering shower) const { + const std::string& stringName = showerToString(shower); + + // check the map + auto itr = m_translator.find(stringName); + if (itr == m_translator.end()) { + return shower; + } else { + // need to apply the translation + return stringToShower(itr->second); + } +} + +std::string SampleXsection::showerToString(const SampleXsection::showering shower) const { + if (shower == showering::pythia) return "pythia"; + else if (shower == showering::herwig) return "herwig"; + else if (shower == showering::herwigpp) return "herwig"; + else if (shower == showering::sherpa) return "sherpa"; + else if (shower == showering::sherpa21) return "sherpa21"; + else if (shower == showering::pythia8) return "pythia8"; + else if (shower == showering::amcatnlopythia8) return "amcatnlopythia8"; + else if (shower == showering::herwigpp713) return "herwigpp713"; + else if (shower == showering::sherpa228) return "sherpa228"; + + return ""; +} +SampleXsection::showering SampleXsection::stringToShower(const std::string& name) const { + if (name == "pythia") return showering::pythia; + else if (name == "herwig") return showering::herwig; + else if (name == "sherpa") return showering::sherpa; + else if (name == "sherpa21") return showering::sherpa21; + else if (name == "pythia8") return showering::pythia8; + else if (name == "herwigpp") return showering::herwigpp; + else if (name == "amcatnlopythia8") return showering::amcatnlopythia8; + else if (name == "herwigpp713") return showering::herwigpp713; + else if (name == "sherpa228") return showering::sherpa228; + + return showering::unknown; } diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsectionSvc.cxx b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsectionSvc.cxx index 579bf401cd9e79a2368dee991340003ce1620673..49009041bb8c5e36a708c7fec559ea69f1d63180 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsectionSvc.cxx +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/Root/SampleXsectionSvc.cxx @@ -1,22 +1,22 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopDataPreparation/SampleXsectionSvc.h" #include <iostream> #include <cstdlib> -SampleXsectionSvc *SampleXsectionSvc::s_instance = 0; +SampleXsectionSvc* SampleXsectionSvc::s_instance = 0; -SampleXsectionSvc::SampleXsectionSvc(std::string inputFile): +SampleXsectionSvc::SampleXsectionSvc(std::string inputFile) : m_inputFile(inputFile), m_sampleXsection(0) { } //------------------------------------------------------------------------------- -SampleXsectionSvc::~SampleXsectionSvc(){ - if(m_sampleXsection) delete m_sampleXsection; +SampleXsectionSvc::~SampleXsectionSvc() { + if (m_sampleXsection) delete m_sampleXsection; } //------------------------------------------------------------------------------- @@ -24,19 +24,17 @@ SampleXsectionSvc::~SampleXsectionSvc(){ int SampleXsectionSvc::initialize() { m_sampleXsection = new SampleXsection(); - char *rootcoreDir = getenv("ROOTCOREBIN"); + char* rootcoreDir = getenv("ROOTCOREBIN"); if (!m_sampleXsection->readFromFile(m_inputFile.c_str())) { - if(rootcoreDir) {// if file can't be read, maybe it's in the common directory + if (rootcoreDir) {// if file can't be read, maybe it's in the common directory std::string fullpath = std::string(rootcoreDir) + "/data/TopDataPreparation/"; fullpath += m_inputFile; if (!m_sampleXsection->readFromFile(fullpath.c_str())) { std::cerr << "SampleXsection::unable to read input file " << fullpath << std::endl; return 1; - } - else return 0;//all OK - } - else {// if common directory can't be found, then surrender + } else return 0; //all OK + } else {// if common directory can't be found, then surrender std::cerr << "SampleXsection::unable to read input file " << m_inputFile << std::endl; return 1; } @@ -47,16 +45,16 @@ int SampleXsectionSvc::initialize() { //---------------------------------------------------------------- -SampleXsectionSvc *SampleXsectionSvc::svc(std::string inputFile) { - if(s_instance == 0) { +SampleXsectionSvc* SampleXsectionSvc::svc(std::string inputFile) { + if (s_instance == 0) { s_instance = new SampleXsectionSvc(inputFile); - - if(s_instance->initialize() != 0) { + + if (s_instance->initialize() != 0) { std::cerr << "Error: initialize failed. Could not create SampleXsectionSvc." << std::endl; delete s_instance; s_instance = 0; } } - + return s_instance; } diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SamplePDF.h b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SamplePDF.h index 5f43a4be67aa5658f31aac2c1b086c43ddd0b7f7..015fd40121ca36c06eb46ee7800ca048f7f0001c 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SamplePDF.h +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SamplePDF.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SAMPLEPDF_H #define SAMPLEPDF_H @@ -8,31 +8,29 @@ #include <map> /** @class SamplePDFSvc - ** - ** @author David Calvet <calvet@in2p3.fr> - ** - ** @brief A class to provide access to Monte Carlo sample luminosity information. - ** +** +** @author David Calvet <calvet@in2p3.fr> +** +** @brief A class to provide access to Monte Carlo sample luminosity information. +** */ class SamplePDF { - public: - - enum showering{ pythia=0, herwig=1, sherpa=2, pythia8=4, herwigpp=5, sherpa21=6, unknown=10}; - + enum showering { + pythia=0, herwig=1, sherpa=2, pythia8=4, herwigpp=5, sherpa21=6, unknown=10 + }; + inline SamplePDF() : m_PDFs() {} - inline SamplePDF(const SamplePDF &xs) : m_PDFs(xs.m_PDFs) {} + inline SamplePDF(const SamplePDF& xs) : m_PDFs(xs.m_PDFs) {} inline ~SamplePDF() {} - SamplePDF &operator=(const SamplePDF &xs); + SamplePDF& operator = (const SamplePDF& xs); - bool readFromFile(const char *fName); - void setSample(const int dsid,const int PDFid); + bool readFromFile(const char* fName); + void setSample(const int dsid, const int PDFid); int getPDFid(const int dsid) const; - private: - std::map<int, int > m_PDFs; }; diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsection.h b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsection.h index 97a3cc91981a4628a177e06c588b22cdd9f05df8..924d47658c0794948d3b9d8ec20cad7aa3076e53 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsection.h +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsection.h @@ -1,49 +1,66 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef SAMPLEXSECTION_H #define SAMPLEXSECTION_H #include <map> +#include <string> +#include <unordered_map> /** @class SampleXsectionSvc - ** - ** @author David Calvet <calvet@in2p3.fr> - ** - ** @brief A class to provide access to Monte Carlo sample luminosity information. - ** +** +** @author David Calvet <calvet@in2p3.fr> +** +** @brief A class to provide access to Monte Carlo sample luminosity information. +** */ class SampleXsection { - public: - - enum showering{ pythia=0, herwig=1, sherpa=2, pythia8=4, herwigpp=5, sherpa21=6, unknown=10}; + enum showering { + pythia=0, + herwig=1, + sherpa=2, + pythia8=4, + herwigpp=5, + sherpa21=6, + amcatnlopythia8=7, + herwigpp713=8, + sherpa228=9, + unknown=10 + }; inline SampleXsection() : m_Xsects() {} - inline SampleXsection(const SampleXsection &xs) : m_Xsects(xs.m_Xsects) {} + inline SampleXsection(const SampleXsection& xs) : m_Xsects(xs.m_Xsects) {} inline ~SampleXsection() {} - SampleXsection &operator=(const SampleXsection &xs); + SampleXsection& operator = (const SampleXsection& xs); - bool readFromFile(const char *fName); - void setSample(const int dsid,const double xSect,const double kFact,const showering shower, const double xSectDw, const double xSectUp); + bool readFromFile(const char* fName); + void setSample(const int dsid, const double xSect, const double kFact, const showering shower, const double xSectDw, + const double xSectUp); double getRawXsection(const int dsid) const; double getKfactor(const int dsid) const; double getXsection(const int dsid) const; double getXsectionUp(const int dsid) const; double getXsectionDown(const int dsid) const; - std::pair<double,double> getXsectionDownUp(const int dsid) const; + std::pair<double, double> getXsectionDownUp(const int dsid) const; showering getShowering(const int dsid) const; + std::string getShoweringString(const int dsid) const; int getShoweringIndex(const int dsid) const; + void setTranslator(const std::unordered_map<std::string, std::string>& map) {m_translator = map;} private: + std::map<int, std::pair<double, double> > m_Xsects; + std::map<int, std::pair<double, double> > m_Uncert; + std::map<int, showering > m_Showering; + std::unordered_map<std::string, std::string> m_translator; - std::map<int,std::pair<double,double> > m_Xsects; - std::map<int,std::pair<double,double> > m_Uncert; - std::map<int,showering > m_Showering; - + showering applyTranslation(const showering shower) const; + std::string showerToString(const showering shower) const; + showering stringToShower(const std::string& name) const; }; #endif // SAMPLEXSECTION_H diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsectionSvc.h b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsectionSvc.h index 6ebb586dcfe52ab5b67044a3dccf998929c0e19d..2d8ed248862ff4d6f5bd272e3a6d307be831106f 100644 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsectionSvc.h +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/TopDataPreparation/SampleXsectionSvc.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SAMPLEXSECTIONSVC_H #define SAMPLEXSECTIONSVC_H @@ -10,51 +10,48 @@ #include "TopDataPreparation/SampleXsection.h" /** @class SampleXsectionSvc - ** - ** @author W. H. Bell <W.Bell@cern.ch> - ** - ** @brief Singleton class providing access to SampleXsection - ** - ** The files associated with SampleXsection are read once when the unique instance is created. - ** This happens on the first call to - ** SampleXsection::svc(std::string inputFile), - ** which also return a pointer to the instance. Subsequently it is sufficient - ** to call SampleXsectionSvc::svc() without any arguments. - */ +** +** @author W. H. Bell <W.Bell@cern.ch> +** +** @brief Singleton class providing access to SampleXsection +** +** The files associated with SampleXsection are read once when the unique instance is created. +** This happens on the first call to +** SampleXsection::svc(std::string inputFile), +** which also return a pointer to the instance. Subsequently it is sufficient +** to call SampleXsectionSvc::svc() without any arguments. +*/ class SampleXsectionSvc { - public: +public: /** Return a pointer to the unique instance, initialize if necessary. * @param inputFile name of the input file. * @return pointer to SampleXsectionSvc instance, NULL on failure. - */ - static SampleXsectionSvc *svc(std::string inputFile); + */ + static SampleXsectionSvc* svc(std::string inputFile); /** Return a pointer to the unique instance, or NULL if not initialized. * @return pointer to SampleXsectionSvc instance. */ - static SampleXsectionSvc *svc() { return s_instance; } + static SampleXsectionSvc* svc() {return s_instance;} /** Provide access to the WhichPeriod object held by the instance. * @return pointer to the initialized WhichPeriod object. */ - const SampleXsection* sampleXsection() const { return m_sampleXsection; } - - - private: - + const SampleXsection* sampleXsection() const {return m_sampleXsection;} +private: /** Singleton pattern: Private constructor. */ - SampleXsectionSvc(std::string inputFile=""); - + SampleXsectionSvc(std::string inputFile = ""); + /** Singleton pattern: Private destructor. */ ~SampleXsectionSvc(); - + /** Singleton pattern: Copy constructor is private and undefined. */ - SampleXsectionSvc(const SampleXsectionSvc &); + SampleXsectionSvc(const SampleXsectionSvc&); /** Singleton pattern: Assignment operator is private and undefined. */ - SampleXsectionSvc &operator=(const SampleXsectionSvc &); - + SampleXsectionSvc& operator = (const SampleXsectionSvc&); + /** A pointer to carry the address of the unique instance. */ - static SampleXsectionSvc *s_instance; - + static SampleXsectionSvc* s_instance; + /** A member function to setup the WhichPeriod object. */ int initialize(void); @@ -62,9 +59,7 @@ class SampleXsectionSvc { std::string m_inputFile; /** The SampleXsection instance. */ - SampleXsection *m_sampleXsection; + SampleXsection* m_sampleXsection; }; #endif - - diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/data/README.md b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ef6b19f7152359f41d66f8d5d94ece217cc84cd3 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/data/README.md @@ -0,0 +1,5 @@ +# 29 Jan 2018 - Important functional update for R21 + + * The files in this directory have now been moved to /cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/TopDataPreparation. + * Requests to update these files should proceed as usual via the ANALYSISTO Jira, but changes can now be propagated via cvmfs, rather than via new releases. + diff --git a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/python/getPDF.py b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/python/getPDF.py index 580dc0d9862c281f3986a71f73337e84f9ad47b3..9dbb32c120a98827b6260aeccf8e51b7e4fa5c9e 100755 --- a/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/python/getPDF.py +++ b/PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation/python/getPDF.py @@ -7,7 +7,7 @@ import os def getWikiFile(): WikiFile = "svn+ssh://svn.cern.ch/reps/atlasphys/Physics/Top/Software/Production/TopMC12twiki/status/" com = "svn co "+WikiFile - print com + print(com) os.system(com) @@ -31,9 +31,9 @@ def producePDFfile(fileout_name='PDF-MC12-8TeV.data'): if DSID>="110899" and DSID<="110910": PDF = "21000" else: - print "wrong format for",line[:-1] - print "-->",PDF,"====" - print "\n" + print("wrong format for",line[:-1]) + print("-->",PDF,"====") + print("\n") continue else : # good format @@ -43,9 +43,9 @@ def producePDFfile(fileout_name='PDF-MC12-8TeV.data'): if dico.has_key(DSID): if dico[DSID] != PDF: - print DSID,"already exists" - print "\told:",dico[DSID] - print "\tnew:",PDF + print(DSID,"already exists") + print("\told:",dico[DSID]) + print("\tnew:",PDF) else : dico[DSID]=PDF out = DSID+"\t"+PDF @@ -53,13 +53,13 @@ def producePDFfile(fileout_name='PDF-MC12-8TeV.data'): for sample in ["110906", "110909"]: if not dico.has_key(sample): - print "adding missing sample",sample,"by hand" + print("adding missing sample",sample,"by hand") out = sample+"\t21000" fileout.write(out+"\n") for sample in ["203307", "203308", "203309", "203310", "203311", "203312", "203313", "203314", "203315", "203316", "203317", "203318"]: if not dico.has_key(sample): - print "adding missing sample",sample,"by hand" + print("adding missing sample",sample,"by hand") out = sample+"\t10042" fileout.write(out+"\n") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/CMakeLists.txt index 61452def1bec7ab6ff6f7365f86a98851dd2ee47..04ec018efe4934d35f6b7e094e6b83c9c6158c42 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopAnalysis ) @@ -11,6 +10,7 @@ atlas_depends_on_subdirs( PUBLIC xAODJet xAODMissingET xAODCutFlow + xAODMetaData AsgTools AthContainers PATInterfaces @@ -23,24 +23,24 @@ atlas_depends_on_subdirs( PUBLIC TopPartons TopObjectSelectionTools TopSystematicObjectMaker - TopFakes - TopDataPreparation - TopHLUpgrade ) + TopDataPreparation + #TopHLUpgrade + Tools/PathResolver + #FakeBkgTools + ) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopAnalysis _cintDictSource - ROOT_HEADERS TopAnalysis/ObjectLoaderStandardCuts.h - TopAnalysis/EventSaverFlatNtuple.h TopAnalysis/EventSaverxAOD.h - TopAnalysis/EventSaverxAODNext.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopAnalysis Root/*.cxx Root/*.h Root/*.icc TopAnalysis/*.h TopAnalysis/*.icc TopAnalysis/*/*.h - TopAnalysis/*/*.icc ${_cintDictSource} + TopAnalysis/*/*.icc ${_cintDictSource} PUBLIC_HEADERS TopAnalysis LINK_LIBRARIES xAODCore xAODRootAccess @@ -49,6 +49,7 @@ atlas_add_library( TopAnalysis Root/*.cxx Root/*.h Root/*.icc xAODJet xAODMissingET xAODCutFlow + xAODMetaData AsgTools AthContainers PATInterfaces @@ -61,9 +62,10 @@ atlas_add_library( TopAnalysis Root/*.cxx Root/*.h Root/*.icc TopPartons TopObjectSelectionTools TopSystematicObjectMaker - TopFakes - TopDataPreparation - TopHLUpgrade + TopDataPreparation + #TopHLUpgrade + PathResolver + #FakeBkgToolsLib ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) @@ -83,6 +85,37 @@ atlas_add_executable( top-xaod xAODJet xAODMissingET xAODCutFlow + xAODMetaData + AsgTools + AthContainers + PATInterfaces + TopCPTools + TopEventSelectionTools + TopConfiguration + TopCorrections + TopEvent + TopParticleLevel + TopPartons + TopObjectSelectionTools + TopSystematicObjectMaker + TopDataPreparation + #TopHLUpgrade + PathResolver + ${ROOT_LIBRARIES} + TopAnalysis + #FakeBkgToolsLib + ) + +atlas_add_executable( top-tool-ftag + util/top-tool-ftag.cxx + LINK_LIBRARIES xAODCore + xAODRootAccess + xAODEgamma + xAODMuon + xAODJet + xAODMissingET + xAODCutFlow + xAODMetaData AsgTools AthContainers PATInterfaces @@ -95,9 +128,9 @@ atlas_add_executable( top-xaod TopPartons TopObjectSelectionTools TopSystematicObjectMaker - TopFakes - TopDataPreparation - TopHLUpgrade + TopDataPreparation + #TopHLUpgrade + PathResolver ${ROOT_LIBRARIES} TopAnalysis ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/AnalysisTrackingHelper.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/AnalysisTrackingHelper.cxx new file mode 100644 index 0000000000000000000000000000000000000000..36d1d944df1b029df5f401850fdce1c19344e63f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/AnalysisTrackingHelper.cxx @@ -0,0 +1,256 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopAnalysis/AnalysisTrackingHelper.h" + +#include "TopConfiguration/ConfigurationSettings.h" +#include "TopConfiguration/JsonUtils.h" +#include "TopConfiguration/TopConfig.h" +#include "TopEvent/EventTools.h" + +#include "AsgTools/AsgTool.h" +#include "AsgTools/PropertyMgr.h" +#include "AsgTools/ToolStore.h" +#include "xAODCore/tools/IOStats.h" +#include "xAODCore/tools/ReadStats.h" + +#include <TTree.h> + +#include <boost/algorithm/string/classification.hpp> +#include <boost/algorithm/string.hpp> +#include <boost/optional.hpp> +#include <boost/regex.hpp> +#include <boost/scope_exit.hpp> + +#include <cstdlib> +#include <fstream> +#include <functional> +#include <set> +#include <sstream> +#include <stdexcept> + +namespace { +/** + * @brief List all tools registered in asg::ToolStore. + */ + std::vector<std::string> listToolStore() { + std::stringstream buffer; + { + auto&& stdoutbuf = std::cout.rdbuf(buffer.rdbuf()); + BOOST_SCOPE_EXIT(&stdoutbuf) { + std::cout.rdbuf(stdoutbuf); + } BOOST_SCOPE_EXIT_END + asg::ToolStore::dumpToolConfig(); + } + std::vector<std::string> result; + { + boost::regex re("(\\S+)\\s+=\\s+[^/]+/\\1\\s*"); + for (std::string line; std::getline(buffer, line); ) { + boost::cmatch m; + if (boost::regex_match(line.c_str(), m, re)) { + result.push_back(m[1]); + } + } + } + return result; + } +} + +namespace top { + AnalysisTrackingHelper::AnalysisTrackingHelper() : + m_finished(false) + { } + + + AnalysisTrackingHelper::~AnalysisTrackingHelper() { } + + + void AnalysisTrackingHelper::addInputFile(std::string const& path, unsigned long long entriesProcessed) { + top::check(!m_finished, "AnalysisTrackingHelper::addInputFile called on finished instance"); + char* fullpath = realpath(path.c_str(), NULL); + BOOST_SCOPE_EXIT(fullpath) { + free(fullpath); + } BOOST_SCOPE_EXIT_END + m_inputFiles.emplace_back((fullpath == nullptr ? path.c_str() : fullpath), entriesProcessed); + } + + void AnalysisTrackingHelper::setTopConfig(std::shared_ptr<top::TopConfig> const& topConfig) { + top::check(!m_finished, "AnalysisTrackingHelper::setTopConfig called on finished instance"); + m_topConfig = topConfig; + } + + void AnalysisTrackingHelper::writeTree(std::string const& treename) { + finish(); + TTree* t = new TTree(treename.c_str(), ""); + t->SetAutoSave(0); + t->SetAutoFlush(0); + t->Branch("jsonData", &m_json, 262144); + t->Fill(); + t->Write(); + } + + void AnalysisTrackingHelper::finish() { + std::ostringstream out; + + std::string const json_null("null"); + out << "{\n"; + { + // Store settings from configuration file: + out << json_dump("configSettings") << ": {"; + auto const& config = *top::ConfigurationSettings::get(); + char const* sep = "\n "; + for (auto&& kv : config.stringData()) { + if (!kv.second.m_set) continue; + out << sep << json_dump(kv.first) << ": " << json_dump(kv.second.m_data); + sep = ",\n "; + } + out << "},\n"; + } + { + // Store small subset of environment variables: + out << json_dump("environment") << ": {"; + char const* sep = "\n "; + auto dumpEnvVar = [&](char const* name) { + char const* value = std::getenv(name); + + out << sep << json_dump(name) << ": " << (value == nullptr ? json_null : json_dump(value)); + sep = ",\n "; + }; + dumpEnvVar("AnalysisBase_DIR"); + dumpEnvVar("AnalysisBase_VERSION"); + dumpEnvVar("AnalysisBaseExternals_DIR"); + dumpEnvVar("AnalysisBaseExternals_VERSION"); + dumpEnvVar("AnalysisTop_DIR"); + dumpEnvVar("AnalysisTop_VERSION"); + dumpEnvVar("AtlasVersion"); + dumpEnvVar("HOSTNAME"); + dumpEnvVar("PanDA_TaskID"); + dumpEnvVar("PandaID"); + out << "},\n"; + } + { + // Store metadata of inputs: + out << json_dump("inputConfig") << ": {\n"; + out << " " << json_dump("amiTag") << ": " << json_dump(m_topConfig->getAmiTag()) << ",\n"; + out << " " << json_dump("derivationFormat") << ": " << json_dump(m_topConfig->getDerivationStream()) << ",\n"; + out << " " << json_dump("dsid") << ": " << json_dump(m_topConfig->getDSID()) << ",\n"; + out << " " << json_dump("isMC") << ": " << json_dump(m_topConfig->isMC()) << ",\n"; + out << " " << json_dump("isAtlFast2") << ": " << json_dump(m_topConfig->isAFII()) << "\n"; + out << " " << json_dump("BtagCDIPath") << ": " << json_dump(m_topConfig->bTaggingCDIPath()) << "\n"; + out << "},\n"; + } + { + // List paths of loaded libraries, grouping them by directory: + bool ok; + std::map<std::string, std::set<std::string> > libs; + try { + boost::regex reLine("\\s*(?:\\S+\\s+){5}(/.*)"); + boost::cmatch m; + std::ifstream stream("/proc/self/maps", std::ios_base::in | std::ios_base::binary); + for (std::string line; std::getline(stream, line); ) { + if (boost::regex_match(line.c_str(), m, reLine)) { + std::string const& path = m[1]; + size_t i = path.rfind('/'); + assert(i != std::string::npos); + std::string const& basename = path.substr(i + 1); + if (boost::starts_with(basename, "lib")) { + std::string dirpath = path.substr(0, (i ? i : 1)); + libs[dirpath].insert(basename); + } + } + } + stream.close(); + ok = true; + } + catch (std::exception const&) { + ok = false; + } + // Store sorted list of loaded libraries (if listing was successful): + if (ok) { + out << json_dump("images") << ": ["; + char const* sep1 = "\n "; + for (auto&& lib : libs) { + out << sep1 << "[" << json_dump(lib.first) << ", ["; + sep1 = ",\n "; + char const* sep2 = "\n "; + for (auto&& basename : lib.second) { + out << sep2 << json_dump(basename); + sep2 = ",\n "; + } + out << "]]"; + } + out << "],\n"; + } + } + { + // Store information about processed input files: + out << json_dump("inputFiles") << ": ["; + char const* sep = "\n "; + for (auto const& inputFile : m_inputFiles) { + out << sep << "[" << json_dump(inputFile.path) << "," << json_dump(inputFile.entriesProcessed) << "]"; + sep = ",\n "; + } + out << "],\n"; + } + { + // Store various PerfStats: + auto&& readStats = xAOD::IOStats::instance().stats(); + out << json_dump("perfStats") << ": {\n"; + { + out << " " << json_dump("readEntriesByContainer") << ": {"; + char const* sep = "\n "; + for (auto&& kv : readStats.containers()) { + xAOD::BranchStats const& bs = kv.second; + if (boost::ends_with(bs.GetName(), "TDS") || boost::ends_with(bs.GetName(), "Aux.")) continue; + if (bs.readEntries()) { + out << sep << json_dump(bs.GetName()) << ": " << json_dump(bs.readEntries()); + sep = ",\n "; + } + } + out << "},\n"; + } + { + out << " " << json_dump("readEntriesByBranch") << ": {"; + char const* sep = "\n "; + for (auto&& kv : readStats.branches()) { + for (xAOD::BranchStats const* bs : kv.second) { + if (bs && bs->readEntries()) { + out << sep << json_dump(bs->GetName()) << ": " << json_dump(bs->readEntries()); + sep = ",\n "; + } + } + } + out << "},\n"; + } + out << " " << json_dump("totalEntries") << ": " << json_dump(readStats.nEvents()) << "},\n"; + } + { + // Store configuration of all (CP) tools: + out << json_dump("toolConfig") << ": {"; + PropertyValueJsonDumper json_dump_prop; + char const* toolsep = "\n "; + for (std::string const& toolname : listToolStore()) { + auto&& tool = asg::ToolStore::get<asg::AsgTool>(toolname); + if (tool == nullptr) continue; + if (boost::starts_with(tool->name(), "top::")) continue; + out << toolsep << json_dump(tool->name()) << ": {"; + auto&& props = *tool->getPropertyMgr(); + char const* propsep = "\n "; + for (auto&& prop : props.getProperties()) { + if (!prop.second->isValid()) continue; + auto&& jvalue = json_dump_prop(prop.second); + if (jvalue == boost::none) continue; + out << propsep << json_dump(prop.first) << ": " << *jvalue; + propsep = ",\n "; + } + out << "}"; + toolsep = ",\n "; + } + out << "},\n"; + } + out << json_dump("format") << ": " << json_dump(1) << "\n}\n"; + out.str().swap(m_json); + m_finished = true; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverFlatNtuple.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverFlatNtuple.cxx index 07f2e141fb421c55a452209bedb0c4757f007d62..980df371278e90743c13c8365c9f518f3082b601 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverFlatNtuple.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverFlatNtuple.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/EventSaverFlatNtuple.h" @@ -8,2684 +8,5590 @@ #include "TopEvent/EventTools.h" #include "TopConfiguration/TopConfig.h" #include "TopEventSelectionTools/TreeManager.h" +#include "TopParticleLevel/TruthTools.h" +#include "xAODMissingET/MissingETContainer.h" #include "AthContainers/AuxTypeRegistry.h" #include "TFile.h" #include <cmath> #include <iostream> +#include <regex> #include <boost/algorithm/string.hpp> #include "TopParticleLevel/ParticleLevelEvent.h" -#include "TopFakes/TopFakesMMWeightCalculator.h" +//#include "FakeBkgTools/AsymptMatrixTool.h" -namespace top { +#include "xAODTracking/TrackParticlexAODHelpers.h" - EventSaverFlatNtuple::EventSaverFlatNtuple() : - asg::AsgTool( "top::EventSaverFlatNtuple" ), - m_config(nullptr), - m_sfRetriever(nullptr), - m_outputFile(nullptr), - m_truthTreeManager(nullptr), - m_particleLevelTreeManager(nullptr), - - m_weight_mc(0.), - m_weight_pileup(0.), - - // cumulative SF - m_weight_leptonSF(0.), - - m_weight_leptonSF_EL_SF_Trigger_UP(0.), - m_weight_leptonSF_EL_SF_Trigger_DOWN(0.), - m_weight_leptonSF_EL_SF_Reco_UP(0.), - m_weight_leptonSF_EL_SF_Reco_DOWN(0.), - m_weight_leptonSF_EL_SF_ID_UP(0.), - m_weight_leptonSF_EL_SF_ID_DOWN(0.), - m_weight_leptonSF_EL_SF_Isol_UP(0.), - m_weight_leptonSF_EL_SF_Isol_DOWN(0.), - - m_weight_leptonSF_MU_SF_Trigger_STAT_UP(0.), - m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN(0.), - m_weight_leptonSF_MU_SF_Trigger_SYST_UP(0.), - m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN(0.), - // Muon ID SF systematics (regular) - m_weight_leptonSF_MU_SF_ID_STAT_UP(0.), - m_weight_leptonSF_MU_SF_ID_STAT_DOWN(0.), - m_weight_leptonSF_MU_SF_ID_SYST_UP(0.), - m_weight_leptonSF_MU_SF_ID_SYST_DOWN(0.), - // Muon ID SF systematics (low pt) - m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP(0.), - m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN(0.), - m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP(0.), - m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN(0.), - // Muon isolation SF systematics - m_weight_leptonSF_MU_SF_Isol_STAT_UP(0.), - m_weight_leptonSF_MU_SF_Isol_STAT_DOWN(0.), - m_weight_leptonSF_MU_SF_Isol_SYST_UP(0.), - m_weight_leptonSF_MU_SF_Isol_SYST_DOWN(0.), - m_weight_leptonSF_MU_SF_TTVA_STAT_UP(0.), - m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN(0.), - m_weight_leptonSF_MU_SF_TTVA_SYST_UP(0.), - m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN(0.), - - // individual components electrons - m_weight_indiv_SF_EL_Trigger(0.), - m_weight_indiv_SF_EL_Trigger_UP(0.), - m_weight_indiv_SF_EL_Trigger_DOWN(0.), - m_weight_indiv_SF_EL_Reco(0.), - m_weight_indiv_SF_EL_Reco_UP(0.), - m_weight_indiv_SF_EL_Reco_DOWN(0.), - m_weight_indiv_SF_EL_ID(0.), - m_weight_indiv_SF_EL_ID_UP(0.), - m_weight_indiv_SF_EL_ID_DOWN(0.), - m_weight_indiv_SF_EL_Isol(0.), - m_weight_indiv_SF_EL_Isol_UP(0.), - m_weight_indiv_SF_EL_Isol_DOWN(0.), - m_weight_indiv_SF_EL_ChargeID(0.), - m_weight_indiv_SF_EL_ChargeID_UP(0.), - m_weight_indiv_SF_EL_ChargeID_DOWN(0.), - m_weight_indiv_SF_EL_ChargeMisID(0.), - m_weight_indiv_SF_EL_ChargeMisID_STAT_UP(0.), - m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN(0.), - m_weight_indiv_SF_EL_ChargeMisID_SYST_UP(0.), - m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN(0.), - - m_weight_indiv_SF_MU_Trigger(0.), - m_weight_indiv_SF_MU_Trigger_STAT_UP(0.), - m_weight_indiv_SF_MU_Trigger_STAT_DOWN(0.), - m_weight_indiv_SF_MU_Trigger_SYST_UP(0.), - m_weight_indiv_SF_MU_Trigger_SYST_DOWN(0.), - // Muon ID SF systematics (regular) - m_weight_indiv_SF_MU_ID(0.), - m_weight_indiv_SF_MU_ID_STAT_UP(0.), - m_weight_indiv_SF_MU_ID_STAT_DOWN(0.), - m_weight_indiv_SF_MU_ID_SYST_UP(0.), - m_weight_indiv_SF_MU_ID_SYST_DOWN(0.), - // Muon ID SF systematics (low pt) - m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP(0.), - m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN(0.), - m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP(0.), - m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN(0.), - // Muon isolation SF systematics - m_weight_indiv_SF_MU_Isol(0.), - m_weight_indiv_SF_MU_Isol_SYST_UP(0.), - m_weight_indiv_SF_MU_Isol_SYST_DOWN(0.), - m_weight_indiv_SF_MU_Isol_STAT_UP(0.), - m_weight_indiv_SF_MU_Isol_STAT_DOWN(0.), - m_weight_indiv_SF_MU_TTVA(0.), - m_weight_indiv_SF_MU_TTVA_SYST_UP(0.), - m_weight_indiv_SF_MU_TTVA_SYST_DOWN(0.), - m_weight_indiv_SF_MU_TTVA_STAT_UP(0.), - m_weight_indiv_SF_MU_TTVA_STAT_DOWN(0.), - - m_fakesMM_weights(), - - m_eventNumber(0), - m_runNumber(0), - m_randomRunNumber(0), - m_mcChannelNumber(0), - - m_mu_original(0.), - m_mu(0.), - - m_backgroundFlags(0), - m_hasBadMuon(0), - m_makeRCJets(false), - m_makeVarRCJets(false), - m_met_met(0.), - m_met_phi(0.) - { +namespace top { + EventSaverFlatNtuple::EventSaverFlatNtuple() : + asg::AsgTool("top::EventSaverFlatNtuple"), + m_config(nullptr), + m_sfRetriever(nullptr), + m_outputFile(nullptr), + m_truthTreeManager(nullptr), + m_particleLevelTreeManager(nullptr), + + m_weight_mc(0.), + m_weight_pileup(0.), + + m_weight_fwdElSF(0.), + m_weight_fwdElSF_FWDEL_SF_ID_UP(0.), + m_weight_fwdElSF_FWDEL_SF_ID_DOWN(0.), + + // cumulative SF + m_weight_leptonSF(0.), + + m_weight_leptonSF_EL_SF_Trigger_UP(0.), + m_weight_leptonSF_EL_SF_Trigger_DOWN(0.), + m_weight_leptonSF_EL_SF_Reco_UP(0.), + m_weight_leptonSF_EL_SF_Reco_DOWN(0.), + m_weight_leptonSF_EL_SF_ID_UP(0.), + m_weight_leptonSF_EL_SF_ID_DOWN(0.), + m_weight_leptonSF_EL_SF_Isol_UP(0.), + m_weight_leptonSF_EL_SF_Isol_DOWN(0.), + + m_weight_leptonSF_MU_SF_Trigger_STAT_UP(0.), + m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN(0.), + m_weight_leptonSF_MU_SF_Trigger_SYST_UP(0.), + m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN(0.), + // Muon ID SF systematics (regular) + m_weight_leptonSF_MU_SF_ID_STAT_UP(0.), + m_weight_leptonSF_MU_SF_ID_STAT_DOWN(0.), + m_weight_leptonSF_MU_SF_ID_SYST_UP(0.), + m_weight_leptonSF_MU_SF_ID_SYST_DOWN(0.), + // Muon ID SF systematics (low pt) + m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP(0.), + m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN(0.), + m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP(0.), + m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN(0.), + // Muon isolation SF systematics + m_weight_leptonSF_MU_SF_Isol_STAT_UP(0.), + m_weight_leptonSF_MU_SF_Isol_STAT_DOWN(0.), + m_weight_leptonSF_MU_SF_Isol_SYST_UP(0.), + m_weight_leptonSF_MU_SF_Isol_SYST_DOWN(0.), + m_weight_leptonSF_MU_SF_TTVA_STAT_UP(0.), + m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN(0.), + m_weight_leptonSF_MU_SF_TTVA_SYST_UP(0.), + m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN(0.), + // Special global lepton trigger SF + systematics + m_weight_globalLeptonTriggerSF(0.), + m_weight_globalLeptonTriggerSF_EL_Trigger_UP(0.), + m_weight_globalLeptonTriggerSF_EL_Trigger_DOWN(0.), + m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP(0.), + m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN(0.), + m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP(0.), + m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN(0.), + m_weight_oldTriggerSF(0.), + m_weight_oldTriggerSF_EL_Trigger_UP(0.), + m_weight_oldTriggerSF_EL_Trigger_DOWN(0.), + m_weight_oldTriggerSF_MU_Trigger_STAT_UP(0.), + m_weight_oldTriggerSF_MU_Trigger_STAT_DOWN(0.), + m_weight_oldTriggerSF_MU_Trigger_SYST_UP(0.), + m_weight_oldTriggerSF_MU_Trigger_SYST_DOWN(0.), + + // individual components electrons + m_weight_indiv_SF_EL_Reco(0.), + m_weight_indiv_SF_EL_Reco_UP(0.), + m_weight_indiv_SF_EL_Reco_DOWN(0.), + m_weight_indiv_SF_EL_ID(0.), + m_weight_indiv_SF_EL_ID_UP(0.), + m_weight_indiv_SF_EL_ID_DOWN(0.), + m_weight_indiv_SF_EL_Isol(0.), + m_weight_indiv_SF_EL_Isol_UP(0.), + m_weight_indiv_SF_EL_Isol_DOWN(0.), + m_weight_indiv_SF_EL_ChargeID(0.), + m_weight_indiv_SF_EL_ChargeID_UP(0.), + m_weight_indiv_SF_EL_ChargeID_DOWN(0.), + m_weight_indiv_SF_EL_ChargeMisID(0.), + m_weight_indiv_SF_EL_ChargeMisID_STAT_UP(0.), + m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN(0.), + m_weight_indiv_SF_EL_ChargeMisID_SYST_UP(0.), + m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN(0.), + + // Muon ID SF systematics (regular) + m_weight_indiv_SF_MU_ID(0.), + m_weight_indiv_SF_MU_ID_STAT_UP(0.), + m_weight_indiv_SF_MU_ID_STAT_DOWN(0.), + m_weight_indiv_SF_MU_ID_SYST_UP(0.), + m_weight_indiv_SF_MU_ID_SYST_DOWN(0.), + // Muon ID SF systematics (low pt) + m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP(0.), + m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN(0.), + m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP(0.), + m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN(0.), + // Muon isolation SF systematics + m_weight_indiv_SF_MU_Isol(0.), + m_weight_indiv_SF_MU_Isol_SYST_UP(0.), + m_weight_indiv_SF_MU_Isol_SYST_DOWN(0.), + m_weight_indiv_SF_MU_Isol_STAT_UP(0.), + m_weight_indiv_SF_MU_Isol_STAT_DOWN(0.), + m_weight_indiv_SF_MU_TTVA(0.), + m_weight_indiv_SF_MU_TTVA_SYST_UP(0.), + m_weight_indiv_SF_MU_TTVA_SYST_DOWN(0.), + m_weight_indiv_SF_MU_TTVA_STAT_UP(0.), + m_weight_indiv_SF_MU_TTVA_STAT_DOWN(0.), + + m_ASMsize(0.), + m_ASMweights(), + m_ASMweights_Syst(), + m_ASMweights_Systname(), + + m_eventNumber(0), + m_runNumber(0), + m_randomRunNumber(0), + m_mcChannelNumber(0), + + m_mu_original(0.), + m_mu(0.), + m_mu_actual_original(0.), + m_mu_actual(0.), + + m_backgroundFlags(0), + m_hasBadMuon(0), + m_makeRCJets(false), + m_makeVarRCJets(false), + m_useRCJSS(false), + m_useRCAdditionalJSS(false), + m_useVarRCJSS(false), + m_useVarRCAdditionalJSS(false), + m_useElectronChargeIDSelection(false), + m_met_met(0.), + m_met_phi(0.), + m_met_met_withLooseObjects(0.), + m_met_phi_withLooseObjects(0.) { + m_weight_leptonSF_EL_SF_CorrModel_Reco_UP = std::vector<float>(); + m_weight_leptonSF_EL_SF_CorrModel_Reco_DOWN = std::vector<float>(); + m_weight_leptonSF_EL_SF_CorrModel_ID_UP = std::vector<float>(); + m_weight_leptonSF_EL_SF_CorrModel_ID_DOWN = std::vector<float>(); + m_weight_leptonSF_EL_SF_CorrModel_Iso_UP = std::vector<float>(); + m_weight_leptonSF_EL_SF_CorrModel_Iso_DOWN = std::vector<float>(); + } + + EventSaverFlatNtuple::~EventSaverFlatNtuple() { + for (std::unordered_map<std::string, int*>::iterator i = m_extraTruthVars_int.begin(); + i != m_extraTruthVars_int.end(); ++i) + delete (*i).second; + + for (std::unordered_map<std::string, float*>::iterator i = m_extraTruthVars_float.begin(); + i != m_extraTruthVars_float.end(); ++i) + delete (*i).second; + } + + std::shared_ptr<top::TopConfig> EventSaverFlatNtuple::topConfig() { + return m_config; + } + + std::vector<std::shared_ptr<top::TreeManager> > EventSaverFlatNtuple::treeManagers() { + return m_treeManagers; + } + + std::shared_ptr<top::TreeManager> EventSaverFlatNtuple::truthTreeManager() { + return m_truthTreeManager; + } + + std::shared_ptr<top::TreeManager> EventSaverFlatNtuple::particleLevelTreeManager() { + return m_particleLevelTreeManager; + } + + //std::shared_ptr<top::ScaleFactorRetriever> EventSaverFlatNtuple::scaleFactorRetriever() + top::ScaleFactorRetriever* EventSaverFlatNtuple::scaleFactorRetriever() { + return m_sfRetriever; + } + + std::shared_ptr<top::TreeManager> EventSaverFlatNtuple::upgradeTreeManager() { + return m_upgradeTreeManager; + } + + std::vector<top::TreeManager::BranchFilter>& EventSaverFlatNtuple::branchFilters() { + return m_branchFilters; + } + + void EventSaverFlatNtuple::initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches) { + m_config = config; + m_outputFile = file; + m_extraBranches = extraBranches; + m_selectionDecisions.resize(m_extraBranches.size()); + + // set the branch filters + branchFilters().push_back(std::bind(&EventSaverFlatNtuple::filterBranches, this, std::placeholders::_1, + std::placeholders::_2)); + + // fixed-R re-clustering (RC) + if (config->useRCJets()) { + m_makeRCJets = true; + m_useRCJSS = config->useRCJetSubstructure(); + m_useRCAdditionalJSS = config->useRCJetAdditionalSubstructure(); } - EventSaverFlatNtuple::~EventSaverFlatNtuple() - { - for (std::unordered_map<std::string,int*>::iterator i=m_extraTruthVars_int.begin();i!=m_extraTruthVars_int.end();++i) - delete (*i).second; - - for (std::unordered_map<std::string,float*>::iterator i=m_extraTruthVars_float.begin();i!=m_extraTruthVars_float.end();++i) - delete (*i).second; - } + // variable-R re-clustering (VarRC) + if (config->useVarRCJets()) { + m_makeVarRCJets = true; + m_VarRCjetBranches.clear(); // clear map of branches just in case + m_VarRCjetsubBranches.clear(); + m_VarRCjetBranchesParticle.clear(); + m_VarRCjetsubBranchesParticle.clear(); - std::shared_ptr<top::TopConfig> EventSaverFlatNtuple::topConfig() - { - return m_config; - } - std::vector<std::shared_ptr<top::TreeManager>> EventSaverFlatNtuple::treeManagers() - { - return m_treeManagers; - } + boost::split(m_VarRCJetRho, config->VarRCJetRho(), boost::is_any_of(",")); + boost::split(m_VarRCJetMassScale, config->VarRCJetMassScale(), boost::is_any_of(",")); - std::shared_ptr<top::TreeManager> EventSaverFlatNtuple::truthTreeManager() - { - return m_truthTreeManager; - } + m_useVarRCJSS = config->useVarRCJetSubstructure(); + m_useVarRCAdditionalJSS = config->useVarRCJetAdditionalSubstructure(); + } // end make VarRC jets - std::shared_ptr<top::TreeManager> EventSaverFlatNtuple::particleLevelTreeManager() - { - return m_particleLevelTreeManager; + if (config->useElectronChargeIDSelection()) { + m_useElectronChargeIDSelection = true; } - std::shared_ptr<top::ScaleFactorRetriever> EventSaverFlatNtuple::scaleFactorRetriever() - { - return m_sfRetriever; + //make a tree for each systematic + std::string nominalTTreeName("SetMe"), nominalLooseTTreeName("SetMe"); + if (m_config->doTightEvents() && !m_config->HLLHC()) { + for (auto treeName : *config->systAllTTreeNames()) { + if (treeName.first == m_config->nominalHashValue() || m_config->doTightSysts()) { + m_treeManagers.push_back(std::shared_ptr<top::TreeManager>(new top::TreeManager(treeName.second, file, + m_config-> + outputFileNEventAutoFlush(), + m_config-> + outputFileBasketSizePrimitive(), + m_config-> + outputFileBasketSizeVector()))); + m_treeManagers.back()->branchFilters() = branchFilters(); + if (treeName.first == m_config->nominalHashValue()) { + nominalTTreeName = treeName.second; + } + } + } } - std::vector<top::TreeManager::BranchFilter> & EventSaverFlatNtuple::branchFilters() - { - return m_branchFilters; + if (m_config->doLooseEvents()) { + for (auto treeName : *config->systAllTTreeNames()) { + if (treeName.first == m_config->nominalHashValue() || m_config->doLooseSysts()) { + m_treeManagers.push_back(std::shared_ptr<top::TreeManager>(new top::TreeManager(treeName.second + "_Loose", + file, + m_config-> + outputFileNEventAutoFlush(), + m_config->outputFileBasketSizePrimitive(), + m_config-> + outputFileBasketSizeVector()))); + m_treeManagers.back()->branchFilters() = branchFilters(); + if (treeName.first == m_config->nominalHashValue()) { + nominalLooseTTreeName = treeName.second + "_Loose"; + } + } + } } - void EventSaverFlatNtuple::initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches) { - m_config = config; - m_outputFile = file; - m_extraBranches = extraBranches; - m_selectionDecisions.resize(m_extraBranches.size()); - + // Truth tree + if (m_config->isMC()) { + if (asg::ToolStore::contains<ScaleFactorRetriever>("top::ScaleFactorRetriever")) { + m_sfRetriever = asg::ToolStore::get<ScaleFactorRetriever>("top::ScaleFactorRetriever"); + } else { + top::ScaleFactorRetriever* topSFR = new top::ScaleFactorRetriever("top::ScaleFactorRetriever"); + top::check(asg::setProperty(topSFR, "config", m_config), "Failed to set config"); + top::check(topSFR->initialize(), "Failed to initalialise"); + m_sfRetriever = topSFR; + } - // fixed-R re-clustering (RC) - if (config->useRCJets() == true){ - m_makeRCJets = true; - m_rc = std::unique_ptr<RCJetMC15> ( new RCJetMC15( "RCJetMC15" ) ); - top::check(m_rc->setProperty( "config" , config ) , "Failed to set config property of RCJetMC15"); - top::check(m_rc->initialize(),"Failed to initialize RCJetMC15"); - } + m_truthTreeManager = + std::shared_ptr<top::TreeManager>(new top::TreeManager("truth", file, m_config->outputFileNEventAutoFlush(), + m_config->outputFileBasketSizePrimitive(), + m_config->outputFileBasketSizeVector())); + m_truthTreeManager->branchFilters() = branchFilters(); + m_truthTreeManager->makeOutputVariable(m_weight_mc, "weight_mc"); + m_truthTreeManager->makeOutputVariable(m_eventNumber, "eventNumber"); + m_truthTreeManager->makeOutputVariable(m_runNumber, "runNumber"); + m_truthTreeManager->makeOutputVariable(m_mu, "mu"); + m_truthTreeManager->makeOutputVariable(m_mu_actual, "mu_actual"); + m_truthTreeManager->makeOutputVariable(m_weight_pileup, "weight_pileup"); + if (m_config->isMC() && m_config->doPileupReweighting()) m_truthTreeManager->makeOutputVariable(m_randomRunNumber, + "randomRunNumber"); + + m_truthTreeManager->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); + + // Only if you really really want it - this is BIG + if (m_config->useTruthParticles() && m_config->doTruthBlockInfo()) { + m_truthTreeManager->makeOutputVariable(m_mc_pt, "mc_pt"); + m_truthTreeManager->makeOutputVariable(m_mc_eta, "mc_eta"); + m_truthTreeManager->makeOutputVariable(m_mc_phi, "mc_phi"); + m_truthTreeManager->makeOutputVariable(m_mc_e, "mc_e"); + m_truthTreeManager->makeOutputVariable(m_mc_pdgId, "mc_pdgId"); + m_truthTreeManager->makeOutputVariable(m_mc_charge, "mc_charge"); + m_truthTreeManager->makeOutputVariable(m_mc_status, "mc_status"); + m_truthTreeManager->makeOutputVariable(m_mc_barcode, "mc_barcode"); + } - // variable-R re-clustering (VarRC) - if (config->useVarRCJets() == true){ - m_makeVarRCJets = true; - m_VarRCjetBranches.clear(); // clear map of branches just in case - m_VarRCjetsubBranches.clear(); - - boost::split(m_VarRCJetRho, config->VarRCJetRho(), boost::is_any_of(",")); - boost::split(m_VarRCJetMassScale, config->VarRCJetMassScale(), boost::is_any_of(",")); - - for (auto& rho : m_VarRCJetRho){ - for (auto& mass_scale : m_VarRCJetMassScale){ - std::replace( rho.begin(), rho.end(), '.', '_'); - std::string name = rho+mass_scale; - m_VarRC[name] = std::unique_ptr<RCJetMC15> ( new RCJetMC15( "VarRCJetMC15_"+name ) ); - top::check(m_VarRC[name]->setProperty( "config" , config ) , "Failed to set config property of VarRCJetMC15"); - top::check(m_VarRC[name]->setProperty( "VarRCjets", true ) , "Failed to set VarRCjets property of VarRCJetMC15"); - top::check(m_VarRC[name]->setProperty( "VarRCjets_rho", rho ) , "Failed to set VarRCjets rho property of VarRCJetMC15"); - top::check(m_VarRC[name]->setProperty( "VarRCjets_mass_scale", mass_scale ) , "Failed to set VarRCjets mass scale property of VarRCJetMC15"); - top::check(m_VarRC[name]->initialize(),"Failed to initialize VarRCJetMC15"); - } // end loop over mass scale parameters (e.g., top mass, w mass, etc.) - } // end loop over mass scale multiplies (e.g., 1.,2.,etc.) - } // end make VarRC jets - - - //make a tree for each systematic - std::string nominalTTreeName("SetMe"),nominalLooseTTreeName("SetMe"); - if (!m_config->doLooseTreeOnly() && !m_config->HLLHC()) { - for (auto treeName : *config->systAllTTreeNames()) { - m_treeManagers.push_back(std::shared_ptr<top::TreeManager>( new top::TreeManager(treeName.second, file , m_config->outputFileSetAutoFlushZero()) ) ); - m_treeManagers.back()->branchFilters() = branchFilters(); - if (treeName.first == m_config->nominalHashValue()) { - nominalTTreeName = treeName.second; - } + // PDF information + if (m_config->doTruthPDFInfo()) { + if (m_config->doTruthPDFInfoInNominalTrees()) {//if PDF info requested to be saved in nominal trees of truth one + for (auto systematicTree : m_treeManagers) {//loop on systematic trees to only get the nominal ones + if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { + systematicTree->makeOutputVariable(m_PDFinfo_X1, "PDFinfo_X1"); + systematicTree->makeOutputVariable(m_PDFinfo_X2, "PDFinfo_X2"); + systematicTree->makeOutputVariable(m_PDFinfo_PDGID1, "PDFinfo_PDGID1"); + systematicTree->makeOutputVariable(m_PDFinfo_PDGID2, "PDFinfo_PDGID2"); + systematicTree->makeOutputVariable(m_PDFinfo_Q, "PDFinfo_Q"); + systematicTree->makeOutputVariable(m_PDFinfo_XF1, "PDFinfo_XF1"); + systematicTree->makeOutputVariable(m_PDFinfo_XF2, "PDFinfo_XF2"); + } } + } else { + m_truthTreeManager->makeOutputVariable(m_PDFinfo_X1, "PDFinfo_X1"); + m_truthTreeManager->makeOutputVariable(m_PDFinfo_X2, "PDFinfo_X2"); + m_truthTreeManager->makeOutputVariable(m_PDFinfo_PDGID1, "PDFinfo_PDGID1"); + m_truthTreeManager->makeOutputVariable(m_PDFinfo_PDGID2, "PDFinfo_PDGID2"); + m_truthTreeManager->makeOutputVariable(m_PDFinfo_Q, "PDFinfo_Q"); + m_truthTreeManager->makeOutputVariable(m_PDFinfo_XF1, "PDFinfo_XF1"); + m_truthTreeManager->makeOutputVariable(m_PDFinfo_XF2, "PDFinfo_XF2"); } + } - if (m_config->doLooseEvents()) { - for (auto treeName : *config->systAllTTreeNames()) { - m_treeManagers.push_back(std::shared_ptr<top::TreeManager>( new top::TreeManager(treeName.second+"_Loose", file , m_config->outputFileSetAutoFlushZero()) ) ); - m_treeManagers.back()->branchFilters() = branchFilters(); - if (treeName.first == m_config->nominalHashValue()) { - nominalLooseTTreeName = treeName.second+"_Loose"; - } + // MC Generator weights + if (m_config->doMCGeneratorWeights()) { + if (m_config->doMCGeneratorWeightsInNominalTrees()) {//if MCGeneratorWeights requested to be saved in nominal + // trees of truth one + for (auto systematicTree : m_treeManagers) {//loop on systematic trees to only get the nominal ones + if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { + systematicTree->makeOutputVariable(m_mc_generator_weights, "mc_generator_weights"); } + } + } else { + m_truthTreeManager->makeOutputVariable(m_mc_generator_weights, "mc_generator_weights"); } + } - // Truth tree - if (m_config->isMC()) { - - m_sfRetriever = std::unique_ptr<top::ScaleFactorRetriever> ( new top::ScaleFactorRetriever( m_config ) ); - - m_truthTreeManager = std::shared_ptr<top::TreeManager>( new top::TreeManager( "truth" , file , m_config->outputFileSetAutoFlushZero()) ); - m_truthTreeManager->branchFilters() = branchFilters(); - m_truthTreeManager->makeOutputVariable(m_weight_mc, "weight_mc"); - m_truthTreeManager->makeOutputVariable(m_eventNumber, "eventNumber"); - m_truthTreeManager->makeOutputVariable(m_runNumber, "runNumber"); - m_truthTreeManager->makeOutputVariable(m_mu, "mu"); - m_truthTreeManager->makeOutputVariable(m_weight_pileup, "weight_pileup"); - if (m_config->isMC() && m_config->doPileupReweighting()) m_truthTreeManager->makeOutputVariable(m_randomRunNumber, "randomRunNumber"); - m_truthTreeManager->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); - - // Only if you really really want it - this is BIG - if (m_config->useTruthParticles() && m_config->doTruthBlockInfo() ) { - m_truthTreeManager->makeOutputVariable(m_mc_pt, "mc_pt"); - m_truthTreeManager->makeOutputVariable(m_mc_eta, "mc_eta"); - m_truthTreeManager->makeOutputVariable(m_mc_phi, "mc_phi"); - m_truthTreeManager->makeOutputVariable(m_mc_e, "mc_e"); - m_truthTreeManager->makeOutputVariable(m_mc_pdgId, "mc_pdgId"); - } - - // PDF information - if (m_config->doTruthPDFInfo()) { - if (m_config->doTruthPDFInfoInNominalTrees()) {//if PDF info requested to be saved in nominal trees of truth one - for (auto systematicTree : m_treeManagers) {//loop on systematic trees to only get the nominal ones - if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { - systematicTree->makeOutputVariable(m_PDFinfo_X1,"PDFinfo_X1"); - systematicTree->makeOutputVariable(m_PDFinfo_X2,"PDFinfo_X2"); - systematicTree->makeOutputVariable(m_PDFinfo_PDGID1,"PDFinfo_PDGID1"); - systematicTree->makeOutputVariable(m_PDFinfo_PDGID2,"PDFinfo_PDGID2"); - systematicTree->makeOutputVariable(m_PDFinfo_Q,"PDFinfo_Q"); - systematicTree->makeOutputVariable(m_PDFinfo_XF1,"PDFinfo_XF1"); - systematicTree->makeOutputVariable(m_PDFinfo_XF2,"PDFinfo_XF2"); - } - } - } - else { - m_truthTreeManager->makeOutputVariable(m_PDFinfo_X1,"PDFinfo_X1"); - m_truthTreeManager->makeOutputVariable(m_PDFinfo_X2,"PDFinfo_X2"); - m_truthTreeManager->makeOutputVariable(m_PDFinfo_PDGID1,"PDFinfo_PDGID1"); - m_truthTreeManager->makeOutputVariable(m_PDFinfo_PDGID2,"PDFinfo_PDGID2"); - m_truthTreeManager->makeOutputVariable(m_PDFinfo_Q,"PDFinfo_Q"); - m_truthTreeManager->makeOutputVariable(m_PDFinfo_XF1,"PDFinfo_XF1"); - m_truthTreeManager->makeOutputVariable(m_PDFinfo_XF2,"PDFinfo_XF2"); - } + if (m_config->saveLHAPDFEvent()) { + for (const auto& pdfset : m_config->LHAPDFSets()) + m_PDF_eventWeights[ pdfset ] = std::vector<float>(); + + for (auto& pdf : m_PDF_eventWeights) { + if (m_config->doLHAPDFInNominalTrees()) {//if PDF weights requested to be saved in nominal trees instead of + // truth one + for (auto systematicTree : m_treeManagers) {//loop on systematic trees to only get the nominal ones + if (systematicTree->name() == nominalTTreeName || + systematicTree->name() == + nominalLooseTTreeName) systematicTree->makeOutputVariable(pdf.second, pdf.first); } + } else { + m_truthTreeManager->makeOutputVariable(pdf.second, pdf.first); + } + } + } + } - // MC Generator weights - if (m_config->doMCGeneratorWeights()) { - if (m_config->doMCGeneratorWeightsInNominalTrees()) {//if MCGeneratorWeights requested to be saved in nominal trees of truth one - for (auto systematicTree : m_treeManagers) {//loop on systematic trees to only get the nominal ones - if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { - systematicTree->makeOutputVariable(m_mc_generator_weights,"mc_generator_weights"); - } - } - } - else { - m_truthTreeManager->makeOutputVariable(m_mc_generator_weights,"mc_generator_weights"); - } - } - - if( m_config->saveLHAPDFEvent() ){ - for( const auto& pdfset : m_config->LHAPDFSets() ) - m_PDF_eventWeights[ pdfset ] = std::vector<float>(); - - for( auto& pdf : m_PDF_eventWeights ) { - if (m_config->doLHAPDFInNominalTrees()) {//if PDF weights requested to be saved in nominal trees instead of truth one - for (auto systematicTree : m_treeManagers) {//loop on systematic trees to only get the nominal ones - if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) - systematicTree->makeOutputVariable( pdf.second, pdf.first ); - } - } - else { - m_truthTreeManager->makeOutputVariable( pdf.second, pdf.first ); - } - } - } + if (m_config->useLargeRJets()) { + for (const std::pair<std::string, std::string>& taggerName : m_config->boostedJetTaggers()) + m_boostedJetTaggersNames.push_back(taggerName.first + "_" + taggerName.second); + for (const std::pair<std::string, std::string>& taggerSF : m_config->boostedTaggerSFnames()) + m_boostedJetTaggersNamesCalibrated.push_back(taggerSF.first); + } + if (m_config->useJets()) { + for (const std::string& algo : m_config->bTagAlgo_available()) { + if (DLx.count(algo) == 0) { + DLx.emplace(algo, SG::AuxElement::ConstAccessor<float>("AnalysisTop_" + algo)); + m_jet_DLx[algo] = std::vector<float>(); + m_jet_DLx_pb[algo] = std::vector<float>(); + m_jet_DLx_pc[algo] = std::vector<float>(); + m_jet_DLx_pu[algo] = std::vector<float>(); } + } + } - //loop over systematics and attach variables - for (auto systematicTree : m_treeManagers) { - - if (m_config->isMC()) { - - systematicTree->makeOutputVariable(m_weight_mc, "weight_mc"); - - //some event weights - systematicTree->makeOutputVariable(m_weight_pileup, "weight_pileup"); - systematicTree->makeOutputVariable(m_weight_leptonSF , "weight_leptonSF"); - - if (m_config->usePhotons()) - systematicTree->makeOutputVariable(m_weight_photonSF, - "weight_photonSF"); - - if (m_config->useTaus()) - systematicTree->makeOutputVariable(m_weight_tauSF, - "weight_tauSF"); - - // nominal b-tagging SFs - for( auto& tagWP : m_config -> bTagWP_available()){ - // skip uncalibrated though available WPs - if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; - m_weight_bTagSF[tagWP] = 0.; - systematicTree->makeOutputVariable(m_weight_bTagSF[tagWP] , "weight_bTagSF_"+shortBtagWP(tagWP)); - } - if( m_config->useTrackJets() ) { - for( auto& tagWP : m_config -> bTagWP_available_trkJet()) { - // skip uncalibrated though available WPs - if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; - m_weight_trackjet_bTagSF[tagWP] = 0.; - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF[tagWP] , "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)); - } - } - - systematicTree->makeOutputVariable(m_weight_jvt, "weight_jvt"); - - if (m_config->isSherpa22Vjets()) - systematicTree->makeOutputVariable(m_weight_sherpa_22_vjets, - "weight_sherpa_22_vjets"); - - if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { - - systematicTree->makeOutputVariable(m_weight_pileup_UP , "weight_pileup_UP"); - systematicTree->makeOutputVariable(m_weight_pileup_DOWN , "weight_pileup_DOWN"); - - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Trigger_UP, "weight_leptonSF_EL_SF_Trigger_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Trigger_DOWN, "weight_leptonSF_EL_SF_Trigger_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Reco_UP, "weight_leptonSF_EL_SF_Reco_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Reco_DOWN, "weight_leptonSF_EL_SF_Reco_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_ID_UP, "weight_leptonSF_EL_SF_ID_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_ID_DOWN, "weight_leptonSF_EL_SF_ID_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Isol_UP, "weight_leptonSF_EL_SF_Isol_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Isol_DOWN, "weight_leptonSF_EL_SF_Isol_DOWN"); - - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_STAT_UP, "weight_leptonSF_MU_SF_Trigger_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN, "weight_leptonSF_MU_SF_Trigger_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_SYST_UP, "weight_leptonSF_MU_SF_Trigger_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN, "weight_leptonSF_MU_SF_Trigger_SYST_DOWN"); - // Muon ID SF systematics (regular) - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_UP, "weight_leptonSF_MU_SF_ID_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_DOWN, "weight_leptonSF_MU_SF_ID_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_UP, "weight_leptonSF_MU_SF_ID_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_DOWN, "weight_leptonSF_MU_SF_ID_SYST_DOWN"); - // Muon ID SF systematics (low pt) - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP, "weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN, "weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP, "weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN, "weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN"); - // Muon isolation SF systematics - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_STAT_UP, "weight_leptonSF_MU_SF_Isol_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_STAT_DOWN, "weight_leptonSF_MU_SF_Isol_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_SYST_UP, "weight_leptonSF_MU_SF_Isol_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_SYST_DOWN, "weight_leptonSF_MU_SF_Isol_SYST_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_STAT_UP, "weight_leptonSF_MU_SF_TTVA_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN, "weight_leptonSF_MU_SF_TTVA_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_SYST_UP, "weight_leptonSF_MU_SF_TTVA_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN, "weight_leptonSF_MU_SF_TTVA_SYST_DOWN"); - - - // write also out the individual components: - - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Trigger, "weight_indiv_SF_EL_Trigger"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Trigger_UP, "weight_indiv_SF_EL_Trigger_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Trigger_DOWN, "weight_indiv_SF_EL_Trigger_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Reco, "weight_indiv_SF_EL_Reco"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Reco_UP, "weight_indiv_SF_EL_Reco_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Reco_DOWN, "weight_indiv_SF_EL_Reco_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ID, "weight_indiv_SF_EL_ID"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ID_UP, "weight_indiv_SF_EL_ID_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ID_DOWN, "weight_indiv_SF_EL_ID_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Isol, "weight_indiv_SF_EL_Isol"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Isol_UP, "weight_indiv_SF_EL_Isol_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Isol_DOWN, "weight_indiv_SF_EL_Isol_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeID, "weight_indiv_SF_EL_ChargeID"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeID_UP, "weight_indiv_SF_EL_ChargeID_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeID_DOWN, "weight_indiv_SF_EL_ChargeID_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID, "weight_indiv_SF_EL_ChargeMisID"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_STAT_UP, "weight_indiv_SF_EL_ChargeMisID_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN,"weight_indiv_SF_EL_ChargeMisID_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_SYST_UP, "weight_indiv_SF_EL_ChargeMisID_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN,"weight_indiv_SF_EL_ChargeMisID_SYST_DOWN"); - - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Trigger, "weight_indiv_SF_MU_Trigger"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Trigger_STAT_UP, "weight_indiv_SF_MU_Trigger_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Trigger_STAT_DOWN, "weight_indiv_SF_MU_Trigger_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Trigger_SYST_UP, "weight_indiv_SF_MU_Trigger_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Trigger_SYST_DOWN, "weight_indiv_SF_MU_Trigger_SYST_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID, "weight_indiv_SF_MU_ID"); - // Muon ID SF systematics (regular) - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_UP, "weight_indiv_SF_MU_ID_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_DOWN, "weight_indiv_SF_MU_ID_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_UP, "weight_indiv_SF_MU_ID_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_DOWN, "weight_indiv_SF_MU_ID_SYST_DOWN"); - // Muon ID SF systematics (low pt) - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP, "weight_indiv_SF_MU_ID_STAT_LOWPT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN, "weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP, "weight_indiv_SF_MU_ID_SYST_LOWPT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN, "weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN"); - // Muon isolation SF systematics - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol, "weight_indiv_SF_MU_Isol"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_STAT_UP, "weight_indiv_SF_MU_Isol_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_STAT_DOWN, "weight_indiv_SF_MU_Isol_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_SYST_UP, "weight_indiv_SF_MU_Isol_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_SYST_DOWN, "weight_indiv_SF_MU_Isol_SYST_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA, "weight_indiv_SF_MU_TTVA"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_STAT_UP, "weight_indiv_SF_MU_TTVA_STAT_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_STAT_DOWN, "weight_indiv_SF_MU_TTVA_STAT_DOWN"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_SYST_UP, "weight_indiv_SF_MU_TTVA_SYST_UP"); - systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_SYST_DOWN, "weight_indiv_SF_MU_TTVA_SYST_DOWN"); - - if (m_config->useTaus()) { - systematicTree->makeOutputVariable(m_weight_tauSF_ELEOLR_UP, - "weight_tauSF_ELEOLR_UP"); - systematicTree->makeOutputVariable(m_weight_tauSF_ELEOLR_DOWN, - "weight_tauSF_ELEOLR_DOWN"); - systematicTree->makeOutputVariable(m_weight_tauSF_JETID_UP, - "weight_tauSF_JETID_UP"); - systematicTree->makeOutputVariable(m_weight_tauSF_JETID_DOWN, - "weight_tauSF_JETID_DOWN"); - systematicTree->makeOutputVariable(m_weight_tauSF_RECO_UP, - "weight_tauSF_RECO_UP"); - systematicTree->makeOutputVariable(m_weight_tauSF_RECO_DOWN, - "weight_tauSF_RECO_DOWN"); - } - - if (m_config->usePhotons()) { - systematicTree->makeOutputVariable(m_weight_photonSF_ID_UP, - "weight_photonSF_ID_UP"); - systematicTree->makeOutputVariable(m_weight_photonSF_ID_DOWN, - "weight_photonSF_ID_DOWN"); - systematicTree->makeOutputVariable(m_weight_photonSF_effIso, - "weight_photonSF_effIso"); - systematicTree->makeOutputVariable(m_weight_photonSF_effLowPtIso_UP, - "weight_photonSF_effLowPtIso_UP"); - systematicTree->makeOutputVariable(m_weight_photonSF_effLowPtIso_DOWN, - "weight_photonSF_effLowPtIso_DOWN"); - systematicTree->makeOutputVariable(m_weight_photonSF_effTrkIso_UP, - "weight_photonSF_effTrkIso_UP"); - systematicTree->makeOutputVariable(m_weight_photonSF_effTrkIso_DOWN, - "weight_photonSF_effTrkIso_DOWN"); - } - - systematicTree->makeOutputVariable(m_weight_jvt_up, "weight_jvt_UP"); - systematicTree->makeOutputVariable(m_weight_jvt_down, "weight_jvt_DOWN"); - - } - - // for b-tagging SFs, can also have systematic-shifted in systematics trees - if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName || m_config->dumpBtagSystsInSystTrees()) { - // b-tagging SFs: eigenvectors and named systematics - for( auto& tagWP : m_config -> bTagWP_available()) { - // skip uncalibrated though available WPs - if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; - // up - systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_B_up[tagWP], "weight_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_B_up"); - systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_C_up[tagWP], "weight_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_C_up"); - systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_Light_up[tagWP], "weight_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_Light_up"); - // down - systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_B_down[tagWP], "weight_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_B_down"); - systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_C_down[tagWP], "weight_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_C_down"); - systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_Light_down[tagWP], "weight_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_Light_down"); - // named systematics - for (auto name : m_config->btagging_namedSysts(tagWP)) { - systematicTree->makeOutputVariable(m_weight_bTagSF_named_up[tagWP][name], "weight_bTagSF_"+shortBtagWP(tagWP)+"_"+betterBtagNamedSyst(name)+"_up" ); - systematicTree->makeOutputVariable(m_weight_bTagSF_named_down[tagWP][name], "weight_bTagSF_"+shortBtagWP(tagWP)+"_"+betterBtagNamedSyst(name)+"_down" ); - } - } - if( m_config->useTrackJets() ) { - for( auto& tagWP : m_config -> bTagWP_available_trkJet()) { - // skip uncalibrated though available WPs - if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; - // up - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_B_up[tagWP], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_B_up"); - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_C_up[tagWP], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_C_up"); - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_Light_up[tagWP], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_Light_up"); - // down - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_B_down[tagWP], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_B_down"); - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_C_down[tagWP], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_C_down"); - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_Light_down[tagWP], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_eigenvars_Light_down"); - // named systematics - for (auto name : m_config->trkjet_btagging_namedSysts(tagWP)) { - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_named_up[tagWP][name], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_"+betterBtagNamedSyst(name)+"_up" ); - systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_named_down[tagWP][name], "weight_trackjet_bTagSF_"+shortBtagWP(tagWP)+"_"+betterBtagNamedSyst(name)+"_down" ); - } - } - } - } - } + if (m_config->useTrackJets()) { + for (const std::string& algo : m_config->bTagAlgo_available_trkJet()) { + if (DLx.count(algo) == 0) { + DLx.emplace(algo, SG::AuxElement::ConstAccessor<float>("AnalysisTop_" + algo)); + m_tjet_DLx[algo] = std::vector<float>(); + m_tjet_DLx_pb[algo] = std::vector<float>(); + m_tjet_DLx_pc[algo] = std::vector<float>(); + m_tjet_DLx_pu[algo] = std::vector<float>(); + } + } + } - ///-- weights for matrix-method fakes estimate --/// - if (!m_config->isMC() && systematicTree->name().find("Loose") != std::string::npos && m_config->doFakesMMWeights()) { - top::TopFakesMMWeightCalculator const* fakesMMWeightCalc(nullptr); - if ( asg::ToolStore::contains<top::TopFakesMMWeightCalculator>("MMWeightCalculator") ) { - fakesMMWeightCalc = asg::ToolStore::get<top::TopFakesMMWeightCalculator>("MMWeightCalculator"); - } - else { - ATH_MSG_ERROR("EventSaverFlatNtuple::initialize" ); - throw std::runtime_error("Unable to retrieve top::TopFakesMMWeightCalculator tool"); - } - for(const auto& branchName : m_extraBranches){//loop on selections - for(const auto& conf : fakesMMWeightCalc->GetFakesMMConfigNames(branchName)) { - std::string MMweight_branch_name = "fakesMM_weight_" + branchName + "_" + conf; - systematicTree->makeOutputVariable(m_fakesMM_weights[branchName][conf], MMweight_branch_name); - } - } - } + //loop over systematics and attach variables + for (auto systematicTree : m_treeManagers) { + if (m_config->isMC()) { + systematicTree->makeOutputVariable(m_weight_mc, "weight_mc"); - //event info - systematicTree->makeOutputVariable(m_eventNumber, "eventNumber"); - systematicTree->makeOutputVariable(m_runNumber, "runNumber"); - if (m_config->isMC() && m_config->doPileupReweighting()) systematicTree->makeOutputVariable(m_randomRunNumber, "randomRunNumber"); - systematicTree->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); - systematicTree->makeOutputVariable(m_mu, "mu"); - if (!m_config->isMC()) { - systematicTree->makeOutputVariable(m_mu_original, "mu_original_xAOD"); - } - systematicTree->makeOutputVariable(m_backgroundFlags, "backgroundFlags"); - if (m_config->useMuons()) - systematicTree->makeOutputVariable(m_hasBadMuon, "hasBadMuon"); - - //electrons - if (m_config->useElectrons()) { - systematicTree->makeOutputVariable(m_el_pt, "el_pt"); - systematicTree->makeOutputVariable(m_el_eta, "el_eta"); - systematicTree->makeOutputVariable(m_el_cl_eta, "el_cl_eta"); - systematicTree->makeOutputVariable(m_el_phi, "el_phi"); - systematicTree->makeOutputVariable(m_el_e, "el_e"); - systematicTree->makeOutputVariable(m_el_charge, "el_charge"); - systematicTree->makeOutputVariable(m_el_topoetcone20, "el_topoetcone20"); - systematicTree->makeOutputVariable(m_el_ptvarcone20, "el_ptvarcone20"); - if (systematicTree->name().find("Loose") != std::string::npos) { - systematicTree->makeOutputVariable(m_el_isTight, "el_isTight"); - } - systematicTree->makeOutputVariable(m_el_CF, "el_CF"); - systematicTree->makeOutputVariable(m_el_d0sig, "el_d0sig"); - systematicTree->makeOutputVariable(m_el_delta_z0_sintheta, "el_delta_z0_sintheta"); - if (m_config->isMC()) { - systematicTree->makeOutputVariable(m_el_true_type, "el_true_type"); - systematicTree->makeOutputVariable(m_el_true_origin, "el_true_origin"); - systematicTree->makeOutputVariable(m_el_true_typebkg, "el_true_typebkg"); - systematicTree->makeOutputVariable(m_el_true_originbkg, "el_true_originbkg"); - } + //some event weights + systematicTree->makeOutputVariable(m_weight_pileup, "weight_pileup"); + systematicTree->makeOutputVariable(m_weight_leptonSF, "weight_leptonSF"); + + if (m_config->useFwdElectrons()) systematicTree->makeOutputVariable(m_weight_fwdElSF, "weight_fwdElSF"); + + if (m_config->usePhotons()) systematicTree->makeOutputVariable(m_weight_photonSF, "weight_photonSF"); + + if (m_config->useTaus()) systematicTree->makeOutputVariable(m_weight_tauSF, + "weight_tauSF"); + + if (m_config->useGlobalTriggerConfiguration()) systematicTree->makeOutputVariable( + m_weight_globalLeptonTriggerSF, "weight_globalLeptonTriggerSF"); + systematicTree->makeOutputVariable(m_weight_oldTriggerSF, "weight_oldTriggerSF"); + + // nominal b-tagging SFs + for (auto& tagWP : m_config->bTagWP_available()) { + // skip uncalibrated though available WPs + if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), + tagWP) == m_config->bTagWP_calibrated().end()) continue; + m_weight_bTagSF[tagWP] = 0.; + systematicTree->makeOutputVariable(m_weight_bTagSF[tagWP], "weight_bTagSF_" + shortBtagWP(tagWP)); + if (m_config->storePerJetBtagSFs() && m_config->isMC()) { + m_perjet_weight_bTagSF[tagWP] = std::vector<float>(); + m_perjet_weight_bTagSF_eigen_B_up[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_bTagSF_eigen_B_down[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_bTagSF_eigen_C_up[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_bTagSF_eigen_C_down[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_bTagSF_eigen_Light_up[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_bTagSF_eigen_Light_down[tagWP] = std::vector<std::vector<float> >(); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF[tagWP], + "weight_perjet_bTagSF_" + shortBtagWP(tagWP)); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_eigen_B_up[tagWP], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_up"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_eigen_B_down[tagWP], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_down"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_eigen_C_up[tagWP], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_up"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_eigen_C_down[tagWP], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_down"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_eigen_Light_up[tagWP], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_Light_up"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_eigen_Light_down[tagWP], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_Light_down"); + for (const std::string& name : m_config->btagging_namedSysts(tagWP)) { + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_named_up[tagWP][name], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_up"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_named_down[tagWP][name], "weight_perjet_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_down"); } - - //muons - if (m_config->useMuons()) { - systematicTree->makeOutputVariable(m_mu_pt, "mu_pt"); - systematicTree->makeOutputVariable(m_mu_eta, "mu_eta"); - systematicTree->makeOutputVariable(m_mu_phi, "mu_phi"); - systematicTree->makeOutputVariable(m_mu_e, "mu_e"); - systematicTree->makeOutputVariable(m_mu_charge, "mu_charge"); - systematicTree->makeOutputVariable(m_mu_topoetcone20, "mu_topoetcone20"); - systematicTree->makeOutputVariable(m_mu_ptvarcone30, "mu_ptvarcone30"); - if (systematicTree->name().find("Loose") != std::string::npos) { - systematicTree->makeOutputVariable(m_mu_isTight, "mu_isTight"); - } - systematicTree->makeOutputVariable(m_mu_d0sig, "mu_d0sig"); - systematicTree->makeOutputVariable(m_mu_delta_z0_sintheta, "mu_delta_z0_sintheta"); - if (m_config->isMC()) { - systematicTree->makeOutputVariable(m_mu_true_type, "mu_true_type"); - systematicTree->makeOutputVariable(m_mu_true_origin, "mu_true_origin"); + } + } + if (m_config->useTrackJets()) { + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + // skip uncalibrated though available WPs + if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), m_config->bTagWP_calibrated_trkJet().end(), + tagWP) == m_config->bTagWP_calibrated_trkJet().end()) continue; + m_weight_trackjet_bTagSF[tagWP] = 0.; + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF[tagWP], + "weight_trackjet_bTagSF_" + shortBtagWP(tagWP)); + if (m_config->storePerJetBtagSFs() && m_config->isMC()) { + m_perjet_weight_trackjet_bTagSF[tagWP] = std::vector<float>(); + m_perjet_weight_trackjet_bTagSF_eigen_B_up[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_trackjet_bTagSF_eigen_B_down[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_trackjet_bTagSF_eigen_C_up[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_trackjet_bTagSF_eigen_C_down[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_trackjet_bTagSF_eigen_Light_up[tagWP] = std::vector<std::vector<float> >(); + m_perjet_weight_trackjet_bTagSF_eigen_Light_down[tagWP] = std::vector<std::vector<float> >(); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP)); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF_eigen_B_up[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_up"); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF_eigen_B_down[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_down"); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF_eigen_C_up[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_up"); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF_eigen_C_down[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_down"); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF_eigen_Light_up[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_Light_up"); + systematicTree->makeOutputVariable(m_perjet_weight_trackjet_bTagSF_eigen_Light_down[tagWP], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_Light_down"); + for (const std::string& name : m_config->trkjet_btagging_namedSysts(tagWP)) { + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_named_up[tagWP][name], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_up"); + systematicTree->makeOutputVariable(m_perjet_weight_bTagSF_named_down[tagWP][name], "weight_perjet_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_down"); } } + } + } - //photons - if (m_config->usePhotons()) { - systematicTree->makeOutputVariable(m_ph_pt, "ph_pt"); - systematicTree->makeOutputVariable(m_ph_eta, "ph_eta"); - systematicTree->makeOutputVariable(m_ph_phi, "ph_phi"); - systematicTree->makeOutputVariable(m_ph_e, "ph_e"); - systematicTree->makeOutputVariable(m_ph_iso, "ph_iso"); - } - - //taus - if (m_config->useTaus()) { - systematicTree->makeOutputVariable(m_tau_pt, "tau_pt"); - systematicTree->makeOutputVariable(m_tau_eta, "tau_eta"); - systematicTree->makeOutputVariable(m_tau_phi, "tau_phi"); - systematicTree->makeOutputVariable(m_tau_charge, "tau_charge"); - } - - //jets - if (m_config->useJets()) { - systematicTree->makeOutputVariable(m_jet_pt, "jet_pt"); - systematicTree->makeOutputVariable(m_jet_eta, "jet_eta"); - systematicTree->makeOutputVariable(m_jet_phi, "jet_phi"); - systematicTree->makeOutputVariable(m_jet_e, "jet_e"); - systematicTree->makeOutputVariable(m_jet_mv2c00, "jet_mv2c00"); - systematicTree->makeOutputVariable(m_jet_mv2c10, "jet_mv2c10"); - systematicTree->makeOutputVariable(m_jet_mv2c20, "jet_mv2c20"); - systematicTree->makeOutputVariable(m_jet_ip3dsv1, "jet_ip3dsv1"); - systematicTree->makeOutputVariable(m_jet_jvt, "jet_jvt"); - systematicTree->makeOutputVariable(m_jet_passfjvt,"jet_passfjvt"); - if (m_config->isMC()) { - systematicTree->makeOutputVariable(m_jet_truthflav, "jet_truthflav"); - systematicTree->makeOutputVariable(m_jet_truthPartonLabel, "jet_truthPartonLabel"); - systematicTree->makeOutputVariable(m_jet_isTrueHS, "jet_isTrueHS"); - } - for( auto& tagWP : m_config -> bTagWP_available()){ - if (tagWP!= "Continuous") systematicTree->makeOutputVariable(m_jet_isbtagged[tagWP] , "jet_isbtagged_"+shortBtagWP(tagWP)); - else systematicTree->makeOutputVariable(m_jet_tagWeightBin , "jet_tagWeightBin"); - } - } - - //large-R jets - if (m_config->useLargeRJets()) { - systematicTree->makeOutputVariable(m_ljet_pt, "ljet_pt"); - systematicTree->makeOutputVariable(m_ljet_eta, "ljet_eta"); - systematicTree->makeOutputVariable(m_ljet_phi, "ljet_phi"); - systematicTree->makeOutputVariable(m_ljet_e, "ljet_e"); - systematicTree->makeOutputVariable(m_ljet_m, "ljet_m"); - systematicTree->makeOutputVariable(m_ljet_sd12, "ljet_sd12"); - } - //track jets - if (m_config->useTrackJets()) { - systematicTree->makeOutputVariable(m_tjet_pt, "tjet_pt"); - systematicTree->makeOutputVariable(m_tjet_eta, "tjet_eta"); - systematicTree->makeOutputVariable(m_tjet_phi, "tjet_phi"); - systematicTree->makeOutputVariable(m_tjet_e, "tjet_e"); - systematicTree->makeOutputVariable(m_tjet_mv2c00, "tjet_mv2c00"); - systematicTree->makeOutputVariable(m_tjet_mv2c10, "tjet_mv2c10"); - systematicTree->makeOutputVariable(m_tjet_mv2c20, "tjet_mv2c20"); - for( auto& tagWP : m_config -> bTagWP_available_trkJet()){ - if (tagWP!= "Continuous") systematicTree->makeOutputVariable(m_tjet_isbtagged[tagWP] , "tjet_isbtagged_"+shortBtagWP(tagWP)); - else systematicTree->makeOutputVariable(m_tjet_tagWeightBin , "tjet_tagWeightBin"); - } - } + systematicTree->makeOutputVariable(m_weight_jvt, "weight_jvt"); + if (m_config->getfJVTWP() != "None") systematicTree->makeOutputVariable(m_weight_forwardjvt, "weight_forwardjvt"); - // RC branches - if (m_makeRCJets){ - systematicTree->makeOutputVariable(m_rcjet_pt, "rcjet_pt"); - systematicTree->makeOutputVariable(m_rcjet_eta, "rcjet_eta"); - systematicTree->makeOutputVariable(m_rcjet_phi, "rcjet_phi"); - systematicTree->makeOutputVariable(m_rcjet_e, "rcjet_e"); - systematicTree->makeOutputVariable(m_rcjet_d12, "rcjet_d12"); // requires >= 2 subjets - systematicTree->makeOutputVariable(m_rcjet_d23, "rcjet_d23"); // requires >= 3 subjets - systematicTree->makeOutputVariable(m_rcjetsub_pt, "rcjetsub_pt"); // vector of vectors for subjet info - systematicTree->makeOutputVariable(m_rcjetsub_eta, "rcjetsub_eta"); - systematicTree->makeOutputVariable(m_rcjetsub_phi, "rcjetsub_phi"); - systematicTree->makeOutputVariable(m_rcjetsub_e, "rcjetsub_e"); - systematicTree->makeOutputVariable(m_rcjetsub_mv2c10, "rcjetsub_mv2c10"); - } + if (m_config->isSherpa22Vjets()) systematicTree->makeOutputVariable(m_weight_sherpa_22_vjets, + "weight_sherpa_22_vjets"); - // vRC branches - if (m_makeVarRCJets){ - std::string VarRC = "vrcjet"; - - for (auto& rho : m_VarRCJetRho){ - for (auto& mass_scale : m_VarRCJetMassScale){ - std::replace( rho.begin(), rho.end(), '.', '_'); - std::string name = rho+mass_scale; - systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC+"_"+name+"_pt"], VarRC+"_"+name+"_pt"); - systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC+"_"+name+"_eta"],VarRC+"_"+name+"_eta"); - systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC+"_"+name+"_phi"],VarRC+"_"+name+"_phi"); - systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC+"_"+name+"_e"], VarRC+"_"+name+"_e"); - systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC+"_"+name+"_d12"],VarRC+"_"+name+"_d12"); // requires >= 2 subjets - systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC+"_"+name+"_d23"],VarRC+"_"+name+"_d23"); // requires >= 3 subjets - systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_pt"], VarRC+"sub_"+name+"_pt"); // vector of vectors for subjet info - systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_eta"], VarRC+"sub_"+name+"_eta"); - systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_phi"], VarRC+"sub_"+name+"_phi"); - systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_e"], VarRC+"sub_"+name+"_e"); - systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_mv2c10"], VarRC+"sub_"+name+"_mv2c10"); - } // end loop over mass parameters - } // end loop over multipliers for mass scale - } // end if VarRC jets - - //met - systematicTree->makeOutputVariable(m_met_met, "met_met"); - systematicTree->makeOutputVariable(m_met_phi, "met_phi"); - - if (m_config->doKLFitter()) { - systematicTree->makeOutputVariable(m_klfitter_selected,"klfitter_selected"); - systematicTree->makeOutputVariable(m_klfitter_minuitDidNotConverge,"klfitter_minuitDidNotConverge"); - systematicTree->makeOutputVariable(m_klfitter_fitAbortedDueToNaN,"klfitter_fitAbortedDueToNaN"); - systematicTree->makeOutputVariable(m_klfitter_atLeastOneFitParameterAtItsLimit,"klfitter_atLeastOneFitParameterAtItsLimit"); - systematicTree->makeOutputVariable(m_klfitter_invalidTransferFunctionAtConvergence,"klfitter_invalidTransferFunctionAtConvergence"); - - /// Global result - systematicTree->makeOutputVariable(m_klfitter_bestPermutation,"klfitter_bestPermutation"); - systematicTree->makeOutputVariable(m_klfitter_logLikelihood,"klfitter_logLikelihood"); - systematicTree->makeOutputVariable(m_klfitter_eventProbability,"klfitter_eventProbability"); - systematicTree->makeOutputVariable(m_klfitter_parameters,"klfitter_parameters"); - systematicTree->makeOutputVariable(m_klfitter_parameterErrors,"klfitter_parameterErrors"); - - /// Model - systematicTree->makeOutputVariable(m_klfitter_model_bhad_pt,"klfitter_model_bhad_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_bhad_eta,"klfitter_model_bhad_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_bhad_phi,"klfitter_model_bhad_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_bhad_E,"klfitter_model_bhad_E"); - systematicTree->makeOutputVariable(m_klfitter_model_bhad_jetIndex,"klfitter_model_bhad_jetIndex"); - - systematicTree->makeOutputVariable(m_klfitter_model_blep_pt,"klfitter_model_blep_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_blep_eta,"klfitter_model_blep_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_blep_phi,"klfitter_model_blep_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_blep_E,"klfitter_model_blep_E"); - systematicTree->makeOutputVariable(m_klfitter_model_blep_jetIndex,"klfitter_model_blep_jetIndex"); - - systematicTree->makeOutputVariable(m_klfitter_model_lq1_pt,"klfitter_model_lq1_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_lq1_eta,"klfitter_model_lq1_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_lq1_phi,"klfitter_model_lq1_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_lq1_E,"klfitter_model_lq1_E"); - systematicTree->makeOutputVariable(m_klfitter_model_lq1_jetIndex,"klfitter_model_lq1_jetIndex"); - - systematicTree->makeOutputVariable(m_klfitter_model_lq2_pt,"klfitter_model_lq2_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_lq2_eta,"klfitter_model_lq2_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_lq2_phi,"klfitter_model_lq2_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_lq2_E,"klfitter_model_lq2_E"); - systematicTree->makeOutputVariable(m_klfitter_model_lq2_jetIndex,"klfitter_model_lq2_jetIndex"); - - if(m_config->KLFitterLH() == "ttH"){ - - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_pt,"klfitter_model_Higgs_b1_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_eta,"klfitter_model_Higgs_b1_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_phi,"klfitter_model_Higgs_b1_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_E,"klfitter_model_Higgs_b1_E"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_jetIndex,"klfitter_model_Higgs_b1_jetIndex"); - - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_pt,"klfitter_model_Higgs_b2_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_eta,"klfitter_model_Higgs_b2_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_phi,"klfitter_model_Higgs_b2_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_E,"klfitter_model_Higgs_b2_E"); - systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_jetIndex,"klfitter_model_Higgs_b2_jetIndex"); - - } - - systematicTree->makeOutputVariable(m_klfitter_model_lep_pt,"klfitter_model_lep_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_lep_eta,"klfitter_model_lep_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_lep_phi,"klfitter_model_lep_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_lep_E,"klfitter_model_lep_E"); - - systematicTree->makeOutputVariable(m_klfitter_model_nu_pt,"klfitter_model_nu_pt"); - systematicTree->makeOutputVariable(m_klfitter_model_nu_eta,"klfitter_model_nu_eta"); - systematicTree->makeOutputVariable(m_klfitter_model_nu_phi,"klfitter_model_nu_phi"); - systematicTree->makeOutputVariable(m_klfitter_model_nu_E,"klfitter_model_nu_E"); - - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_pt,"klfitter_bestPerm_topLep_pt"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_eta,"klfitter_bestPerm_topLep_eta"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_phi,"klfitter_bestPerm_topLep_phi"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_E,"klfitter_bestPerm_topLep_E"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_m,"klfitter_bestPerm_topLep_m"); - - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_pt,"klfitter_bestPerm_topHad_pt"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_eta,"klfitter_bestPerm_topHad_eta"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_phi,"klfitter_bestPerm_topHad_phi"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_E,"klfitter_bestPerm_topHad_E"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_m,"klfitter_bestPerm_topHad_m"); - - systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_pt,"klfitter_bestPerm_ttbar_pt"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_eta,"klfitter_bestPerm_ttbar_eta"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_phi,"klfitter_bestPerm_ttbar_phi"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_E,"klfitter_bestPerm_ttbar_E"); - systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_m,"klfitter_bestPerm_ttbar_m"); + if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { + systematicTree->makeOutputVariable(m_weight_pileup_UP, "weight_pileup_UP"); + systematicTree->makeOutputVariable(m_weight_pileup_DOWN, "weight_pileup_DOWN"); + if (m_config->useFwdElectrons()) { + systematicTree->makeOutputVariable(m_weight_fwdElSF_FWDEL_SF_ID_UP, "weight_fwdElSF_FWDEL_SF_ID_UP"); + systematicTree->makeOutputVariable(m_weight_fwdElSF_FWDEL_SF_ID_DOWN, "weight_fwdElSF_FWDEL_SF_ID_DOWN"); + } + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Trigger_UP, "weight_leptonSF_EL_SF_Trigger_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Trigger_DOWN, + "weight_leptonSF_EL_SF_Trigger_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Reco_UP, "weight_leptonSF_EL_SF_Reco_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Reco_DOWN, "weight_leptonSF_EL_SF_Reco_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_ID_UP, "weight_leptonSF_EL_SF_ID_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_ID_DOWN, "weight_leptonSF_EL_SF_ID_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Isol_UP, "weight_leptonSF_EL_SF_Isol_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_Isol_DOWN, "weight_leptonSF_EL_SF_Isol_DOWN"); + + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_CorrModel_Reco_UP, + "weight_leptonSF_EL_SF_" + m_config->electronEfficiencySystematicModel() + + "_Reco_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_CorrModel_Reco_DOWN, + "weight_leptonSF_EL_SF_" + m_config->electronEfficiencySystematicModel() + + "_Reco_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_CorrModel_ID_UP, + "weight_leptonSF_EL_SF_" + m_config->electronEfficiencySystematicModel() + + "_ID_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_CorrModel_ID_DOWN, + "weight_leptonSF_EL_SF_" + m_config->electronEfficiencySystematicModel() + + "_ID_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_CorrModel_Iso_UP, + "weight_leptonSF_EL_SF_" + m_config->electronEfficiencySystematicModel() + + "_Iso_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_EL_SF_CorrModel_Iso_DOWN, + "weight_leptonSF_EL_SF_" + m_config->electronEfficiencySystematicModel() + + "_Iso_DOWN"); + } + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_STAT_UP, + "weight_leptonSF_MU_SF_Trigger_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN, + "weight_leptonSF_MU_SF_Trigger_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_SYST_UP, + "weight_leptonSF_MU_SF_Trigger_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN, + "weight_leptonSF_MU_SF_Trigger_SYST_DOWN"); + // Muon ID SF systematics (regular) + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_UP, "weight_leptonSF_MU_SF_ID_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_DOWN, + "weight_leptonSF_MU_SF_ID_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_UP, "weight_leptonSF_MU_SF_ID_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_DOWN, + "weight_leptonSF_MU_SF_ID_SYST_DOWN"); + // Muon ID SF systematics (low pt) + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP, + "weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN, + "weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP, + "weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN, + "weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN"); + // Muon isolation SF systematics + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_STAT_UP, + "weight_leptonSF_MU_SF_Isol_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_STAT_DOWN, + "weight_leptonSF_MU_SF_Isol_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_SYST_UP, + "weight_leptonSF_MU_SF_Isol_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_Isol_SYST_DOWN, + "weight_leptonSF_MU_SF_Isol_SYST_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_STAT_UP, + "weight_leptonSF_MU_SF_TTVA_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN, + "weight_leptonSF_MU_SF_TTVA_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_SYST_UP, + "weight_leptonSF_MU_SF_TTVA_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN, + "weight_leptonSF_MU_SF_TTVA_SYST_DOWN"); + // Special global lepton trigger SF when requested + if (m_config->useGlobalTriggerConfiguration()) { + systematicTree->makeOutputVariable(m_weight_globalLeptonTriggerSF_EL_Trigger_UP, + "weight_globalLeptonTriggerSF_EL_Trigger_UP"); + systematicTree->makeOutputVariable(m_weight_globalLeptonTriggerSF_EL_Trigger_DOWN, + "weight_globalLeptonTriggerSF_EL_Trigger_DOWN"); + systematicTree->makeOutputVariable(m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP, + "weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN, + "weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP, + "weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN, + "weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN"); + } + systematicTree->makeOutputVariable(m_weight_oldTriggerSF_EL_Trigger_UP, "weight_oldTriggerSF_EL_Trigger_UP"); + systematicTree->makeOutputVariable(m_weight_oldTriggerSF_EL_Trigger_DOWN, + "weight_oldTriggerSF_EL_Trigger_DOWN"); + systematicTree->makeOutputVariable(m_weight_oldTriggerSF_MU_Trigger_STAT_UP, + "weight_oldTriggerSF_MU_Trigger_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_oldTriggerSF_MU_Trigger_STAT_DOWN, + "weight_oldTriggerSF_MU_Trigger_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_oldTriggerSF_MU_Trigger_SYST_UP, + "weight_oldTriggerSF_MU_Trigger_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_oldTriggerSF_MU_Trigger_SYST_DOWN, + "weight_oldTriggerSF_MU_Trigger_SYST_DOWN"); + + // write also out the individual components: + + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Reco, "weight_indiv_SF_EL_Reco"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Reco_UP, "weight_indiv_SF_EL_Reco_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Reco_DOWN, "weight_indiv_SF_EL_Reco_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ID, "weight_indiv_SF_EL_ID"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ID_UP, "weight_indiv_SF_EL_ID_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ID_DOWN, "weight_indiv_SF_EL_ID_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Isol, "weight_indiv_SF_EL_Isol"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Isol_UP, "weight_indiv_SF_EL_Isol_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_Isol_DOWN, "weight_indiv_SF_EL_Isol_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeID, "weight_indiv_SF_EL_ChargeID"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeID_UP, "weight_indiv_SF_EL_ChargeID_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeID_DOWN, "weight_indiv_SF_EL_ChargeID_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID, "weight_indiv_SF_EL_ChargeMisID"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_STAT_UP, + "weight_indiv_SF_EL_ChargeMisID_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN, + "weight_indiv_SF_EL_ChargeMisID_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_SYST_UP, + "weight_indiv_SF_EL_ChargeMisID_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN, + "weight_indiv_SF_EL_ChargeMisID_SYST_DOWN"); + + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID, "weight_indiv_SF_MU_ID"); + // Muon ID SF systematics (regular) + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_UP, "weight_indiv_SF_MU_ID_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_DOWN, "weight_indiv_SF_MU_ID_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_UP, "weight_indiv_SF_MU_ID_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_DOWN, "weight_indiv_SF_MU_ID_SYST_DOWN"); + // Muon ID SF systematics (low pt) + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP, + "weight_indiv_SF_MU_ID_STAT_LOWPT_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN, + "weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP, + "weight_indiv_SF_MU_ID_SYST_LOWPT_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN, + "weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN"); + // Muon isolation SF systematics + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol, "weight_indiv_SF_MU_Isol"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_STAT_UP, "weight_indiv_SF_MU_Isol_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_STAT_DOWN, "weight_indiv_SF_MU_Isol_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_SYST_UP, "weight_indiv_SF_MU_Isol_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_Isol_SYST_DOWN, "weight_indiv_SF_MU_Isol_SYST_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA, "weight_indiv_SF_MU_TTVA"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_STAT_UP, "weight_indiv_SF_MU_TTVA_STAT_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_STAT_DOWN, "weight_indiv_SF_MU_TTVA_STAT_DOWN"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_SYST_UP, "weight_indiv_SF_MU_TTVA_SYST_UP"); + systematicTree->makeOutputVariable(m_weight_indiv_SF_MU_TTVA_SYST_DOWN, "weight_indiv_SF_MU_TTVA_SYST_DOWN"); + + if (m_config->useTaus()) { + // Tau-electron overlap removal + for (top::topSFSyst i = top::topSFSyst(top::topSFSyst::TAU_SF_NOMINAL + 1); i < top::topSFSyst::TAU_SF_END; + i = top::topSFSyst(i + 1)) { + if (top::tauSF_alias.find(i) == top::tauSF_alias.end()) continue; + if (m_config->tauSFDoRNNID() == false && top::tauSF_name.at(i).Contains("RNN")) continue; + if (m_config->tauSFDoBDTID() == false && top::tauSF_name.at(i).Contains("JETID")) continue; + m_weight_tauSF_variations[i] = 1; + systematicTree->makeOutputVariable(m_weight_tauSF_variations[i], ("weight_tauSF_" + top::tauSF_alias.at( + i)).Data()); } + } - if (m_config->doPseudoTop()) { - - systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_pt, "PseudoTop_Reco_ttbar_pt"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_eta, "PseudoTop_Reco_ttbar_eta"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_phi, "PseudoTop_Reco_ttbar_phi"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_m, "PseudoTop_Reco_ttbar_m"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_pt, "PseudoTop_Reco_top_had_pt"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_eta, "PseudoTop_Reco_top_had_eta"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_phi, "PseudoTop_Reco_top_had_phi"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_m, "PseudoTop_Reco_top_had_m"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_pt, "PseudoTop_Reco_top_lep_pt"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_eta, "PseudoTop_Reco_top_lep_eta"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_phi, "PseudoTop_Reco_top_lep_phi"); - systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_m, "PseudoTop_Reco_top_lep_m"); + if (m_config->usePhotons()) { + systematicTree->makeOutputVariable(m_weight_photonSF_ID_UP, + "weight_photonSF_ID_UP"); + systematicTree->makeOutputVariable(m_weight_photonSF_ID_DOWN, + "weight_photonSF_ID_DOWN"); + systematicTree->makeOutputVariable(m_weight_photonSF_effIso_UP, + "weight_photonSF_effIso_UP"); + systematicTree->makeOutputVariable(m_weight_photonSF_effIso_DOWN, + "weight_photonSF_effIso_DOWN"); + } - } + systematicTree->makeOutputVariable(m_weight_jvt_up, "weight_jvt_UP"); + systematicTree->makeOutputVariable(m_weight_jvt_down, "weight_jvt_DOWN"); + if (m_config->getfJVTWP() != "None") { + systematicTree->makeOutputVariable(m_weight_forwardjvt_up, "weight_forwardjvt_UP"); + systematicTree->makeOutputVariable(m_weight_forwardjvt_down, "weight_forwardjvt_DOWN"); + } + } - //extra branches telling you if the event passed / failed a selection - int index(0); - for (const auto& branchName : m_extraBranches) { - m_selectionDecisions[index] = 0; - systematicTree->makeOutputVariable(m_selectionDecisions[index], branchName); - // Add all triggers to a map so we don't get any duplicates - for (auto& trigger_name : m_config->allTriggers( branchName ) ) { - m_triggerDecisions [trigger_name] = 0; - if (!m_config->isMC() && m_config->doFakesMMWeights()) - m_triggerPrescales [trigger_name] = -99999.;//initialised to dummmy value, in case it can't be retrieved by the tool - } - for (auto& trigger_name : m_config->electronTriggers( branchName ) ) - m_el_trigMatched [trigger_name] = std::vector<char>(); - for (auto& trigger_name : m_config->muonTriggers( branchName ) ) - m_mu_trigMatched [trigger_name] = std::vector<char>(); - ++index; + // for b-tagging SFs, can also have systematic-shifted in systematics trees + if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName || + m_config->dumpBtagSystsInSystTrees()) { + // b-tagging SFs: eigenvectors and named systematics + for (auto& tagWP : m_config->bTagWP_available()) { + // skip uncalibrated though available WPs + if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), + tagWP) == m_config->bTagWP_calibrated().end()) continue; + // up + systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_B_up[tagWP], "weight_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_up"); + systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_C_up[tagWP], "weight_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_up"); + systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_Light_up[tagWP], + "weight_bTagSF_" + shortBtagWP(tagWP) + "_eigenvars_Light_up"); + // down + systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_B_down[tagWP], "weight_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_down"); + systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_C_down[tagWP], "weight_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_down"); + systematicTree->makeOutputVariable(m_weight_bTagSF_eigen_Light_down[tagWP], + "weight_bTagSF_" + shortBtagWP(tagWP) + "_eigenvars_Light_down"); + // named systematics + for (auto name : m_config->btagging_namedSysts(tagWP)) { + systematicTree->makeOutputVariable(m_weight_bTagSF_named_up[tagWP][name], + "weight_bTagSF_" + shortBtagWP(tagWP) + "_" + betterBtagNamedSyst( + name) + "_up"); + systematicTree->makeOutputVariable(m_weight_bTagSF_named_down[tagWP][name], "weight_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_down"); } - - for( auto& trig_name : m_triggerDecisions ) - systematicTree->makeOutputVariable( trig_name.second, trig_name.first ); - if (!m_config->isMC() && m_config->doFakesMMWeights()) { - for( auto& trig_name : m_triggerPrescales ) - systematicTree->makeOutputVariable( trig_name.second, "PS_"+trig_name.first ); + } + if (m_config->useTrackJets()) { + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + // skip uncalibrated though available WPs + if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), m_config->bTagWP_calibrated_trkJet().end(), + tagWP) == m_config->bTagWP_calibrated_trkJet().end()) continue; + // up + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_B_up[tagWP], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_up"); + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_C_up[tagWP], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_up"); + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_Light_up[tagWP], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_Light_up"); + // down + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_B_down[tagWP], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_B_down"); + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_C_down[tagWP], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_C_down"); + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_eigen_Light_down[tagWP], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_eigenvars_Light_down"); + // named systematics + for (auto name : m_config->trkjet_btagging_namedSysts(tagWP)) { + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_named_up[tagWP][name], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_up"); + systematicTree->makeOutputVariable(m_weight_trackjet_bTagSF_named_down[tagWP][name], "weight_trackjet_bTagSF_" + shortBtagWP( + tagWP) + "_" + betterBtagNamedSyst(name) + "_down"); + } } - for( auto& trig_name : m_el_trigMatched ) - systematicTree->makeOutputVariable( trig_name.second, "el_trigMatch_"+trig_name.first ); - for( auto& trig_name : m_mu_trigMatched ) - systematicTree->makeOutputVariable( trig_name.second, "mu_trigMatch_"+trig_name.first ); - + } } - } + } - void EventSaverFlatNtuple::setupParticleLevelTreeManager(const top::ParticleLevelEvent& plEvent){ - // Quick return if particle level is disabled or the tree is already initialised. - // If particle level is disabled, no tree will be created. - if ( not m_config->doTopParticleLevel() or m_particleLevelTreeManager ){ - return; - } + ///-- weights for matrix-method fakes estimate by IFF --/// + if (!m_config->isMC() && systematicTree->name() == nominalLooseTTreeName && m_config->doFakesMMWeightsIFF()) { + // std::vector<CP::AsymptMatrixTool*> fakesMMWeightCalcIFF; + // while (asg::ToolStore::contains<CP::AsymptMatrixTool>("AsymptMatrixTool_" + std::to_string (m_ASMsize))) { + // fakesMMWeightCalcIFF.push_back(asg::ToolStore::get<CP::AsymptMatrixTool>("AsymptMatrixTool_" + std::to_string (m_ASMsize))); + // ++m_ASMsize; + // } + // std::string ASMweights_branch_name = "ASM_weight"; + // std::string ASMweights_Syst_branch_name = "ASM_weight_Syst"; + // std::string ASMweights_Systname_branch_name = "ASM_weight_Systname"; + // systematicTree->makeOutputVariable(m_ASMweights, ASMweights_branch_name); + // m_ASMweights_Syst.resize(m_ASMsize); + // m_ASMweights_Systname.resize(m_ASMsize); + // for (int mmi = 0; mmi < m_ASMsize; ++mmi) { + // systematicTree->makeOutputVariable(m_ASMweights_Syst[mmi], + // ASMweights_Syst_branch_name + "_" + std::to_string(mmi)); + // systematicTree->makeOutputVariable(m_ASMweights_Systname[mmi], ASMweights_Systname_branch_name + "_" + std::to_string( + // mmi)); + // } + } - m_particleLevelTreeManager = std::make_shared<top::TreeManager>( "particleLevel", m_outputFile, m_config->outputFileSetAutoFlushZero() ); + /// Bootstrapping poisson weights + if (m_config->saveBootstrapWeights()) { + systematicTree->makeOutputVariable(m_weight_poisson, "weight_poisson"); + } - m_particleLevelTreeManager->makeOutputVariable(m_weight_mc, "weight_mc"); + //event info + systematicTree->makeOutputVariable(m_eventNumber, "eventNumber"); + systematicTree->makeOutputVariable(m_runNumber, "runNumber"); + if (m_config->isMC() && m_config->doPileupReweighting()) systematicTree->makeOutputVariable(m_randomRunNumber, + "randomRunNumber"); + systematicTree->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); + systematicTree->makeOutputVariable(m_mu, "mu"); + systematicTree->makeOutputVariable(m_mu_actual, "mu_actual"); + if (!m_config->isMC()) { + systematicTree->makeOutputVariable(m_mu_original, "mu_original_xAOD"); + systematicTree->makeOutputVariable(m_mu_actual_original, "mu_actual_original_xAOD"); + } + systematicTree->makeOutputVariable(m_backgroundFlags, "backgroundFlags"); + if (m_config->useMuons()) systematicTree->makeOutputVariable(m_hasBadMuon, "hasBadMuon"); + + //electrons + if (m_config->useElectrons()) { + systematicTree->makeOutputVariable(m_el_pt, "el_pt"); + systematicTree->makeOutputVariable(m_el_eta, "el_eta"); + systematicTree->makeOutputVariable(m_el_cl_eta, "el_cl_eta"); + systematicTree->makeOutputVariable(m_el_phi, "el_phi"); + systematicTree->makeOutputVariable(m_el_e, "el_e"); + systematicTree->makeOutputVariable(m_el_charge, "el_charge"); + systematicTree->makeOutputVariable(m_el_topoetcone20, "el_topoetcone20"); + systematicTree->makeOutputVariable(m_el_ptvarcone20, "el_ptvarcone20"); + if (systematicTree->name().find("Loose") != std::string::npos) { + systematicTree->makeOutputVariable(m_el_isTight, "el_isTight"); + } + systematicTree->makeOutputVariable(m_el_CF, "el_CF"); + systematicTree->makeOutputVariable(m_el_d0sig, "el_d0sig"); + systematicTree->makeOutputVariable(m_el_delta_z0_sintheta, "el_delta_z0_sintheta"); + if (m_useElectronChargeIDSelection) { + systematicTree->makeOutputVariable(m_el_ECIDS, "el_ECIDS"); + systematicTree->makeOutputVariable(m_el_ECIDSResult, "el_ECIDSResult"); + } + if (m_config->isMC()) { + systematicTree->makeOutputVariable(m_el_true_type, "el_true_type"); + systematicTree->makeOutputVariable(m_el_true_origin, "el_true_origin"); + systematicTree->makeOutputVariable(m_el_true_firstEgMotherTruthType, "el_true_firstEgMotherTruthType"); + systematicTree->makeOutputVariable(m_el_true_firstEgMotherTruthOrigin, "el_true_firstEgMotherTruthOrigin"); + systematicTree->makeOutputVariable(m_el_true_firstEgMotherPdgId, "el_true_firstEgMotherPdgId"); + systematicTree->makeOutputVariable(m_el_true_isPrompt, "el_true_isPrompt"); + systematicTree->makeOutputVariable(m_el_true_isChargeFl, "el_true_isChargeFl"); + } + if (m_config->enablePromptLeptonImprovedVetoStudies()) { + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonRNN_conversion, "PLIV_el_PromptLeptonRNN_conversion"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonRNN_non_prompt_b, "PLIV_el_PromptLeptonRNN_non_prompt_b"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonRNN_non_prompt_c, "PLIV_el_PromptLeptonRNN_non_prompt_c"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonRNN_prompt, "PLIV_el_PromptLeptonRNN_prompt"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_MVAXBin, "PLIV_el_PromptLeptonImprovedInput_MVAXBin"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack, "PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_topoetcone30rel, "PLIV_el_PromptLeptonImprovedInput_topoetcone30rel"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel, "PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_PtFrac, "PLIV_el_PromptLeptonImprovedInput_PtFrac"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_DRlj, "PLIV_el_PromptLeptonImprovedInput_DRlj"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel, "PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_PtRel, "PLIV_el_PromptLeptonImprovedInput_PtRel"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx, "PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedVetoBARR, "PLIV_el_PromptLeptonImprovedVetoBARR"); + systematicTree->makeOutputVariable(m_PLIV_el_PromptLeptonImprovedVetoECAP, "PLIV_el_PromptLeptonImprovedVetoECAP"); + } + } - //event info - m_particleLevelTreeManager->makeOutputVariable(m_eventNumber, "eventNumber"); - m_particleLevelTreeManager->makeOutputVariable(m_runNumber, "runNumber"); - if (m_config->isMC() && m_config->doPileupReweighting()) m_particleLevelTreeManager->makeOutputVariable(m_randomRunNumber, "randomRunNumber"); - m_particleLevelTreeManager->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); - m_particleLevelTreeManager->makeOutputVariable(m_mu, "mu"); - m_particleLevelTreeManager->makeOutputVariable(m_weight_pileup, "weight_pileup"); + //forward electrons + if (m_config->useFwdElectrons()) { + systematicTree->makeOutputVariable(m_fwdel_pt, "fwdel_pt"); + systematicTree->makeOutputVariable(m_fwdel_eta, "fwdel_eta"); + systematicTree->makeOutputVariable(m_fwdel_phi, "fwdel_phi"); + systematicTree->makeOutputVariable(m_fwdel_e, "fwdel_e"); + systematicTree->makeOutputVariable(m_fwdel_etcone20, "fwdel_etcone20"); + systematicTree->makeOutputVariable(m_fwdel_etcone30, "fwdel_etcone30"); + systematicTree->makeOutputVariable(m_fwdel_etcone40, "fwdel_etcone40"); + if (systematicTree->name().find("Loose") != std::string::npos) { + systematicTree->makeOutputVariable(m_fwdel_isTight, "fwdel_isTight"); + } + }//end of fwd electrons branches + + //muons + if (m_config->useMuons()) { + systematicTree->makeOutputVariable(m_mu_pt, "mu_pt"); + systematicTree->makeOutputVariable(m_mu_eta, "mu_eta"); + systematicTree->makeOutputVariable(m_mu_phi, "mu_phi"); + systematicTree->makeOutputVariable(m_mu_e, "mu_e"); + systematicTree->makeOutputVariable(m_mu_charge, "mu_charge"); + systematicTree->makeOutputVariable(m_mu_topoetcone20, "mu_topoetcone20"); + systematicTree->makeOutputVariable(m_mu_ptvarcone30, "mu_ptvarcone30"); + if (systematicTree->name().find("Loose") != std::string::npos) { + systematicTree->makeOutputVariable(m_mu_isTight, "mu_isTight"); + } + systematicTree->makeOutputVariable(m_mu_d0sig, "mu_d0sig"); + systematicTree->makeOutputVariable(m_mu_delta_z0_sintheta, "mu_delta_z0_sintheta"); + if (m_config->isMC()) { + systematicTree->makeOutputVariable(m_mu_true_type, "mu_true_type"); + systematicTree->makeOutputVariable(m_mu_true_origin, "mu_true_origin"); + systematicTree->makeOutputVariable(m_mu_true_isPrompt, "mu_true_isPrompt"); + } + if (m_config->enablePromptLeptonImprovedVetoStudies()) { + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonRNN_non_prompt_b, "PLIV_mu_PromptLeptonRNN_non_prompt_b"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonRNN_non_prompt_c, "PLIV_mu_PromptLeptonRNN_non_prompt_c"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonRNN_prompt, "PLIV_mu_PromptLeptonRNN_prompt"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_MVAXBin, "PLIV_mu_PromptLeptonImprovedInput_MVAXBin"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel, "PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_PtFrac, "PLIV_mu_PromptLeptonImprovedInput_PtFrac"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_DRlj, "PLIV_mu_PromptLeptonImprovedInput_DRlj"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel, "PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel, "PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest, "PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest"); + systematicTree->makeOutputVariable(m_PLIV_mu_PromptLeptonImprovedVeto, "PLIV_mu_PromptLeptonImprovedVeto"); + } + } - if (m_config->doPseudoTop()) { + //soft muons + if (m_config->useSoftMuons()) { + systematicTree->makeOutputVariable(m_softmu_pt, "softmu_pt"); + systematicTree->makeOutputVariable(m_softmu_eta, "softmu_eta"); + systematicTree->makeOutputVariable(m_softmu_phi, "softmu_phi"); + systematicTree->makeOutputVariable(m_softmu_e, "softmu_e"); + systematicTree->makeOutputVariable(m_softmu_charge, "softmu_charge"); + systematicTree->makeOutputVariable(m_softmu_d0, "softmu_d0"); + systematicTree->makeOutputVariable(m_softmu_d0sig, "softmu_d0sig"); + systematicTree->makeOutputVariable(m_softmu_delta_z0_sintheta, "softmu_delta_z0_sintheta"); + if (m_config->isMC()) { + systematicTree->makeOutputVariable(m_softmu_true_type, "softmu_true_type"); + systematicTree->makeOutputVariable(m_softmu_true_origin, "softmu_true_origin"); + systematicTree->makeOutputVariable(m_softmu_SF_ID, "softmu_SF_ID"); + + if (systematicTree->name() == nominalTTreeName || systematicTree->name() == nominalLooseTTreeName) { + systematicTree->makeOutputVariable(m_softmu_SF_ID_STAT_UP, "softmu_SF_ID_STAT_UP"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_STAT_DOWN, "softmu_SF_ID_STAT_DOWN"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_SYST_UP, "softmu_SF_ID_SYST_UP"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_SYST_DOWN, "softmu_SF_ID_SYST_DOWN"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_STAT_LOWPT_UP, "softmu_SF_ID_STAT_LOWPT_UP"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_STAT_LOWPT_DOWN, "softmu_SF_ID_STAT_LOWPT_DOWN"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_SYST_LOWPT_UP, "softmu_SF_ID_SYST_LOWPT_UP"); + systematicTree->makeOutputVariable(m_softmu_SF_ID_SYST_LOWPT_DOWN, "softmu_SF_ID_SYST_LOWPT_DOWN"); + } + if(m_config->softmuonAdditionalTruthInfo()) + { + if(m_config->softmuonAdditionalTruthInfoCheckPartonOrigin()) systematicTree->makeOutputVariable(m_softmu_parton_origin_flag, "softmu_parton_origin_flag"); + systematicTree->makeOutputVariable(m_softmu_particle_origin_flag, "softmu_particle_origin_flag"); + systematicTree->makeOutputVariable(m_softmu_parent_pdgid,"softmu_parent_pdgid"); + systematicTree->makeOutputVariable(m_softmu_b_hadron_parent_pdgid,"softmu_b_hadron_parent_pdgid"); + systematicTree->makeOutputVariable(m_softmu_c_hadron_parent_pdgid,"softmu_c_hadron_parent_pdgid"); + } + }//end of if (m_config->isMC()) + }//end of if (m_config->useSoftMuons()) + + //photons + if (m_config->usePhotons()) { + systematicTree->makeOutputVariable(m_ph_pt, "ph_pt"); + systematicTree->makeOutputVariable(m_ph_eta, "ph_eta"); + systematicTree->makeOutputVariable(m_ph_phi, "ph_phi"); + systematicTree->makeOutputVariable(m_ph_e, "ph_e"); + systematicTree->makeOutputVariable(m_ph_iso, "ph_iso"); + } - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_pt, "PseudoTop_Particle_ttbar_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_eta, "PseudoTop_Particle_ttbar_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_phi, "PseudoTop_Particle_ttbar_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_m, "PseudoTop_Particle_ttbar_m"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_pt, "PseudoTop_Particle_top_had_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_eta, "PseudoTop_Particle_top_had_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_phi, "PseudoTop_Particle_top_had_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_m, "PseudoTop_Particle_top_had_m"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_pt, "PseudoTop_Particle_top_lep_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_eta, "PseudoTop_Particle_top_lep_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_phi, "PseudoTop_Particle_top_lep_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_m, "PseudoTop_Particle_top_lep_m"); + //taus + if (m_config->useTaus()) { + systematicTree->makeOutputVariable(m_tau_pt, "tau_pt"); + systematicTree->makeOutputVariable(m_tau_eta, "tau_eta"); + systematicTree->makeOutputVariable(m_tau_phi, "tau_phi"); + systematicTree->makeOutputVariable(m_tau_charge, "tau_charge"); + } + //jets + if (m_config->useJets()) { + systematicTree->makeOutputVariable(m_jet_pt, "jet_pt"); + systematicTree->makeOutputVariable(m_jet_eta, "jet_eta"); + systematicTree->makeOutputVariable(m_jet_phi, "jet_phi"); + systematicTree->makeOutputVariable(m_jet_e, "jet_e"); + if (m_config->bTagAlgo_MV2c10_used()) { + systematicTree->makeOutputVariable(m_jet_mv2c10, "jet_mv2c10"); + } + systematicTree->makeOutputVariable(m_jet_jvt, "jet_jvt"); + if (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None") { + systematicTree->makeOutputVariable(m_jet_fjvt, "jet_forwardjvt"); + systematicTree->makeOutputVariable(m_jet_passfjvt, "jet_passforwardjvt"); } + if (m_config->isMC() && m_config->jetStoreTruthLabels()) { + systematicTree->makeOutputVariable(m_jet_truthflav, "jet_truthflav"); + systematicTree->makeOutputVariable(m_jet_truthPartonLabel, "jet_truthPartonLabel"); + systematicTree->makeOutputVariable(m_jet_isTrueHS, "jet_isTrueHS"); + systematicTree->makeOutputVariable(m_jet_HadronConeExclExtendedTruthLabelID, "jet_truthflavExtended"); + } - //electrons - if ( m_config->useTruthElectrons() ){ - m_particleLevelTreeManager->makeOutputVariable(m_el_pt, "el_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_el_eta, "el_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_el_phi, "el_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_el_e, "el_e"); - m_particleLevelTreeManager->makeOutputVariable(m_el_charge, "el_charge"); - m_particleLevelTreeManager->makeOutputVariable(m_el_pt_bare, "el_pt_bare"); - m_particleLevelTreeManager->makeOutputVariable(m_el_eta_bare, "el_eta_bare"); - m_particleLevelTreeManager->makeOutputVariable(m_el_phi_bare, "el_phi_bare"); - m_particleLevelTreeManager->makeOutputVariable(m_el_e_bare, "el_e_bare"); + if (m_config->useJetGhostTrack()) { + systematicTree->makeOutputVariable(m_jet_ghostTrack_pt, "jet_ghostTrack_pt"); + systematicTree->makeOutputVariable(m_jet_ghostTrack_eta, "jet_ghostTrack_eta"); + systematicTree->makeOutputVariable(m_jet_ghostTrack_phi, "jet_ghostTrack_phi"); + systematicTree->makeOutputVariable(m_jet_ghostTrack_e, "jet_ghostTrack_e"); + systematicTree->makeOutputVariable(m_jet_ghostTrack_d0, "jet_ghostTrack_d0"); + systematicTree->makeOutputVariable(m_jet_ghostTrack_z0, "jet_ghostTrack_z0"); + systematicTree->makeOutputVariable(m_jet_ghostTrack_qOverP, "jet_ghostTrack_qOverP"); } - //muons - if ( m_config->useTruthMuons() ){ - m_particleLevelTreeManager->makeOutputVariable(m_mu_pt, "mu_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_eta, "mu_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_phi, "mu_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_e, "mu_e"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_charge, "mu_charge"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_pt_bare, "mu_pt_bare"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_eta_bare, "mu_eta_bare"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_phi_bare, "mu_phi_bare"); - m_particleLevelTreeManager->makeOutputVariable(m_mu_e_bare, "mu_e_bare"); + for (auto& tagWP : m_config->bTagWP_available()) { + if (tagWP.find("Continuous") == std::string::npos) systematicTree->makeOutputVariable(m_jet_isbtagged[tagWP], "jet_isbtagged_" + shortBtagWP( + tagWP)); + else systematicTree->makeOutputVariable(m_jet_tagWeightBin[tagWP], "jet_tagWeightBin_" + tagWP); } - //photons - if (m_config->useTruthPhotons()) { - m_particleLevelTreeManager->makeOutputVariable(m_ph_pt, "ph_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_ph_eta, "ph_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_ph_phi, "ph_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_ph_e, "ph_e"); + for (const std::string& algo : m_config->bTagAlgo_available()) { + systematicTree->makeOutputVariable(m_jet_DLx[algo], "jet_" + algo); + systematicTree->makeOutputVariable(m_jet_DLx_pb[algo], "jet_" + algo + "_pb"); + systematicTree->makeOutputVariable(m_jet_DLx_pc[algo], "jet_" + algo + "_pc"); + systematicTree->makeOutputVariable(m_jet_DLx_pu[algo], "jet_" + algo + "_pu"); } + } - //jets - if ( m_config->useTruthJets() ){ - m_particleLevelTreeManager->makeOutputVariable(m_jet_pt, "jet_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_jet_eta, "jet_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_jet_phi, "jet_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_jet_e, "jet_e"); - - m_particleLevelTreeManager->makeOutputVariable(m_jet_Ghosts_BHadron_Final_Count, "jet_nGhosts_bHadron"); - m_particleLevelTreeManager->makeOutputVariable(m_jet_Ghosts_CHadron_Final_Count, "jet_nGhosts_cHadron"); + // fail-JVT jets + if (m_config->saveFailJVTJets()) { + systematicTree->makeOutputVariable(m_failJvt_jet_pt, "failJvt_jet_pt"); + systematicTree->makeOutputVariable(m_failJvt_jet_eta, "failJvt_jet_eta"); + systematicTree->makeOutputVariable(m_failJvt_jet_phi, "failJvt_jet_phi"); + systematicTree->makeOutputVariable(m_failJvt_jet_e, "failJvt_jet_e"); + systematicTree->makeOutputVariable(m_failJvt_jet_jvt, "failJvt_jet_jvt"); + if (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None") { + systematicTree->makeOutputVariable(m_failJvt_jet_fjvt, "failJvt_jet_forwardjvt"); + systematicTree->makeOutputVariable(m_failJvt_jet_passfjvt, "failJvt_jet_passforwardjvt"); + } + if (m_config->isMC() && m_config->jetStoreTruthLabels()) { + systematicTree->makeOutputVariable(m_failJvt_jet_truthflav, "failJvt_jet_truthflav"); + systematicTree->makeOutputVariable(m_failJvt_jet_truthPartonLabel, "failJvt_jet_truthPartonLabel"); + systematicTree->makeOutputVariable(m_failJvt_jet_isTrueHS, "failJvt_jet_isTrueHS"); + systematicTree->makeOutputVariable(m_failJvt_jet_HadronConeExclExtendedTruthLabelID, + "failJvt_jet_truthflavExtended"); } - //large R jets - if ( m_config->useTruthLargeRJets() ){ - m_particleLevelTreeManager->makeOutputVariable(m_ljet_pt, "ljet_pt"); - m_particleLevelTreeManager->makeOutputVariable(m_ljet_eta, "ljet_eta"); - m_particleLevelTreeManager->makeOutputVariable(m_ljet_phi, "ljet_phi"); - m_particleLevelTreeManager->makeOutputVariable(m_ljet_e, "ljet_e"); - - m_particleLevelTreeManager->makeOutputVariable(m_ljet_Ghosts_BHadron_Final_Count, "ljet_nGhosts_bHadron"); - m_particleLevelTreeManager->makeOutputVariable(m_ljet_Ghosts_CHadron_Final_Count, "ljet_nGhosts_cHadron"); + if (m_config->useJetGhostTrack()) { + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_pt, "failJvt_jet_ghostTrack_pt"); + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_eta, "failJvt_jet_ghostTrack_eta"); + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_phi, "failJvt_jet_ghostTrack_phi"); + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_e, "failJvt_jet_ghostTrack_e"); + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_d0, "failJvt_jet_ghostTrack_d0"); + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_z0, "failJvt_jet_ghostTrack_z0"); + systematicTree->makeOutputVariable(m_failJvt_jet_ghostTrack_qOverP, "failJvt_jet_ghostTrack_qOverP"); } + } - //met - if ( m_config->useTruthMET() ){ - m_particleLevelTreeManager->makeOutputVariable(m_met_met, "met_met"); - m_particleLevelTreeManager->makeOutputVariable(m_met_phi, "met_phi"); + // fail-FJVT jets + if (m_config->getfJVTWP() != "None" && m_config->saveFailForwardJVTJets()) { + systematicTree->makeOutputVariable(m_failFJvt_jet_pt, "failforwardJvt_jet_pt"); + systematicTree->makeOutputVariable(m_failFJvt_jet_eta, "failforwardJvt_jet_eta"); + systematicTree->makeOutputVariable(m_failFJvt_jet_phi, "failforwardJvt_jet_phi"); + systematicTree->makeOutputVariable(m_failFJvt_jet_e, "failforwardJvt_jet_e"); + systematicTree->makeOutputVariable(m_failFJvt_jet_jvt, "failforwardJvt_jet_jvt"); + systematicTree->makeOutputVariable(m_failFJvt_jet_fjvt, "failforwardJvt_jet_forwardjvt"); + systematicTree->makeOutputVariable(m_failFJvt_jet_passjvt, "failforwardJvt_jet_passjvt"); + + if (m_config->isMC() && m_config->jetStoreTruthLabels()) { + systematicTree->makeOutputVariable(m_failFJvt_jet_truthflav, "failforwardJvt_jet_truthflav"); + systematicTree->makeOutputVariable(m_failFJvt_jet_truthPartonLabel, "failforwardJvt_jet_truthPartonLabel"); + systematicTree->makeOutputVariable(m_failFJvt_jet_isTrueHS, "failforwardJvt_jet_isTrueHS"); + systematicTree->makeOutputVariable(m_failFJvt_jet_HadronConeExclExtendedTruthLabelID, + "failforwardJvt_jet_truthflavExtended"); } - // Setup PDF info branches if PDF info is requested. - if (m_config->doTruthPDFInfo()) { - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_X1, "PDFinfo_X1"); - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_X2, "PDFinfo_X2"); - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_PDGID1, "PDFinfo_PDGID1"); - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_PDGID2, "PDFinfo_PDGID2"); - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_Q, "PDFinfo_Q"); - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_XF1, "PDFinfo_XF1"); - m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_XF2, "PDFinfo_XF2"); + if (m_config->useJetGhostTrack()) { + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_pt, "failforwardJvt_jet_ghostTrack_pt"); + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_eta, "failforwardJvt_jet_ghostTrack_eta"); + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_phi, "failforwardJvt_jet_ghostTrack_phi"); + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_e, "failforwardJvt_jet_ghostTrack_e"); + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_d0, "failforwardJvt_jet_ghostTrack_d0"); + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_z0, "failforwardJvt_jet_ghostTrack_z0"); + systematicTree->makeOutputVariable(m_failFJvt_jet_ghostTrack_qOverP, "failforwardJvt_jet_ghostTrack_qOverP"); } + } - // Setup MC generator weights branch if requested. - if (m_config->doMCGeneratorWeights()) { - m_particleLevelTreeManager->makeOutputVariable(m_mc_generator_weights, "mc_generator_weights"); - } + //large-R jets + if (m_config->useLargeRJets()) { + systematicTree->makeOutputVariable(m_ljet_pt, "ljet_pt"); + systematicTree->makeOutputVariable(m_ljet_eta, "ljet_eta"); + systematicTree->makeOutputVariable(m_ljet_phi, "ljet_phi"); + systematicTree->makeOutputVariable(m_ljet_e, "ljet_e"); + systematicTree->makeOutputVariable(m_ljet_m, "ljet_m"); - // Setup PDF weight branches if PDF systematics are requested, - if( m_config->saveLHAPDFEvent() ){ - for ( auto & pdf : m_PDF_eventWeights ) { - m_particleLevelTreeManager->makeOutputVariable( pdf.second, pdf.first ); - } - } + for (const std::pair<std::string,std::string>& it : m_config->largeRJetSubstructureVariables()) { + systematicTree->makeOutputVariable(m_ljet_substructure[it.first],"ljet_"+it.first); + } - // Setup the selection decision branches. This is a two-step process: - // - // (1) First, we need to create an array of variables which will be used to - // store the data in the TTree. The variable - // m_particleLevel_SelectionDecisions is just that: A std::vector of - // pairs, thwere the .first corresponds to the name of the selection, - // and the .second is the actual variable. - // (2) Secondly, we need to attach the newly created variables to the - // particle level tree manager. - m_particleLevel_SelectionDecisions.reserve( plEvent.m_selectionDecisions.size() ); - for ( const auto & selectionDecision : plEvent.m_selectionDecisions ){ - m_particleLevel_SelectionDecisions.push_back( std::make_pair( selectionDecision.first, - selectionDecision.second ) ); + for (const std::string& taggerName : m_boostedJetTaggersNames) { + systematicTree->makeOutputVariable(m_ljet_isTagged[taggerName], "ljet_isTagged_" + taggerName); } - for ( auto & selectionDecision : m_particleLevel_SelectionDecisions ){ - m_particleLevelTreeManager->makeOutputVariable( selectionDecision.second, selectionDecision.first ); + if (m_config->isMC()) { + systematicTree->makeOutputVariable(m_ljet_truthLabel, "ljet_truthLabel"); + for (const std::string& taggerName : m_boostedJetTaggersNamesCalibrated) { + systematicTree->makeOutputVariable(m_ljet_tagSF[taggerName], "ljet_tagSF_" + taggerName); + } } - } + } - void EventSaverFlatNtuple::setupUpgradeTreeManager(/*const top::ParticleLevelEvent& upgradeEvent*/){ - // Quick return if upgrade is disabled or the tree is already initialised. - if ( not m_config->HLLHC() or m_upgradeTreeManager ){ - return; + //track jets + if (m_config->useTrackJets()) { + systematicTree->makeOutputVariable(m_tjet_pt, "tjet_pt"); + systematicTree->makeOutputVariable(m_tjet_eta, "tjet_eta"); + systematicTree->makeOutputVariable(m_tjet_phi, "tjet_phi"); + systematicTree->makeOutputVariable(m_tjet_e, "tjet_e"); + if (m_config->bTagAlgo_MV2c10_used_trkJet()) { + systematicTree->makeOutputVariable(m_tjet_mv2c10, "tjet_mv2c10"); + } + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + if (tagWP.find("Continuous") == std::string::npos) systematicTree->makeOutputVariable(m_tjet_isbtagged[tagWP], "tjet_isbtagged_" + shortBtagWP(tagWP)); + else systematicTree->makeOutputVariable(m_tjet_tagWeightBin[tagWP], "tjet_tagWeightBin_" + tagWP); } - m_upgradeTreeManager = std::make_shared<top::TreeManager>( "upgrade", m_outputFile, m_config->outputFileSetAutoFlushZero() ); + for (const std::string& algo : m_config->bTagAlgo_available_trkJet()) { + systematicTree->makeOutputVariable(m_tjet_DLx[algo], "tjet_" + algo); + systematicTree->makeOutputVariable(m_tjet_DLx_pb[algo], "tjet_" + algo + "_pb"); + systematicTree->makeOutputVariable(m_tjet_DLx_pc[algo], "tjet_" + algo + "_pc"); + systematicTree->makeOutputVariable(m_tjet_DLx_pu[algo], "tjet_" + algo + "_pu"); + } + } - m_upgradeTreeManager->makeOutputVariable(m_weight_mc, "weight_mc"); + if (m_config->useTracks()) { + systematicTree->makeOutputVariable(m_track_pt, "track_pt"); + systematicTree->makeOutputVariable(m_track_eta, "track_eta"); + systematicTree->makeOutputVariable(m_track_phi, "track_phi"); + systematicTree->makeOutputVariable(m_track_e, "track_e"); + systematicTree->makeOutputVariable(m_track_charge, "track_charge"); + systematicTree->makeOutputVariable(m_track_d0, "track_d0"); + systematicTree->makeOutputVariable(m_track_d0_significance, "track_d0_significance"); + systematicTree->makeOutputVariable(m_track_z0, "track_z0"); + systematicTree->makeOutputVariable(m_track_z0_significance, "track_z0_significance"); + systematicTree->makeOutputVariable(m_track_phi0, "track_phi0"); + systematicTree->makeOutputVariable(m_track_theta, "track_theta"); + systematicTree->makeOutputVariable(m_track_qOverP, "track_qOverP"); + systematicTree->makeOutputVariable(m_track_chiSquared, "track_chiSquared"); + systematicTree->makeOutputVariable(m_track_numberDoF, "track_numberDoF"); + } + + + + // RC branches + if (m_makeRCJets) { + systematicTree->makeOutputVariable(m_rcjet_pt, "rcjet_pt"); + systematicTree->makeOutputVariable(m_rcjet_eta, "rcjet_eta"); + systematicTree->makeOutputVariable(m_rcjet_phi, "rcjet_phi"); + systematicTree->makeOutputVariable(m_rcjet_e, "rcjet_e"); + systematicTree->makeOutputVariable(m_rcjet_d12, "rcjet_d12"); // requires >= 2 subjets + systematicTree->makeOutputVariable(m_rcjet_d23, "rcjet_d23"); // requires >= 3 subjets + systematicTree->makeOutputVariable(m_rcjetsub_pt, "rcjetsub_pt"); // vector of vectors for subjet info + systematicTree->makeOutputVariable(m_rcjetsub_eta, "rcjetsub_eta"); + systematicTree->makeOutputVariable(m_rcjetsub_phi, "rcjetsub_phi"); + systematicTree->makeOutputVariable(m_rcjetsub_e, "rcjetsub_e"); + if (m_config->bTagAlgo_MV2c10_used()) { + systematicTree->makeOutputVariable(m_rcjetsub_mv2c10, "rcjetsub_mv2c10"); + } - //event info - m_upgradeTreeManager->makeOutputVariable(m_eventNumber, "eventNumber"); - m_upgradeTreeManager->makeOutputVariable(m_runNumber, "runNumber"); - m_upgradeTreeManager->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); - m_upgradeTreeManager->makeOutputVariable(m_mu, "mu"); + if (m_useRCJSS || m_useRCAdditionalJSS) { + systematicTree->makeOutputVariable(m_rrcjet_pt, "rrcjet_pt"); + systematicTree->makeOutputVariable(m_rrcjet_eta, "rrcjet_eta"); + systematicTree->makeOutputVariable(m_rrcjet_phi, "rrcjet_phi"); + systematicTree->makeOutputVariable(m_rrcjet_e, "rrcjet_e"); + } + if (m_useRCJSS) { + // RCJet SS from Clusters + systematicTree->makeOutputVariable(m_rcjet_tau32_clstr, "rcjet_tau32_clstr"); + systematicTree->makeOutputVariable(m_rcjet_tau21_clstr, "rcjet_tau21_clstr"); + systematicTree->makeOutputVariable(m_rcjet_tau3_clstr, "rcjet_tau3_clstr"); + systematicTree->makeOutputVariable(m_rcjet_tau2_clstr, "rcjet_tau2_clstr"); + systematicTree->makeOutputVariable(m_rcjet_tau1_clstr, "rcjet_tau1_clstr"); + systematicTree->makeOutputVariable(m_rcjet_d12_clstr, "rcjet_d12_clstr"); + systematicTree->makeOutputVariable(m_rcjet_d23_clstr, "rcjet_d23_clstr"); + systematicTree->makeOutputVariable(m_rcjet_Qw_clstr, "rcjet_Qw_clstr"); + systematicTree->makeOutputVariable(m_rcjet_nconstituent_clstr, "rcjet_nconstituent_clstr"); + systematicTree->makeOutputVariable(m_rcjet_D2_clstr, "rcjet_D2_clstr"); + systematicTree->makeOutputVariable(m_rcjet_ECF1_clstr, "rcjet_ECF1_clstr"); + systematicTree->makeOutputVariable(m_rcjet_ECF2_clstr, "rcjet_ECF2_clstr"); + systematicTree->makeOutputVariable(m_rcjet_ECF3_clstr, "rcjet_ECF3_clstr"); + } + if (m_useRCAdditionalJSS) { + systematicTree->makeOutputVariable(m_rcjet_gECF332_clstr, "rcjet_gECF332_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF461_clstr, "rcjet_gECF461_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF322_clstr, "rcjet_gECF322_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF331_clstr, "rcjet_gECF331_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF422_clstr, "rcjet_gECF422_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF441_clstr, "rcjet_gECF441_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF212_clstr, "rcjet_gECF212_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF321_clstr, "rcjet_gECF321_clstr"); + systematicTree->makeOutputVariable(m_rcjet_gECF311_clstr, "rcjet_gECF311_clstr"); + systematicTree->makeOutputVariable(m_rcjet_L1_clstr, "rcjet_L1_clstr"); + systematicTree->makeOutputVariable(m_rcjet_L2_clstr, "rcjet_L2_clstr"); + systematicTree->makeOutputVariable(m_rcjet_L3_clstr, "rcjet_L3_clstr"); + systematicTree->makeOutputVariable(m_rcjet_L4_clstr, "rcjet_L4_clstr"); + systematicTree->makeOutputVariable(m_rcjet_L5_clstr, "rcjet_L5_clstr"); + } + } + // vRC branches + if (m_makeVarRCJets) { + std::string VarRC = "vrcjet"; + + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_pt"], VarRC + "_" + name + "_pt"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_eta"], VarRC + "_" + name + "_eta"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_phi"], VarRC + "_" + name + "_phi"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_e"], VarRC + "_" + name + "_e"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_d12"], VarRC + "_" + name + "_d12"); // requires + // >= + // 2 + // subjets + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_d23"], VarRC + "_" + name + "_d23"); // requires + // >= + // 3 + // subjets + systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_pt"], VarRC + "sub_" + name + "_pt"); // vector + // of + // vectors + // for + // subjet + // info + systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_eta"], VarRC + "sub_" + name + "_eta"); + systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_phi"], VarRC + "sub_" + name + "_phi"); + systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_e"], VarRC + "sub_" + name + "_e"); + if (m_config->bTagAlgo_MV2c10_used()) { + systematicTree->makeOutputVariable(m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_mv2c10"], VarRC + "sub_" + name + "_mv2c10"); + } - // electrons - m_upgradeTreeManager->makeOutputVariable(m_el_pt, "el_pt"); - m_upgradeTreeManager->makeOutputVariable(m_el_eta, "el_eta"); - m_upgradeTreeManager->makeOutputVariable(m_el_phi, "el_phi"); - m_upgradeTreeManager->makeOutputVariable(m_el_e, "el_e"); - m_upgradeTreeManager->makeOutputVariable(m_el_charge, "el_charge"); + if (m_useVarRCJSS || m_useVarRCAdditionalJSS) { + systematicTree->makeOutputVariable(m_VarRCjetBranches["vrrcjet_" + name + "_pt"], "vrrcjet_" + name + "_pt"); + systematicTree->makeOutputVariable(m_VarRCjetBranches["vrrcjet_" + name + "_eta"], "vrrcjet_" + name + "_eta"); + systematicTree->makeOutputVariable(m_VarRCjetBranches["vrrcjet_" + name + "_phi"], "vrrcjet_" + name + "_phi"); + systematicTree->makeOutputVariable(m_VarRCjetBranches["vrrcjet_" + name + "_e"], "vrrcjet_" + name + "_e"); + } + if (m_useVarRCJSS) { + // RCJet SS from Clusters + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_tau32_clstr"], VarRC + "_" + name + "_tau32_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_tau21_clstr"], VarRC + "_" + name + "_tau21_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_tau3_clstr"], VarRC + "_" + name + "_tau3_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_tau2_clstr"], VarRC + "_" + name + "_tau2_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_tau1_clstr"], VarRC + "_" + name + "_tau1_clstr"); + + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_d12_clstr"], VarRC + "_" + name + "_d12_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_d23_clstr"], VarRC + "_" + name + "_d23_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_Qw_clstr"], VarRC + "_" + name + "_Qw_clstr"); + + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_D2_clstr"], VarRC + "_" + name + "_D2_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_ECF1_clstr"], VarRC + "_" + name + "_ECF1_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_ECF2_clstr"], VarRC + "_" + name + "_ECF2_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_ECF3_clstr"], VarRC + "_" + name + "_ECF3_clstr"); + } + if (m_useVarRCAdditionalJSS) { + + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF332_clstr"], VarRC + "_" + name + "_gECF332_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF461_clstr"], VarRC + "_" + name + "_gECF461_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF322_clstr"], VarRC + "_" + name + "_gECF322_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF331_clstr"], VarRC + "_" + name + "_gECF331_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF422_clstr"], VarRC + "_" + name + "_gECF422_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF441_clstr"], VarRC + "_" + name + "_gECF441_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF212_clstr"], VarRC + "_" + name + "_gECF212_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF321_clstr"], VarRC + "_" + name + "_gECF321_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_gECF311_clstr"], VarRC + "_" + name + "_gECF311_clstr"); + + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_L1_clstr"], VarRC + "_" + name + "_L1_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_L2_clstr"], VarRC + "_" + name + "_L2_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_L3_clstr"], VarRC + "_" + name + "_L3_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_L4_clstr"], VarRC + "_" + name + "_L4_clstr"); + systematicTree->makeOutputVariable(m_VarRCjetBranches[VarRC + "_" + name + "_L5_clstr"], VarRC + "_" + name + "_L5_clstr"); + } + } // end loop over mass parameters + } // end loop over multipliers for mass scale + } // end if VarRC jets + + //met + systematicTree->makeOutputVariable(m_met_met, "met_met"); + systematicTree->makeOutputVariable(m_met_phi, "met_phi"); + //these are for specific studies on the met, turned off by default, and turned on with the WriteMETBuiltWithLooseObjects option + if(m_config->writeMETBuiltWithLooseObjects()) + { + systematicTree->makeOutputVariable(m_met_met_withLooseObjects, "met_met_withLooseObjects"); + systematicTree->makeOutputVariable(m_met_phi_withLooseObjects, "met_phi_withLooseObjects"); + } - // muons - m_upgradeTreeManager->makeOutputVariable(m_mu_pt, "mu_pt"); - m_upgradeTreeManager->makeOutputVariable(m_mu_eta, "mu_eta"); - m_upgradeTreeManager->makeOutputVariable(m_mu_phi, "mu_phi"); - m_upgradeTreeManager->makeOutputVariable(m_mu_e, "mu_e"); - m_upgradeTreeManager->makeOutputVariable(m_mu_charge, "mu_charge"); + if (m_config->doKLFitter()) { + /// Global result + systematicTree->makeOutputVariable(m_klfitter_logLikelihood, "klfitter_logLikelihood"); + systematicTree->makeOutputVariable(m_klfitter_eventProbability, "klfitter_eventProbability"); + systematicTree->makeOutputVariable(m_klfitter_selected, "klfitter_selected"); + + // If FULL information is requested + if (m_config->KLFitterOutput() == "FULL") { + /// Debugging information + systematicTree->makeOutputVariable(m_klfitter_selection, "klfitter_selection"); + systematicTree->makeOutputVariable(m_klfitter_minuitDidNotConverge, "klfitter_minuitDidNotConverge"); + systematicTree->makeOutputVariable(m_klfitter_fitAbortedDueToNaN, "klfitter_fitAbortedDueToNaN"); + systematicTree->makeOutputVariable(m_klfitter_atLeastOneFitParameterAtItsLimit, "klfitter_atLeastOneFitParameterAtItsLimit"); + systematicTree->makeOutputVariable(m_klfitter_invalidTransferFunctionAtConvergence, "klfitter_invalidTransferFunctionAtConvergence"); + /// Global + systematicTree->makeOutputVariable(m_klfitter_parameters_size, "klfitter_parameters_size"); + systematicTree->makeOutputVariable(m_klfitter_parameters, "klfitter_parameters"); + systematicTree->makeOutputVariable(m_klfitter_parameterErrors, "klfitter_parameterErrors"); + systematicTree->makeOutputVariable(m_klfitter_bestPermutation, "klfitter_bestPermutation"); + } - // jets - m_upgradeTreeManager->makeOutputVariable(m_jet_pt, "jet_pt"); - m_upgradeTreeManager->makeOutputVariable(m_jet_eta, "jet_eta"); - m_upgradeTreeManager->makeOutputVariable(m_jet_phi, "jet_phi"); - m_upgradeTreeManager->makeOutputVariable(m_jet_e, "jet_e"); - m_upgradeTreeManager->makeOutputVariable(m_jet_mv1eff, "jet_mv1eff"); - m_upgradeTreeManager->makeOutputVariable(m_jet_isPileup, "jet_isPileup"); + if (m_config->KLFitterOutput() == "FULL" || m_config->KLFitterOutput() == "JETPERM_ONLY") { + /// Model + if (m_config->KLFitterLH() == "ttbar" || m_config->KLFitterLH() == "ttZTrilepton" || m_config->KLFitterLH() == "ttH" || m_config->KLFitterLH() == "ttbar_JetAngles" || m_config->KLFitterLH() == "ttbar_BoostedLJets") { + systematicTree->makeOutputVariable(m_klfitter_model_bhad_pt, "klfitter_model_bhad_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_bhad_eta, "klfitter_model_bhad_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_bhad_phi, "klfitter_model_bhad_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_bhad_E, "klfitter_model_bhad_E"); + systematicTree->makeOutputVariable(m_klfitter_model_bhad_jetIndex, "klfitter_model_bhad_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_blep_pt, "klfitter_model_blep_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_blep_eta, "klfitter_model_blep_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_blep_phi, "klfitter_model_blep_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_blep_E, "klfitter_model_blep_E"); + systematicTree->makeOutputVariable(m_klfitter_model_blep_jetIndex, "klfitter_model_blep_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_lq1_pt, "klfitter_model_lq1_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lq1_eta, "klfitter_model_lq1_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lq1_phi, "klfitter_model_lq1_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lq1_E, "klfitter_model_lq1_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lq1_jetIndex, "klfitter_model_lq1_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_lep_pt, "klfitter_model_lep_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lep_eta, "klfitter_model_lep_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lep_phi, "klfitter_model_lep_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lep_E, "klfitter_model_lep_E"); + + systematicTree->makeOutputVariable(m_klfitter_model_nu_pt, "klfitter_model_nu_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_nu_eta, "klfitter_model_nu_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_nu_phi, "klfitter_model_nu_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_nu_E, "klfitter_model_nu_E"); + + if (m_config->KLFitterLH() != "ttbar_BoostedLJets") { + systematicTree->makeOutputVariable(m_klfitter_model_lq2_pt, "klfitter_model_lq2_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lq2_eta, "klfitter_model_lq2_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lq2_phi, "klfitter_model_lq2_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lq2_E, "klfitter_model_lq2_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lq2_jetIndex, "klfitter_model_lq2_jetIndex"); + + if (m_config->KLFitterLH() == "ttZTrilepton") { + systematicTree->makeOutputVariable(m_klfitter_model_lep_index, "klfitter_model_lep_index"); + + systematicTree->makeOutputVariable(m_klfitter_model_lepZ1_pt, "klfitter_model_lepZ1_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ1_eta, "klfitter_model_lepZ1_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ1_phi, "klfitter_model_lepZ1_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ1_E, "klfitter_model_lepZ1_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ1_index, "klfitter_model_lepZ1_index"); + + systematicTree->makeOutputVariable(m_klfitter_model_lepZ2_pt, "klfitter_model_lepZ2_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ2_eta, "klfitter_model_lepZ2_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ2_phi, "klfitter_model_lepZ2_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ2_E, "klfitter_model_lepZ2_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lepZ2_index, "klfitter_model_lepZ2_index"); + } - m_upgradeTreeManager->makeOutputVariable(m_jet_Ghosts_BHadron_Final_Count, "jet_nGhosts_bHadron"); - m_upgradeTreeManager->makeOutputVariable(m_jet_Ghosts_CHadron_Final_Count, "jet_nGhosts_cHadron"); - - // MET - m_upgradeTreeManager->makeOutputVariable(m_met_met, "met_met"); - m_upgradeTreeManager->makeOutputVariable(m_met_phi, "met_phi"); - }//setupUpgradeTreeManager + if (m_config->KLFitterLH() == "ttH") { + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_pt, "klfitter_model_Higgs_b1_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_eta, "klfitter_model_Higgs_b1_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_phi, "klfitter_model_Higgs_b1_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_E, "klfitter_model_Higgs_b1_E"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b1_jetIndex, "klfitter_model_Higgs_b1_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_pt, "klfitter_model_Higgs_b2_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_eta, "klfitter_model_Higgs_b2_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_phi, "klfitter_model_Higgs_b2_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_E, "klfitter_model_Higgs_b2_E"); + systematicTree->makeOutputVariable(m_klfitter_model_Higgs_b2_jetIndex, "klfitter_model_Higgs_b2_jetIndex"); + } + } + } else if (m_config->KLFitterLH() == "ttbar_AllHadronic") { + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top1_pt, "klfitter_model_b_from_top1_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top1_eta, "klfitter_model_b_from_top1_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top1_phi, "klfitter_model_b_from_top1_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top1_E, "klfitter_model_b_from_top1_E"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top1_jetIndex, "klfitter_model_b_from_top1_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top2_pt, "klfitter_model_b_from_top2_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top2_eta, "klfitter_model_b_from_top2_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top2_phi, "klfitter_model_b_from_top2_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top2_E, "klfitter_model_b_from_top2_E"); + systematicTree->makeOutputVariable(m_klfitter_model_b_from_top2_jetIndex, "klfitter_model_b_from_top2_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top1_pt, "klfitter_model_lj1_from_top1_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top1_eta, "klfitter_model_lj1_from_top1_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top1_phi, "klfitter_model_lj1_from_top1_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top1_E, "klfitter_model_lj1_from_top1_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top1_jetIndex, "klfitter_model_lj1_from_top1_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top1_pt, "klfitter_model_lj2_from_top1_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top1_eta, "klfitter_model_lj2_from_top1_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top1_phi, "klfitter_model_lj2_from_top1_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top1_E, "klfitter_model_lj2_from_top1_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top1_jetIndex, "klfitter_model_lj2_from_top1_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top2_pt, "klfitter_model_lj1_from_top2_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top2_eta, "klfitter_model_lj1_from_top2_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top2_phi, "klfitter_model_lj1_from_top2_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top2_E, "klfitter_model_lj1_from_top2_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lj1_from_top2_jetIndex, "klfitter_model_lj1_from_top2_jetIndex"); + + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top2_pt, "klfitter_model_lj2_from_top2_pt"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top2_eta, "klfitter_model_lj2_from_top2_eta"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top2_phi, "klfitter_model_lj2_from_top2_phi"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top2_E, "klfitter_model_lj2_from_top2_E"); + systematicTree->makeOutputVariable(m_klfitter_model_lj2_from_top2_jetIndex, "klfitter_model_lj2_from_top2_jetIndex"); + } + } - void EventSaverFlatNtuple::recordSelectionDecision(const top::Event& event) { - int index(0); - for (const auto& branchName : m_extraBranches) { - m_selectionDecisions[index] = event.m_info->auxdataConst<int>(branchName); - ++index; + if (m_config->KLFitterOutput() == "FULL" || m_config->KLFitterOutput() == "FITTEDTOPS_ONLY") { + if (m_config->KLFitterLH() == "ttbar" || m_config->KLFitterLH() == "ttZTrilepton" || m_config->KLFitterLH() == "ttH" || m_config->KLFitterLH() == "ttbar_JetAngles") { + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_pt, "klfitter_bestPerm_topLep_pt"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_eta, "klfitter_bestPerm_topLep_eta"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_phi, "klfitter_bestPerm_topLep_phi"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_E, "klfitter_bestPerm_topLep_E"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topLep_m, "klfitter_bestPerm_topLep_m"); + + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_pt, "klfitter_bestPerm_topHad_pt"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_eta, "klfitter_bestPerm_topHad_eta"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_phi, "klfitter_bestPerm_topHad_phi"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_E, "klfitter_bestPerm_topHad_E"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_topHad_m, "klfitter_bestPerm_topHad_m"); + + systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_pt, "klfitter_bestPerm_ttbar_pt"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_eta, "klfitter_bestPerm_ttbar_eta"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_phi, "klfitter_bestPerm_ttbar_phi"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_E, "klfitter_bestPerm_ttbar_E"); + systematicTree->makeOutputVariable(m_klfitter_bestPerm_ttbar_m, "klfitter_bestPerm_ttbar_m"); + } } - } + } - void EventSaverFlatNtuple::recordTriggerDecision(const top::Event& event) { + if (m_config->doPseudoTop()) { + systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_pt, "PseudoTop_Reco_ttbar_pt"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_eta, "PseudoTop_Reco_ttbar_eta"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_phi, "PseudoTop_Reco_ttbar_phi"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_ttbar_m, "PseudoTop_Reco_ttbar_m"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_pt, "PseudoTop_Reco_top_had_pt"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_eta, "PseudoTop_Reco_top_had_eta"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_phi, "PseudoTop_Reco_top_had_phi"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_had_m, "PseudoTop_Reco_top_had_m"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_pt, "PseudoTop_Reco_top_lep_pt"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_eta, "PseudoTop_Reco_top_lep_eta"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_phi, "PseudoTop_Reco_top_lep_phi"); + systematicTree->makeOutputVariable(m_PseudoTop_Reco_top_lep_m, "PseudoTop_Reco_top_lep_m"); + } - for (const auto& trigger : m_triggerDecisions) - m_triggerDecisions[trigger.first] = event.m_info->auxdataConst<char>("TRIGDEC_"+trigger.first); - if (!m_config->isMC() && m_config->doFakesMMWeights()) { - for (const auto& trigger : m_triggerPrescales) - m_triggerPrescales[trigger.first] = event.m_info->auxdataConst<float>("TRIGPS_"+trigger.first); + //extra branches telling you if the event passed / failed a selection + int index(0); + for (const auto& branchName : m_extraBranches) { + m_selectionDecisions[index] = 0; + systematicTree->makeOutputVariable(m_selectionDecisions[index], branchName); + // Add all triggers to a map so we don't get any duplicates + for (auto& trigger_name : m_config->allTriggers_Tight(branchName)) { + m_triggerDecisions [trigger_name] = 0; + } + for (auto& trigger_name : m_config->allTriggers_Loose(branchName)) { + // let's make sure this isn't done twice + if (m_triggerDecisions.find(trigger_name) != m_triggerDecisions.end() + && m_triggerPrescales.find(trigger_name) != m_triggerPrescales.end()) continue; + m_triggerDecisions [trigger_name] = 0; + } + for (auto& trigger_name : m_config->electronTriggers_Tight(branchName)) + m_el_trigMatched [trigger_name] = std::vector<char>(); + for (auto& trigger_name : m_config->electronTriggers_Loose(branchName)) { + // let's make sure this isn't done twice + if (m_el_trigMatched.find(trigger_name) != m_el_trigMatched.end()) continue; + m_el_trigMatched [trigger_name] = std::vector<char>(); } + for (auto& trigger_name : m_config->muonTriggers_Tight(branchName)) + m_mu_trigMatched [trigger_name] = std::vector<char>(); + for (auto& trigger_name : m_config->muonTriggers_Loose(branchName)) { + // let's make sure this isn't done twice + if (m_mu_trigMatched.find(trigger_name) != m_mu_trigMatched.end()) continue; + m_mu_trigMatched [trigger_name] = std::vector<char>(); + } + ++index; + } + for (auto& trig_name : m_triggerDecisions) + systematicTree->makeOutputVariable(trig_name.second, trig_name.first); + for (auto& trig_name : m_el_trigMatched) + systematicTree->makeOutputVariable(trig_name.second, "el_trigMatch_" + trig_name.first); + for (auto& trig_name : m_mu_trigMatched) + systematicTree->makeOutputVariable(trig_name.second, "mu_trigMatch_" + trig_name.first); } - void EventSaverFlatNtuple::saveEvent(const top::Event& event) { + setupUpgradeTreeManager(); + setupParticleLevelTreeManager(); + } - // record the event? - if (m_config->saveOnlySelectedEvents() && !event.m_saveEvent) - return; + void EventSaverFlatNtuple::execute() { + if (m_config->isMC() && m_config->doMCGeneratorWeights()) { + loadMCGeneratorWeights(); + } - //We have decorated event-info with a variable for each selection - with pass / fail - recordSelectionDecision(event); + if (m_config->isMC() && m_config->doTruthPDFInfo()) { + loadPdfInfo(); + } - recordTriggerDecision(event); + if (m_config->isMC() && m_config->saveLHAPDFEvent()) { + loadPdfWeights(); + } + } - //some event weights - m_weight_mc = 0.; - if (m_config->isMC()) -// m_weight_mc = event.m_info->mcEventWeight(); - m_weight_mc = event.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + void EventSaverFlatNtuple::setupParticleLevelTreeManager(/*const top::ParticleLevelEvent& plEvent*/) { + // Quick return if particle level is disabled or the tree is already initialised. + // If particle level is disabled, no tree will be created. + if (not m_config->doTopParticleLevel() or m_particleLevelTreeManager) { + return; + } - if (m_config->isMC()) { + m_particleLevelTreeManager = std::make_shared<top::TreeManager>("particleLevel", m_outputFile, m_config->outputFileNEventAutoFlush(), m_config->outputFileBasketSizePrimitive(), m_config->outputFileBasketSizeVector()); + + m_particleLevelTreeManager->branchFilters() = branchFilters(); + m_particleLevelTreeManager->makeOutputVariable(m_weight_mc, "weight_mc"); + + //event info + m_particleLevelTreeManager->makeOutputVariable(m_eventNumber, "eventNumber"); + m_particleLevelTreeManager->makeOutputVariable(m_runNumber, "runNumber"); + if (m_config->isMC() && m_config->doPileupReweighting()) m_particleLevelTreeManager->makeOutputVariable(m_randomRunNumber, "randomRunNumber"); + m_particleLevelTreeManager->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); + m_particleLevelTreeManager->makeOutputVariable(m_mu, "mu"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_actual, "mu_actual"); + m_particleLevelTreeManager->makeOutputVariable(m_weight_pileup, "weight_pileup"); + + if (m_config->doPseudoTop()) { + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_pt, "PseudoTop_Particle_ttbar_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_eta, "PseudoTop_Particle_ttbar_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_phi, "PseudoTop_Particle_ttbar_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_ttbar_m, "PseudoTop_Particle_ttbar_m"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_pt, "PseudoTop_Particle_top_had_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_eta, "PseudoTop_Particle_top_had_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_phi, "PseudoTop_Particle_top_had_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_had_m, "PseudoTop_Particle_top_had_m"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_pt, "PseudoTop_Particle_top_lep_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_eta, "PseudoTop_Particle_top_lep_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_phi, "PseudoTop_Particle_top_lep_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_PseudoTop_Particle_top_lep_m, "PseudoTop_Particle_top_lep_m"); + } - m_weight_pileup = m_sfRetriever->pileupSF(event); + //electrons + if (m_config->useTruthElectrons()) { + m_particleLevelTreeManager->makeOutputVariable(m_el_pt, "el_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_el_eta, "el_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_el_phi, "el_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_el_e, "el_e"); + m_particleLevelTreeManager->makeOutputVariable(m_el_charge, "el_charge"); + + m_particleLevelTreeManager->makeOutputVariable(m_el_true_type, "el_true_type"); + m_particleLevelTreeManager->makeOutputVariable(m_el_true_origin, "el_true_origin"); + + m_particleLevelTreeManager->makeOutputVariable(m_el_pt_bare, "el_pt_bare"); + m_particleLevelTreeManager->makeOutputVariable(m_el_eta_bare, "el_eta_bare"); + m_particleLevelTreeManager->makeOutputVariable(m_el_phi_bare, "el_phi_bare"); + m_particleLevelTreeManager->makeOutputVariable(m_el_e_bare, "el_e_bare"); + } - m_weight_leptonSF = m_sfRetriever->leptonSF(event,top::topSFSyst::nominal); + //muons + if (m_config->useTruthMuons()) { + m_particleLevelTreeManager->makeOutputVariable(m_mu_pt, "mu_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_eta, "mu_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_phi, "mu_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_e, "mu_e"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_charge, "mu_charge"); + + m_particleLevelTreeManager->makeOutputVariable(m_mu_true_type, "mu_true_type"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_true_origin, "mu_true_origin"); + + m_particleLevelTreeManager->makeOutputVariable(m_mu_pt_bare, "mu_pt_bare"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_eta_bare, "mu_eta_bare"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_phi_bare, "mu_phi_bare"); + m_particleLevelTreeManager->makeOutputVariable(m_mu_e_bare, "mu_e_bare"); + + if(m_config->useSoftMuons()) + { + m_particleLevelTreeManager->makeOutputVariable(m_softmu_pt, "softmu_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_eta, "softmu_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_phi, "softmu_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_e, "softmu_e"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_charge, "softmu_charge"); + + m_particleLevelTreeManager->makeOutputVariable(m_softmu_true_type, "softmu_true_type"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_true_origin, "softmu_true_origin"); + + if(m_config->softmuonAdditionalTruthInfo()) + { + if(m_config->softmuonAdditionalTruthInfoCheckPartonOrigin()) m_particleLevelTreeManager->makeOutputVariable(m_softmu_parton_origin_flag, "softmu_parton_origin_flag"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_particle_origin_flag, "softmu_particle_origin_flag"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_parent_pdgid,"softmu_parent_pdgid"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_b_hadron_parent_pdgid,"softmu_b_hadron_parent_pdgid"); + m_particleLevelTreeManager->makeOutputVariable(m_softmu_c_hadron_parent_pdgid,"softmu_c_hadron_parent_pdgid"); + } + } + }//end of muons branches + + //photons + if (m_config->useTruthPhotons()) { + m_particleLevelTreeManager->makeOutputVariable(m_ph_pt, "ph_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_ph_eta, "ph_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_ph_phi, "ph_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_ph_e, "ph_e"); + } - if (m_config->useTaus()) - m_weight_tauSF = m_sfRetriever->tauSF(event, top::topSFSyst::nominal); + //jets + if (m_config->useTruthJets()) { + m_particleLevelTreeManager->makeOutputVariable(m_jet_pt, "jet_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_jet_eta, "jet_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_jet_phi, "jet_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_jet_e, "jet_e"); - if (m_config->usePhotons()) - m_weight_photonSF = m_sfRetriever->photonSF(event, top::topSFSyst::nominal); + m_particleLevelTreeManager->makeOutputVariable(m_jet_Ghosts_BHadron_Final_Count, "jet_nGhosts_bHadron"); + m_particleLevelTreeManager->makeOutputVariable(m_jet_Ghosts_CHadron_Final_Count, "jet_nGhosts_cHadron"); + } - for( auto& tagWP : m_config -> bTagWP_available()) { - m_weight_bTagSF[tagWP] = m_sfRetriever->btagSF(event, top::topSFSyst::nominal, tagWP); - } - if (m_config->useTrackJets()) { - for( auto& tagWP : m_config -> bTagWP_available_trkJet()) { - m_weight_trackjet_bTagSF[tagWP] = m_sfRetriever->btagSF(event, top::topSFSyst::nominal, tagWP, true); - } - } + //large R jets + if (m_config->useTruthLargeRJets()) { + m_particleLevelTreeManager->makeOutputVariable(m_ljet_pt, "ljet_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_ljet_eta, "ljet_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_ljet_phi, "ljet_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_ljet_e, "ljet_e"); - m_weight_jvt = m_sfRetriever->jvtSF(event, top::topSFSyst::nominal); + m_particleLevelTreeManager->makeOutputVariable(m_ljet_Ghosts_BHadron_Final_Count, "ljet_nGhosts_bHadron"); + m_particleLevelTreeManager->makeOutputVariable(m_ljet_Ghosts_CHadron_Final_Count, "ljet_nGhosts_cHadron"); + } - if (m_config->isSherpa22Vjets()) { - if (event.m_info->isAvailable<double>("Sherpa22VJetsWeight")) { - m_weight_sherpa_22_vjets = event.m_info->auxdataConst<double>("Sherpa22VJetsWeight"); - } - } + //taus + if (m_config->useTruthTaus()) { + m_particleLevelTreeManager->makeOutputVariable(m_tau_pt, "tau_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_tau_eta, "tau_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_tau_phi, "tau_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_tau_e, "tau_e"); + m_particleLevelTreeManager->makeOutputVariable(m_tau_charge, "tau_charge"); + m_particleLevelTreeManager->makeOutputVariable(m_tau_isHadronic, "tau_isHadronic"); + } - // writing the systematic-shifted SFs only in the nominal (or nominal_Loose) tree - if (event.m_hashValue == m_config->nominalHashValue()) { - - m_weight_pileup_UP = m_sfRetriever->pileupSF( event, +1 ); // up variation - m_weight_pileup_DOWN = m_sfRetriever->pileupSF( event, -1 ); // down variation - - m_weight_leptonSF_EL_SF_Trigger_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_Trigger_UP); - m_weight_leptonSF_EL_SF_Trigger_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_Trigger_DOWN); - m_weight_leptonSF_EL_SF_Reco_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_Reco_UP); - m_weight_leptonSF_EL_SF_Reco_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_Reco_DOWN); - m_weight_leptonSF_EL_SF_ID_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_ID_UP); - m_weight_leptonSF_EL_SF_ID_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_ID_DOWN); - m_weight_leptonSF_EL_SF_Isol_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_Isol_UP); - m_weight_leptonSF_EL_SF_Isol_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::EL_SF_Isol_DOWN); - - m_weight_leptonSF_MU_SF_Trigger_STAT_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Trigger_STAT_UP); - m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Trigger_STAT_DOWN); - m_weight_leptonSF_MU_SF_Trigger_SYST_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Trigger_SYST_UP); - m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Trigger_SYST_DOWN); - // Muon ID SF systematics (regular) - m_weight_leptonSF_MU_SF_ID_STAT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_UP); - m_weight_leptonSF_MU_SF_ID_STAT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_DOWN); - m_weight_leptonSF_MU_SF_ID_SYST_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_UP); - m_weight_leptonSF_MU_SF_ID_SYST_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_DOWN); - // Muon ID SF systematics (regular) - m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP); - m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN); - m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP); - m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN); - // Muon isolation SF systematics - m_weight_leptonSF_MU_SF_Isol_STAT_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Isol_STAT_UP); - m_weight_leptonSF_MU_SF_Isol_STAT_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Isol_STAT_DOWN); - m_weight_leptonSF_MU_SF_Isol_SYST_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Isol_SYST_UP); - m_weight_leptonSF_MU_SF_Isol_SYST_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_Isol_SYST_DOWN); - m_weight_leptonSF_MU_SF_TTVA_STAT_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_TTVA_STAT_UP); - m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_TTVA_STAT_DOWN); - m_weight_leptonSF_MU_SF_TTVA_SYST_UP = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_TTVA_SYST_UP); - m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN = m_sfRetriever->leptonSF(event,top::topSFSyst::MU_SF_TTVA_SYST_DOWN); - - - m_weight_indiv_SF_EL_Trigger = m_sfRetriever -> triggerSF(event,top::topSFSyst::nominal); - m_weight_indiv_SF_EL_Trigger_UP = m_sfRetriever -> triggerSF(event,top::topSFSyst::EL_SF_Trigger_UP); - m_weight_indiv_SF_EL_Trigger_DOWN = m_sfRetriever -> triggerSF(event,top::topSFSyst::EL_SF_Trigger_DOWN); - m_weight_indiv_SF_EL_Reco = m_sfRetriever -> electronSF(event,top::topSFSyst::nominal, top::topSFComp::RECO); - m_weight_indiv_SF_EL_Reco_UP = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_Reco_UP, top::topSFComp::RECO); - m_weight_indiv_SF_EL_Reco_DOWN = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_Reco_DOWN, top::topSFComp::RECO); - m_weight_indiv_SF_EL_ID = m_sfRetriever -> electronSF(event,top::topSFSyst::nominal, top::topSFComp::ID); - m_weight_indiv_SF_EL_ID_UP = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ID_UP, top::topSFComp::ID); - m_weight_indiv_SF_EL_ID_DOWN = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ID_DOWN, top::topSFComp::ID); - m_weight_indiv_SF_EL_Isol = m_sfRetriever -> electronSF(event,top::topSFSyst::nominal, top::topSFComp::ISOLATION); - m_weight_indiv_SF_EL_Isol_UP = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_Isol_UP, top::topSFComp::ISOLATION); - m_weight_indiv_SF_EL_Isol_DOWN = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_Isol_DOWN, top::topSFComp::ISOLATION); - m_weight_indiv_SF_EL_ChargeID = m_sfRetriever -> electronSF(event,top::topSFSyst::nominal, top::topSFComp::CHARGEID); - m_weight_indiv_SF_EL_ChargeID_UP = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ChargeID_UP, top::topSFComp::CHARGEID); - m_weight_indiv_SF_EL_ChargeID_DOWN = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ChargeID_DOWN,top::topSFComp::CHARGEID); - m_weight_indiv_SF_EL_ChargeMisID = m_sfRetriever -> electronSF(event,top::topSFSyst::nominal, top::topSFComp::CHARGEMISID); - m_weight_indiv_SF_EL_ChargeMisID_STAT_UP = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ChargeMisID_STAT_UP, top::topSFComp::CHARGEMISID); - m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ChargeMisID_STAT_DOWN,top::topSFComp::CHARGEMISID); - m_weight_indiv_SF_EL_ChargeMisID_SYST_UP = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ChargeMisID_SYST_UP, top::topSFComp::CHARGEMISID); - m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN = m_sfRetriever -> electronSF(event,top::topSFSyst::EL_SF_ChargeMisID_SYST_DOWN,top::topSFComp::CHARGEMISID); - ATH_MSG_DEBUG("Electron Trigger SF = "<<m_weight_indiv_SF_EL_Trigger<<" + "<<m_weight_indiv_SF_EL_Trigger_UP<<" - "<<m_weight_indiv_SF_EL_Trigger_DOWN); - ATH_MSG_DEBUG("Electron Reco SF = "<<m_weight_indiv_SF_EL_Reco<<" + "<<m_weight_indiv_SF_EL_Reco_UP<<" - "<<m_weight_indiv_SF_EL_Reco_DOWN); - ATH_MSG_DEBUG("Electron ID SF = "<<m_weight_indiv_SF_EL_ID<<" + "<<m_weight_indiv_SF_EL_ID_UP<<" - "<<m_weight_indiv_SF_EL_ID_DOWN); - ATH_MSG_DEBUG("Electron Charge ID SF = "<<m_weight_indiv_SF_EL_ChargeID<<" + "<<m_weight_indiv_SF_EL_ChargeID_UP<<" - "<<m_weight_indiv_SF_EL_ChargeID_DOWN); - ATH_MSG_DEBUG("Electron Charge Mis ID SF = "<<m_weight_indiv_SF_EL_ChargeMisID<<" + "<<m_weight_indiv_SF_EL_ChargeMisID_STAT_UP<<" - "<<m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN<<" + "<<m_weight_indiv_SF_EL_ChargeMisID_SYST_UP<<" - "<<m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN); - - m_weight_indiv_SF_MU_Trigger = m_sfRetriever -> triggerSF(event,top::topSFSyst::nominal); - m_weight_indiv_SF_MU_Trigger_STAT_UP = m_sfRetriever -> triggerSF(event,top::topSFSyst::MU_SF_Trigger_STAT_UP); - m_weight_indiv_SF_MU_Trigger_STAT_DOWN = m_sfRetriever -> triggerSF(event,top::topSFSyst::MU_SF_Trigger_STAT_DOWN); - m_weight_indiv_SF_MU_Trigger_SYST_UP = m_sfRetriever -> triggerSF(event,top::topSFSyst::MU_SF_Trigger_SYST_UP); - m_weight_indiv_SF_MU_Trigger_SYST_DOWN = m_sfRetriever -> triggerSF(event,top::topSFSyst::MU_SF_Trigger_SYST_DOWN); - m_weight_indiv_SF_MU_ID = m_sfRetriever -> muonSF(event,top::topSFSyst::nominal, top::topSFComp::ID); - // Muon ID SF systematics (regular) - m_weight_indiv_SF_MU_ID_STAT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_UP, top::topSFComp::ID); - m_weight_indiv_SF_MU_ID_STAT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_DOWN, top::topSFComp::ID); - m_weight_indiv_SF_MU_ID_SYST_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_UP, top::topSFComp::ID); - m_weight_indiv_SF_MU_ID_SYST_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_DOWN, top::topSFComp::ID); - // Muon ID SF systematics (low pt) - m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP, top::topSFComp::ID); - m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN, top::topSFComp::ID); - m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP, top::topSFComp::ID); - m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN, top::topSFComp::ID); - // Muon isolation SF systematics - m_weight_indiv_SF_MU_Isol = m_sfRetriever -> muonSF(event,top::topSFSyst::nominal, top::topSFComp::ISOLATION); - m_weight_indiv_SF_MU_Isol_STAT_UP = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_Isol_STAT_UP, top::topSFComp::ISOLATION); - m_weight_indiv_SF_MU_Isol_STAT_DOWN = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_Isol_STAT_DOWN, top::topSFComp::ISOLATION); - m_weight_indiv_SF_MU_Isol_SYST_UP = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_Isol_SYST_UP, top::topSFComp::ISOLATION); - m_weight_indiv_SF_MU_Isol_SYST_DOWN = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_Isol_SYST_DOWN, top::topSFComp::ISOLATION); - m_weight_indiv_SF_MU_TTVA = m_sfRetriever -> muonSF(event,top::topSFSyst::nominal, top::topSFComp::TTVA); - m_weight_indiv_SF_MU_TTVA_STAT_UP = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_TTVA_STAT_UP, top::topSFComp::TTVA); - m_weight_indiv_SF_MU_TTVA_STAT_DOWN = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_TTVA_STAT_DOWN, top::topSFComp::TTVA); - m_weight_indiv_SF_MU_TTVA_SYST_UP = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_TTVA_SYST_UP, top::topSFComp::TTVA); - m_weight_indiv_SF_MU_TTVA_SYST_DOWN = m_sfRetriever -> muonSF(event,top::topSFSyst::MU_SF_TTVA_SYST_DOWN, top::topSFComp::TTVA); - - - ATH_MSG_DEBUG("Muon Trigger SF = "<<m_weight_indiv_SF_MU_Trigger<<" + "<< m_weight_indiv_SF_MU_Trigger_STAT_UP<<" - "<< m_weight_indiv_SF_MU_Trigger_STAT_DOWN<<" + "<< m_weight_indiv_SF_MU_Trigger_SYST_UP<<" - "<< m_weight_indiv_SF_MU_Trigger_SYST_DOWN); - - ATH_MSG_DEBUG("Muon ID SF = "<<m_weight_indiv_SF_MU_ID<<" + "<< m_weight_indiv_SF_MU_ID_STAT_UP<<" - "<< m_weight_indiv_SF_MU_ID_STAT_DOWN<<" + "<< m_weight_indiv_SF_MU_ID_SYST_UP<<" - "<< m_weight_indiv_SF_MU_ID_SYST_DOWN); - - - if (m_config->useTaus()) { - // Tau-electron overlap removal - m_weight_tauSF_ELEOLR_UP = m_sfRetriever->tauSF(event, top::topSFSyst::TAU_SF_ELEOLR_TOTAL_UP); - m_weight_tauSF_ELEOLR_DOWN = m_sfRetriever->tauSF(event, top::topSFSyst::TAU_SF_ELEOLR_TOTAL_DOWN); - // Tau Jet IDWP - m_weight_tauSF_JETID_UP = m_sfRetriever->tauSF(event, top::topSFSyst::TAU_SF_JETID_TOTAL_UP); - m_weight_tauSF_JETID_DOWN = m_sfRetriever->tauSF(event, top::topSFSyst::TAU_SF_JETID_TOTAL_DOWN); - // Tau reconstruction - m_weight_tauSF_RECO_UP = m_sfRetriever->tauSF(event, top::topSFSyst::TAU_SF_RECO_TOTAL_UP); - m_weight_tauSF_RECO_DOWN = m_sfRetriever->tauSF(event, top::topSFSyst::TAU_SF_RECO_TOTAL_DOWN); - } - - if (m_config->usePhotons()) { - m_weight_photonSF_ID_UP = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_IDSF_UP); - m_weight_photonSF_ID_DOWN = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_IDSF_DOWN); - m_weight_photonSF_effIso = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_ISO); - m_weight_photonSF_effLowPtIso_UP = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_LOWPTISO_UP); - m_weight_photonSF_effLowPtIso_DOWN = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_LOWPTISO_DOWN); - m_weight_photonSF_effTrkIso_UP = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_TRKISO_UP); - m_weight_photonSF_effTrkIso_DOWN = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_TRKISO_DOWN); - } - - - m_weight_jvt_up = m_sfRetriever->jvtSF(event, top::topSFSyst::JVT_UP); - m_weight_jvt_down = m_sfRetriever->jvtSF(event, top::topSFSyst::JVT_DOWN); - } + // RC branches + if (m_makeRCJets) { + // create the branches + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_pt, "rcjet_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_eta, "rcjet_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_phi, "rcjet_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_e, "rcjet_e"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_d12, "rcjet_d12"); // requires >= 2 subjets + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_d23, "rcjet_d23"); // requires >= 3 subjets + m_particleLevelTreeManager->makeOutputVariable(m_rcjetsub_pt, "rcjetsub_pt"); // vector of vectors for subjet + // info + m_particleLevelTreeManager->makeOutputVariable(m_rcjetsub_eta, "rcjetsub_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjetsub_phi, "rcjetsub_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjetsub_e, "rcjetsub_e"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjetsub_Ghosts_BHadron_Final_Count, "rcjetsub_nGhosts_bHadron"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjetsub_Ghosts_CHadron_Final_Count, "rcjetsub_nGhosts_cHadron"); + + if (m_useRCJSS || m_useRCAdditionalJSS) { + m_particleLevelTreeManager->makeOutputVariable(m_rrcjet_pt, "rrcjet_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_rrcjet_eta, "rrcjet_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_rrcjet_phi, "rrcjet_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_rrcjet_e, "rrcjet_e"); + } - // for b-tagging SFs, can also have systematic-shifted in systematics trees - if (event.m_hashValue == m_config->nominalHashValue() || m_config->dumpBtagSystsInSystTrees()) { - for( auto& tagWP : m_config -> bTagWP_available()) { - // skip uncalibrated though available WPs - if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; - m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_B, - m_weight_bTagSF_eigen_B_up[tagWP], - m_weight_bTagSF_eigen_B_down[tagWP], tagWP); - m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_C, - m_weight_bTagSF_eigen_C_up[tagWP], - m_weight_bTagSF_eigen_C_down[tagWP], tagWP); - m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_LIGHT, - m_weight_bTagSF_eigen_Light_up[tagWP], - m_weight_bTagSF_eigen_Light_down[tagWP], tagWP); - for (auto name : m_config->btagging_namedSysts(tagWP)) { - m_weight_bTagSF_named_up[tagWP][name] = m_sfRetriever->btagSF( event, top::topSFSyst::BTAG_SF_NAMED_UP, tagWP, false, name ); - m_weight_bTagSF_named_down[tagWP][name] = m_sfRetriever->btagSF( event, top::topSFSyst::BTAG_SF_NAMED_DOWN, tagWP, false, name ); - } - } - if (m_config->useTrackJets()) { - for( auto& tagWP : m_config -> bTagWP_available_trkJet()) { - // skip uncalibrated though available WPs - if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; - m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_B, - m_weight_trackjet_bTagSF_eigen_B_up[tagWP], - m_weight_trackjet_bTagSF_eigen_B_down[tagWP], tagWP, true); - m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_C, - m_weight_trackjet_bTagSF_eigen_C_up[tagWP], - m_weight_trackjet_bTagSF_eigen_C_down[tagWP], tagWP, true); - m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_LIGHT, - m_weight_trackjet_bTagSF_eigen_Light_up[tagWP], - m_weight_trackjet_bTagSF_eigen_Light_down[tagWP], tagWP, true); - for (auto name : m_config->btagging_namedSysts(tagWP)) { - m_weight_trackjet_bTagSF_named_up[tagWP][name] = m_sfRetriever->btagSF( event, top::topSFSyst::BTAG_SF_NAMED_UP, tagWP, true, name); - m_weight_trackjet_bTagSF_named_down[tagWP][name] = m_sfRetriever->btagSF( event, top::topSFSyst::BTAG_SF_NAMED_DOWN, tagWP, true, name ); - } - } - } - } - } + if (m_useRCJSS) { + // RCJet SS from Clusters + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_tau32_clstr, "rcjet_tau32_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_tau21_clstr, "rcjet_tau21_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_tau3_clstr, "rcjet_tau3_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_tau2_clstr, "rcjet_tau2_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_tau1_clstr, "rcjet_tau1_clstr"); + + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_d12_clstr, "rcjet_d12_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_d23_clstr, "rcjet_d23_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_Qw_clstr, "rcjet_Qw_clstr"); + + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_nconstituent_clstr, "rcjet_nconstituent_clstr"); + + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_D2_clstr, "rcjet_D2_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_ECF1_clstr, "rcjet_ECF1_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_ECF2_clstr, "rcjet_ECF2_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_ECF3_clstr, "rcjet_ECF3_clstr"); - ///-- weights for matrix-method fakes estimate --/// - if (!m_config->isMC() && m_config->doFakesMMWeights()) { - top::TopFakesMMWeightCalculator const* fakesMMWeightCalc(nullptr); - if ( asg::ToolStore::contains<top::TopFakesMMWeightCalculator>("MMWeightCalculator") ) { - fakesMMWeightCalc = asg::ToolStore::get<top::TopFakesMMWeightCalculator>("MMWeightCalculator"); - } - else { - ATH_MSG_ERROR("EventSaverFlatNtuple::initialize" ); - throw std::runtime_error("Unable to retrieve top::TopFakesMMWeightCalculator tool"); - } - for(const auto& branchName : m_extraBranches) {//loop on selections - for(const auto& conf : fakesMMWeightCalc->GetFakesMMConfigNames(branchName)) { - std::string MMweight_branch_name = "fakesMM_weight_" + branchName + "_" + conf; - std::string decorName = "MMWeight_"; decorName += branchName; decorName += "_"; decorName += conf; - if( event.m_info->isAvailable<float>(decorName.c_str()) ) { - m_fakesMM_weights[branchName][conf] = event.m_info->auxdataConst<float>(decorName.c_str()); - } - else {//if decoration is not present, it means this weight is not relevant for this channel - a hurtless weight=1. is then applied - m_fakesMM_weights[branchName][conf] = 1.; - } - } - } - } + } + if (m_useRCAdditionalJSS) { + + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF332_clstr, "rcjet_gECF332_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF461_clstr, "rcjet_gECF461_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF322_clstr, "rcjet_gECF322_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF331_clstr, "rcjet_gECF331_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF422_clstr, "rcjet_gECF422_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF441_clstr, "rcjet_gECF441_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF212_clstr, "rcjet_gECF212_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF321_clstr, "rcjet_gECF321_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_gECF311_clstr, "rcjet_gECF311_clstr"); + + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_L1_clstr, "rcjet_L1_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_L2_clstr, "rcjet_L2_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_L3_clstr, "rcjet_L3_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_L4_clstr, "rcjet_L4_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_rcjet_L5_clstr, "rcjet_L5_clstr"); + } + } - //event info - m_eventNumber = event.m_info -> eventNumber(); - m_runNumber = event.m_info -> runNumber(); - m_randomRunNumber = 0; - if (m_config->isMC() && m_config->doPileupReweighting()) { - if (event.m_info->isAvailable<unsigned int>("RandomRunNumber")) - m_randomRunNumber = event.m_info->auxdataConst<unsigned int>("RandomRunNumber"); - } - m_mcChannelNumber = 0; - - if (m_config->isMC()) - m_mcChannelNumber = event.m_info -> mcChannelNumber(); - - // (non-collision-)background flags - m_backgroundFlags = 0; - if (event.m_info->isAvailable<unsigned int>("backgroundFlags")) - m_backgroundFlags = event.m_info->auxdataConst<unsigned int>("backgroundFlags"); - - // hasBadMuon flag - m_hasBadMuon = 0; - if (m_config->useMuons() && event.m_info->isAvailable<char>("AnalysisTop_HASBADMUON")) - m_hasBadMuon = event.m_info->auxdataConst<char>("AnalysisTop_HASBADMUON"); - - // mu values (original and corrected by pileup reweighting tool) - m_mu_original = event.m_info->averageInteractionsPerCrossing(); - - // set these all to zero (maybe not the most sensible value...) - m_mu = 0; - - if (m_config->isMC()) - m_mu = m_mu_original; - if (!m_config->isMC()) { - // If we have the corrected mu value from pileup reweighting then save that - // instead of mu value in (d)xAOD. - if( event.m_info->isAvailable<float>("corrected_averageInteractionsPerCrossing") ) - m_mu = event.m_info->auxdataConst<float>("corrected_averageInteractionsPerCrossing"); - } - - ATH_MSG_DEBUG(" mu = "<<m_mu_original<<" -> "<<m_mu); - - //electrons - if (m_config->useElectrons()) { - unsigned int i(0); - unsigned int n_electrons = event.m_electrons.size(); - m_el_pt.resize(n_electrons); - m_el_eta.resize(n_electrons); - m_el_cl_eta.resize(n_electrons); - m_el_phi.resize(n_electrons); - m_el_e.resize(n_electrons); - m_el_charge.resize(n_electrons); - m_el_topoetcone20.resize(n_electrons); - m_el_ptvarcone20.resize(n_electrons); - m_el_isTight.resize(n_electrons); - m_el_CF.resize(n_electrons); - for( const auto& trigger : m_el_trigMatched ) - m_el_trigMatched[trigger.first].resize(n_electrons); - m_el_d0sig.resize(n_electrons); - m_el_delta_z0_sintheta.resize(n_electrons); - if (m_config->isMC()) { - m_el_true_type.resize(n_electrons); - m_el_true_origin.resize(n_electrons); - m_el_true_typebkg.resize(n_electrons); - m_el_true_originbkg.resize(n_electrons); - } + if (m_makeVarRCJets) { + std::string VarRC = "vrcjet"; + + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_pt"], VarRC + "_" + name + "_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_eta"], VarRC + "_" + name + "_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_phi"], VarRC + "_" + name + "_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_e"], VarRC + "_" + name + "_e"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d12"], VarRC + "_" + name + "_d12"); // requires + // >= + // 2 + // subjets + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d23"], VarRC + "_" + name + "_d23"); // requires + // >= + // 3 + // subjets + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_pt"], VarRC + "sub_" + name + "_pt"); // vector + // of + // vectors + // for + // subjet + // info + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_eta"], VarRC + "sub_" + name + "_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_phi"], VarRC + "sub_" + name + "_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_e"], VarRC + "sub_" + name + "_e"); + + if (m_useVarRCJSS || m_useVarRCAdditionalJSS) { + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle["vrrcjet_" + name + "_pt"], "vrrcjet_" + name + "_pt"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle["vrrcjet_" + name + "_eta"], "vrrcjet_" + name + "_eta"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle["vrrcjet_" + name + "_phi"], "vrrcjet_" + name + "_phi"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle["vrrcjet_" + name + "_e"], "vrrcjet_" + name + "_e"); + } + if (m_useVarRCJSS) { + // RCJet SS from Clusters + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau32_clstr"], VarRC + "_" + name + "_tau32_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau21_clstr"], VarRC + "_" + name + "_tau21_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau3_clstr"], VarRC + "_" + name + "_tau3_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau2_clstr"], VarRC + "_" + name + "_tau2_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau1_clstr"], VarRC + "_" + name + "_tau1_clstr"); + + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d12_clstr"], VarRC + "_" + name + "_d12_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d23_clstr"], VarRC + "_" + name + "_d23_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_Qw_clstr"], VarRC + "_" + name + "_Qw_clstr"); + } + if (m_useVarRCAdditionalJSS) { + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF332_clstr"], VarRC + "_" + name + "_gECF332_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF461_clstr"], VarRC + "_" + name + "_gECF461_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF322_clstr"], VarRC + "_" + name + "_gECF322_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF331_clstr"], VarRC + "_" + name + "_gECF331_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF422_clstr"], VarRC + "_" + name + "_gECF422_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF441_clstr"], VarRC + "_" + name + "_gECF441_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF212_clstr"], VarRC + "_" + name + "_gECF212_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF321_clstr"], VarRC + "_" + name + "_gECF321_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF311_clstr"], VarRC + "_" + name + "_gECF311_clstr"); + + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L1_clstr"], VarRC + "_" + name + "_L1_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L2_clstr"], VarRC + "_" + name + "_L2_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L3_clstr"], VarRC + "_" + name + "_L3_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L4_clstr"], VarRC + "_" + name + "_L4_clstr"); + m_particleLevelTreeManager->makeOutputVariable(m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L5_clstr"], VarRC + "_" + name + "_L5_clstr"); + } + } // end loop over mass parameters + } // end loop over multipliers for mass scale + } // end if VarRC jets + + //met + if (m_config->useTruthMET()) { + m_particleLevelTreeManager->makeOutputVariable(m_met_met, "met_met"); + m_particleLevelTreeManager->makeOutputVariable(m_met_phi, "met_phi"); + } - for (const auto* const elPtr : event.m_electrons) { - m_el_pt[i] = elPtr->pt(); - m_el_eta[i] = elPtr->eta(); - m_el_cl_eta[i] = elPtr->caloCluster()->etaBE(2); - m_el_phi[i] = elPtr->phi(); - m_el_e[i] = elPtr->e(); - m_el_charge[i] = elPtr->charge(); - elPtr->isolationValue( m_el_topoetcone20[i] , xAOD::Iso::topoetcone20 ); - elPtr->isolationValue( m_el_ptvarcone20[i] , xAOD::Iso::ptvarcone20 ); - if (event.m_isLoose) { - if (elPtr->isAvailable<char>("passPreORSelection")) { - m_el_isTight[i] = elPtr->auxdataConst<char>("passPreORSelection"); - } - } - if (elPtr->isAvailable<char>("passChargeID")) - m_el_CF[i] = elPtr->auxdataConst<char>("passChargeID"); - for( const auto& trigger : m_el_trigMatched ){ - std::string trig = "TRIGMATCH_"+trigger.first; - m_el_trigMatched[trigger.first][i] = elPtr->auxdataConst<char>(trig); - } - if( elPtr->isAvailable<float>("d0sig") ) - m_el_d0sig[i] = elPtr->auxdataConst<float>("d0sig"); - if( elPtr->isAvailable<float>("delta_z0_sintheta") ) - m_el_delta_z0_sintheta[i] = elPtr->auxdataConst<float>("delta_z0_sintheta"); - - //retrieve the truth-matching variables from MCTruthClassifier - if (m_config->isMC()) { - m_el_true_type[i] = 0; - m_el_true_origin[i] = 0; - m_el_true_typebkg[i] = 0; - m_el_true_originbkg[i] = 0; - static SG::AuxElement::Accessor<int> typeel("truthType"); - static SG::AuxElement::Accessor<int> origel("truthOrigin"); - static SG::AuxElement::Accessor<int> typebkgel("bkgTruthType"); - static SG::AuxElement::Accessor<int> origbkgel("bkgTruthOrigin"); - if (typeel.isAvailable(*elPtr)) m_el_true_type[i] = typeel(*elPtr); - if (origel.isAvailable(*elPtr)) m_el_true_origin[i] = origel(*elPtr); - if (typebkgel.isAvailable(*elPtr)) m_el_true_typebkg[i] = typebkgel(*elPtr); - if (origbkgel.isAvailable(*elPtr)) m_el_true_originbkg[i] = origbkgel(*elPtr); - } - ++i; - } - } + // Setup PDF info branches if PDF info is requested. + if (m_config->doTruthPDFInfo()) { + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_X1, "PDFinfo_X1"); + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_X2, "PDFinfo_X2"); + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_PDGID1, "PDFinfo_PDGID1"); + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_PDGID2, "PDFinfo_PDGID2"); + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_Q, "PDFinfo_Q"); + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_XF1, "PDFinfo_XF1"); + m_particleLevelTreeManager->makeOutputVariable(m_PDFinfo_XF2, "PDFinfo_XF2"); + } - //muons - if (m_config->useMuons()) { - unsigned int i(0); - unsigned int n_muons = event.m_muons.size(); - m_mu_pt.resize(n_muons); - m_mu_eta.resize(n_muons); - m_mu_phi.resize(n_muons); - m_mu_e.resize(n_muons); - m_mu_charge.resize(n_muons); - m_mu_topoetcone20.resize(n_muons); - m_mu_ptvarcone30.resize(n_muons); - m_mu_isTight.resize(n_muons); - for( const auto& trigger : m_mu_trigMatched ) - m_mu_trigMatched[trigger.first].resize(n_muons); - m_mu_d0sig.resize(n_muons); - m_mu_delta_z0_sintheta.resize(n_muons); - if (m_config->isMC()) { - m_mu_true_type.resize(n_muons); - m_mu_true_origin.resize(n_muons); - } + // Setup MC generator weights branch if requested. + if (m_config->doMCGeneratorWeights()) { + m_particleLevelTreeManager->makeOutputVariable(m_mc_generator_weights, "mc_generator_weights"); + } - for (const auto* const muPtr : event.m_muons) { - m_mu_pt[i] = muPtr->pt(); - m_mu_eta[i] = muPtr->eta(); - m_mu_phi[i] = muPtr->phi(); - m_mu_e[i] = muPtr->e(); - m_mu_charge[i] = muPtr->charge(); - muPtr->isolation( m_mu_topoetcone20[i] , xAOD::Iso::topoetcone20 ); - muPtr->isolation( m_mu_ptvarcone30[i] , xAOD::Iso::ptvarcone30 ); - if (event.m_isLoose) { - if (muPtr->isAvailable<char>("passPreORSelection")) { - m_mu_isTight[i] = muPtr->auxdataConst<char>("passPreORSelection"); - } - } - for( const auto& trigger : m_mu_trigMatched ){ - std::string trig = "TRIGMATCH_"+trigger.first; - m_mu_trigMatched[trigger.first][i] = muPtr->auxdataConst<char>(trig); - } - if( muPtr->isAvailable<float>("d0sig") ) - m_mu_d0sig[i] = muPtr->auxdataConst<float>("d0sig"); - if( muPtr->isAvailable<float>("delta_z0_sintheta") ) - m_mu_delta_z0_sintheta[i] = muPtr->auxdataConst<float>("delta_z0_sintheta"); - - //retrieve the truth-matching variables from MCTruthClassifier - if (m_config->isMC()) { - static SG::AuxElement::Accessor<int> acc_mctt("truthType"); - static SG::AuxElement::Accessor<int> acc_mcto("truthOrigin"); - m_mu_true_type[i]=0; - m_mu_true_origin[i]=0; - const xAOD::TrackParticle* mutrack = muPtr->primaryTrackParticle(); - if (mutrack!=nullptr) { - if (acc_mctt.isAvailable(*mutrack)) m_mu_true_type[i] = acc_mctt(*mutrack); - if (acc_mcto.isAvailable(*mutrack)) m_mu_true_origin[i] = acc_mcto(*mutrack); - } - } - ++i; - } - } + // Setup PDF weight branches if PDF systematics are requested, + if (m_config->saveLHAPDFEvent()) { + for (auto& pdf : m_PDF_eventWeights) { + m_particleLevelTreeManager->makeOutputVariable(pdf.second, pdf.first); + } + } - //photons - if (m_config->usePhotons()) { - unsigned int i(0); - m_ph_pt.resize(event.m_photons.size()); - m_ph_eta.resize(event.m_photons.size()); - m_ph_phi.resize(event.m_photons.size()); - m_ph_e.resize(event.m_photons.size()); - m_ph_iso.resize(event.m_photons.size()); - for (const auto* const phPtr : event.m_photons) { - m_ph_pt[i] = phPtr->pt(); - m_ph_eta[i] = phPtr->eta(); - m_ph_phi[i] = phPtr->phi(); - m_ph_e[i] = phPtr->e(); - - m_ph_iso[i] = 0.; - if (phPtr->isAvailable<float>("ptvarcone20")) - m_ph_iso[i] = phPtr->auxdata<float>("ptvarcone20"); - - ++i; - } - } + // Setup the selection decision branches. This is a two-step process: + // + // (1) First, we need to create an array of variables which will be used to + // store the data in the TTree. The variable + // m_particleLevel_SelectionDecisions is just that: A std::vector of + // pairs, thwere the .first corresponds to the name of the selection, + // and the .second is the actual variable. + // (2) Secondly, we need to attach the newly created variables to the + // particle level tree manager. + m_particleLevel_SelectionDecisions.reserve(m_extraBranches.size()); + for (const auto& selection : m_extraBranches) { + m_particleLevel_SelectionDecisions.push_back(std::make_pair(selection, int())); + } + for (auto& selectionDecision : m_particleLevel_SelectionDecisions) { + m_particleLevelTreeManager->makeOutputVariable(selectionDecision.second, selectionDecision.first); + } + } - //taus - if (m_config->useTaus()) { - unsigned int i(0); - m_tau_pt.resize(event.m_tauJets.size()); - m_tau_eta.resize(event.m_tauJets.size()); - m_tau_phi.resize(event.m_tauJets.size()); - m_tau_charge.resize(event.m_tauJets.size()); - for (const auto* const tauPtr : event.m_tauJets) { - m_tau_pt[i] = tauPtr->pt(); - m_tau_eta[i] = tauPtr->eta(); - m_tau_phi[i] = tauPtr->phi(); - m_tau_charge[i] = tauPtr->charge(); - ++i; - } - } + void EventSaverFlatNtuple::setupUpgradeTreeManager(/*const top::ParticleLevelEvent& upgradeEvent*/) { + // Quick return if upgrade is disabled or the tree is already initialised. + if (not m_config->HLLHC() or m_upgradeTreeManager) { + return; + } - //jets - if (m_config->useJets()) { - unsigned int i(0); - m_jet_pt.resize(event.m_jets.size()); - m_jet_eta.resize(event.m_jets.size()); - m_jet_phi.resize(event.m_jets.size()); - m_jet_e.resize(event.m_jets.size()); - m_jet_mv2c00.resize(event.m_jets.size()); - m_jet_mv2c10.resize(event.m_jets.size()); - m_jet_mv2c20.resize(event.m_jets.size()); - m_jet_ip3dsv1.resize(event.m_jets.size()); - m_jet_jvt.resize(event.m_jets.size()); - m_jet_passfjvt.resize(event.m_jets.size()); - if (m_config->isMC()) { - m_jet_truthflav.resize(event.m_jets.size()); - m_jet_truthPartonLabel.resize(event.m_jets.size()); - m_jet_isTrueHS.resize(event.m_jets.size()); - } - for( auto& tagWP : m_config -> bTagWP_available()){ - if (tagWP!= "Continuous") m_jet_isbtagged[tagWP].resize(event.m_jets.size()); - else m_jet_tagWeightBin.resize(event.m_jets.size()); - } - for (const auto* const jetPtr : event.m_jets) { - m_jet_pt[i] = jetPtr->pt(); - m_jet_eta[i] = jetPtr->eta(); - m_jet_phi[i] = jetPtr->phi(); - m_jet_e[i] = jetPtr->e(); - m_jet_ip3dsv1[i] = jetPtr->btagging()->SV1plusIP3D_discriminant(); - if (m_config->isMC()) { - m_jet_truthflav[i] = -99; - if(jetPtr->isAvailable<int>("HadronConeExclTruthLabelID")){ - jetPtr->getAttribute("HadronConeExclTruthLabelID", m_jet_truthflav[i]); - } - m_jet_truthPartonLabel[i] = -99; - if(jetPtr->isAvailable<int>("PartonTruthLabelID")){ - jetPtr->getAttribute("PartonTruthLabelID", m_jet_truthPartonLabel[i]); - } - m_jet_isTrueHS[i] = false; - if(jetPtr->isAvailable<char>("AnalysisTop_isHS")){ - jetPtr->getAttribute("AnalysisTop_isHS", m_jet_isTrueHS[i]); - } - } - for( auto& tagWP : m_config -> bTagWP_available()){ - if (tagWP!= "Continuous") { - m_jet_isbtagged[tagWP][i] = false; - if(jetPtr->isAvailable<char>("isbtagged_"+tagWP)) - m_jet_isbtagged[tagWP][i] = jetPtr->auxdataConst<char>("isbtagged_"+tagWP); - } - else { - m_jet_tagWeightBin[i] = -2;// AT default value - if(jetPtr->isAvailable<int>("tagWeightBin")) - m_jet_tagWeightBin[i] = jetPtr->auxdataConst<int>("tagWeightBin"); - } - } - - // for studies on high performance b-tagging - // the following are in DC14 - double mvx = -999; - jetPtr->btagging()->MVx_discriminant("MV2c00", mvx); - m_jet_mv2c00[i] = mvx; - mvx = -999; - jetPtr->btagging()->MVx_discriminant("MV2c10", mvx); - m_jet_mv2c10[i] = mvx; - mvx = -999; - jetPtr->btagging()->MVx_discriminant("MV2c20", mvx); - m_jet_mv2c20[i] = mvx; - - m_jet_jvt[i] = -1; - if (jetPtr->isAvailable<float>("AnalysisTop_JVT")) { - m_jet_jvt[i] = jetPtr->auxdataConst<float>("AnalysisTop_JVT"); - } - m_jet_passfjvt[i] = -1; - if (jetPtr->isAvailable<char>("passFJVT")) { - m_jet_passfjvt[i] = jetPtr->getAttribute<char>("passFJVT"); - } - - ++i; - } - } + m_upgradeTreeManager = std::make_shared<top::TreeManager>("upgrade", m_outputFile, m_config->outputFileNEventAutoFlush(), m_config->outputFileBasketSizePrimitive(), m_config->outputFileBasketSizeVector()); - //large-R jets - if (m_config->useLargeRJets()) { - unsigned int i(0); - m_ljet_pt.resize(event.m_largeJets.size()); - m_ljet_eta.resize(event.m_largeJets.size()); - m_ljet_phi.resize(event.m_largeJets.size()); - m_ljet_e.resize(event.m_largeJets.size()); - m_ljet_m.resize(event.m_largeJets.size()); - m_ljet_sd12.resize(event.m_largeJets.size()); - for (const auto* const jetPtr : event.m_largeJets) { - m_ljet_pt[i] = jetPtr->pt(); - m_ljet_eta[i] = jetPtr->eta(); - m_ljet_phi[i] = jetPtr->phi(); - m_ljet_e[i] = jetPtr->e(); - m_ljet_m[i] = jetPtr->m(); - m_ljet_sd12[i] = 0; - float Split12 = 0; - jetPtr->getAttribute("Split12", Split12); - m_ljet_sd12[i] = Split12; - - ++i; - } - } + m_upgradeTreeManager->makeOutputVariable(m_weight_mc, "weight_mc"); - //track jets - if (m_config->useTrackJets()) { - unsigned int i(0); - m_tjet_pt.resize(event.m_trackJets.size()); - m_tjet_eta.resize(event.m_trackJets.size()); - m_tjet_phi.resize(event.m_trackJets.size()); - m_tjet_e.resize(event.m_trackJets.size()); - m_tjet_mv2c00.resize(event.m_trackJets.size()); - m_tjet_mv2c10.resize(event.m_trackJets.size()); - m_tjet_mv2c20.resize(event.m_trackJets.size()); - for( auto& tagWP : m_config -> bTagWP_available_trkJet()) { - if (tagWP!= "Continuous") m_tjet_isbtagged[tagWP].resize(event.m_trackJets.size()); - else m_tjet_tagWeightBin.resize(event.m_trackJets.size()); - } - for (const auto* const jetPtr : event.m_trackJets) { - m_tjet_pt[i] = jetPtr->pt(); - m_tjet_eta[i] = jetPtr->eta(); - m_tjet_phi[i] = jetPtr->phi(); - m_tjet_e[i] = jetPtr->e(); - - double mvx = -999; - jetPtr->btagging()->MVx_discriminant("MV2c00", mvx); - m_tjet_mv2c00[i] = mvx; - mvx = -999; - jetPtr->btagging()->MVx_discriminant("MV2c10", mvx); - m_tjet_mv2c10[i] = mvx; - mvx = -999; - jetPtr->btagging()->MVx_discriminant("MV2c20", mvx); - m_tjet_mv2c20[i] = mvx; - for( auto& tagWP : m_config -> bTagWP_available_trkJet()){ - if (tagWP!= "Continuous") { - m_tjet_isbtagged[tagWP][i] = false; - if(jetPtr->isAvailable<char>("isbtagged_"+tagWP)) - m_tjet_isbtagged[tagWP][i] = jetPtr->auxdataConst<char>("isbtagged_"+tagWP); - } - else { - m_tjet_tagWeightBin[i] = -2;// AT default value - if(jetPtr->isAvailable<int>("tagWeightBin")) - m_tjet_tagWeightBin[i] = jetPtr->auxdataConst<int>("tagWeightBin"); - } - } - ++i; - } - } + if (m_config->doMCGeneratorWeights()) { + m_upgradeTreeManager->makeOutputVariable(m_mc_generator_weights, "mc_generator_weights"); + } - if (m_makeRCJets){ - // Execute the re-clustering code - // - make jet container of small-r jets in the event, put it in TStore, do re-clustering - top::check(m_rc->execute(event),"Failed to execute RCJetMC15 container"); + //event info + m_upgradeTreeManager->makeOutputVariable(m_eventNumber, "eventNumber"); + m_upgradeTreeManager->makeOutputVariable(m_runNumber, "runNumber"); + m_upgradeTreeManager->makeOutputVariable(m_mcChannelNumber, "mcChannelNumber"); + m_upgradeTreeManager->makeOutputVariable(m_mu, "mu"); + m_upgradeTreeManager->makeOutputVariable(m_mu_actual, "mu_actual"); + + // electrons + m_upgradeTreeManager->makeOutputVariable(m_el_pt, "el_pt"); + m_upgradeTreeManager->makeOutputVariable(m_el_eta, "el_eta"); + m_upgradeTreeManager->makeOutputVariable(m_el_phi, "el_phi"); + m_upgradeTreeManager->makeOutputVariable(m_el_e, "el_e"); + m_upgradeTreeManager->makeOutputVariable(m_el_charge, "el_charge"); + m_upgradeTreeManager->makeOutputVariable(m_el_true_type, "el_true_type"); + m_upgradeTreeManager->makeOutputVariable(m_el_true_origin, "el_true_origin"); + m_upgradeTreeManager->makeOutputVariable(m_el_etcone20, "el_etcone20"); + m_upgradeTreeManager->makeOutputVariable(m_el_ptcone30, "el_ptcone30"); + //m_upgradeTreeManager->makeOutputVariable(m_el_true_firstEgMotherTruthType, "el_true_firstEgMotherTruthType"); + //m_upgradeTreeManager->makeOutputVariable(m_el_true_firstEgMotherTruthOrigin, "el_true_firstEgMotherTruthOrigin"); + //m_upgradeTreeManager->makeOutputVariable(m_el_true_isPrompt, "el_true_isPrompt"); + if (m_config->HLLHCFakes()) m_upgradeTreeManager->makeOutputVariable(m_el_faketype, "el_faketype"); // 0 true 2 + // hfake + + //forward electrons + if (m_config->useFwdElectrons()) { + m_upgradeTreeManager->makeOutputVariable(m_fwdel_pt, "fwdel_pt"); + m_upgradeTreeManager->makeOutputVariable(m_fwdel_eta, "fwdel_eta"); + m_upgradeTreeManager->makeOutputVariable(m_fwdel_phi, "fwdel_phi"); + m_upgradeTreeManager->makeOutputVariable(m_fwdel_e, "fwdel_e"); + m_upgradeTreeManager->makeOutputVariable(m_fwdel_etcone20, "fwdel_etcone20"); + m_upgradeTreeManager->makeOutputVariable(m_fwdel_etcone30, "fwdel_etcone30"); + m_upgradeTreeManager->makeOutputVariable(m_fwdel_etcone40, "fwdel_etcone40"); + } - // Get the name of the container of re-clustered jets in TStore - m_RCJetContainer = m_rc->rcjetContainerName(event.m_hashValue,event.m_isLoose); + // muons + m_upgradeTreeManager->makeOutputVariable(m_mu_pt, "mu_pt"); + m_upgradeTreeManager->makeOutputVariable(m_mu_eta, "mu_eta"); + m_upgradeTreeManager->makeOutputVariable(m_mu_phi, "mu_phi"); + m_upgradeTreeManager->makeOutputVariable(m_mu_e, "mu_e"); + m_upgradeTreeManager->makeOutputVariable(m_mu_charge, "mu_charge"); + m_upgradeTreeManager->makeOutputVariable(m_mu_true_type, "mu_true_type"); + m_upgradeTreeManager->makeOutputVariable(m_mu_true_origin, "mu_true_origin"); + m_upgradeTreeManager->makeOutputVariable(m_mu_etcone20, "mu_etcone20"); + m_upgradeTreeManager->makeOutputVariable(m_mu_ptcone30, "mu_ptcone30"); + m_upgradeTreeManager->makeOutputVariable(m_mu_true_isPrompt, "mu_true_isPrompt"); + m_upgradeTreeManager->makeOutputVariable(m_mu_prodVtx_z, "mu_prodVtx_z"); + m_upgradeTreeManager->makeOutputVariable(m_mu_prodVtx_perp, "mu_prodVtx_perp"); + m_upgradeTreeManager->makeOutputVariable(m_mu_prodVtx_phi, "mu_prodVtx_phi"); + + // jets + m_upgradeTreeManager->makeOutputVariable(m_jet_pt, "jet_pt"); + m_upgradeTreeManager->makeOutputVariable(m_jet_eta, "jet_eta"); + m_upgradeTreeManager->makeOutputVariable(m_jet_phi, "jet_phi"); + m_upgradeTreeManager->makeOutputVariable(m_jet_e, "jet_e"); + m_upgradeTreeManager->makeOutputVariable(m_jet_mv1eff, "jet_mv1eff"); + m_upgradeTreeManager->makeOutputVariable(m_jet_isPileup, "jet_isPileup"); + + m_upgradeTreeManager->makeOutputVariable(m_jet_Ghosts_BHadron_Final_Count, "jet_nGhosts_bHadron"); + m_upgradeTreeManager->makeOutputVariable(m_jet_Ghosts_CHadron_Final_Count, "jet_nGhosts_cHadron"); + + //large R jets + if (m_config->useTruthLargeRJets()) { + m_upgradeTreeManager->makeOutputVariable(m_ljet_pt, "ljet_pt"); + m_upgradeTreeManager->makeOutputVariable(m_ljet_eta, "ljet_eta"); + m_upgradeTreeManager->makeOutputVariable(m_ljet_phi, "ljet_phi"); + m_upgradeTreeManager->makeOutputVariable(m_ljet_e, "ljet_e"); + + m_upgradeTreeManager->makeOutputVariable(m_ljet_Ghosts_BHadron_Final_Count, "ljet_nGhosts_bHadron"); + m_upgradeTreeManager->makeOutputVariable(m_ljet_Ghosts_CHadron_Final_Count, "ljet_nGhosts_cHadron"); + } - // -- Retrieve the re-clustered jets from TStore & save good re-clustered jets -- // - const xAOD::JetContainer* rc_jets(nullptr); - top::check(evtStore()->retrieve(rc_jets,m_RCJetContainer),"Failed to retrieve RC JetContainer"); + if (m_config->useTruthPhotons()) { + m_upgradeTreeManager->makeOutputVariable(m_ph_pt, "ph_pt"); + m_upgradeTreeManager->makeOutputVariable(m_ph_eta, "ph_eta"); + m_upgradeTreeManager->makeOutputVariable(m_ph_phi, "ph_phi"); + m_upgradeTreeManager->makeOutputVariable(m_ph_e, "ph_e"); + m_upgradeTreeManager->makeOutputVariable(m_ph_true_type, "ph_true_type"); + m_upgradeTreeManager->makeOutputVariable(m_ph_true_origin, "ph_true_origin"); + if (m_config->HLLHCFakes()) m_upgradeTreeManager->makeOutputVariable(m_ph_faketype, "ph_faketype"); // 0 + // true + // 1 + // efake + // 2 + // hfake + } - // re-clustered jet substructure - static SG::AuxElement::ConstAccessor<float> RCSplit12("Split12"); - static SG::AuxElement::ConstAccessor<float> RCSplit23("Split23"); + // MET + m_upgradeTreeManager->makeOutputVariable(m_met_met, "met_met"); + m_upgradeTreeManager->makeOutputVariable(m_met_phi, "met_phi"); - // Initialize the vectors to be saved as branches - unsigned int sizeOfRCjets(rc_jets->size()); + m_upgrade_SelectionDecisions.reserve(m_extraBranches.size()); + for (const auto& selection : m_extraBranches) { + m_upgrade_SelectionDecisions.push_back(std::make_pair(selection, int())); + } - m_rcjet_pt.resize(sizeOfRCjets,-999.); - m_rcjet_eta.resize(sizeOfRCjets,-999.); - m_rcjet_phi.resize(sizeOfRCjets,-999.); - m_rcjet_e.resize(sizeOfRCjets,-999.); - m_rcjet_d12.resize(sizeOfRCjets,-999.); - m_rcjet_d23.resize(sizeOfRCjets,-999.); - m_rcjetsub_pt.resize(sizeOfRCjets, std::vector<float>()); - m_rcjetsub_eta.resize(sizeOfRCjets, std::vector<float>()); - m_rcjetsub_phi.resize(sizeOfRCjets, std::vector<float>()); - m_rcjetsub_e.resize(sizeOfRCjets, std::vector<float>()); - m_rcjetsub_mv2c10.resize(sizeOfRCjets, std::vector<float>()); + for (auto& selectionDecision : m_upgrade_SelectionDecisions) { + m_upgradeTreeManager->makeOutputVariable(selectionDecision.second, selectionDecision.first); + } + }//setupUpgradeTreeManager - unsigned int i = 0; - for (xAOD::JetContainer::const_iterator jet_itr = rc_jets->begin(); jet_itr != rc_jets->end(); ++jet_itr) { - const xAOD::Jet* rc_jet = *jet_itr; + void EventSaverFlatNtuple::recordSelectionDecision(const top::Event& event) { + int index(0); - if (!m_rc->passSelection(*rc_jet)) - continue; + for (const auto& branchName : m_extraBranches) { + m_selectionDecisions[index] = event.m_info->auxdataConst<int>(branchName); + ++index; + } + } - m_rcjet_pt[i] = rc_jet->pt(); - m_rcjet_eta[i] = rc_jet->eta(); - m_rcjet_phi[i] = rc_jet->phi(); - m_rcjet_e[i] = rc_jet->e(); + void EventSaverFlatNtuple::recordTriggerDecision(const top::Event& event) { + for (const auto& trigger : m_triggerDecisions) + m_triggerDecisions[trigger.first] = event.m_info->auxdataConst<char>("TRIGDEC_" + trigger.first); + } - m_rcjet_d12[i] = (RCSplit12.isAvailable(*rc_jet)) ? RCSplit12(*rc_jet) : -999.; - m_rcjet_d23[i] = (RCSplit23.isAvailable(*rc_jet)) ? RCSplit23(*rc_jet) : -999.; + void EventSaverFlatNtuple::saveEvent(const top::Event& event) { + // record the event? + if (m_config->saveOnlySelectedEvents() && !event.m_saveEvent) return; - // loop over subjets - m_rcjetsub_pt[i].clear(); // clear the vector size (otherwise it grows out of control!) - m_rcjetsub_eta[i].clear(); - m_rcjetsub_phi[i].clear(); - m_rcjetsub_e[i].clear(); - m_rcjetsub_mv2c10[i].clear(); + this->cleanEvent(); + this->calculateEvent(event); + this->fillEvent(event); + } - const xAOD::Jet* subjet(nullptr); - const xAOD::BTagging* btag(nullptr); - for(auto rc_jet_subjet : rc_jet->getConstituents()){ - subjet = static_cast<const xAOD::Jet*>(rc_jet_subjet->rawConstituent()); - btag = subjet->btagging(); + void EventSaverFlatNtuple::cleanEvent() { + /* Doing nothing for now, but we should put here the (re-)initialisation to dummy values + * of all variables later calculated in calculateEvent(const top::Event& event) + * For example all weights set to 1, all vectors cleaned, all kinematic or angular variables set to -99999. + */ + } - double mvx10(-999.); // b-tagging mv2c10 - - if (btag){ - btag->MVx_discriminant("MV2c10",mvx10); - } - else{ - mvx10 = -999.; - } - - m_rcjetsub_pt[i].push_back(subjet->pt()); - m_rcjetsub_eta[i].push_back(subjet->eta()); - m_rcjetsub_phi[i].push_back(subjet->phi()); - m_rcjetsub_e[i].push_back(subjet->e()); - m_rcjetsub_mv2c10[i].push_back(mvx10); - } // end for-loop over subjets - ++i; - } // end for-loop over re-clustered jets - - m_rcjet_pt.resize(i); - m_rcjet_eta.resize(i); - m_rcjet_phi.resize(i); - m_rcjet_e.resize(i); - m_rcjet_d12.resize(i); - m_rcjet_d23.resize(i); - m_rcjetsub_pt.resize(i, std::vector<float>()); - m_rcjetsub_eta.resize(i, std::vector<float>()); - m_rcjetsub_phi.resize(i, std::vector<float>()); - m_rcjetsub_e.resize(i, std::vector<float>()); - m_rcjetsub_mv2c10.resize(i, std::vector<float>()); - } // end if make rcjets - // end re-clustered jets - - /**********************************/ - // VarRC jets - if (m_makeVarRCJets){ - // Execute the re-clustering code - // - make jet container, put it in TStore, do re-clustering - std::string VarRC = "vrcjet"; - for (auto& rho : m_VarRCJetRho){ - for (auto& mass_scale : m_VarRCJetMassScale){ - std::replace( rho.begin(), rho.end(), '.', '_'); - std::string name = rho+mass_scale; - - top::check(m_VarRC[name]->execute(event),"Failed to execute RCJetMC15 container"); - - // Get the name of the container of re-clustered jets in TStore - m_RCJetContainer = m_VarRC[name]->rcjetContainerName(event.m_hashValue,event.m_isLoose); - - // -- Retrieve the re-clustered jets from TStore & save good re-clustered jets -- // - const xAOD::JetContainer* vrc_jets(nullptr); - top::check(evtStore()->retrieve(vrc_jets,m_RCJetContainer),"Failed to retrieve RC JetContainer"); - - // re-clustered jet substructure - static SG::AuxElement::ConstAccessor<float> VarRCSplit12("Split12"); - static SG::AuxElement::ConstAccessor<float> VarRCSplit23("Split23"); - - // Initialize the vectors to be saved as branches - unsigned int sizeOfRCjets(vrc_jets->size()); - m_VarRCjetBranches[VarRC+"_"+name+"_pt"].resize(sizeOfRCjets,-999.); - m_VarRCjetBranches[VarRC+"_"+name+"_eta"].resize(sizeOfRCjets,-999.); - m_VarRCjetBranches[VarRC+"_"+name+"_phi"].resize(sizeOfRCjets,-999.); - m_VarRCjetBranches[VarRC+"_"+name+"_e"].resize(sizeOfRCjets,-999.); - m_VarRCjetBranches[VarRC+"_"+name+"_d12"].resize(sizeOfRCjets,-999.); - m_VarRCjetBranches[VarRC+"_"+name+"_d23"].resize(sizeOfRCjets,-999.); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_pt"].resize(sizeOfRCjets, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_eta"].resize(sizeOfRCjets, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_phi"].resize(sizeOfRCjets, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_e"].resize(sizeOfRCjets, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_mv2c10"].resize(sizeOfRCjets, std::vector<float>()); - - unsigned int i = 0; - for (xAOD::JetContainer::const_iterator jet_itr = vrc_jets->begin(); jet_itr != vrc_jets->end(); ++jet_itr) { - const xAOD::Jet* rc_jet = *jet_itr; - - if (!m_VarRC[name]->passSelection(*rc_jet)) - continue; - - m_VarRCjetBranches[VarRC+"_"+name+"_pt"][i] = rc_jet->pt(); - m_VarRCjetBranches[VarRC+"_"+name+"_eta"][i] = rc_jet->eta(); - m_VarRCjetBranches[VarRC+"_"+name+"_phi"][i] = rc_jet->phi(); - m_VarRCjetBranches[VarRC+"_"+name+"_e"][i] = rc_jet->e(); - - m_VarRCjetBranches[VarRC+"_"+name+"_d12"][i] = (VarRCSplit12.isAvailable(*rc_jet)) ? VarRCSplit12(*rc_jet) : -999.; - m_VarRCjetBranches[VarRC+"_"+name+"_d23"][i] = (VarRCSplit23.isAvailable(*rc_jet)) ? VarRCSplit23(*rc_jet) : -999.; - - // loop over subjets - const xAOD::Jet* subjet(nullptr); - const xAOD::BTagging* btag(nullptr); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_pt"][i].clear(); // clear the vector size (otherwise it grows out of control!) - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_eta"][i].clear(); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_phi"][i].clear(); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_e"][i].clear(); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_mv2c10"][i].clear(); - for(auto rc_jet_subjet : rc_jet->getConstituents()){ - subjet = static_cast<const xAOD::Jet*>(rc_jet_subjet->rawConstituent()); - btag = subjet->btagging(); - - double mvx10(-999.); // b-tagging mv2c10 - - if (btag){ - btag->MVx_discriminant("MV2c10",mvx10); - } - else{ - mvx10 = -999.; - } - - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_pt"][i].push_back(subjet->pt()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_eta"][i].push_back(subjet->eta()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_phi"][i].push_back(subjet->phi()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_e"][i].push_back(subjet->e()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_mv2c10"][i].push_back(mvx10); - } // end for-loop over subjets - ++i; - - } // end for-loop over re-clustered jets - - m_VarRCjetBranches[VarRC+"_"+name+"_pt"].resize(i); - m_VarRCjetBranches[VarRC+"_"+name+"_eta"].resize(i); - m_VarRCjetBranches[VarRC+"_"+name+"_phi"].resize(i); - m_VarRCjetBranches[VarRC+"_"+name+"_e"].resize(i); - m_VarRCjetBranches[VarRC+"_"+name+"_d12"].resize(i); - m_VarRCjetBranches[VarRC+"_"+name+"_d23"].resize(i); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_pt"].resize(i, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_eta"].resize(i, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_phi"].resize(i, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_e"].resize(i, std::vector<float>()); - m_VarRCjetsubBranches[VarRC+"_"+name+"_sub_mv2c10"].resize(i, std::vector<float>()); - } // end loop over mass parameters - } // end loop over multipliers for mass scale - } // end if make VarRC jets - // end VarRC jets - - - //met - m_met_met = event.m_met->met(); - m_met_phi = event.m_met->phi(); - - //KLFitter - if (m_config->doKLFitter()) { - unsigned int nPermutations(0),iPerm(0),bestPerm(0); - bool validKLFitter(false); - m_klfitter_selected = 0; - if (event.m_KLFitterResults != nullptr) { - validKLFitter = true; - m_klfitter_selected = 1; - nPermutations = event.m_KLFitterResults->size(); - } + void EventSaverFlatNtuple::calculateEvent(const top::Event& event) { + //We have decorated event-info with a variable for each selection - with pass / fail + recordSelectionDecision(event); - m_klfitter_minuitDidNotConverge.resize(nPermutations); - m_klfitter_fitAbortedDueToNaN.resize(nPermutations); - m_klfitter_atLeastOneFitParameterAtItsLimit.resize(nPermutations); - m_klfitter_invalidTransferFunctionAtConvergence.resize(nPermutations); - - /// Global result - m_klfitter_bestPermutation.resize(nPermutations); - m_klfitter_logLikelihood.resize(nPermutations); - m_klfitter_eventProbability.resize(nPermutations); - m_klfitter_parameters.resize(nPermutations); - m_klfitter_parameterErrors.resize(nPermutations); - - /// Model - m_klfitter_model_bhad_pt.resize(nPermutations); - m_klfitter_model_bhad_eta.resize(nPermutations); - m_klfitter_model_bhad_phi.resize(nPermutations); - m_klfitter_model_bhad_E.resize(nPermutations); - m_klfitter_model_bhad_jetIndex.resize(nPermutations); - - m_klfitter_model_blep_pt.resize(nPermutations); - m_klfitter_model_blep_eta.resize(nPermutations); - m_klfitter_model_blep_phi.resize(nPermutations); - m_klfitter_model_blep_E.resize(nPermutations); - m_klfitter_model_blep_jetIndex.resize(nPermutations); - - m_klfitter_model_lq1_pt.resize(nPermutations); - m_klfitter_model_lq1_eta.resize(nPermutations); - m_klfitter_model_lq1_phi.resize(nPermutations); - m_klfitter_model_lq1_E.resize(nPermutations); - m_klfitter_model_lq1_jetIndex.resize(nPermutations); - - m_klfitter_model_lq2_pt.resize(nPermutations); - m_klfitter_model_lq2_eta.resize(nPermutations); - m_klfitter_model_lq2_phi.resize(nPermutations); - m_klfitter_model_lq2_E.resize(nPermutations); - m_klfitter_model_lq2_jetIndex.resize(nPermutations); - - if(m_config -> KLFitterLH() == "ttH"){ - - m_klfitter_model_Higgs_b1_pt.resize(nPermutations); - m_klfitter_model_Higgs_b1_eta.resize(nPermutations); - m_klfitter_model_Higgs_b1_phi.resize(nPermutations); - m_klfitter_model_Higgs_b1_E.resize(nPermutations); - m_klfitter_model_Higgs_b1_jetIndex.resize(nPermutations); - - m_klfitter_model_Higgs_b2_pt.resize(nPermutations); - m_klfitter_model_Higgs_b2_eta.resize(nPermutations); - m_klfitter_model_Higgs_b2_phi.resize(nPermutations); - m_klfitter_model_Higgs_b2_E.resize(nPermutations); - m_klfitter_model_Higgs_b2_jetIndex.resize(nPermutations); + recordTriggerDecision(event); - } + //some event weights + m_weight_mc = 0.; + if (m_config->isMC()) m_weight_mc = event.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); - m_klfitter_model_lep_pt.resize(nPermutations); - m_klfitter_model_lep_eta.resize(nPermutations); - m_klfitter_model_lep_phi.resize(nPermutations); - m_klfitter_model_lep_E.resize(nPermutations); - - m_klfitter_model_nu_pt.resize(nPermutations); - m_klfitter_model_nu_eta.resize(nPermutations); - m_klfitter_model_nu_phi.resize(nPermutations); - m_klfitter_model_nu_E.resize(nPermutations); - - if (validKLFitter) { - for (const auto* const klPtr : *event.m_KLFitterResults) { - m_klfitter_minuitDidNotConverge[iPerm] = klPtr->minuitDidNotConverge(); - m_klfitter_fitAbortedDueToNaN[iPerm] = klPtr->fitAbortedDueToNaN(); - m_klfitter_atLeastOneFitParameterAtItsLimit[iPerm] = klPtr->atLeastOneFitParameterAtItsLimit(); - m_klfitter_invalidTransferFunctionAtConvergence[iPerm] = klPtr->invalidTransferFunctionAtConvergence(); - - /// Global result - m_klfitter_bestPermutation[iPerm] = klPtr->bestPermutation(); - if (klPtr->bestPermutation() == 1){ - bestPerm = iPerm; - } - m_klfitter_logLikelihood[iPerm] = klPtr->logLikelihood(); - m_klfitter_eventProbability[iPerm] = klPtr->eventProbability(); - m_klfitter_parameters[iPerm] = klPtr->parameters(); - m_klfitter_parameterErrors[iPerm] = klPtr->parameterErrors(); - - /// Model - m_klfitter_model_bhad_pt[iPerm] = klPtr->model_bhad_pt(); - m_klfitter_model_bhad_eta[iPerm] = klPtr->model_bhad_eta(); - m_klfitter_model_bhad_phi[iPerm] = klPtr->model_bhad_phi(); - m_klfitter_model_bhad_E[iPerm] = klPtr->model_bhad_E(); - m_klfitter_model_bhad_jetIndex[iPerm] = klPtr->model_bhad_jetIndex(); - - m_klfitter_model_blep_pt[iPerm] = klPtr->model_blep_pt(); - m_klfitter_model_blep_eta[iPerm] = klPtr->model_blep_eta(); - m_klfitter_model_blep_phi[iPerm] = klPtr->model_blep_phi(); - m_klfitter_model_blep_E[iPerm] = klPtr->model_blep_E(); - m_klfitter_model_blep_jetIndex[iPerm] = klPtr->model_blep_jetIndex(); - - m_klfitter_model_lq1_pt[iPerm] = klPtr->model_lq1_pt(); - m_klfitter_model_lq1_eta[iPerm] = klPtr->model_lq1_eta(); - m_klfitter_model_lq1_phi[iPerm] = klPtr->model_lq1_phi(); - m_klfitter_model_lq1_E[iPerm] = klPtr->model_lq1_E(); - m_klfitter_model_lq1_jetIndex[iPerm] = klPtr->model_lq1_jetIndex(); - - m_klfitter_model_lq2_pt[iPerm] = klPtr->model_lq2_pt(); - m_klfitter_model_lq2_eta[iPerm] = klPtr->model_lq2_eta(); - m_klfitter_model_lq2_phi[iPerm] = klPtr->model_lq2_phi(); - m_klfitter_model_lq2_E[iPerm] = klPtr->model_lq2_E(); - m_klfitter_model_lq2_jetIndex[iPerm] = klPtr->model_lq2_jetIndex(); - - if(m_config -> KLFitterLH() == "ttH"){ - - m_klfitter_model_Higgs_b1_pt[iPerm] = klPtr->model_Higgs_b1_pt(); - m_klfitter_model_Higgs_b1_eta[iPerm] = klPtr->model_Higgs_b1_eta(); - m_klfitter_model_Higgs_b1_phi[iPerm] = klPtr->model_Higgs_b1_phi(); - m_klfitter_model_Higgs_b1_E[iPerm] = klPtr->model_Higgs_b1_E(); - m_klfitter_model_Higgs_b1_jetIndex[iPerm] = klPtr->model_Higgs_b1_jetIndex(); - - m_klfitter_model_Higgs_b2_pt[iPerm] = klPtr->model_Higgs_b2_pt(); - m_klfitter_model_Higgs_b2_eta[iPerm] = klPtr->model_Higgs_b2_eta(); - m_klfitter_model_Higgs_b2_phi[iPerm] = klPtr->model_Higgs_b2_phi(); - m_klfitter_model_Higgs_b2_E[iPerm] = klPtr->model_Higgs_b2_E(); - m_klfitter_model_Higgs_b2_jetIndex[iPerm] = klPtr->model_Higgs_b2_jetIndex(); - - } - - m_klfitter_model_lep_pt[iPerm] = klPtr->model_lep_pt(); - m_klfitter_model_lep_eta[iPerm] = klPtr->model_lep_eta(); - m_klfitter_model_lep_phi[iPerm] = klPtr->model_lep_phi(); - m_klfitter_model_lep_E[iPerm] = klPtr->model_lep_E(); - - m_klfitter_model_nu_pt[iPerm] = klPtr->model_nu_pt(); - m_klfitter_model_nu_eta[iPerm] = klPtr->model_nu_eta(); - m_klfitter_model_nu_phi[iPerm] = klPtr->model_nu_phi(); - m_klfitter_model_nu_E[iPerm] = klPtr->model_nu_E(); - - - ++iPerm; - } - - // now take the best permutation and build the tops and the ttbar system! - - TLorentzVector bhad,blep,lq1,lq2,lep,nu,top_had,top_lep,ttbar; - - bhad.SetPtEtaPhiE(m_klfitter_model_bhad_pt[bestPerm], m_klfitter_model_bhad_eta[bestPerm], m_klfitter_model_bhad_phi[bestPerm], m_klfitter_model_bhad_E[bestPerm]); - blep.SetPtEtaPhiE(m_klfitter_model_blep_pt[bestPerm], m_klfitter_model_blep_eta[bestPerm], m_klfitter_model_blep_phi[bestPerm], m_klfitter_model_blep_E[bestPerm]); - lq1.SetPtEtaPhiE(m_klfitter_model_lq1_pt[bestPerm], m_klfitter_model_lq1_eta[bestPerm], m_klfitter_model_lq1_phi[bestPerm], m_klfitter_model_lq1_E[bestPerm]); - lq2.SetPtEtaPhiE(m_klfitter_model_lq2_pt[bestPerm], m_klfitter_model_lq2_eta[bestPerm], m_klfitter_model_lq2_phi[bestPerm], m_klfitter_model_lq2_E[bestPerm]); - lep.SetPtEtaPhiE(m_klfitter_model_lep_pt[bestPerm], m_klfitter_model_lep_eta[bestPerm], m_klfitter_model_lep_phi[bestPerm], m_klfitter_model_lep_E[bestPerm]); - nu.SetPtEtaPhiE(m_klfitter_model_nu_pt[bestPerm], m_klfitter_model_nu_eta[bestPerm], m_klfitter_model_nu_phi[bestPerm], m_klfitter_model_nu_E[bestPerm]); - - top_had = bhad+lq1+lq2; - top_lep = blep+lep+nu; - ttbar = top_had+top_lep; - - m_klfitter_bestPerm_topLep_pt = top_lep.Pt(); - m_klfitter_bestPerm_topLep_eta = top_lep.Eta(); - m_klfitter_bestPerm_topLep_phi = top_lep.Phi(); - m_klfitter_bestPerm_topLep_E = top_lep.E(); - m_klfitter_bestPerm_topLep_m = top_lep.M(); - - m_klfitter_bestPerm_topHad_pt = top_had.Pt(); - m_klfitter_bestPerm_topHad_eta = top_had.Eta(); - m_klfitter_bestPerm_topHad_phi = top_had.Phi(); - m_klfitter_bestPerm_topHad_E = top_had.E(); - m_klfitter_bestPerm_topHad_m = top_had.M(); - - m_klfitter_bestPerm_ttbar_pt = ttbar.Pt(); - m_klfitter_bestPerm_ttbar_eta = ttbar.Eta(); - m_klfitter_bestPerm_ttbar_phi = ttbar.Phi(); - m_klfitter_bestPerm_ttbar_E = ttbar.E(); - m_klfitter_bestPerm_ttbar_m = ttbar.M(); + if (m_config->isMC()) { + m_weight_pileup = m_sfRetriever->pileupSF(event); - + m_weight_leptonSF = m_sfRetriever->leptonSF(event, top::topSFSyst::nominal); + if (m_config->useFwdElectrons()) m_weight_fwdElSF = m_sfRetriever->fwdElectronSF(event, top::topSFSyst::nominal); - } + if (m_config->useTaus()) m_weight_tauSF = m_sfRetriever->tauSF(event, top::topSFSyst::nominal); - } + if (m_config->usePhotons()) m_weight_photonSF = m_sfRetriever->photonSF(event, top::topSFSyst::nominal); - if(m_config->doPseudoTop()){ + if (m_config->useGlobalTriggerConfiguration()) m_weight_globalLeptonTriggerSF = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::nominal); + m_weight_oldTriggerSF = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::nominal); - const xAOD::PseudoTopResultContainer* pseudoTopResultContainer(nullptr); - const xAOD::PseudoTopResult* pseudoTopResult(nullptr); + for (auto& tagWP : m_config->bTagWP_available()) { + if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; + m_weight_bTagSF[tagWP] = m_sfRetriever->btagSF(event, top::topSFSyst::nominal, tagWP); + } + if (m_config->useTrackJets()) { + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), m_config->bTagWP_calibrated_trkJet().end(), tagWP) == m_config->bTagWP_calibrated_trkJet().end()) continue; + m_weight_trackjet_bTagSF[tagWP] = m_sfRetriever->btagSF(event, top::topSFSyst::nominal, tagWP, true); + } + } - if (evtStore()->contains<xAOD::PseudoTopResultContainer>(m_config->sgKeyPseudoTop(event.m_hashValue))) { - top::check(evtStore()->retrieve(pseudoTopResultContainer, m_config->sgKeyPseudoTop(event.m_hashValue)),"Failed to retrieve PseudoTop"); + m_weight_jvt = m_sfRetriever->jvtSF(event, top::topSFSyst::nominal); + if (m_config->getfJVTWP() != "None") m_weight_forwardjvt = m_sfRetriever->fjvtSF(event, top::topSFSyst::nominal); - pseudoTopResult = pseudoTopResultContainer->at(0); + if (m_config->isSherpa22Vjets()) { + if (event.m_info->isAvailable<double>("Sherpa22VJetsWeight")) { + m_weight_sherpa_22_vjets = event.m_info->auxdataConst<double>("Sherpa22VJetsWeight"); + } + } - m_PseudoTop_Reco_ttbar_pt = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_ttbar_pt"); - m_PseudoTop_Reco_ttbar_eta = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_ttbar_eta"); - m_PseudoTop_Reco_ttbar_phi = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_ttbar_phi"); - m_PseudoTop_Reco_ttbar_m = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_ttbar_m"); + // writing the systematic-shifted SFs only in the nominal (or nominal_Loose) tree + if (event.m_hashValue == m_config->nominalHashValue()) { + if (m_config->useFwdElectrons()) { + m_weight_fwdElSF_FWDEL_SF_ID_UP = m_sfRetriever->fwdElectronSF(event, top::topSFSyst::FWDEL_SF_ID_UP); + m_weight_fwdElSF_FWDEL_SF_ID_DOWN = m_sfRetriever->fwdElectronSF(event, top::topSFSyst::FWDEL_SF_ID_DOWN); + } - m_PseudoTop_Reco_top_lep_pt = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_lep_pt"); - m_PseudoTop_Reco_top_lep_eta = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_lep_eta"); - m_PseudoTop_Reco_top_lep_phi = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_lep_phi"); - m_PseudoTop_Reco_top_lep_m = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_lep_m"); + m_weight_pileup_UP = m_sfRetriever->pileupSF(event, +1); // up variation + m_weight_pileup_DOWN = m_sfRetriever->pileupSF(event, -1); // down variation + + m_weight_leptonSF_EL_SF_Trigger_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_Trigger_UP); + m_weight_leptonSF_EL_SF_Trigger_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_Trigger_DOWN); + m_weight_leptonSF_EL_SF_Reco_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_Reco_UP); + m_weight_leptonSF_EL_SF_Reco_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_Reco_DOWN); + m_weight_leptonSF_EL_SF_ID_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_ID_UP); + m_weight_leptonSF_EL_SF_ID_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_ID_DOWN); + m_weight_leptonSF_EL_SF_Isol_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_Isol_UP); + m_weight_leptonSF_EL_SF_Isol_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::EL_SF_Isol_DOWN); + + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + m_weight_leptonSF_EL_SF_CorrModel_Reco_UP = m_sfRetriever->electronSFSystVariationVector(event, top::topSFComp::RECO, 1); + m_weight_leptonSF_EL_SF_CorrModel_Reco_DOWN = m_sfRetriever->electronSFSystVariationVector(event, top::topSFComp::RECO, -1); + m_weight_leptonSF_EL_SF_CorrModel_ID_UP = m_sfRetriever->electronSFSystVariationVector(event, top::topSFComp::ID, 1); + m_weight_leptonSF_EL_SF_CorrModel_ID_DOWN = m_sfRetriever->electronSFSystVariationVector(event, top::topSFComp::ID, -1); + m_weight_leptonSF_EL_SF_CorrModel_Iso_UP = m_sfRetriever->electronSFSystVariationVector(event, top::topSFComp::ISOLATION, 1); + m_weight_leptonSF_EL_SF_CorrModel_Iso_DOWN = m_sfRetriever->electronSFSystVariationVector(event, top::topSFComp::ISOLATION, -1); + } + m_weight_leptonSF_MU_SF_Trigger_STAT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Trigger_STAT_UP); + m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Trigger_STAT_DOWN); + m_weight_leptonSF_MU_SF_Trigger_SYST_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Trigger_SYST_UP); + m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Trigger_SYST_DOWN); + // Muon ID SF systematics (regular) + m_weight_leptonSF_MU_SF_ID_STAT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_UP); + m_weight_leptonSF_MU_SF_ID_STAT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_DOWN); + m_weight_leptonSF_MU_SF_ID_SYST_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_UP); + m_weight_leptonSF_MU_SF_ID_SYST_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_DOWN); + // Muon ID SF systematics (regular) + m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP); + m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN); + m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP); + m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN); + // Muon isolation SF systematics + m_weight_leptonSF_MU_SF_Isol_STAT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Isol_STAT_UP); + m_weight_leptonSF_MU_SF_Isol_STAT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Isol_STAT_DOWN); + m_weight_leptonSF_MU_SF_Isol_SYST_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Isol_SYST_UP); + m_weight_leptonSF_MU_SF_Isol_SYST_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_Isol_SYST_DOWN); + m_weight_leptonSF_MU_SF_TTVA_STAT_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_TTVA_STAT_UP); + m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_TTVA_STAT_DOWN); + m_weight_leptonSF_MU_SF_TTVA_SYST_UP = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_TTVA_SYST_UP); + m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN = m_sfRetriever->leptonSF(event, top::topSFSyst::MU_SF_TTVA_SYST_DOWN); + // Special global lepton trigger SF systematics if requested + if (m_config->useGlobalTriggerConfiguration()) { + m_weight_globalLeptonTriggerSF_EL_Trigger_UP = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::EL_SF_Trigger_UP); + m_weight_globalLeptonTriggerSF_EL_Trigger_DOWN = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::EL_SF_Trigger_DOWN); + m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::MU_SF_Trigger_STAT_UP); + m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::MU_SF_Trigger_STAT_DOWN); + m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::MU_SF_Trigger_SYST_UP); + m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN = m_sfRetriever->globalTriggerSF(event, top::topSFSyst::MU_SF_Trigger_SYST_DOWN); + } + m_weight_oldTriggerSF_EL_Trigger_UP = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::EL_SF_Trigger_UP); + m_weight_oldTriggerSF_EL_Trigger_DOWN = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::EL_SF_Trigger_DOWN); + m_weight_oldTriggerSF_MU_Trigger_STAT_UP = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::MU_SF_Trigger_STAT_UP); + m_weight_oldTriggerSF_MU_Trigger_STAT_DOWN = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::MU_SF_Trigger_STAT_DOWN); + m_weight_oldTriggerSF_MU_Trigger_SYST_UP = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::MU_SF_Trigger_SYST_UP); + m_weight_oldTriggerSF_MU_Trigger_SYST_DOWN = m_sfRetriever->oldTriggerSF(event, top::topSFSyst::MU_SF_Trigger_SYST_DOWN); + + m_weight_indiv_SF_EL_Reco = m_sfRetriever->electronSF(event, top::topSFSyst::nominal, top::topSFComp::RECO); + m_weight_indiv_SF_EL_Reco_UP = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_Reco_UP, top::topSFComp::RECO); + m_weight_indiv_SF_EL_Reco_DOWN = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_Reco_DOWN, top::topSFComp::RECO); + m_weight_indiv_SF_EL_ID = m_sfRetriever->electronSF(event, top::topSFSyst::nominal, top::topSFComp::ID); + m_weight_indiv_SF_EL_ID_UP = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ID_UP, top::topSFComp::ID); + m_weight_indiv_SF_EL_ID_DOWN = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ID_DOWN, top::topSFComp::ID); + m_weight_indiv_SF_EL_Isol = m_sfRetriever->electronSF(event, top::topSFSyst::nominal, top::topSFComp::ISOLATION); + m_weight_indiv_SF_EL_Isol_UP = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_Isol_UP, top::topSFComp::ISOLATION); + m_weight_indiv_SF_EL_Isol_DOWN = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_Isol_DOWN, top::topSFComp::ISOLATION); + m_weight_indiv_SF_EL_ChargeID = m_sfRetriever->electronSF(event, top::topSFSyst::nominal, top::topSFComp::CHARGEID); + m_weight_indiv_SF_EL_ChargeID_UP = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ChargeID_UP, top::topSFComp::CHARGEID); + m_weight_indiv_SF_EL_ChargeID_DOWN = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ChargeID_DOWN, top::topSFComp::CHARGEID); + m_weight_indiv_SF_EL_ChargeMisID = m_sfRetriever->electronSF(event, top::topSFSyst::nominal, top::topSFComp::CHARGEMISID); + m_weight_indiv_SF_EL_ChargeMisID_STAT_UP = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ChargeMisID_STAT_UP, top::topSFComp::CHARGEMISID); + m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ChargeMisID_STAT_DOWN, top::topSFComp::CHARGEMISID); + m_weight_indiv_SF_EL_ChargeMisID_SYST_UP = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ChargeMisID_SYST_UP, top::topSFComp::CHARGEMISID); + m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN = m_sfRetriever->electronSF(event, top::topSFSyst::EL_SF_ChargeMisID_SYST_DOWN, top::topSFComp::CHARGEMISID); + ATH_MSG_DEBUG("Electron Reco SF = " << m_weight_indiv_SF_EL_Reco << " + " << m_weight_indiv_SF_EL_Reco_UP << " - " << m_weight_indiv_SF_EL_Reco_DOWN); + ATH_MSG_DEBUG("Electron ID SF = " << m_weight_indiv_SF_EL_ID << " + " << m_weight_indiv_SF_EL_ID_UP << " - " << m_weight_indiv_SF_EL_ID_DOWN); + ATH_MSG_DEBUG("Electron Charge ID SF = " << m_weight_indiv_SF_EL_ChargeID << " + " << m_weight_indiv_SF_EL_ChargeID_UP << " - " << m_weight_indiv_SF_EL_ChargeID_DOWN); + ATH_MSG_DEBUG("Electron Charge Mis ID SF = " << m_weight_indiv_SF_EL_ChargeMisID << " + " << m_weight_indiv_SF_EL_ChargeMisID_STAT_UP << " - " << m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN << " + " << m_weight_indiv_SF_EL_ChargeMisID_SYST_UP << " - " << m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN); + + m_weight_indiv_SF_MU_ID = m_sfRetriever->muonSF(event, top::topSFSyst::nominal, top::topSFComp::ID); + // Muon ID SF systematics (regular) + m_weight_indiv_SF_MU_ID_STAT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_UP, top::topSFComp::ID); + m_weight_indiv_SF_MU_ID_STAT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_DOWN, top::topSFComp::ID); + m_weight_indiv_SF_MU_ID_SYST_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_UP, top::topSFComp::ID); + m_weight_indiv_SF_MU_ID_SYST_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_DOWN, top::topSFComp::ID); + // Muon ID SF systematics (low pt) + m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP, top::topSFComp::ID); + m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN, top::topSFComp::ID); + m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP, top::topSFComp::ID); + m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN, top::topSFComp::ID); + // Muon isolation SF systematics + m_weight_indiv_SF_MU_Isol = m_sfRetriever->muonSF(event, top::topSFSyst::nominal, top::topSFComp::ISOLATION); + m_weight_indiv_SF_MU_Isol_STAT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_Isol_STAT_UP, top::topSFComp::ISOLATION); + m_weight_indiv_SF_MU_Isol_STAT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_Isol_STAT_DOWN, top::topSFComp::ISOLATION); + m_weight_indiv_SF_MU_Isol_SYST_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_Isol_SYST_UP, top::topSFComp::ISOLATION); + m_weight_indiv_SF_MU_Isol_SYST_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_Isol_SYST_DOWN, top::topSFComp::ISOLATION); + m_weight_indiv_SF_MU_TTVA = m_sfRetriever->muonSF(event, top::topSFSyst::nominal, top::topSFComp::TTVA); + m_weight_indiv_SF_MU_TTVA_STAT_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_TTVA_STAT_UP, top::topSFComp::TTVA); + m_weight_indiv_SF_MU_TTVA_STAT_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_TTVA_STAT_DOWN, top::topSFComp::TTVA); + m_weight_indiv_SF_MU_TTVA_SYST_UP = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_TTVA_SYST_UP, top::topSFComp::TTVA); + m_weight_indiv_SF_MU_TTVA_SYST_DOWN = m_sfRetriever->muonSF(event, top::topSFSyst::MU_SF_TTVA_SYST_DOWN, top::topSFComp::TTVA); - m_PseudoTop_Reco_top_had_pt = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_had_pt"); - m_PseudoTop_Reco_top_had_eta = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_had_eta"); - m_PseudoTop_Reco_top_had_phi = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_had_phi"); - m_PseudoTop_Reco_top_had_m = pseudoTopResult -> auxdecor<float>("PseudoTop_Reco_top_had_m"); + ATH_MSG_DEBUG("Muon ID SF = " << m_weight_indiv_SF_MU_ID << " + " << m_weight_indiv_SF_MU_ID_STAT_UP << " - " << m_weight_indiv_SF_MU_ID_STAT_DOWN << " + " << m_weight_indiv_SF_MU_ID_SYST_UP << " - " << m_weight_indiv_SF_MU_ID_SYST_DOWN); - } + if (m_config->useTaus()) { + // Tau-electron overlap removal + for (auto& tauSFvariation: m_weight_tauSF_variations) { + tauSFvariation.second = m_sfRetriever->tauSF(event, tauSFvariation.first); + } + } + + if (m_config->usePhotons()) { + m_weight_photonSF_ID_UP = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_IDSF_UP); + m_weight_photonSF_ID_DOWN = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_IDSF_DOWN); + m_weight_photonSF_effIso_UP = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_ISO_UP); + m_weight_photonSF_effIso_DOWN = m_sfRetriever->photonSF(event, top::topSFSyst::PHOTON_EFF_ISO_DOWN); + } + + + m_weight_jvt_up = m_sfRetriever->jvtSF(event, top::topSFSyst::JVT_UP); + m_weight_jvt_down = m_sfRetriever->jvtSF(event, top::topSFSyst::JVT_DOWN); + if (m_config->getfJVTWP() != "None"){ + m_weight_forwardjvt_up = m_sfRetriever->fjvtSF(event, top::topSFSyst::FJVT_UP); + m_weight_forwardjvt_down = m_sfRetriever->fjvtSF(event, top::topSFSyst::FJVT_DOWN); } + } + + // for b-tagging SFs, can also have systematic-shifted in systematics trees + if (event.m_hashValue == m_config->nominalHashValue() || m_config->dumpBtagSystsInSystTrees()) { + for (auto& tagWP : m_config->bTagWP_available()) { + // skip uncalibrated though available WPs + if (std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; + m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_B, + m_weight_bTagSF_eigen_B_up[tagWP], + m_weight_bTagSF_eigen_B_down[tagWP], tagWP); + m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_C, + m_weight_bTagSF_eigen_C_up[tagWP], + m_weight_bTagSF_eigen_C_down[tagWP], tagWP); + m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_LIGHT, + m_weight_bTagSF_eigen_Light_up[tagWP], + m_weight_bTagSF_eigen_Light_down[tagWP], tagWP); + for (auto name : m_config->btagging_namedSysts(tagWP)) { + m_weight_bTagSF_named_up[tagWP][name] = m_sfRetriever->btagSF(event, top::topSFSyst::BTAG_SF_NAMED_UP, tagWP, false, name); + m_weight_bTagSF_named_down[tagWP][name] = m_sfRetriever->btagSF(event, top::topSFSyst::BTAG_SF_NAMED_DOWN, tagWP, false, name); + } + } + if (m_config->useTrackJets()) { + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + // skip uncalibrated though available WPs + if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), m_config->bTagWP_calibrated_trkJet().end(), tagWP) == m_config->bTagWP_calibrated_trkJet().end()) continue; + m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_B, + m_weight_trackjet_bTagSF_eigen_B_up[tagWP], + m_weight_trackjet_bTagSF_eigen_B_down[tagWP], tagWP, true); + m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_C, + m_weight_trackjet_bTagSF_eigen_C_up[tagWP], + m_weight_trackjet_bTagSF_eigen_C_down[tagWP], tagWP, true); + m_sfRetriever->btagSF_eigen_vars(event, top::topSFSyst::BTAG_SF_EIGEN_LIGHT, + m_weight_trackjet_bTagSF_eigen_Light_up[tagWP], + m_weight_trackjet_bTagSF_eigen_Light_down[tagWP], tagWP, true); + for (auto name : m_config->trkjet_btagging_namedSysts(tagWP)) { + m_weight_trackjet_bTagSF_named_up[tagWP][name] = m_sfRetriever->btagSF(event, top::topSFSyst::BTAG_SF_NAMED_UP, tagWP, true, name); + m_weight_trackjet_bTagSF_named_down[tagWP][name] = m_sfRetriever->btagSF(event, top::topSFSyst::BTAG_SF_NAMED_DOWN, tagWP, true, name); + } + } + } + } + } - //do it! - m_treeManagers[event.m_ttreeIndex]->fill(); + /// Bootstrapping poisson weights - Moved to run for MC and data + if (m_config->saveBootstrapWeights()) { + m_weight_poisson = event.m_info->auxdataConst<std::vector<int> >("weight_poisson"); } + ///-- weights for matrix-method fakes estimate by IFF --/// + if (event.m_hashValue == m_config->nominalHashValue() && !m_config->isMC() && m_config->doFakesMMWeightsIFF()) { + //std::vector<CP::AsymptMatrixTool*> fakesMMWeightCalcIFF; + //for (int mmi = 0; mmi < m_ASMsize; ++mmi) { + // fakesMMWeightCalcIFF.push_back(asg::ToolStore::get<CP::AsymptMatrixTool>("AsymptMatrixTool_" + std::to_string (mmi))); + //} + //std::string ASMweights_branch_name = "ASMWeight"; + //std::string decorName = "ASMWeight"; + //if (event.m_info->isAvailable<std::vector<float> >(decorName.c_str())) { + // m_ASMweights = event.m_info->auxdataConst<std::vector<float> >(decorName.c_str()); + // if (event.m_info->isAvailable<std::vector<std::vector<float> > >((decorName + "_Syst").c_str())) { + // m_ASMweights_Syst = event.m_info->auxdataConst<std::vector<std::vector<float> > >((decorName + "_Syst").c_str()); + // m_ASMweights_Systname = event.m_info->auxdataConst<std::vector<std::vector<std::string> > >((decorName + "_Systname").c_str()); + // } + //} + } - void EventSaverFlatNtuple::saveTruthEvent() - { + //event info + m_eventNumber = event.m_info->eventNumber(); + m_runNumber = event.m_info->runNumber(); + m_randomRunNumber = 0; + if (m_config->isMC() && m_config->doPileupReweighting()) { + if (event.m_info->isAvailable<unsigned int>("RandomRunNumber")) m_randomRunNumber = event.m_info->auxdataConst<unsigned int>("RandomRunNumber"); + } + m_mcChannelNumber = 0; - const xAOD::EventInfo* eventInfo(nullptr); - top::check( evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()) , "Failed to retrieve EventInfo" ); - - const xAOD::TruthEventContainer * truthEvent(nullptr); - top::check( evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth event container" ); - unsigned int truthEventSize = truthEvent->size(); - top::check( truthEventSize==1 , "Failed to retrieve truth PDF info - truth event container size is different from 1 (strange)" ); - -// m_weight_mc = eventInfo -> mcEventWeight(); - m_weight_mc = truthEvent->at(0)->weights()[0];// FIXME temporary bugfix - m_eventNumber = eventInfo -> eventNumber(); - m_runNumber = eventInfo -> runNumber(); - m_mcChannelNumber = eventInfo -> mcChannelNumber(); - m_mu = eventInfo->averageInteractionsPerCrossing(); - if (m_config->doPileupReweighting() && !m_config->isTruthDxAOD()) { - m_weight_pileup = eventInfo->auxdataConst<float>("PileupWeight"); - m_randomRunNumber = eventInfo->auxdataConst<unsigned int>("RandomRunNumber"); - } - else { - m_weight_pileup = NAN; - m_randomRunNumber = 0; - } - - //MC particle - if (m_config->useTruthParticles() && m_config->doTruthBlockInfo()) { - - const xAOD::TruthParticleContainer* truth(nullptr); - top::check( evtStore()->retrieve(truth,m_config->sgKeyMCParticle()) , "Failed to retrieve TruthParticleContainer" ); - - if (truth != nullptr) { - unsigned int i(0); - unsigned int truthSize = truth->size(); - m_mc_pt.resize(truthSize); - m_mc_eta.resize(truthSize); - m_mc_phi.resize(truthSize); - m_mc_e.resize(truthSize); - m_mc_pdgId.resize(truthSize); - for (const auto* const mcPtr : *truth) { - - // Fix for - // Warning in <TVector3::PseudoRapidity>: transvers momentum = 0! return +/- 10e10 - - float eta(-999.9); - - if ( !( mcPtr->p4().CosTheta()*mcPtr->p4().CosTheta() >= 1 && mcPtr->p4().Pz() != 0 ) ) { - eta = mcPtr->eta(); - } - - m_mc_pt[i] = mcPtr->pt(); - m_mc_eta[i] = eta; - m_mc_phi[i] = mcPtr->phi(); - m_mc_e[i] = mcPtr->e(); - m_mc_pdgId[i] = mcPtr->pdgId(); - ++i; - } - } + if (m_config->isMC()) m_mcChannelNumber = event.m_info->mcChannelNumber(); + + // (non-collision-)background flags + m_backgroundFlags = 0; + if (event.m_info->isAvailable<unsigned int>("backgroundFlags")) m_backgroundFlags = event.m_info->auxdataConst<unsigned int>("backgroundFlags"); + + // hasBadMuon flag + m_hasBadMuon = 0; + if (m_config->useMuons() && event.m_info->isAvailable<char>("AnalysisTop_HASBADMUON")) m_hasBadMuon = event.m_info->auxdataConst<char>("AnalysisTop_HASBADMUON"); + + // mu values (original and corrected by pileup reweighting tool) + m_mu_original = event.m_info->averageInteractionsPerCrossing(); + m_mu_actual_original = event.m_info->actualInteractionsPerCrossing(); + + // set these all to zero (maybe not the most sensible value...) + m_mu = 0; + m_mu_actual = 0; + + if (m_config->isMC()) { + m_mu = m_mu_original; + m_mu_actual = m_mu_actual_original; + } + if (!m_config->isMC()) { + // If we have the corrected mu value from pileup reweighting then save that + // instead of mu value in (d)xAOD. + if (event.m_info->isAvailable<float>("corrected_averageInteractionsPerCrossing")) m_mu = event.m_info->auxdataConst<float>("corrected_averageInteractionsPerCrossing"); + if (event.m_info->isAvailable<float>("corrected_actualInteractionsPerCrossing")) m_mu_actual = event.m_info->auxdataConst<float>("corrected_actualInteractionsPerCrossing"); + } + + ATH_MSG_DEBUG(" mu = " << m_mu_original << " -> " << m_mu); + + //forward electrons + if (m_config->useFwdElectrons()) { + unsigned int i(0); + unsigned int n_electrons = event.m_fwdElectrons.size(); + m_fwdel_pt.resize(n_electrons); + m_fwdel_eta.resize(n_electrons); + m_fwdel_phi.resize(n_electrons); + m_fwdel_e.resize(n_electrons); + m_fwdel_etcone20.resize(n_electrons); + m_fwdel_etcone30.resize(n_electrons); + m_fwdel_etcone40.resize(n_electrons); + m_fwdel_isTight.resize(n_electrons); + + for (const auto* const elPtr : event.m_fwdElectrons) { + m_fwdel_pt[i] = elPtr->pt(); + m_fwdel_eta[i] = elPtr->eta(); + m_fwdel_phi[i] = elPtr->phi(); + m_fwdel_e[i] = elPtr->e(); + + float etcone20 = 0.0; + elPtr->isolationValue(etcone20, xAOD::Iso::topoetcone20); + float etcone30 = 0.0; + elPtr->isolationValue(etcone30, xAOD::Iso::topoetcone30); + float etcone40 = 0.0; + elPtr->isolationValue(etcone40, xAOD::Iso::topoetcone40); + + m_fwdel_etcone20[i] = etcone20; + m_fwdel_etcone30[i] = etcone30; + m_fwdel_etcone40[i] = etcone40; + + if (event.m_isLoose) { + if (elPtr->isAvailable<char>("passPreORSelection")) { + m_fwdel_isTight[i] = elPtr->auxdataConst<char>("passPreORSelection"); + } + } + + ++i; + }//end of loop on fwd electrons + }//end of fwd electrons filling + + //electrons + if (m_config->useElectrons()) { + unsigned int i(0); + unsigned int n_electrons = event.m_electrons.size(); + m_el_pt.resize(n_electrons); + m_el_eta.resize(n_electrons); + m_el_cl_eta.resize(n_electrons); + m_el_phi.resize(n_electrons); + m_el_e.resize(n_electrons); + m_el_charge.resize(n_electrons); + m_el_topoetcone20.resize(n_electrons); + m_el_ptvarcone20.resize(n_electrons); + m_el_isTight.resize(n_electrons); + m_el_CF.resize(n_electrons); + for (const auto& trigger : m_el_trigMatched) + m_el_trigMatched[trigger.first].resize(n_electrons); + m_el_d0sig.resize(n_electrons); + m_el_delta_z0_sintheta.resize(n_electrons); + if (m_useElectronChargeIDSelection) { + m_el_ECIDS.resize(n_electrons); + m_el_ECIDSResult.resize(n_electrons); + } + if (m_config->isMC()) { + m_el_true_type.resize(n_electrons); + m_el_true_origin.resize(n_electrons); + m_el_true_firstEgMotherTruthOrigin.resize(n_electrons); + m_el_true_firstEgMotherTruthType.resize(n_electrons); + m_el_true_firstEgMotherPdgId.resize(n_electrons); + m_el_true_isPrompt.resize(n_electrons); + m_el_true_isChargeFl.resize(n_electrons); + } + if (m_config->enablePromptLeptonImprovedVetoStudies()) { + m_PLIV_el_PromptLeptonRNN_conversion.resize(n_electrons); + m_PLIV_el_PromptLeptonRNN_non_prompt_b.resize(n_electrons); + m_PLIV_el_PromptLeptonRNN_non_prompt_c.resize(n_electrons); + m_PLIV_el_PromptLeptonRNN_prompt.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_MVAXBin.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_topoetcone30rel.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_PtFrac.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_DRlj.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_PtRel.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedVetoBARR.resize(n_electrons); + m_PLIV_el_PromptLeptonImprovedVetoECAP.resize(n_electrons); + } + + static const SG::AuxElement::Accessor<char> accECIDS("DFCommonElectronsECIDS"); + static const SG::AuxElement::Accessor<double> accECIDSResult("DFCommonElectronsECIDSResult"); + + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonRNN_conversion("PromptLeptonRNN_conversion"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonRNN_non_prompt_b("PromptLeptonRNN_non_prompt_b"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonRNN_non_prompt_c("PromptLeptonRNN_non_prompt_c"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonRNN_prompt("PromptLeptonRNN_prompt"); + static const SG::AuxElement::Accessor<short> PLIV_el_PromptLeptonImprovedInput_MVAXBin("PromptLeptonImprovedInput_MVAXBin"); + static const SG::AuxElement::Accessor<short> PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack("PromptLeptonImprovedInput_TrackJetNTrack"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_topoetcone30rel("PromptLeptonImprovedInput_topoetcone30rel"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel("PromptLeptonImprovedInput_ptvarcone30rel"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_PtFrac("PromptLeptonImprovedInput_PtFrac"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_DRlj("PromptLeptonImprovedInput_DRlj"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel("PromptLeptonImprovedInput_CaloClusterSumEtRel"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_PtRel("PromptLeptonImprovedInput_PtRel"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx("PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedVetoBARR("PromptLeptonImprovedVetoBARR"); + static const SG::AuxElement::Accessor<float> PLIV_el_PromptLeptonImprovedVetoECAP("PromptLeptonImprovedVetoECAP"); + + for (const auto* const elPtr : event.m_electrons) { + m_el_pt[i] = elPtr->pt(); + m_el_eta[i] = elPtr->eta(); + m_el_cl_eta[i] = elPtr->caloCluster()->etaBE(2); + m_el_phi[i] = elPtr->phi(); + m_el_e[i] = elPtr->e(); + m_el_charge[i] = elPtr->charge(); + elPtr->isolationValue(m_el_topoetcone20[i], xAOD::Iso::topoetcone20); + elPtr->isolationValue(m_el_ptvarcone20[i], xAOD::Iso::ptvarcone20); + if (event.m_isLoose) { + if (elPtr->isAvailable<char>("passPreORSelection")) { + m_el_isTight[i] = elPtr->auxdataConst<char>("passPreORSelection"); + } + } + if (elPtr->isAvailable<char>("passChargeID")) m_el_CF[i] = elPtr->auxdataConst<char>("passChargeID"); + for (const auto& trigger : m_el_trigMatched) { + std::string trig = "TRIGMATCH_" + trigger.first; + m_el_trigMatched[trigger.first][i] = elPtr->auxdataConst<char>(trig); + } + if (elPtr->isAvailable<float>("d0sig")) m_el_d0sig[i] = elPtr->auxdataConst<float>("d0sig"); + if (elPtr->isAvailable<float>("delta_z0_sintheta")) m_el_delta_z0_sintheta[i] = elPtr->auxdataConst<float>("delta_z0_sintheta"); + + if (m_useElectronChargeIDSelection) { + m_el_ECIDS[i] = accECIDS.isAvailable(*elPtr) ? accECIDS(*elPtr) : 'n'; + m_el_ECIDSResult[i] = accECIDSResult.isAvailable(*elPtr) ? accECIDSResult(*elPtr) : -999.; + } + + if (m_config->enablePromptLeptonImprovedVetoStudies()) { + m_PLIV_el_PromptLeptonRNN_conversion[i] = PLIV_el_PromptLeptonRNN_conversion.isAvailable(*elPtr) ? PLIV_el_PromptLeptonRNN_conversion(*elPtr) : -999.; + m_PLIV_el_PromptLeptonRNN_non_prompt_b[i] = PLIV_el_PromptLeptonRNN_non_prompt_b.isAvailable(*elPtr) ? PLIV_el_PromptLeptonRNN_non_prompt_b(*elPtr) : -999.; + m_PLIV_el_PromptLeptonRNN_non_prompt_c[i] = PLIV_el_PromptLeptonRNN_non_prompt_c.isAvailable(*elPtr) ? PLIV_el_PromptLeptonRNN_non_prompt_c(*elPtr) : -999.; + m_PLIV_el_PromptLeptonRNN_prompt[i] = PLIV_el_PromptLeptonRNN_prompt.isAvailable(*elPtr) ? PLIV_el_PromptLeptonRNN_prompt(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_MVAXBin[i] = PLIV_el_PromptLeptonImprovedInput_MVAXBin.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_MVAXBin(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack[i] = PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_topoetcone30rel[i] = PLIV_el_PromptLeptonImprovedInput_topoetcone30rel.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_topoetcone30rel(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel[i] = PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_PtFrac[i] = PLIV_el_PromptLeptonImprovedInput_PtFrac.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_PtFrac(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_DRlj[i] = PLIV_el_PromptLeptonImprovedInput_DRlj.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_DRlj(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel[i] = PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_PtRel[i] = PLIV_el_PromptLeptonImprovedInput_PtRel.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_PtRel(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx[i] = PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedVetoBARR[i] = PLIV_el_PromptLeptonImprovedVetoBARR.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedVetoBARR(*elPtr) : -999.; + m_PLIV_el_PromptLeptonImprovedVetoECAP[i] = PLIV_el_PromptLeptonImprovedVetoECAP.isAvailable(*elPtr) ? PLIV_el_PromptLeptonImprovedVetoECAP(*elPtr) : -999.; + } + + //retrieve the truth-matching variables from MCTruthClassifier + if (m_config->isMC()) { + m_el_true_type[i] = 0; + m_el_true_origin[i] = 0; + m_el_true_firstEgMotherTruthType[i] = 0; + m_el_true_firstEgMotherTruthOrigin[i] = 0; + m_el_true_firstEgMotherPdgId[i] = 0; + static const SG::AuxElement::Accessor<int> typeel("truthType"); + static const SG::AuxElement::Accessor<int> origel("truthOrigin"); + static const SG::AuxElement::Accessor<int> firstEgMotherTruthType("firstEgMotherTruthType"); + static const SG::AuxElement::Accessor<int> firstEgMotherTruthOrigin("firstEgMotherTruthOrigin"); + static const SG::AuxElement::Accessor<int> firstEgMotherPdgId("firstEgMotherPdgId"); + + if (typeel.isAvailable(*elPtr)) m_el_true_type[i] = typeel(*elPtr); + if (origel.isAvailable(*elPtr)) m_el_true_origin[i] = origel(*elPtr); + if (firstEgMotherTruthType.isAvailable(*elPtr)) m_el_true_firstEgMotherTruthType[i] = firstEgMotherTruthType(*elPtr); + if (firstEgMotherTruthOrigin.isAvailable(*elPtr)) m_el_true_firstEgMotherTruthOrigin[i] = firstEgMotherTruthOrigin(*elPtr); + if (firstEgMotherPdgId.isAvailable(*elPtr)) m_el_true_firstEgMotherPdgId[i] = firstEgMotherPdgId(*elPtr); + + std::pair<bool, bool> isPrompt_isChargeFl = isPromptElectron(m_el_true_type[i], m_el_true_origin[i], m_el_true_firstEgMotherTruthType[i], m_el_true_firstEgMotherTruthOrigin[i], m_el_true_firstEgMotherPdgId[i], m_el_charge[i]); + m_el_true_isPrompt[i] = isPrompt_isChargeFl.first; + m_el_true_isChargeFl[i] = isPrompt_isChargeFl.second; + } + ++i; + } + } + + //muons + if (m_config->useMuons()) { + unsigned int i(0); + unsigned int n_muons = event.m_muons.size(); + m_mu_pt.resize(n_muons); + m_mu_eta.resize(n_muons); + m_mu_phi.resize(n_muons); + m_mu_e.resize(n_muons); + m_mu_charge.resize(n_muons); + m_mu_topoetcone20.resize(n_muons); + m_mu_ptvarcone30.resize(n_muons); + m_mu_isTight.resize(n_muons); + for (const auto& trigger : m_mu_trigMatched) + m_mu_trigMatched[trigger.first].resize(n_muons); + m_mu_d0sig.resize(n_muons); + m_mu_delta_z0_sintheta.resize(n_muons); + if (m_config->isMC()) { + m_mu_true_type.resize(n_muons); + m_mu_true_origin.resize(n_muons); + m_mu_true_isPrompt.resize(n_muons); + } + if (m_config->enablePromptLeptonImprovedVetoStudies()) { + m_PLIV_mu_PromptLeptonRNN_non_prompt_b.resize(n_muons); + m_PLIV_mu_PromptLeptonRNN_non_prompt_c.resize(n_muons); + m_PLIV_mu_PromptLeptonRNN_prompt.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_MVAXBin.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_PtFrac.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_DRlj.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest.resize(n_muons); + m_PLIV_mu_PromptLeptonImprovedVeto.resize(n_muons); + } + + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonRNN_non_prompt_b("PromptLeptonRNN_non_prompt_b"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonRNN_non_prompt_c("PromptLeptonRNN_non_prompt_c"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonRNN_prompt("PromptLeptonRNN_prompt"); + static const SG::AuxElement::Accessor<short> PLIV_mu_PromptLeptonImprovedInput_MVAXBin("PromptLeptonImprovedInput_MVAXBin"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel("PromptLeptonImprovedInput_topoetcone30rel"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedInput_PtFrac("PromptLeptonImprovedInput_PtFrac"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedInput_DRlj("PromptLeptonImprovedInput_DRlj"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel("PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel("PromptLeptonImprovedInput_CaloClusterERel"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest("PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest"); + static const SG::AuxElement::Accessor<float> PLIV_mu_PromptLeptonImprovedVeto("PromptLeptonImprovedVeto"); + + for (const auto* const muPtr : event.m_muons) { + m_mu_pt[i] = muPtr->pt(); + m_mu_eta[i] = muPtr->eta(); + m_mu_phi[i] = muPtr->phi(); + m_mu_e[i] = muPtr->e(); + m_mu_charge[i] = muPtr->charge(); + muPtr->isolation(m_mu_topoetcone20[i], xAOD::Iso::topoetcone20); + muPtr->isolation(m_mu_ptvarcone30[i], xAOD::Iso::ptvarcone30); + if (event.m_isLoose) { + if (muPtr->isAvailable<char>("passPreORSelection")) { + m_mu_isTight[i] = muPtr->auxdataConst<char>("passPreORSelection"); + } + } + for (const auto& trigger : m_mu_trigMatched) { + std::string trig = "TRIGMATCH_" + trigger.first; + m_mu_trigMatched[trigger.first][i] = muPtr->auxdataConst<char>(trig); } + if (muPtr->isAvailable<float>("d0sig")) m_mu_d0sig[i] = muPtr->auxdataConst<float>("d0sig"); + if (muPtr->isAvailable<float>("delta_z0_sintheta")) m_mu_delta_z0_sintheta[i] = muPtr->auxdataConst<float>("delta_z0_sintheta"); + + if (m_config->enablePromptLeptonImprovedVetoStudies()) { + m_PLIV_mu_PromptLeptonRNN_non_prompt_b[i] = PLIV_mu_PromptLeptonRNN_non_prompt_b.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonRNN_non_prompt_b(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonRNN_non_prompt_c[i] = PLIV_mu_PromptLeptonRNN_non_prompt_c.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonRNN_non_prompt_c(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonRNN_prompt[i] = PLIV_mu_PromptLeptonRNN_prompt.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonRNN_prompt(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_MVAXBin[i] = PLIV_mu_PromptLeptonImprovedInput_MVAXBin.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_MVAXBin(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel[i] = PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_PtFrac[i] = PLIV_mu_PromptLeptonImprovedInput_PtFrac.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_PtFrac(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_DRlj[i] = PLIV_mu_PromptLeptonImprovedInput_DRlj.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_DRlj(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel[i] = PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel[i] = PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest[i] = PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest(*muPtr) : -999.; + m_PLIV_mu_PromptLeptonImprovedVeto[i] = PLIV_mu_PromptLeptonImprovedVeto.isAvailable(*muPtr) ? PLIV_mu_PromptLeptonImprovedVeto(*muPtr) : -999.; + } - if (m_config->doTruthPDFInfo()) { - // delegate to helper function. - loadPdfInfo(); + //retrieve the truth-matching variables from MCTruthClassifier + if (m_config->isMC()) { + static const SG::AuxElement::Accessor<int> acc_mctt("truthType"); + static const SG::AuxElement::Accessor<int> acc_mcto("truthOrigin"); + m_mu_true_type[i] = 0; + m_mu_true_origin[i] = 0; + if (acc_mctt.isAvailable(*muPtr)) m_mu_true_type[i] = acc_mctt(*muPtr); + if (acc_mcto.isAvailable(*muPtr)) m_mu_true_origin[i] = acc_mcto(*muPtr); + m_mu_true_isPrompt[i] = isPromptMuon(m_mu_true_type[i], m_mu_true_origin[i]); } + ++i; + } + } - if (m_config->doMCGeneratorWeights()) { - // delegate to helper function. - loadMCGeneratorWeights(); + //soft muons + if (m_config->useSoftMuons()) { + unsigned int i(0); + unsigned int n_muons = event.m_softmuons.size(); + + m_softmu_pt.resize(n_muons); + m_softmu_eta.resize(n_muons); + m_softmu_phi.resize(n_muons); + m_softmu_e.resize(n_muons); + m_softmu_charge.resize(n_muons); + m_softmu_d0.resize(n_muons); + m_softmu_d0sig.resize(n_muons); + m_softmu_delta_z0_sintheta.resize(n_muons); + + if (m_config->isMC()) { + m_softmu_true_type.resize(n_muons); + m_softmu_true_origin.resize(n_muons); + m_softmu_true_isPrompt.resize(n_muons); + m_softmu_SF_ID.resize(n_muons); + m_softmu_SF_ID_STAT_UP.resize(n_muons); + m_softmu_SF_ID_STAT_DOWN.resize(n_muons); + m_softmu_SF_ID_SYST_UP.resize(n_muons); + m_softmu_SF_ID_SYST_DOWN.resize(n_muons); + m_softmu_SF_ID_STAT_LOWPT_UP.resize(n_muons); + m_softmu_SF_ID_STAT_LOWPT_DOWN.resize(n_muons); + m_softmu_SF_ID_SYST_LOWPT_UP.resize(n_muons); + m_softmu_SF_ID_SYST_LOWPT_DOWN.resize(n_muons); + + if(m_config->softmuonAdditionalTruthInfo()) + { + m_softmu_parton_origin_flag.resize(n_muons); + m_softmu_particle_origin_flag.resize(n_muons); + m_softmu_parent_pdgid.resize(n_muons); + m_softmu_b_hadron_parent_pdgid.resize(n_muons); + m_softmu_c_hadron_parent_pdgid.resize(n_muons); } + } + + for (const auto* const muPtr : event.m_softmuons) { + m_softmu_pt[i] = muPtr->pt(); + m_softmu_eta[i] = muPtr->eta(); + m_softmu_phi[i] = muPtr->phi(); + m_softmu_e[i] = muPtr->e(); + m_softmu_charge[i] = muPtr->charge(); + + m_softmu_d0[i] = 999.; + m_softmu_d0sig[i] = 999.; + m_softmu_delta_z0_sintheta[i] = 999.; + + const xAOD::TrackParticle* mutrack = muPtr->primaryTrackParticle(); - if (m_config->doTopPartonHistory()) { + if (mutrack) m_softmu_d0[i] = mutrack->d0(); + if (muPtr->isAvailable<float>("d0sig")) m_softmu_d0sig[i] = muPtr->auxdataConst<float>("d0sig"); + if (muPtr->isAvailable<float>("delta_z0_sintheta")) m_softmu_delta_z0_sintheta[i] = muPtr->auxdataConst<float>("delta_z0_sintheta"); - const xAOD::PartonHistoryContainer* partonHistoryContainer(nullptr); - const xAOD::PartonHistory* partonHistory(nullptr); - if (evtStore()->contains<xAOD::PartonHistoryContainer>(m_config->sgKeyTopPartonHistory())) { - top::check(evtStore()->retrieve(partonHistoryContainer, m_config->sgKeyTopPartonHistory()),"Failed to retrieve Top Parton History"); - if (partonHistoryContainer->size() == 1) { - partonHistory = partonHistoryContainer->at(0); - } + if (m_config->isMC()) { + m_softmu_SF_ID[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::nominal); + if (event.m_hashValue == m_config->nominalHashValue()) { + m_softmu_SF_ID_STAT_UP[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_STAT_UP); + m_softmu_SF_ID_STAT_DOWN[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_STAT_DOWN); + m_softmu_SF_ID_SYST_UP[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_SYST_UP); + m_softmu_SF_ID_SYST_DOWN[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_SYST_DOWN); + m_softmu_SF_ID_STAT_LOWPT_UP[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP); + m_softmu_SF_ID_STAT_LOWPT_DOWN[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN); + m_softmu_SF_ID_SYST_LOWPT_UP[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP); + m_softmu_SF_ID_SYST_LOWPT_DOWN[i] = m_sfRetriever->softmuonSF_ID(*muPtr, top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN); + } + + static const SG::AuxElement::Accessor<int> acc_mctt("truthType"); + static const SG::AuxElement::Accessor<int> acc_mcto("truthOrigin"); + m_softmu_true_type[i] = 0; + m_softmu_true_origin[i] = 0; + if (acc_mctt.isAvailable(*muPtr)) m_softmu_true_type[i] = acc_mctt(*muPtr); + if (acc_mcto.isAvailable(*muPtr)) m_softmu_true_origin[i] = acc_mcto(*muPtr); + m_softmu_true_isPrompt[i] = isPromptMuon(m_softmu_true_type[i], m_softmu_true_origin[i]); + + if(m_config->softmuonAdditionalTruthInfo()) + { + //these truth info are written in SoftMuonObjectCollectionMaker.cxx + + m_softmu_parton_origin_flag[i]=0; + if(m_config->softmuonAdditionalTruthInfoCheckPartonOrigin()) + { + static const SG::AuxElement::Accessor<top::LepPartonOriginFlag> leppartonoriginflag("LepPartonOriginFlag"); + if(leppartonoriginflag.isAvailable(*muPtr)) m_softmu_parton_origin_flag[i]=static_cast<int>(leppartonoriginflag(*muPtr)); } + m_softmu_particle_origin_flag[i]=0; + m_softmu_parent_pdgid[i]=0; + m_softmu_b_hadron_parent_pdgid[i]=0; + m_softmu_c_hadron_parent_pdgid[i]=0; + static const SG::AuxElement::Accessor<top::LepParticleOriginFlag> lepparticleoriginflag("LepParticleOriginFlag"); + if(lepparticleoriginflag.isAvailable(*muPtr)) m_softmu_particle_origin_flag[i]=static_cast<int>(lepparticleoriginflag(*muPtr)); + + static const SG::AuxElement::Accessor<const xAOD::TruthParticle*> Mother("truthMotherLink"); + const xAOD::TruthParticle* mother = 0; + if(Mother.isAvailable(*muPtr)) mother=Mother(*muPtr); + if(mother) m_softmu_parent_pdgid[i]=mother->pdgId(); + + static const SG::AuxElement::Accessor<const xAOD::TruthParticle*> BMother("truthBMotherLink"); + const xAOD::TruthParticle* Bmother = 0; + if(BMother.isAvailable(*muPtr)) Bmother=BMother(*muPtr); + if(Bmother) m_softmu_b_hadron_parent_pdgid[i]=Bmother->pdgId(); + + static const SG::AuxElement::Accessor<const xAOD::TruthParticle*> CMother("truthCMotherLink"); + const xAOD::TruthParticle* Cmother = 0; + if(CMother.isAvailable(*muPtr)) Cmother=CMother(*muPtr); + if(Cmother) m_softmu_c_hadron_parent_pdgid[i]=Cmother->pdgId(); + + if(m_config->softmuonAdditionalTruthInfoDoVerbose()) asg::msgUserCode::ATH_MSG_INFO("writing soft muon with pt="<<m_softmu_pt[i] <<" parton_origin_flag="<<m_softmu_parton_origin_flag[i]<<" particle_origin_flag="<<m_softmu_particle_origin_flag[i]<<" parent_pdg_id="<<m_softmu_parent_pdgid[i]<<" b_hadron_parent_pdg_id="<<m_softmu_b_hadron_parent_pdgid[i]<<" c_hadron_parent_pdg_id="<<m_softmu_c_hadron_parent_pdgid[i]); + } + }//end of if (m_config->isMC()) + ++i; + }//end of loop on softmuons + }//end of if (m_config->useSoftMuons()) + + //photons + if (m_config->usePhotons()) { + unsigned int i(0); + m_ph_pt.resize(event.m_photons.size()); + m_ph_eta.resize(event.m_photons.size()); + m_ph_phi.resize(event.m_photons.size()); + m_ph_e.resize(event.m_photons.size()); + m_ph_iso.resize(event.m_photons.size()); + for (const auto* const phPtr : event.m_photons) { + m_ph_pt[i] = phPtr->pt(); + m_ph_eta[i] = phPtr->eta(); + m_ph_phi[i] = phPtr->phi(); + m_ph_e[i] = phPtr->e(); + + m_ph_iso[i] = 0.; + if (phPtr->isAvailable<float>("ptvarcone20")) m_ph_iso[i] = phPtr->auxdata<float>("ptvarcone20"); + + ++i; + } + } + + + //taus + if (m_config->useTaus()) { + unsigned int i(0); + m_tau_pt.resize(event.m_tauJets.size()); + m_tau_eta.resize(event.m_tauJets.size()); + m_tau_phi.resize(event.m_tauJets.size()); + m_tau_charge.resize(event.m_tauJets.size()); + for (const auto* const tauPtr : event.m_tauJets) { + m_tau_pt[i] = tauPtr->pt(); + m_tau_eta[i] = tauPtr->eta(); + m_tau_phi[i] = tauPtr->phi(); + m_tau_charge[i] = tauPtr->charge(); + ++i; + } + } + + // tracks + if (m_config->useTracks()) { + + m_track_pt.resize(event.m_tracks.size()); + m_track_eta.resize(event.m_tracks.size()); + m_track_phi.resize(event.m_tracks.size()); + m_track_e.resize(event.m_tracks.size()); + m_track_charge.resize(event.m_tracks.size()); + m_track_d0.resize(event.m_tracks.size()); + m_track_d0_significance.resize(event.m_tracks.size()); + m_track_z0.resize(event.m_tracks.size()); + m_track_z0_significance.resize(event.m_tracks.size()); + m_track_phi0.resize(event.m_tracks.size()); + m_track_theta.resize(event.m_tracks.size()); + m_track_qOverP.resize(event.m_tracks.size()); + m_track_chiSquared.resize(event.m_tracks.size()); + m_track_numberDoF.resize(event.m_tracks.size()); + + unsigned int i = 0; + for (const auto* const trkPtr : event.m_tracks){ + + m_track_pt[i] = trkPtr->pt(); + m_track_eta[i] = trkPtr->eta(); + m_track_phi[i] = trkPtr->phi(); + m_track_e[i] = trkPtr->e(); + m_track_charge[i] = trkPtr->charge(); + m_track_d0[i] = trkPtr->d0(); + m_track_d0_significance[i] = xAOD::TrackingHelpers::d0significance(trkPtr); + m_track_z0[i] = trkPtr->z0(); + m_track_z0_significance[i] = xAOD::TrackingHelpers::z0significance(trkPtr); + m_track_phi0[i] = trkPtr->phi0(); + m_track_theta[i] = trkPtr->theta(); + m_track_qOverP[i] = trkPtr->qOverP(); + m_track_chiSquared[i] = trkPtr->chiSquared(); + m_track_numberDoF[i] = trkPtr->numberDoF(); + + ++i; + + } - if (partonHistory != nullptr) { - if (!m_config->isTopPartonHistoryRegisteredInNtuple()) { - registerObjectIntoTruthTree( *(partonHistory) ); - m_config->setTopPartonHistoryRegisteredInNtuple(); - } - saveObjectIntoTruthTree( *(partonHistory) ); + } + + + + //jets + if (m_config->useJets()) { + unsigned int i(0); + m_jet_pt.resize(event.m_jets.size()); + m_jet_eta.resize(event.m_jets.size()); + m_jet_phi.resize(event.m_jets.size()); + m_jet_e.resize(event.m_jets.size()); + if (m_config->bTagAlgo_MV2c10_used()) { + m_jet_mv2c10.resize(event.m_jets.size()); + } + m_jet_jvt.resize(event.m_jets.size()); + m_jet_fjvt.resize(event.m_jets.size()); + m_jet_passfjvt.resize(event.m_jets.size()); + + // ghost tracks + if (m_config->useJetGhostTrack()) { + m_jet_ghostTrack_pt.clear(); + m_jet_ghostTrack_eta.clear(); + m_jet_ghostTrack_phi.clear(); + m_jet_ghostTrack_e.clear(); + m_jet_ghostTrack_d0.clear(); + m_jet_ghostTrack_z0.clear(); + m_jet_ghostTrack_qOverP.clear(); + + + m_jet_ghostTrack_pt.resize(event.m_jets.size()); + m_jet_ghostTrack_eta.resize(event.m_jets.size()); + m_jet_ghostTrack_phi.resize(event.m_jets.size()); + m_jet_ghostTrack_e.resize(event.m_jets.size()); + m_jet_ghostTrack_d0.resize(event.m_jets.size()); + m_jet_ghostTrack_z0.resize(event.m_jets.size()); + m_jet_ghostTrack_qOverP.resize(event.m_jets.size()); + } + + // R21 b-tagging + for (const std::string& algo : m_config->bTagAlgo_available()) { + m_jet_DLx[algo].resize(event.m_jets.size()); + m_jet_DLx_pb[algo].resize(event.m_jets.size()); + m_jet_DLx_pc[algo].resize(event.m_jets.size()); + m_jet_DLx_pu[algo].resize(event.m_jets.size()); + } + if (m_config->isMC()) { + m_jet_truthflav.resize(event.m_jets.size()); + m_jet_truthPartonLabel.resize(event.m_jets.size()); + m_jet_isTrueHS.resize(event.m_jets.size()); + m_jet_HadronConeExclExtendedTruthLabelID.resize(event.m_jets.size()); + } + for (auto& tagWP : m_config->bTagWP_available()) { + + if (tagWP.find("Continuous") == std::string::npos) { + m_jet_isbtagged[tagWP].resize(event.m_jets.size()); + if (std::find(m_config->bTagWP_calibrated().begin(), + m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; + + if (m_config->isMC() && m_config->storePerJetBtagSFs()) { + m_perjet_weight_bTagSF[tagWP].resize(event.m_jets.size()); + m_perjet_weight_bTagSF_eigen_B_up[tagWP].resize(event.m_jets.size(), std::vector<float>(m_config->btagging_num_B_eigenvars(tagWP))); + m_perjet_weight_bTagSF_eigen_B_down[tagWP].resize(event.m_jets.size(), std::vector<float>(m_config->btagging_num_B_eigenvars(tagWP))); + m_perjet_weight_bTagSF_eigen_C_up[tagWP].resize(event.m_jets.size(), std::vector<float>(m_config->btagging_num_C_eigenvars(tagWP))); + m_perjet_weight_bTagSF_eigen_C_down[tagWP].resize(event.m_jets.size(), std::vector<float>(m_config->btagging_num_C_eigenvars(tagWP))); + m_perjet_weight_bTagSF_eigen_Light_up[tagWP].resize(event.m_jets.size(), std::vector<float>(m_config->btagging_num_Light_eigenvars(tagWP))); + m_perjet_weight_bTagSF_eigen_Light_down[tagWP].resize(event.m_jets.size(), std::vector<float>(m_config->btagging_num_Light_eigenvars(tagWP))); + for (const std::string& name : m_config->btagging_namedSysts(tagWP)) { + m_perjet_weight_bTagSF_named_up[tagWP][name].resize(event.m_jets.size()); + m_perjet_weight_bTagSF_named_down[tagWP][name].resize(event.m_jets.size()); } + } + } else m_jet_tagWeightBin[tagWP].resize(event.m_jets.size()); + } + for (const auto* const jetPtr : event.m_jets) { + m_jet_pt[i] = jetPtr->pt(); + m_jet_eta[i] = jetPtr->eta(); + m_jet_phi[i] = jetPtr->phi(); + m_jet_e[i] = jetPtr->e(); + // In R21, list of b-tagging variables is changing and this is outdated + //const xAOD::BTagging* btag(nullptr); + //btag = jetPtr->btagging(); + if (m_config->isMC()) { + m_jet_truthflav[i] = -99; + if (jetPtr->isAvailable<int>("HadronConeExclTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclTruthLabelID", m_jet_truthflav[i]); + } + m_jet_truthPartonLabel[i] = -99; + if (jetPtr->isAvailable<int>("PartonTruthLabelID")) { + jetPtr->getAttribute("PartonTruthLabelID", m_jet_truthPartonLabel[i]); + } + m_jet_isTrueHS[i] = false; + if (jetPtr->isAvailable<char>("AnalysisTop_isHS")) { + jetPtr->getAttribute("AnalysisTop_isHS", m_jet_isTrueHS[i]); + } + m_jet_HadronConeExclExtendedTruthLabelID[i] = -99; + if (jetPtr->isAvailable<int>("HadronConeExclExtendedTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclExtendedTruthLabelID", m_jet_HadronConeExclExtendedTruthLabelID[i]); + } + } + + if (m_config->useJetGhostTrack() && m_jet_pt[i] > m_config->jetPtGhostTracks() && std::abs(m_jet_eta[i])<m_config->jetEtaGhostTracks()) { + static const SG::AuxElement::Accessor< float > accD0("d0"); + static const SG::AuxElement::Accessor< float > accZ0("z0"); + static const SG::AuxElement::Accessor< float > accQOverP("qOverP"); + + std::vector<const xAOD::TrackParticle*> ghostTracks; + + if(jetPtr->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(event.m_hashValue),ghostTracks)) { + + const unsigned int nghostTracks = ghostTracks.size(); + + m_jet_ghostTrack_pt[i].clear(); + m_jet_ghostTrack_eta[i].clear(); + m_jet_ghostTrack_phi[i].clear(); + m_jet_ghostTrack_e[i].clear(); + m_jet_ghostTrack_d0[i].clear(); + m_jet_ghostTrack_z0[i].clear(); + m_jet_ghostTrack_qOverP[i].clear(); + + m_jet_ghostTrack_pt[i].reserve(nghostTracks); + m_jet_ghostTrack_eta[i].reserve(nghostTracks); + m_jet_ghostTrack_phi[i].reserve(nghostTracks); + m_jet_ghostTrack_e[i].reserve(nghostTracks); + m_jet_ghostTrack_d0[i].reserve(nghostTracks); + m_jet_ghostTrack_z0[i].reserve(nghostTracks); + m_jet_ghostTrack_qOverP[i].reserve(nghostTracks); + + + for (unsigned int iGhost = 0; iGhost < nghostTracks; ++iGhost) { + + top::check(ghostTracks.at(iGhost), "Error in EventSaverFlatNtuple: Found jet with null pointer in ghost track vector."); + + if(ghostTracks.at(iGhost)->auxdataConst< char >("passPreORSelection") != 1) + { continue;} + + m_jet_ghostTrack_pt[i].emplace_back(ghostTracks.at(iGhost)->pt()); + m_jet_ghostTrack_eta[i].emplace_back(ghostTracks.at(iGhost)->eta()); + m_jet_ghostTrack_phi[i].emplace_back(ghostTracks.at(iGhost)->phi()); + m_jet_ghostTrack_e[i].emplace_back(ghostTracks.at(iGhost)->e()); + m_jet_ghostTrack_d0[i].emplace_back(accD0(*ghostTracks.at(iGhost))); + m_jet_ghostTrack_z0[i].emplace_back(accZ0(*ghostTracks.at(iGhost))); + m_jet_ghostTrack_qOverP[i].emplace_back(accQOverP(*ghostTracks.at(iGhost))); + } + + } + } + + + for (auto& tagWP : m_config->bTagWP_available()) { + if (tagWP.find("Continuous") == std::string::npos) { + m_jet_isbtagged[tagWP][i] = false; + if (jetPtr->isAvailable<char>("isbtagged_" + tagWP)) m_jet_isbtagged[tagWP][i] = jetPtr->auxdataConst<char>("isbtagged_" + tagWP); + if (m_config->isMC() && m_config->storePerJetBtagSFs()) { + if (std::find(m_config->bTagWP_calibrated().begin(), + m_config->bTagWP_calibrated().end(), tagWP) == m_config->bTagWP_calibrated().end()) continue; + m_perjet_weight_bTagSF[tagWP][i] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_nom"); + for (size_t ivar = 0; ivar < m_config->btagging_num_B_eigenvars(tagWP); ++ivar) { + m_perjet_weight_bTagSF_eigen_B_up[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_B_" + std::to_string(ivar) + "__1up"); + m_perjet_weight_bTagSF_eigen_B_down[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_B_" + std::to_string(ivar) + "__1down"); + } + for (size_t ivar = 0; ivar < m_config->btagging_num_C_eigenvars(tagWP); ++ivar) { + m_perjet_weight_bTagSF_eigen_C_up[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_C_" + std::to_string(ivar) + "__1up"); + m_perjet_weight_bTagSF_eigen_C_down[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_C_" + std::to_string(ivar) + "__1down"); + } + for (size_t ivar = 0; ivar < m_config->btagging_num_Light_eigenvars(tagWP); ++ivar) { + m_perjet_weight_bTagSF_eigen_Light_up[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_Light_" + std::to_string(ivar) + "__1up"); + m_perjet_weight_bTagSF_eigen_Light_down[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_Light_" + std::to_string(ivar) + "__1down"); + } + for (const std::string& name : m_config->btagging_namedSysts(tagWP)) { + m_perjet_weight_bTagSF_named_up[tagWP][name][i] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_" + name + "__1up"); + m_perjet_weight_bTagSF_named_down[tagWP][name][i] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_" + name + "__1down"); + } + } + } else { + m_jet_tagWeightBin[tagWP][i] = -2;// AT default value + if (jetPtr->isAvailable<int>("tagWeightBin_" + tagWP)) m_jet_tagWeightBin[tagWP][i] = jetPtr->auxdataConst<int>("tagWeightBin_" + tagWP); + } } - if( m_config->saveLHAPDFEvent() ){ - // Delegate to helper function. - loadPdfWeights(); + // for studies on high performance b-tagging + // the following are in DC14 + + if (m_config->bTagAlgo_MV2c10_used()) { + double mvx = -999; + //if (btag) btag->MVx_discriminant("MV2c10", mvx); + m_jet_mv2c10[i] = mvx; } - m_truthTreeManager->fill(); + m_jet_jvt[i] = -1; + if (jetPtr->isAvailable<float>("AnalysisTop_JVT")) { + m_jet_jvt[i] = jetPtr->auxdataConst<float>("AnalysisTop_JVT"); + } + m_jet_fjvt[i] = -1; + if (jetPtr->isAvailable<float>("fJvt")){ + m_jet_fjvt[i] = jetPtr->auxdataConst<float>("fJvt"); + } + m_jet_passfjvt[i] = -1; + if (jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")){ + m_jet_passfjvt[i] = jetPtr->getAttribute<char>("AnalysisTop_fJVTdecision"); + } + + ++i; + } + // loop over selected DL1 algos and fill all calo jet b-tagging information + // the accessor uses decoration created in TopSystematicObjectMaker/JetObjectCollectionMaker + // calculated by BtaggingSelectionTool + for (const std::string& algo : m_config->bTagAlgo_available()) { + std::vector<float>& m_jet_DLx_pick = m_jet_DLx.at(algo); + //std::vector<float>& m_jet_DLx_pb_pick = m_jet_DLx_pb.at(algo); + //std::vector<float>& m_jet_DLx_pc_pick = m_jet_DLx_pc.at(algo); + //std::vector<float>& m_jet_DLx_pu_pick = m_jet_DLx_pu.at(algo); + const SG::AuxElement::ConstAccessor<float>& DLx_acc = DLx.at(algo); + i = 0; + for (const auto* const jetPtr : event.m_jets) { + m_jet_DLx_pick[i] = DLx_acc(*jetPtr); + + //const xAOD::BTagging* btag(nullptr); + //btag = jetPtr->btagging(); + //if (btag) { + // double pu = -999; + // double pc = -999; + // double pb = -999; + // btag->pu(algo, pu); + // btag->pc(algo, pc); + // btag->pb(algo, pb); + // m_jet_DLx_pb_pick[i] = pb; + // m_jet_DLx_pc_pick[i] = pc; + // m_jet_DLx_pu_pick[i] = pu; + //} + ++i; + } + } } - void EventSaverFlatNtuple::saveParticleLevelEvent(const top::ParticleLevelEvent& plEvent){ - // Quick return if particle level is disabled. No tree will be created! - if ( not m_config->doTopParticleLevel() ){ - return; + // fail-JVT jets + // btagging info is removed since btagging calibration isn't available for fail-JVT jets + if (m_config->saveFailJVTJets()) { + unsigned int i(0); + m_failJvt_jet_pt.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_eta.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_phi.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_e.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_jvt.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_fjvt.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_passfjvt.resize(event.m_failJvt_jets.size()); + + // ghost tracks + // fail-JVT jet could still have some ghost tracks, so these variables are kept + if (m_config->useJetGhostTrack()) { + + m_failJvt_jet_ghostTrack_pt.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_ghostTrack_eta.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_ghostTrack_phi.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_ghostTrack_e.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_ghostTrack_d0.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_ghostTrack_z0.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_ghostTrack_qOverP.resize(event.m_failJvt_jets.size()); + } + + if (m_config->isMC()) { + m_failJvt_jet_truthflav.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_truthPartonLabel.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_isTrueHS.resize(event.m_failJvt_jets.size()); + m_failJvt_jet_HadronConeExclExtendedTruthLabelID.resize(event.m_failJvt_jets.size()); + } + + for (const auto* const jetPtr : event.m_failJvt_jets) { + m_failJvt_jet_pt[i] = jetPtr->pt(); + m_failJvt_jet_eta[i] = jetPtr->eta(); + m_failJvt_jet_phi[i] = jetPtr->phi(); + m_failJvt_jet_e[i] = jetPtr->e(); + if (m_config->isMC()) { + m_failJvt_jet_truthflav[i] = -99; + if (jetPtr->isAvailable<int>("HadronConeExclTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclTruthLabelID", m_failJvt_jet_truthflav[i]); + } + m_failJvt_jet_truthPartonLabel[i] = -99; + if (jetPtr->isAvailable<int>("PartonTruthLabelID")) { + jetPtr->getAttribute("PartonTruthLabelID", m_failJvt_jet_truthPartonLabel[i]); + } + m_failJvt_jet_isTrueHS[i] = false; + if (jetPtr->isAvailable<char>("AnalysisTop_isHS")) { + jetPtr->getAttribute("AnalysisTop_isHS", m_failJvt_jet_isTrueHS[i]); + } + m_failJvt_jet_HadronConeExclExtendedTruthLabelID[i] = -99; + if (jetPtr->isAvailable<int>("HadronConeExclExtendedTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclExtendedTruthLabelID", m_failJvt_jet_HadronConeExclExtendedTruthLabelID[i]); + } } - // Setup the TTree. This should come at the very top in order to make sure - // that event for non-MC data, the TTree will be created (but remains empty). - setupParticleLevelTreeManager( plEvent ); + if (m_config->useJetGhostTrack() && m_failJvt_jet_pt[i] > m_config->jetPtGhostTracks() && std::abs(m_failJvt_jet_eta[i])<m_config->jetEtaGhostTracks()) { + static const SG::AuxElement::Accessor< float > accD0("d0"); + static const SG::AuxElement::Accessor< float > accZ0("z0"); + static const SG::AuxElement::Accessor< float > accQOverP("qOverP"); + + std::vector<const xAOD::TrackParticle*> ghostTracks; + if(jetPtr->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(event.m_hashValue),ghostTracks)) { + + const unsigned int nghostTracks = ghostTracks.size(); + + m_failJvt_jet_ghostTrack_pt[i].clear(); + m_failJvt_jet_ghostTrack_eta[i].clear(); + m_failJvt_jet_ghostTrack_phi[i].clear(); + m_failJvt_jet_ghostTrack_e[i].clear(); + m_failJvt_jet_ghostTrack_d0[i].clear(); + m_failJvt_jet_ghostTrack_z0[i].clear(); + m_failJvt_jet_ghostTrack_qOverP[i].clear(); + + m_failJvt_jet_ghostTrack_pt[i].reserve(nghostTracks); + m_failJvt_jet_ghostTrack_eta[i].reserve(nghostTracks); + m_failJvt_jet_ghostTrack_phi[i].reserve(nghostTracks); + m_failJvt_jet_ghostTrack_e[i].reserve(nghostTracks); + m_failJvt_jet_ghostTrack_d0[i].reserve(nghostTracks); + m_failJvt_jet_ghostTrack_z0[i].reserve(nghostTracks); + m_failJvt_jet_ghostTrack_qOverP[i].reserve(nghostTracks); + + for (unsigned int iGhost = 0; iGhost < nghostTracks; ++iGhost) { + + top::check(ghostTracks.at(iGhost), "Error in EventSaverFlatNtuple: Found jet with null pointer in ghost track vector."); + + if(ghostTracks.at(iGhost)->auxdataConst< char >("passPreORSelection") != 1) + {continue;} + + m_failJvt_jet_ghostTrack_pt[i].emplace_back(ghostTracks.at(iGhost)->pt()); + m_failJvt_jet_ghostTrack_eta[i].emplace_back(ghostTracks.at(iGhost)->eta()); + m_failJvt_jet_ghostTrack_phi[i].emplace_back(ghostTracks.at(iGhost)->phi()); + m_failJvt_jet_ghostTrack_e[i].emplace_back(ghostTracks.at(iGhost)->e()); + m_failJvt_jet_ghostTrack_d0[i].emplace_back(accD0(*ghostTracks.at(iGhost))); + m_failJvt_jet_ghostTrack_z0[i].emplace_back(accZ0(*ghostTracks.at(iGhost))); + m_failJvt_jet_ghostTrack_qOverP[i].emplace_back(accQOverP(*ghostTracks.at(iGhost))); + } + + } + } - // No need to attempt to write out anything for non-MC data. - if ( ! m_config->isMC() ){ - return; + m_failJvt_jet_jvt[i] = -1; + if (jetPtr->isAvailable<float>("AnalysisTop_JVT")) { + m_failJvt_jet_jvt[i] = jetPtr->auxdataConst<float>("AnalysisTop_JVT"); } - for ( auto & selectionDecision : m_particleLevel_SelectionDecisions ){ - selectionDecision.second = plEvent.m_selectionDecisions[ selectionDecision.first ]; + m_failJvt_jet_fjvt[i] = -1; + if (jetPtr->isAvailable<float>("fJvt")) { + m_failJvt_jet_fjvt[i] = jetPtr->auxdataConst<float>("fJvt"); } - - // to get the fixed mc weight - const xAOD::TruthEventContainer * truthEvent(nullptr); - top::check( evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth event container" ); - unsigned int truthEventSize = truthEvent->size(); - top::check( truthEventSize==1 , "Failed to retrieve truth PDF info - truth event container size is different from 1 (strange)" ); - -// m_weight_mc = plEvent.m_info->mcEventWeight(); - m_weight_mc = truthEvent->at(0)->weights()[0];// FIXME temporary bugfix - - m_eventNumber = plEvent.m_info->eventNumber(); - m_runNumber = plEvent.m_info->runNumber(); - m_mcChannelNumber = plEvent.m_info->mcChannelNumber(); - - m_mu = plEvent.m_info->averageInteractionsPerCrossing(); - - if (m_config->doPileupReweighting() && !m_config->isTruthDxAOD()) { - m_weight_pileup = plEvent.m_info->auxdataConst<float>("PileupWeight"); - m_randomRunNumber = plEvent.m_info->auxdataConst<unsigned int>("RandomRunNumber"); - } - else { - m_weight_pileup = NAN; - m_randomRunNumber = 0; - } - - //electrons - if ( m_config->useTruthElectrons() ){ - unsigned int i = 0; - - m_el_pt.resize(plEvent.m_electrons->size()); - m_el_eta.resize(plEvent.m_electrons->size()); - m_el_phi.resize(plEvent.m_electrons->size()); - m_el_e.resize(plEvent.m_electrons->size()); - m_el_charge.resize(plEvent.m_electrons->size()); - - m_el_pt_bare.resize(plEvent.m_electrons->size()); - m_el_eta_bare.resize(plEvent.m_electrons->size()); - m_el_phi_bare.resize(plEvent.m_electrons->size()); - m_el_e_bare.resize(plEvent.m_electrons->size()); - - for (const auto & elPtr : * plEvent.m_electrons) { - m_el_pt[i] = elPtr->pt(); - m_el_eta[i] = elPtr->eta(); - m_el_phi[i] = elPtr->phi(); - m_el_e[i] = elPtr->e(); - m_el_charge[i] = elPtr->charge(); - - m_el_pt_bare[i] = elPtr->auxdata<float>( "pt_bare" ); - m_el_eta_bare[i] = elPtr->auxdata<float>( "eta_bare" ); - m_el_phi_bare[i] = elPtr->auxdata<float>( "phi_bare" ); - m_el_e_bare[i] = elPtr->auxdata<float>( "e_bare" ); - - ++i; - } + m_failJvt_jet_passfjvt[i] = -1; + if (jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")) { + m_failJvt_jet_passfjvt[i] = jetPtr->getAttribute<char>("AnalysisTop_fJVTdecision"); + } + + ++i; + } + }//ifSaveJVT + + // fail-FJVT jets + // btagging info removed as this is only looking at forward jets + if (m_config->getfJVTWP() != "None" && m_config->saveFailForwardJVTJets()) { + unsigned int i(0); + m_failFJvt_jet_pt.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_eta.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_phi.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_e.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_jvt.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_fjvt.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_passjvt.resize(event.m_failFJvt_jets.size()); + + // ghost tracks + // fail-FJVT jet could still have some ghost tracks, so these variables are kept + if (m_config->useJetGhostTrack()) { + + m_failFJvt_jet_ghostTrack_pt.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_ghostTrack_eta.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_ghostTrack_phi.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_ghostTrack_e.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_ghostTrack_d0.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_ghostTrack_z0.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_ghostTrack_qOverP.resize(event.m_failFJvt_jets.size()); + } + + if (m_config->isMC()) { + m_failFJvt_jet_truthflav.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_truthPartonLabel.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_isTrueHS.resize(event.m_failFJvt_jets.size()); + m_failFJvt_jet_HadronConeExclExtendedTruthLabelID.resize(event.m_failFJvt_jets.size()); + } + + for (const auto* const jetPtr : event.m_failFJvt_jets) { + m_failFJvt_jet_pt[i] = jetPtr->pt(); + m_failFJvt_jet_eta[i] = jetPtr->eta(); + m_failFJvt_jet_phi[i] = jetPtr->phi(); + m_failFJvt_jet_e[i] = jetPtr->e(); + if (m_config->isMC()) { + m_failFJvt_jet_truthflav[i] = -99; + if (jetPtr->isAvailable<int>("HadronConeExclTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclTruthLabelID", m_failFJvt_jet_truthflav[i]); + } + m_failFJvt_jet_truthPartonLabel[i] = -99; + if (jetPtr->isAvailable<int>("PartonTruthLabelID")) { + jetPtr->getAttribute("PartonTruthLabelID", m_failFJvt_jet_truthPartonLabel[i]); + } + m_failFJvt_jet_isTrueHS[i] = false; + if (jetPtr->isAvailable<char>("AnalysisTop_isHS")) { + jetPtr->getAttribute("AnalysisTop_isHS", m_failFJvt_jet_isTrueHS[i]); + } + m_failFJvt_jet_HadronConeExclExtendedTruthLabelID[i] = -99; + if (jetPtr->isAvailable<int>("HadronConeExclExtendedTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclExtendedTruthLabelID", m_failFJvt_jet_HadronConeExclExtendedTruthLabelID[i]); + } } - //muons - if ( m_config->useTruthMuons() ){ - unsigned int i = 0; + if (m_config->useJetGhostTrack() && m_failFJvt_jet_pt[i] > m_config->jetPtGhostTracks() && std::abs(m_failFJvt_jet_eta[i])<m_config->jetEtaGhostTracks()) { + static const SG::AuxElement::Accessor< float > accD0("d0"); + static const SG::AuxElement::Accessor< float > accZ0("z0"); + static const SG::AuxElement::Accessor< float > accQOverP("qOverP"); + + std::vector<const xAOD::TrackParticle*> ghostTracks; + if(jetPtr->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(event.m_hashValue),ghostTracks)) { + + const unsigned int nghostTracks = ghostTracks.size(); + + m_failFJvt_jet_ghostTrack_pt[i].clear(); + m_failFJvt_jet_ghostTrack_eta[i].clear(); + m_failFJvt_jet_ghostTrack_phi[i].clear(); + m_failFJvt_jet_ghostTrack_e[i].clear(); + m_failFJvt_jet_ghostTrack_d0[i].clear(); + m_failFJvt_jet_ghostTrack_z0[i].clear(); + m_failFJvt_jet_ghostTrack_qOverP[i].clear(); + + m_failFJvt_jet_ghostTrack_pt[i].reserve(nghostTracks); + m_failFJvt_jet_ghostTrack_eta[i].reserve(nghostTracks); + m_failFJvt_jet_ghostTrack_phi[i].reserve(nghostTracks); + m_failFJvt_jet_ghostTrack_e[i].reserve(nghostTracks); + m_failFJvt_jet_ghostTrack_d0[i].reserve(nghostTracks); + m_failFJvt_jet_ghostTrack_z0[i].reserve(nghostTracks); + m_failFJvt_jet_ghostTrack_qOverP[i].reserve(nghostTracks); + + + for (unsigned int iGhost = 0; iGhost < nghostTracks; ++iGhost) { + top::check(ghostTracks.at(iGhost), "Error in EventSaverFlatNtuple: Found jet with null pointer in ghost track vector."); + + if(ghostTracks.at(iGhost)->auxdataConst< char >("passPreORSelection") != 1) + { continue;} + + + m_failFJvt_jet_ghostTrack_pt[i].emplace_back(ghostTracks.at(iGhost)->pt()); + m_failFJvt_jet_ghostTrack_eta[i].emplace_back(ghostTracks.at(iGhost)->eta()); + m_failFJvt_jet_ghostTrack_phi[i].emplace_back(ghostTracks.at(iGhost)->phi()); + m_failFJvt_jet_ghostTrack_e[i].emplace_back(ghostTracks.at(iGhost)->e()); + m_failFJvt_jet_ghostTrack_d0[i].emplace_back(accD0(*ghostTracks.at(iGhost))); + m_failFJvt_jet_ghostTrack_z0[i].emplace_back(accZ0(*ghostTracks.at(iGhost))); + m_failFJvt_jet_ghostTrack_qOverP[i].emplace_back(accQOverP(*ghostTracks.at(iGhost))); + } + + + } + } - m_mu_pt.resize(plEvent.m_muons->size()); - m_mu_eta.resize(plEvent.m_muons->size()); - m_mu_phi.resize(plEvent.m_muons->size()); - m_mu_e.resize(plEvent.m_muons->size()); - m_mu_charge.resize(plEvent.m_muons->size()); + m_failFJvt_jet_jvt[i] = -1; + if (jetPtr->isAvailable<float>("AnalysisTop_JVT")) { + m_failFJvt_jet_jvt[i] = jetPtr->auxdataConst<float>("AnalysisTop_JVT"); + } + m_failFJvt_jet_passjvt[i] = -1; + if (jetPtr->isAvailable<char>("passJVT")) { + m_failFJvt_jet_passjvt[i] = jetPtr->getAttribute<char>("passJVT"); + } + m_failFJvt_jet_fjvt[i] = -1; + if (jetPtr->isAvailable<float>("fJvt")) { + m_failFJvt_jet_fjvt[i] = jetPtr->auxdataConst<float>("fJvt"); + } + + ++i; + } + }//ifSaveFJVT - m_mu_pt_bare.resize(plEvent.m_muons->size()); - m_mu_eta_bare.resize(plEvent.m_muons->size()); - m_mu_phi_bare.resize(plEvent.m_muons->size()); - m_mu_e_bare.resize(plEvent.m_muons->size()); - for (const auto & muPtr : * plEvent.m_muons) { - m_mu_pt[i] = muPtr->pt(); - m_mu_eta[i] = muPtr->eta(); - m_mu_phi[i] = muPtr->phi(); - m_mu_e[i] = muPtr->e(); - m_mu_charge[i] = muPtr->charge(); + //large-R jets + if (m_config->useLargeRJets()) { + unsigned int i(0); + const unsigned int nLargeRJets = event.m_largeJets.size(); + m_ljet_pt.resize(nLargeRJets); + m_ljet_eta.resize(nLargeRJets); + m_ljet_phi.resize(nLargeRJets); + m_ljet_e.resize(nLargeRJets); + m_ljet_m.resize(nLargeRJets); - m_mu_pt_bare[i] = muPtr->auxdata<float>( "pt_bare" ); - m_mu_eta_bare[i] = muPtr->auxdata<float>( "eta_bare" ); - m_mu_phi_bare[i] = muPtr->auxdata<float>( "phi_bare" ); - m_mu_e_bare[i] = muPtr->auxdata<float>( "e_bare" ); + for (const std::pair<std::string,std::string>& it : m_config->largeRJetSubstructureVariables()) { + m_ljet_substructure[it.first].resize(nLargeRJets); + } - ++i; + for (const std::string& taggerName : m_boostedJetTaggersNames) + m_ljet_isTagged[taggerName].resize(nLargeRJets); + if (m_config->isMC()) { + m_ljet_truthLabel.resize(nLargeRJets); + for (const std::string& taggerName : m_boostedJetTaggersNamesCalibrated) + m_ljet_tagSF[taggerName].resize(nLargeRJets); + } + + for (const auto* const jetPtr : event.m_largeJets) { + m_ljet_pt[i] = jetPtr->pt(); + m_ljet_eta[i] = jetPtr->eta(); + m_ljet_phi[i] = jetPtr->phi(); + m_ljet_e[i] = jetPtr->e(); + m_ljet_m[i] = jetPtr->m(); + + for (const std::pair<std::string,std::string>& it : m_config->largeRJetSubstructureVariables()) { + m_ljet_substructure[it.first][i] = jetPtr->isAvailable<float>(it.second) ? jetPtr->auxdata<float>(it.second) : -999; + } + + for (const std::string& taggerName : m_boostedJetTaggersNames) { + m_ljet_isTagged[taggerName][i] = jetPtr->getAttribute<char>("isTagged_" + taggerName); + } + + if (m_config->isMC()) { + m_ljet_truthLabel[i] = jetPtr->auxdata<int>("R10TruthLabel_R21Consolidated"); + for (const std::pair<std::string, std::string>& tagSF : m_config->boostedTaggerSFnames()) { + m_ljet_tagSF[tagSF.first][i] = jetPtr->auxdata<float>(tagSF.second); + } + } + + ++i; + } + } + + //track jets + if (m_config->useTrackJets()) { + unsigned int i(0); + m_tjet_pt.resize(event.m_trackJets.size()); + m_tjet_eta.resize(event.m_trackJets.size()); + m_tjet_phi.resize(event.m_trackJets.size()); + m_tjet_e.resize(event.m_trackJets.size()); + if (m_config->bTagAlgo_MV2c10_used_trkJet()) { + m_tjet_mv2c10.resize(event.m_trackJets.size()); + } + for (const std::string& algo : m_config->bTagAlgo_available_trkJet()) { + m_tjet_DLx[algo].resize(event.m_trackJets.size()); + m_tjet_DLx_pb[algo].resize(event.m_trackJets.size()); + m_tjet_DLx_pc[algo].resize(event.m_trackJets.size()); + m_tjet_DLx_pu[algo].resize(event.m_trackJets.size()); + } + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + if (tagWP.find("Continuous") == std::string::npos) { + m_tjet_isbtagged[tagWP].resize(event.m_trackJets.size()); + if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), + m_config->bTagWP_calibrated_trkJet().end(), tagWP) == m_config->bTagWP_calibrated_trkJet().end()) continue; + if (m_config->isMC() && m_config->storePerJetBtagSFs()) { + m_perjet_weight_trackjet_bTagSF[tagWP].resize(event.m_trackJets.size()); + m_perjet_weight_trackjet_bTagSF_eigen_B_up[tagWP].resize(event.m_trackJets.size(), std::vector<float>(m_config->trkjet_btagging_num_B_eigenvars(tagWP))); + m_perjet_weight_trackjet_bTagSF_eigen_B_down[tagWP].resize(event.m_trackJets.size(), std::vector<float>(m_config->trkjet_btagging_num_B_eigenvars(tagWP))); + m_perjet_weight_trackjet_bTagSF_eigen_C_up[tagWP].resize(event.m_trackJets.size(), std::vector<float>(m_config->trkjet_btagging_num_C_eigenvars(tagWP))); + m_perjet_weight_trackjet_bTagSF_eigen_C_down[tagWP].resize(event.m_trackJets.size(), std::vector<float>(m_config->trkjet_btagging_num_C_eigenvars(tagWP))); + m_perjet_weight_trackjet_bTagSF_eigen_Light_up[tagWP].resize(event.m_trackJets.size(), std::vector<float>(m_config->trkjet_btagging_num_Light_eigenvars(tagWP))); + m_perjet_weight_trackjet_bTagSF_eigen_Light_down[tagWP].resize(event.m_trackJets.size(), std::vector<float>(m_config->trkjet_btagging_num_Light_eigenvars(tagWP))); + for (const std::string& name : m_config->trkjet_btagging_namedSysts(tagWP)) { + m_perjet_weight_trackjet_bTagSF_named_up[tagWP][name].resize(event.m_trackJets.size()); + m_perjet_weight_trackjet_bTagSF_named_down[tagWP][name].resize(event.m_trackJets.size()); } + } + } else m_tjet_tagWeightBin[tagWP].resize(event.m_trackJets.size()); + } + for (const auto* const jetPtr : event.m_trackJets) { + m_tjet_pt[i] = jetPtr->pt(); + m_tjet_eta[i] = jetPtr->eta(); + m_tjet_phi[i] = jetPtr->phi(); + m_tjet_e[i] = jetPtr->e(); + + if (m_config->bTagAlgo_MV2c10_used_trkJet()) { + //const xAOD::BTagging* btag(nullptr); + //btag = jetPtr->btagging(); + double mvx = -999; + //if (btag) btag->MVx_discriminant("MV2c10", mvx); + m_tjet_mv2c10[i] = mvx; } - //photons - if (m_config->useTruthPhotons()) { - unsigned int i(0); - m_ph_pt.resize(plEvent.m_photons->size()); - m_ph_eta.resize(plEvent.m_photons->size()); - m_ph_phi.resize(plEvent.m_photons->size()); - m_ph_e.resize(plEvent.m_photons->size()); - for (const auto* const phPtr : * plEvent.m_photons) { - m_ph_pt[i] = phPtr->pt(); - m_ph_eta[i] = phPtr->eta(); - m_ph_phi[i] = phPtr->phi(); - m_ph_e[i] = phPtr->e(); - - ++i; + for (auto& tagWP : m_config->bTagWP_available_trkJet()) { + if (tagWP.find("Continuous") == std::string::npos) { + m_tjet_isbtagged[tagWP][i] = false; + if (jetPtr->isAvailable<char>("isbtagged_" + tagWP)) m_tjet_isbtagged[tagWP][i] = jetPtr->auxdataConst<char>("isbtagged_" + tagWP); + if (m_config->isMC() && m_config->storePerJetBtagSFs()) { + if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), + m_config->bTagWP_calibrated_trkJet().end(), tagWP) == m_config->bTagWP_calibrated_trkJet().end()) continue; + m_perjet_weight_trackjet_bTagSF[tagWP][i] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_nom"); + for (size_t ivar = 0; ivar < m_config->trkjet_btagging_num_B_eigenvars(tagWP); ++ivar) { + m_perjet_weight_trackjet_bTagSF_eigen_B_up[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_B_" + std::to_string(ivar) + "__1up"); + m_perjet_weight_trackjet_bTagSF_eigen_B_down[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_B_" + std::to_string(ivar) + "__1down"); + } + for (size_t ivar = 0; ivar < m_config->trkjet_btagging_num_C_eigenvars(tagWP); ++ivar) { + m_perjet_weight_trackjet_bTagSF_eigen_C_up[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_C_" + std::to_string(ivar) + "__1up"); + m_perjet_weight_trackjet_bTagSF_eigen_C_down[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_C_" + std::to_string(ivar) + "__1down"); + } + for (size_t ivar = 0; ivar < m_config->trkjet_btagging_num_Light_eigenvars(tagWP); ++ivar) { + m_perjet_weight_trackjet_bTagSF_eigen_Light_up[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_Light_" + std::to_string(ivar) + "__1up"); + m_perjet_weight_trackjet_bTagSF_eigen_Light_down[tagWP][i][ivar] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_FT_EFF_Eigen_Light_" + std::to_string(ivar) + "__1down"); + } + for (const std::string& name : m_config->trkjet_btagging_namedSysts(tagWP)) { + m_perjet_weight_trackjet_bTagSF_named_up[tagWP][name][i] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_" + name + "__1up"); + m_perjet_weight_trackjet_bTagSF_named_down[tagWP][name][i] = jetPtr->auxdataConst<float>("btag_SF_" + tagWP + "_" + name + "__1down"); + } } + } else { + m_tjet_tagWeightBin[tagWP][i] = -2;// AT default value + if (jetPtr->isAvailable<int>("tagWeightBin_" + tagWP)) m_tjet_tagWeightBin[tagWP][i] = jetPtr->auxdataConst<int>("tagWeightBin_" + tagWP); + } } + ++i; + } - //jets - if ( m_config->useTruthJets() ){ - unsigned int i = 0; + // loop over selected DL1 algos and fill all track jet b-tagging information + // the accessor uses decoration created in TopSystematicObjectMaker/JetObjectCollectionMaker + // calculated by BtaggingSelectionTool + for (const std::string& algo : m_config->bTagAlgo_available_trkJet()) { + std::vector<float>& m_tjet_DLx_pick = m_tjet_DLx.at(algo); + //std::vector<float>& m_tjet_DLx_pb_pick = m_tjet_DLx_pb.at(algo); + //std::vector<float>& m_tjet_DLx_pc_pick = m_tjet_DLx_pc.at(algo); + //std::vector<float>& m_tjet_DLx_pu_pick = m_tjet_DLx_pu.at(algo); + const SG::AuxElement::ConstAccessor<float>& DLx_acc = DLx.at(algo); + i = 0; + for (const auto* const jetPtr : event.m_trackJets) { + m_tjet_DLx_pick[i] = DLx_acc(*jetPtr); + + //const xAOD::BTagging* btag(nullptr); + //btag = jetPtr->btagging(); + //if (btag) { + // double pu = -999; + // double pc = -999; + // double pb = -999; + // btag->pu(algo, pu); + // btag->pc(algo, pc); + // btag->pb(algo, pb); + // m_tjet_DLx_pb_pick[i] = pb; + // m_tjet_DLx_pc_pick[i] = pc; + // m_tjet_DLx_pu_pick[i] = pu; + //} + ++i; + } + } + } - m_jet_pt.resize(plEvent.m_jets->size()); - m_jet_eta.resize(plEvent.m_jets->size()); - m_jet_phi.resize(plEvent.m_jets->size()); - m_jet_e.resize(plEvent.m_jets->size()); - m_jet_Ghosts_BHadron_Final_Count.resize(plEvent.m_jets->size()); - m_jet_Ghosts_CHadron_Final_Count.resize(plEvent.m_jets->size()); - for (const auto & jetPtr : * plEvent.m_jets) { - m_jet_pt[i] = jetPtr->pt(); - m_jet_eta[i] = jetPtr->eta(); - m_jet_phi[i] = jetPtr->phi(); - m_jet_e[i] = jetPtr->e(); + if (m_makeRCJets) { + // re-clustered jet substructure + static const SG::AuxElement::ConstAccessor<float> RCSplit12("Split12"); + static const SG::AuxElement::ConstAccessor<float> RCSplit23("Split23"); + + + + // re-clustered jet substructure from clusters + static const SG::AuxElement::ConstAccessor<float> Tau21_clstr("Tau21_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau32_clstr("Tau32_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau3_clstr("Tau3_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau2_clstr("Tau2_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau1_clstr("Tau1_clstr"); + static const SG::AuxElement::ConstAccessor<float> D2_clstr("D2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF1_clstr("ECF1_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF2_clstr("ECF2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF3_clstr("ECF3_clstr"); + static const SG::AuxElement::ConstAccessor<float> d12_clstr("d12_clstr"); + static const SG::AuxElement::ConstAccessor<float> d23_clstr("d23_clstr"); + static const SG::AuxElement::ConstAccessor<float> Qw_clstr("Qw_clstr"); + static const SG::AuxElement::ConstAccessor<float> nconstituent_clstr("nconstituent_clstr"); + + static const SG::AuxElement::ConstAccessor<float> gECF332_clstr("gECF332_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF461_clstr("gECF461_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF322_clstr("gECF322_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF331_clstr("gECF331_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF422_clstr("gECF422_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF441_clstr("gECF441_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF212_clstr("gECF212_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF321_clstr("gECF321_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF311_clstr("gECF311_clstr"); + static const SG::AuxElement::ConstAccessor<float> L1_clstr("L1_clstr"); + static const SG::AuxElement::ConstAccessor<float> L2_clstr("L2_clstr"); + static const SG::AuxElement::ConstAccessor<float> L3_clstr("L3_clstr"); + static const SG::AuxElement::ConstAccessor<float> L4_clstr("L4_clstr"); + static const SG::AuxElement::ConstAccessor<float> L5_clstr("L5_clstr"); + // store also the jet that is rebuilt to calculate the JSS + static const SG::AuxElement::ConstAccessor<float> RRCJet_pt("RRCJet_pt"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_eta("RRCJet_eta"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_phi("RRCJet_phi"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_e("RRCJet_e"); + + // Initialize the vectors to be saved as branches + unsigned int sizeOfRCjets(event.m_RCJets.size()); + + m_rcjet_pt.clear(); + m_rcjet_eta.clear(); + m_rcjet_phi.clear(); + m_rcjet_e.clear(); + m_rcjet_d12.clear(); + m_rcjet_d23.clear(); + m_rcjetsub_pt.clear(); + m_rcjetsub_eta.clear(); + m_rcjetsub_phi.clear(); + m_rcjetsub_e.clear(); + if (m_config->bTagAlgo_MV2c10_used()) { + m_rcjetsub_mv2c10.clear(); + } + m_rrcjet_pt.clear(); + m_rrcjet_eta.clear(); + m_rrcjet_phi.clear(); + m_rrcjet_e.clear(); + + + m_rcjet_tau32_clstr.clear(); + m_rcjet_tau21_clstr.clear(); + m_rcjet_tau3_clstr.clear(); + m_rcjet_tau2_clstr.clear(); + m_rcjet_tau1_clstr.clear(); + + m_rcjet_D2_clstr.clear(); + m_rcjet_ECF1_clstr.clear(); + m_rcjet_ECF2_clstr.clear(); + m_rcjet_ECF3_clstr.clear(); + + m_rcjet_d12_clstr.clear(); + m_rcjet_d23_clstr.clear(); + m_rcjet_Qw_clstr.clear(); + m_rcjet_nconstituent_clstr.clear(); + m_rcjet_gECF332_clstr.clear(); + m_rcjet_gECF461_clstr.clear(); + m_rcjet_gECF322_clstr.clear(); + m_rcjet_gECF331_clstr.clear(); + m_rcjet_gECF422_clstr.clear(); + m_rcjet_gECF441_clstr.clear(); + m_rcjet_gECF212_clstr.clear(); + m_rcjet_gECF321_clstr.clear(); + m_rcjet_gECF311_clstr.clear(); + m_rcjet_L1_clstr.clear(); + m_rcjet_L2_clstr.clear(); + m_rcjet_L3_clstr.clear(); + m_rcjet_L4_clstr.clear(); + m_rcjet_L5_clstr.clear(); + + m_rcjet_pt.resize(sizeOfRCjets, -999.); + m_rcjet_eta.resize(sizeOfRCjets, -999.); + m_rcjet_phi.resize(sizeOfRCjets, -999.); + m_rcjet_e.resize(sizeOfRCjets, -999.); + m_rcjet_d12.resize(sizeOfRCjets, -999.); + m_rcjet_d23.resize(sizeOfRCjets, -999.); + m_rcjetsub_pt.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_eta.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_phi.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_e.resize(sizeOfRCjets, std::vector<float>()); + if (m_config->bTagAlgo_MV2c10_used()) { + m_rcjetsub_mv2c10.resize(sizeOfRCjets, std::vector<float>()); + } - m_jet_Ghosts_BHadron_Final_Count[i] = jetPtr->auxdata<int>( "GhostBHadronsFinalCount" ); - m_jet_Ghosts_CHadron_Final_Count[i] = jetPtr->auxdata<int>( "GhostCHadronsFinalCount" ); + if (m_useRCJSS || m_useRCAdditionalJSS) { + m_rrcjet_pt.resize(sizeOfRCjets, -999.); + m_rrcjet_eta.resize(sizeOfRCjets, -999.); + m_rrcjet_phi.resize(sizeOfRCjets, -999.); + m_rrcjet_e.resize(sizeOfRCjets, -999.); + } + if (m_useRCJSS) { + m_rcjet_tau32_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau21_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau1_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau3_clstr.resize(sizeOfRCjets, -999.); + + m_rcjet_d12_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_d23_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_Qw_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_nconstituent_clstr.resize(sizeOfRCjets, -999.); + + m_rcjet_D2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_ECF1_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_ECF2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_ECF3_clstr.resize(sizeOfRCjets, -999.); + } + if (m_useRCAdditionalJSS) { + + m_rcjet_gECF332_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF461_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF322_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF331_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF422_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF441_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF212_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF321_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF311_clstr.resize(sizeOfRCjets, -999.); + + m_rcjet_L1_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L3_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L4_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L5_clstr.resize(sizeOfRCjets, -999.); + } + unsigned int i = 0; + for (auto jet_itr = event.m_RCJets.begin(); jet_itr != event.m_RCJets.end(); ++jet_itr) { + const xAOD::Jet* rc_jet = *jet_itr; - ++i; - } + + m_rcjet_pt[i] = rc_jet->pt(); + m_rcjet_eta[i] = rc_jet->eta(); + m_rcjet_phi[i] = rc_jet->phi(); + m_rcjet_e[i] = rc_jet->e(); + + m_rcjet_d12[i] = (RCSplit12.isAvailable(*rc_jet)) ? RCSplit12(*rc_jet) : -999.; + m_rcjet_d23[i] = (RCSplit23.isAvailable(*rc_jet)) ? RCSplit23(*rc_jet) : -999.; + + if (m_useRCJSS || m_useRCAdditionalJSS) { + m_rrcjet_pt[i] = (RRCJet_pt.isAvailable(*rc_jet)) ? RRCJet_pt(*rc_jet) : -999.; + m_rrcjet_eta[i] = (RRCJet_eta.isAvailable(*rc_jet)) ? RRCJet_eta(*rc_jet) : -999.; + m_rrcjet_phi[i] = (RRCJet_phi.isAvailable(*rc_jet)) ? RRCJet_phi(*rc_jet) : -999.; + m_rrcjet_e[i] = (RRCJet_e.isAvailable(*rc_jet)) ? RRCJet_e(*rc_jet) : -999.; + } + if (m_useRCJSS) { + m_rcjet_tau32_clstr[i] = (Tau32_clstr.isAvailable(*rc_jet)) ? Tau32_clstr(*rc_jet) : -999.; + m_rcjet_tau21_clstr[i] = (Tau21_clstr.isAvailable(*rc_jet)) ? Tau21_clstr(*rc_jet) : -999.; + m_rcjet_tau3_clstr[i] = (Tau3_clstr.isAvailable(*rc_jet)) ? Tau3_clstr(*rc_jet) : -999.; + m_rcjet_tau2_clstr[i] = (Tau2_clstr.isAvailable(*rc_jet)) ? Tau2_clstr(*rc_jet) : -999.; + m_rcjet_tau1_clstr[i] = (Tau1_clstr.isAvailable(*rc_jet)) ? Tau1_clstr(*rc_jet) : -999.; + + m_rcjet_d12_clstr[i] = (d12_clstr.isAvailable(*rc_jet)) ? d12_clstr(*rc_jet) : -999.; + m_rcjet_d23_clstr[i] = (d23_clstr.isAvailable(*rc_jet)) ? d23_clstr(*rc_jet) : -999.; + m_rcjet_Qw_clstr[i] = (Qw_clstr.isAvailable(*rc_jet)) ? Qw_clstr(*rc_jet) : -999.; + m_rcjet_nconstituent_clstr[i] = (nconstituent_clstr.isAvailable(*rc_jet)) ? nconstituent_clstr(*rc_jet) : -999.; + + m_rcjet_D2_clstr[i] = (D2_clstr.isAvailable(*rc_jet)) ? D2_clstr(*rc_jet) : -999.; + m_rcjet_ECF1_clstr[i] = (ECF1_clstr.isAvailable(*rc_jet)) ? ECF1_clstr(*rc_jet) : -999.; + m_rcjet_ECF2_clstr[i] = (ECF2_clstr.isAvailable(*rc_jet)) ? ECF2_clstr(*rc_jet) : -999.; + m_rcjet_ECF3_clstr[i] = (ECF3_clstr.isAvailable(*rc_jet)) ? ECF3_clstr(*rc_jet) : -999.; + + } + if (m_useRCAdditionalJSS) { + + m_rcjet_gECF332_clstr[i] = (gECF332_clstr.isAvailable(*rc_jet)) ? gECF332_clstr(*rc_jet) : -999.; + m_rcjet_gECF461_clstr[i] = (gECF461_clstr.isAvailable(*rc_jet)) ? gECF461_clstr(*rc_jet) : -999.; + m_rcjet_gECF322_clstr[i] = (gECF322_clstr.isAvailable(*rc_jet)) ? gECF322_clstr(*rc_jet) : -999.; + m_rcjet_gECF331_clstr[i] = (gECF331_clstr.isAvailable(*rc_jet)) ? gECF331_clstr(*rc_jet) : -999.; + m_rcjet_gECF422_clstr[i] = (gECF422_clstr.isAvailable(*rc_jet)) ? gECF422_clstr(*rc_jet) : -999.; + m_rcjet_gECF441_clstr[i] = (gECF441_clstr.isAvailable(*rc_jet)) ? gECF441_clstr(*rc_jet) : -999.; + m_rcjet_gECF212_clstr[i] = (gECF212_clstr.isAvailable(*rc_jet)) ? gECF212_clstr(*rc_jet) : -999.; + m_rcjet_gECF321_clstr[i] = (gECF321_clstr.isAvailable(*rc_jet)) ? gECF321_clstr(*rc_jet) : -999.; + m_rcjet_gECF311_clstr[i] = (gECF311_clstr.isAvailable(*rc_jet)) ? gECF311_clstr(*rc_jet) : -999.; + + m_rcjet_L1_clstr[i] = (L1_clstr.isAvailable(*rc_jet)) ? L1_clstr(*rc_jet) : -999.; + m_rcjet_L2_clstr[i] = (L2_clstr.isAvailable(*rc_jet)) ? L2_clstr(*rc_jet) : -999.; + m_rcjet_L3_clstr[i] = (L3_clstr.isAvailable(*rc_jet)) ? L3_clstr(*rc_jet) : -999.; + m_rcjet_L4_clstr[i] = (L4_clstr.isAvailable(*rc_jet)) ? L4_clstr(*rc_jet) : -999.; + m_rcjet_L5_clstr[i] = (L5_clstr.isAvailable(*rc_jet)) ? L5_clstr(*rc_jet) : -999.; } - //large R jets - if ( m_config->useTruthLargeRJets() ){ - unsigned int i = 0; + // loop over subjets + m_rcjetsub_pt[i].clear(); // clear the vector size (otherwise it grows out of control!) + m_rcjetsub_eta[i].clear(); + m_rcjetsub_phi[i].clear(); + m_rcjetsub_e[i].clear(); + if (m_config->bTagAlgo_MV2c10_used()) { + m_rcjetsub_mv2c10[i].clear(); + } + + const xAOD::Jet* subjet(nullptr); + //const xAOD::BTagging* btag(nullptr); + for (auto rc_jet_subjet : rc_jet->getConstituents()) { + subjet = static_cast<const xAOD::Jet*>(rc_jet_subjet->rawConstituent()); + + if (m_config->bTagAlgo_MV2c10_used()) { + //btag = subjet->btagging(); + + //double mvx10(-999.); // b-tagging mv2c10 + + //if (btag) { + // btag->MVx_discriminant("MV2c10", mvx10); + //} else { + // mvx10 = -999.; + //} + //m_rcjetsub_mv2c10[i].push_back(mvx10); + } + + m_rcjetsub_pt[i].push_back(subjet->pt()); + m_rcjetsub_eta[i].push_back(subjet->eta()); + m_rcjetsub_phi[i].push_back(subjet->phi()); + m_rcjetsub_e[i].push_back(subjet->e()); + } // end for-loop over subjets + ++i; + } // end for-loop over re-clustered jets + } // end if make rcjets + // end re-clustered jets + + /**********************************/ + // VarRC jets + if (m_makeVarRCJets) { + std::string VarRC = "vrcjet"; + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + + // re-clustered jet substructure + static const SG::AuxElement::ConstAccessor<float> VarRCSplit12("Split12"); + static const SG::AuxElement::ConstAccessor<float> VarRCSplit23("Split23"); + + // re-clustered jet substructure from clusters + static const SG::AuxElement::ConstAccessor<float> Tau21_clstr("Tau21_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau32_clstr("Tau32_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau3_clstr("Tau3_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau2_clstr("Tau2_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau1_clstr("Tau1_clstr"); + static const SG::AuxElement::ConstAccessor<float> D2_clstr("D2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF1_clstr("ECF1_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF2_clstr("ECF2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF3_clstr("ECF3_clstr"); + static const SG::AuxElement::ConstAccessor<float> d12_clstr("d12_clstr"); + static const SG::AuxElement::ConstAccessor<float> d23_clstr("d23_clstr"); + static const SG::AuxElement::ConstAccessor<float> Qw_clstr("Qw_clstr"); + + static const SG::AuxElement::ConstAccessor<float> gECF332_clstr("gECF332_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF461_clstr("gECF461_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF322_clstr("gECF322_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF331_clstr("gECF331_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF422_clstr("gECF422_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF441_clstr("gECF441_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF212_clstr("gECF212_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF321_clstr("gECF321_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF311_clstr("gECF311_clstr"); + static const SG::AuxElement::ConstAccessor<float> L1_clstr("L1_clstr"); + static const SG::AuxElement::ConstAccessor<float> L2_clstr("L2_clstr"); + static const SG::AuxElement::ConstAccessor<float> L3_clstr("L3_clstr"); + static const SG::AuxElement::ConstAccessor<float> L4_clstr("L4_clstr"); + static const SG::AuxElement::ConstAccessor<float> L5_clstr("L5_clstr"); + // store also the jet that is rebuilt to calculate the JSS + static const SG::AuxElement::ConstAccessor<float> RRCJet_pt("RRCJet_pt"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_eta("RRCJet_eta"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_phi("RRCJet_phi"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_e("RRCJet_e"); + + // Initialize the vectors to be saved as branches + + xAOD::JetContainer* vrc_jets = event.m_VarRCJets[name].get(); + unsigned int sizeOfRCjets = vrc_jets->size(); + m_VarRCjetBranches[VarRC + "_" + name + "_pt"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_eta"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_phi"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_e"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_d12"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_d23"].resize(sizeOfRCjets, -999.); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_pt"].resize(sizeOfRCjets, std::vector<float>()); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_eta"].resize(sizeOfRCjets, std::vector<float>()); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_phi"].resize(sizeOfRCjets, std::vector<float>()); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_e"].resize(sizeOfRCjets, std::vector<float>()); + if (m_config->bTagAlgo_MV2c10_used()) { + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_mv2c10"].resize(sizeOfRCjets, std::vector<float>()); + } + + if (m_useVarRCJSS || m_useVarRCAdditionalJSS) { + m_VarRCjetBranches["vrrcjet_" + name + "_pt"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches["vrrcjet_" + name + "_eta"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches["vrrcjet_" + name + "_phi"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches["vrrcjet_" + name + "_e"].resize(sizeOfRCjets, -999.); + } + if (m_useVarRCJSS) { + m_VarRCjetBranches[VarRC + "_" + name + "_tau32_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_tau21_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_tau1_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_tau2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_tau3_clstr"].resize(sizeOfRCjets, -999.); + + m_VarRCjetBranches[VarRC + "_" + name + "_d12_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_d23_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_Qw_clstr"].resize(sizeOfRCjets, -999.); + + m_VarRCjetBranches[VarRC + "_" + name + "_D2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_ECF1_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_ECF2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_ECF3_clstr"].resize(sizeOfRCjets, -999.); + } + if (m_useVarRCAdditionalJSS) { + m_VarRCjetBranches[VarRC + "_" + name + "_gECF332_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF461_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF322_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF331_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF422_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF441_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF212_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF321_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_gECF311_clstr"].resize(sizeOfRCjets, -999.); + + m_VarRCjetBranches[VarRC + "_" + name + "_L1_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_L2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_L3_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_L4_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranches[VarRC + "_" + name + "_L5_clstr"].resize(sizeOfRCjets, -999.); + } + - m_ljet_pt.resize(plEvent.m_largeRJets->size()); - m_ljet_eta.resize(plEvent.m_largeRJets->size()); - m_ljet_phi.resize(plEvent.m_largeRJets->size()); - m_ljet_e.resize(plEvent.m_largeRJets->size()); - m_ljet_Ghosts_BHadron_Final_Count.resize(plEvent.m_largeRJets->size()); - m_ljet_Ghosts_CHadron_Final_Count.resize(plEvent.m_largeRJets->size()); - for (const auto & jetPtr : * plEvent.m_largeRJets) { - m_ljet_pt[i] = jetPtr->pt(); - m_ljet_eta[i] = jetPtr->eta(); - m_ljet_phi[i] = jetPtr->phi(); - m_ljet_e[i] = jetPtr->e(); + unsigned int i = 0; - m_ljet_Ghosts_BHadron_Final_Count[i] = jetPtr->auxdata<int>( "GhostBHadronsFinalCount" ); - m_ljet_Ghosts_CHadron_Final_Count[i] = jetPtr->auxdata<int>( "GhostCHadronsFinalCount" ); + for (auto jet_ptr : *vrc_jets) { + const xAOD::Jet* rc_jet = jet_ptr; - ++i; + m_VarRCjetBranches[VarRC + "_" + name + "_pt"][i] = rc_jet->pt(); + m_VarRCjetBranches[VarRC + "_" + name + "_eta"][i] = rc_jet->eta(); + m_VarRCjetBranches[VarRC + "_" + name + "_phi"][i] = rc_jet->phi(); + m_VarRCjetBranches[VarRC + "_" + name + "_e"][i] = rc_jet->e(); + + m_VarRCjetBranches[VarRC + "_" + name + "_d12"][i] = (VarRCSplit12.isAvailable(*rc_jet)) ? VarRCSplit12(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_d23"][i] = (VarRCSplit23.isAvailable(*rc_jet)) ? VarRCSplit23(*rc_jet) : -999.; + + if (m_useVarRCJSS || m_useVarRCAdditionalJSS) { + m_VarRCjetBranches["vrrcjet_" + name + "_pt"][i] = (RRCJet_pt.isAvailable(*rc_jet)) ? RRCJet_pt(*rc_jet) : -999.; + m_VarRCjetBranches["vrrcjet_" + name + "_eta"][i] = (RRCJet_eta.isAvailable(*rc_jet)) ? RRCJet_eta(*rc_jet) : -999.; + m_VarRCjetBranches["vrrcjet_" + name + "_phi"][i] = (RRCJet_phi.isAvailable(*rc_jet)) ? RRCJet_phi(*rc_jet) : -999.; + m_VarRCjetBranches["vrrcjet_" + name + "_e"][i] = (RRCJet_e.isAvailable(*rc_jet)) ? RRCJet_e(*rc_jet) : -999.; } - } + if (m_useVarRCJSS) { + m_VarRCjetBranches[VarRC + "_" + name + "_tau32_clstr"][i] = (Tau32_clstr.isAvailable(*rc_jet)) ? Tau32_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_tau21_clstr"][i] = (Tau21_clstr.isAvailable(*rc_jet)) ? Tau21_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_tau3_clstr"][i] = (Tau3_clstr.isAvailable(*rc_jet)) ? Tau3_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_tau2_clstr"][i] = (Tau2_clstr.isAvailable(*rc_jet)) ? Tau2_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_tau1_clstr"][i] = (Tau1_clstr.isAvailable(*rc_jet)) ? Tau1_clstr(*rc_jet) : -999.; + + m_VarRCjetBranches[VarRC + "_" + name + "_d12_clstr"][i] = (d12_clstr.isAvailable(*rc_jet)) ? d12_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_d23_clstr"][i] = (d23_clstr.isAvailable(*rc_jet)) ? d23_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_Qw_clstr"][i] = (Qw_clstr.isAvailable(*rc_jet)) ? Qw_clstr(*rc_jet) : -999.; + + m_VarRCjetBranches[VarRC + "_" + name + "_D2_clstr"][i] = (D2_clstr.isAvailable(*rc_jet)) ? D2_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_ECF1_clstr"][i] = (ECF1_clstr.isAvailable(*rc_jet)) ? ECF1_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_ECF2_clstr"][i] = (ECF2_clstr.isAvailable(*rc_jet)) ? ECF2_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_ECF3_clstr"][i] = (ECF3_clstr.isAvailable(*rc_jet)) ? ECF3_clstr(*rc_jet) : -999.; + } + if (m_useVarRCAdditionalJSS) { + m_VarRCjetBranches[VarRC + "_" + name + "_gECF332_clstr"][i] = (gECF332_clstr.isAvailable(*rc_jet)) ? gECF332_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF461_clstr"][i] = (gECF461_clstr.isAvailable(*rc_jet)) ? gECF461_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF322_clstr"][i] = (gECF322_clstr.isAvailable(*rc_jet)) ? gECF322_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF331_clstr"][i] = (gECF331_clstr.isAvailable(*rc_jet)) ? gECF331_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF422_clstr"][i] = (gECF422_clstr.isAvailable(*rc_jet)) ? gECF422_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF441_clstr"][i] = (gECF441_clstr.isAvailable(*rc_jet)) ? gECF441_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF212_clstr"][i] = (gECF212_clstr.isAvailable(*rc_jet)) ? gECF212_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF321_clstr"][i] = (gECF321_clstr.isAvailable(*rc_jet)) ? gECF321_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_gECF311_clstr"][i] = (gECF311_clstr.isAvailable(*rc_jet)) ? gECF311_clstr(*rc_jet) : -999.; + + m_VarRCjetBranches[VarRC + "_" + name + "_L1_clstr"][i] = (L1_clstr.isAvailable(*rc_jet)) ? L1_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_L2_clstr"][i] = (L2_clstr.isAvailable(*rc_jet)) ? L2_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_L3_clstr"][i] = (L3_clstr.isAvailable(*rc_jet)) ? L3_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_L4_clstr"][i] = (L4_clstr.isAvailable(*rc_jet)) ? L4_clstr(*rc_jet) : -999.; + m_VarRCjetBranches[VarRC + "_" + name + "_L5_clstr"][i] = (L5_clstr.isAvailable(*rc_jet)) ? L5_clstr(*rc_jet) : -999.; + } + + + // loop over subjets + const xAOD::Jet* subjet(nullptr); + //const xAOD::BTagging* btag(nullptr); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_pt"][i].clear(); // clear the vector size (otherwise it + // grows out of control!) + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_eta"][i].clear(); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_phi"][i].clear(); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_e"][i].clear(); + if (m_config->bTagAlgo_MV2c10_used()) { + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_mv2c10"][i].clear(); + } + for (auto rc_jet_subjet : rc_jet->getConstituents()) { + subjet = static_cast<const xAOD::Jet*>(rc_jet_subjet->rawConstituent()); + + if (m_config->bTagAlgo_MV2c10_used()) { + //btag = subjet->btagging(); + + //double mvx10(-999.); // b-tagging mv2c10 - //met - if ( m_config->useTruthMET() ){ - m_met_met = plEvent.m_met->met(); - m_met_phi = plEvent.m_met->phi(); + //if (btag) { + // btag->MVx_discriminant("MV2c10", mvx10); + //} else { + // mvx10 = -999.; + //} + //m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_mv2c10"][i].push_back(mvx10); + } + + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_pt"][i].push_back(subjet->pt()); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_eta"][i].push_back(subjet->eta()); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_phi"][i].push_back(subjet->phi()); + m_VarRCjetsubBranches[VarRC + "_" + name + "_sub_e"][i].push_back(subjet->e()); + } // end for-loop over subjets + ++i; + } // end for-loop over re-clustered jets + } // end loop over mass parameters + } // end loop over multipliers for mass scale + } // end if make VarRC jets + // end VarRC jets + + + //met + m_met_met = event.m_met->met(); + m_met_phi = event.m_met->phi(); + + if(m_config->writeMETBuiltWithLooseObjects()) + { + const xAOD::MissingETContainer* mets(nullptr); + if(event.m_isLoose) top::check(evtStore()->retrieve(mets, m_config->sgKeyMissingEtLoose(event.m_hashValue)+"WithLooseObjects"), "Failed to retrieve MET"); + else top::check(evtStore()->retrieve(mets, m_config->sgKeyMissingEt(event.m_hashValue)+"WithLooseObjects"), "Failed to retrieve MET"); + + m_met_met_withLooseObjects=(*mets)["FinalTrk"]->met(); + m_met_phi_withLooseObjects=(*mets)["FinalTrk"]->phi(); + } + + //KLFitter + if (m_config->doKLFitter()) { + unsigned int nPermutations(0), iPerm(0), bestPerm(0); + bool validKLFitter(false); + m_klfitter_selected = 0; + if (event.m_KLFitterResults != nullptr) { + validKLFitter = true; + m_klfitter_selected = 1; + nPermutations = event.m_KLFitterResults->size(); + } + + m_klfitter_selection.resize(nPermutations); + m_klfitter_minuitDidNotConverge.resize(nPermutations); + m_klfitter_fitAbortedDueToNaN.resize(nPermutations); + m_klfitter_atLeastOneFitParameterAtItsLimit.resize(nPermutations); + m_klfitter_invalidTransferFunctionAtConvergence.resize(nPermutations); + + /// Global result + m_klfitter_bestPermutation.resize(nPermutations); + m_klfitter_logLikelihood.resize(nPermutations); + m_klfitter_eventProbability.resize(nPermutations); + m_klfitter_parameters_size.resize(nPermutations); + m_klfitter_parameters.resize(nPermutations); + m_klfitter_parameterErrors.resize(nPermutations); + + if (m_config->KLFitterLH() == "ttbar" || m_config->KLFitterLH() == "ttZTrilepton" || m_config->KLFitterLH() == "ttH" || m_config->KLFitterLH() == "ttbar_JetAngles" || m_config->KLFitterLH() == "ttbar_BoostedLJets") { + /// Model + m_klfitter_model_bhad_pt.resize(nPermutations); + m_klfitter_model_bhad_eta.resize(nPermutations); + m_klfitter_model_bhad_phi.resize(nPermutations); + m_klfitter_model_bhad_E.resize(nPermutations); + m_klfitter_model_bhad_jetIndex.resize(nPermutations); + + m_klfitter_model_blep_pt.resize(nPermutations); + m_klfitter_model_blep_eta.resize(nPermutations); + m_klfitter_model_blep_phi.resize(nPermutations); + m_klfitter_model_blep_E.resize(nPermutations); + m_klfitter_model_blep_jetIndex.resize(nPermutations); + + m_klfitter_model_lq1_pt.resize(nPermutations); + m_klfitter_model_lq1_eta.resize(nPermutations); + m_klfitter_model_lq1_phi.resize(nPermutations); + m_klfitter_model_lq1_E.resize(nPermutations); + m_klfitter_model_lq1_jetIndex.resize(nPermutations); + + if (m_config->KLFitterLH() != "ttbar_BoostedLJets") { + m_klfitter_model_lq2_pt.resize(nPermutations); + m_klfitter_model_lq2_eta.resize(nPermutations); + m_klfitter_model_lq2_phi.resize(nPermutations); + m_klfitter_model_lq2_E.resize(nPermutations); + m_klfitter_model_lq2_jetIndex.resize(nPermutations); + + if (m_config->KLFitterLH() == "ttH") { + m_klfitter_model_Higgs_b1_pt.resize(nPermutations); + m_klfitter_model_Higgs_b1_eta.resize(nPermutations); + m_klfitter_model_Higgs_b1_phi.resize(nPermutations); + m_klfitter_model_Higgs_b1_E.resize(nPermutations); + m_klfitter_model_Higgs_b1_jetIndex.resize(nPermutations); + + m_klfitter_model_Higgs_b2_pt.resize(nPermutations); + m_klfitter_model_Higgs_b2_eta.resize(nPermutations); + m_klfitter_model_Higgs_b2_phi.resize(nPermutations); + m_klfitter_model_Higgs_b2_E.resize(nPermutations); + m_klfitter_model_Higgs_b2_jetIndex.resize(nPermutations); + } } - // Let us write the PDF Info into the branch variable(s). - if ( m_config->doTruthPDFInfo() ) { - // Delegate to helper function. - loadPdfInfo(); + m_klfitter_model_lep_pt.resize(nPermutations); + m_klfitter_model_lep_eta.resize(nPermutations); + m_klfitter_model_lep_phi.resize(nPermutations); + m_klfitter_model_lep_E.resize(nPermutations); + m_klfitter_model_lep_index.resize(nPermutations); + + m_klfitter_model_lepZ1_pt.resize(nPermutations); + m_klfitter_model_lepZ1_eta.resize(nPermutations); + m_klfitter_model_lepZ1_phi.resize(nPermutations); + m_klfitter_model_lepZ1_E.resize(nPermutations); + m_klfitter_model_lepZ1_index.resize(nPermutations); + + m_klfitter_model_lepZ2_pt.resize(nPermutations); + m_klfitter_model_lepZ2_eta.resize(nPermutations); + m_klfitter_model_lepZ2_phi.resize(nPermutations); + m_klfitter_model_lepZ2_E.resize(nPermutations); + m_klfitter_model_lepZ2_index.resize(nPermutations); + + m_klfitter_model_nu_pt.resize(nPermutations); + m_klfitter_model_nu_eta.resize(nPermutations); + m_klfitter_model_nu_phi.resize(nPermutations); + m_klfitter_model_nu_E.resize(nPermutations); + } else if (m_config->KLFitterLH() == "ttbar_AllHadronic") { + m_klfitter_model_b_from_top1_pt.resize(nPermutations); + m_klfitter_model_b_from_top1_eta.resize(nPermutations); + m_klfitter_model_b_from_top1_phi.resize(nPermutations); + m_klfitter_model_b_from_top1_E.resize(nPermutations); + m_klfitter_model_b_from_top1_jetIndex.resize(nPermutations); + + m_klfitter_model_b_from_top2_pt.resize(nPermutations); + m_klfitter_model_b_from_top2_eta.resize(nPermutations); + m_klfitter_model_b_from_top2_phi.resize(nPermutations); + m_klfitter_model_b_from_top2_E.resize(nPermutations); + m_klfitter_model_b_from_top2_jetIndex.resize(nPermutations); + + m_klfitter_model_lj1_from_top1_pt.resize(nPermutations); + m_klfitter_model_lj1_from_top1_eta.resize(nPermutations); + m_klfitter_model_lj1_from_top1_phi.resize(nPermutations); + m_klfitter_model_lj1_from_top1_E.resize(nPermutations); + m_klfitter_model_lj1_from_top1_jetIndex.resize(nPermutations); + + m_klfitter_model_lj2_from_top1_pt.resize(nPermutations); + m_klfitter_model_lj2_from_top1_eta.resize(nPermutations); + m_klfitter_model_lj2_from_top1_phi.resize(nPermutations); + m_klfitter_model_lj2_from_top1_E.resize(nPermutations); + m_klfitter_model_lj2_from_top1_jetIndex.resize(nPermutations); + + m_klfitter_model_lj1_from_top2_pt.resize(nPermutations); + m_klfitter_model_lj1_from_top2_eta.resize(nPermutations); + m_klfitter_model_lj1_from_top2_phi.resize(nPermutations); + m_klfitter_model_lj1_from_top2_E.resize(nPermutations); + m_klfitter_model_lj1_from_top2_jetIndex.resize(nPermutations); + + m_klfitter_model_lj2_from_top2_pt.resize(nPermutations); + m_klfitter_model_lj2_from_top2_eta.resize(nPermutations); + m_klfitter_model_lj2_from_top2_phi.resize(nPermutations); + m_klfitter_model_lj2_from_top2_E.resize(nPermutations); + m_klfitter_model_lj2_from_top2_jetIndex.resize(nPermutations); + } + + if (validKLFitter) { + for (const auto* const klPtr : *event.m_KLFitterResults) { + m_klfitter_selection[iPerm] = "unknown"; + std::hash<std::string> st_hash; + for (unsigned int s = 0; s < m_config->allSelectionNames()->size(); ++s) { + if (st_hash(m_config->allSelectionNames()->at(s)) == klPtr->selectionCode()) { + m_klfitter_selection[iPerm] = m_config->allSelectionNames()->at(s); + break; + } + } + m_klfitter_minuitDidNotConverge[iPerm] = klPtr->minuitDidNotConverge(); + m_klfitter_fitAbortedDueToNaN[iPerm] = klPtr->fitAbortedDueToNaN(); + m_klfitter_atLeastOneFitParameterAtItsLimit[iPerm] = klPtr->atLeastOneFitParameterAtItsLimit(); + m_klfitter_invalidTransferFunctionAtConvergence[iPerm] = klPtr->invalidTransferFunctionAtConvergence(); + + /// Global result + m_klfitter_bestPermutation[iPerm] = klPtr->bestPermutation(); + if (klPtr->bestPermutation() == 1) { + bestPerm = iPerm; + } + m_klfitter_logLikelihood[iPerm] = klPtr->logLikelihood(); + m_klfitter_eventProbability[iPerm] = klPtr->eventProbability(); + m_klfitter_parameters_size[iPerm] = klPtr->parameters().size(); + m_klfitter_parameters[iPerm] = klPtr->parameters(); + m_klfitter_parameterErrors[iPerm] = klPtr->parameterErrors(); + + /// Model + if (m_config->KLFitterLH() == "ttbar" || m_config->KLFitterLH() == "ttZTrilepton" || m_config->KLFitterLH() == "ttH" || m_config->KLFitterLH() == "ttbar_JetAngles" || m_config->KLFitterLH() == "ttbar_BoostedLJets") { + m_klfitter_model_bhad_pt[iPerm] = klPtr->model_bhad_pt(); + m_klfitter_model_bhad_eta[iPerm] = klPtr->model_bhad_eta(); + m_klfitter_model_bhad_phi[iPerm] = klPtr->model_bhad_phi(); + m_klfitter_model_bhad_E[iPerm] = klPtr->model_bhad_E(); + m_klfitter_model_bhad_jetIndex[iPerm] = klPtr->model_bhad_jetIndex(); + + m_klfitter_model_blep_pt[iPerm] = klPtr->model_blep_pt(); + m_klfitter_model_blep_eta[iPerm] = klPtr->model_blep_eta(); + m_klfitter_model_blep_phi[iPerm] = klPtr->model_blep_phi(); + m_klfitter_model_blep_E[iPerm] = klPtr->model_blep_E(); + m_klfitter_model_blep_jetIndex[iPerm] = klPtr->model_blep_jetIndex(); + + m_klfitter_model_lq1_pt[iPerm] = klPtr->model_lq1_pt(); + m_klfitter_model_lq1_eta[iPerm] = klPtr->model_lq1_eta(); + m_klfitter_model_lq1_phi[iPerm] = klPtr->model_lq1_phi(); + m_klfitter_model_lq1_E[iPerm] = klPtr->model_lq1_E(); + m_klfitter_model_lq1_jetIndex[iPerm] = klPtr->model_lq1_jetIndex(); + + if (m_config->KLFitterLH() != "ttbar_BoostedLJets") { + m_klfitter_model_lq2_pt[iPerm] = klPtr->model_lq2_pt(); + m_klfitter_model_lq2_eta[iPerm] = klPtr->model_lq2_eta(); + m_klfitter_model_lq2_phi[iPerm] = klPtr->model_lq2_phi(); + m_klfitter_model_lq2_E[iPerm] = klPtr->model_lq2_E(); + m_klfitter_model_lq2_jetIndex[iPerm] = klPtr->model_lq2_jetIndex(); + + if (m_config->KLFitterLH() == "ttH") { + m_klfitter_model_Higgs_b1_pt[iPerm] = klPtr->model_Higgs_b1_pt(); + m_klfitter_model_Higgs_b1_eta[iPerm] = klPtr->model_Higgs_b1_eta(); + m_klfitter_model_Higgs_b1_phi[iPerm] = klPtr->model_Higgs_b1_phi(); + m_klfitter_model_Higgs_b1_E[iPerm] = klPtr->model_Higgs_b1_E(); + m_klfitter_model_Higgs_b1_jetIndex[iPerm] = klPtr->model_Higgs_b1_jetIndex(); + + m_klfitter_model_Higgs_b2_pt[iPerm] = klPtr->model_Higgs_b2_pt(); + m_klfitter_model_Higgs_b2_eta[iPerm] = klPtr->model_Higgs_b2_eta(); + m_klfitter_model_Higgs_b2_phi[iPerm] = klPtr->model_Higgs_b2_phi(); + m_klfitter_model_Higgs_b2_E[iPerm] = klPtr->model_Higgs_b2_E(); + m_klfitter_model_Higgs_b2_jetIndex[iPerm] = klPtr->model_Higgs_b2_jetIndex(); + } + } + m_klfitter_model_lep_pt[iPerm] = klPtr->model_lep_pt(); + m_klfitter_model_lep_eta[iPerm] = klPtr->model_lep_eta(); + m_klfitter_model_lep_phi[iPerm] = klPtr->model_lep_phi(); + m_klfitter_model_lep_E[iPerm] = klPtr->model_lep_E(); + m_klfitter_model_lep_index[iPerm] = klPtr->model_lep_index(); + + m_klfitter_model_lepZ1_pt[iPerm] = klPtr->model_lepZ1_pt(); + m_klfitter_model_lepZ1_eta[iPerm] = klPtr->model_lepZ1_eta(); + m_klfitter_model_lepZ1_phi[iPerm] = klPtr->model_lepZ1_phi(); + m_klfitter_model_lepZ1_E[iPerm] = klPtr->model_lepZ1_E(); + m_klfitter_model_lepZ1_index[iPerm] = klPtr->model_lepZ1_index(); + + m_klfitter_model_lepZ2_pt[iPerm] = klPtr->model_lepZ2_pt(); + m_klfitter_model_lepZ2_eta[iPerm] = klPtr->model_lepZ2_eta(); + m_klfitter_model_lepZ2_phi[iPerm] = klPtr->model_lepZ2_phi(); + m_klfitter_model_lepZ2_E[iPerm] = klPtr->model_lepZ2_E(); + m_klfitter_model_lepZ2_index[iPerm] = klPtr->model_lepZ2_index(); + + m_klfitter_model_nu_pt[iPerm] = klPtr->model_nu_pt(); + m_klfitter_model_nu_eta[iPerm] = klPtr->model_nu_eta(); + m_klfitter_model_nu_phi[iPerm] = klPtr->model_nu_phi(); + m_klfitter_model_nu_E[iPerm] = klPtr->model_nu_E(); + } else if (m_config->KLFitterLH() == "ttbar_AllHadronic") { + m_klfitter_model_b_from_top1_pt[iPerm] = klPtr->model_b_from_top1_pt(); + m_klfitter_model_b_from_top1_eta[iPerm] = klPtr->model_b_from_top1_eta(); + m_klfitter_model_b_from_top1_phi[iPerm] = klPtr->model_b_from_top1_phi(); + m_klfitter_model_b_from_top1_E[iPerm] = klPtr->model_b_from_top1_E(); + m_klfitter_model_b_from_top1_jetIndex[iPerm] = klPtr->model_b_from_top1_jetIndex(); + + m_klfitter_model_b_from_top2_pt[iPerm] = klPtr->model_b_from_top2_pt(); + m_klfitter_model_b_from_top2_eta[iPerm] = klPtr->model_b_from_top2_eta(); + m_klfitter_model_b_from_top2_phi[iPerm] = klPtr->model_b_from_top2_phi(); + m_klfitter_model_b_from_top2_E[iPerm] = klPtr->model_b_from_top2_E(); + m_klfitter_model_b_from_top2_jetIndex[iPerm] = klPtr->model_b_from_top2_jetIndex(); + + m_klfitter_model_lj1_from_top1_pt[iPerm] = klPtr->model_lj1_from_top1_pt(); + m_klfitter_model_lj1_from_top1_eta[iPerm] = klPtr->model_lj1_from_top1_eta(); + m_klfitter_model_lj1_from_top1_phi[iPerm] = klPtr->model_lj1_from_top1_phi(); + m_klfitter_model_lj1_from_top1_E[iPerm] = klPtr->model_lj1_from_top1_E(); + m_klfitter_model_lj1_from_top1_jetIndex[iPerm] = klPtr->model_lj1_from_top1_jetIndex(); + + m_klfitter_model_lj2_from_top1_pt[iPerm] = klPtr->model_lj2_from_top1_pt(); + m_klfitter_model_lj2_from_top1_eta[iPerm] = klPtr->model_lj2_from_top1_eta(); + m_klfitter_model_lj2_from_top1_phi[iPerm] = klPtr->model_lj2_from_top1_phi(); + m_klfitter_model_lj2_from_top1_E[iPerm] = klPtr->model_lj2_from_top1_E(); + m_klfitter_model_lj2_from_top1_jetIndex[iPerm] = klPtr->model_lj2_from_top1_jetIndex(); + + m_klfitter_model_lj1_from_top2_pt[iPerm] = klPtr->model_lj1_from_top2_pt(); + m_klfitter_model_lj1_from_top2_eta[iPerm] = klPtr->model_lj1_from_top2_eta(); + m_klfitter_model_lj1_from_top2_phi[iPerm] = klPtr->model_lj1_from_top2_phi(); + m_klfitter_model_lj1_from_top2_E[iPerm] = klPtr->model_lj1_from_top2_E(); + m_klfitter_model_lj1_from_top2_jetIndex[iPerm] = klPtr->model_lj1_from_top2_jetIndex(); + + m_klfitter_model_lj2_from_top2_pt[iPerm] = klPtr->model_lj2_from_top2_pt(); + m_klfitter_model_lj2_from_top2_eta[iPerm] = klPtr->model_lj2_from_top2_eta(); + m_klfitter_model_lj2_from_top2_phi[iPerm] = klPtr->model_lj2_from_top2_phi(); + m_klfitter_model_lj2_from_top2_E[iPerm] = klPtr->model_lj2_from_top2_E(); + m_klfitter_model_lj2_from_top2_jetIndex[iPerm] = klPtr->model_lj2_from_top2_jetIndex(); + } + + + ++iPerm; } - if (m_config->doMCGeneratorWeights()) { - // delegate to helper function. - loadMCGeneratorWeights(); + // now take the best permutation and build the tops and the ttbar system! + if (m_config->KLFitterLH() == "ttbar" || m_config->KLFitterLH() == "ttZTrilepton" || m_config->KLFitterLH() == "ttH" || m_config->KLFitterLH() == "ttbar_JetAngles") { + if (nPermutations != 0) { + TLorentzVector bhad, blep, lq1, lq2, lep, nu, top_had, top_lep, ttbar; + + bhad.SetPtEtaPhiE(m_klfitter_model_bhad_pt[bestPerm], m_klfitter_model_bhad_eta[bestPerm], m_klfitter_model_bhad_phi[bestPerm], m_klfitter_model_bhad_E[bestPerm]); + blep.SetPtEtaPhiE(m_klfitter_model_blep_pt[bestPerm], m_klfitter_model_blep_eta[bestPerm], m_klfitter_model_blep_phi[bestPerm], m_klfitter_model_blep_E[bestPerm]); + lq1.SetPtEtaPhiE(m_klfitter_model_lq1_pt[bestPerm], m_klfitter_model_lq1_eta[bestPerm], m_klfitter_model_lq1_phi[bestPerm], m_klfitter_model_lq1_E[bestPerm]); + lq2.SetPtEtaPhiE(m_klfitter_model_lq2_pt[bestPerm], m_klfitter_model_lq2_eta[bestPerm], m_klfitter_model_lq2_phi[bestPerm], m_klfitter_model_lq2_E[bestPerm]); + lep.SetPtEtaPhiE(m_klfitter_model_lep_pt[bestPerm], m_klfitter_model_lep_eta[bestPerm], m_klfitter_model_lep_phi[bestPerm], m_klfitter_model_lep_E[bestPerm]); + nu.SetPtEtaPhiE(m_klfitter_model_nu_pt[bestPerm], m_klfitter_model_nu_eta[bestPerm], m_klfitter_model_nu_phi[bestPerm], m_klfitter_model_nu_E[bestPerm]); + + top_had = bhad + lq1 + lq2; + top_lep = blep + lep + nu; + ttbar = top_had + top_lep; + + m_klfitter_bestPerm_topLep_pt = top_lep.Pt(); + m_klfitter_bestPerm_topLep_eta = top_lep.Eta(); + m_klfitter_bestPerm_topLep_phi = top_lep.Phi(); + m_klfitter_bestPerm_topLep_E = top_lep.E(); + m_klfitter_bestPerm_topLep_m = top_lep.M(); + + m_klfitter_bestPerm_topHad_pt = top_had.Pt(); + m_klfitter_bestPerm_topHad_eta = top_had.Eta(); + m_klfitter_bestPerm_topHad_phi = top_had.Phi(); + m_klfitter_bestPerm_topHad_E = top_had.E(); + m_klfitter_bestPerm_topHad_m = top_had.M(); + + m_klfitter_bestPerm_ttbar_pt = ttbar.Pt(); + m_klfitter_bestPerm_ttbar_eta = ttbar.Eta(); + m_klfitter_bestPerm_ttbar_phi = ttbar.Phi(); + m_klfitter_bestPerm_ttbar_E = ttbar.E(); + m_klfitter_bestPerm_ttbar_m = ttbar.M(); + } } + } + } - // Let us write the PDF weights into the branch variable(s). - if( m_config->saveLHAPDFEvent() ){ - // Delegate to helper function. - loadPdfWeights(); + if (m_config->doPseudoTop()) { + const xAOD::PseudoTopResultContainer* pseudoTopResultContainer(nullptr); + const xAOD::PseudoTopResult* pseudoTopResult(nullptr); + + if ((!event.m_isLoose && evtStore()->contains<xAOD::PseudoTopResultContainer>(topConfig()->sgKeyPseudoTop(event.m_hashValue))) || + (event.m_isLoose && evtStore()->contains<xAOD::PseudoTopResultContainer>(topConfig()->sgKeyPseudoTopLoose(event.m_hashValue)))) { + if (!event.m_isLoose) { + top::check(evtStore()->retrieve(pseudoTopResultContainer, topConfig()->sgKeyPseudoTop(event.m_hashValue)), "Failed to retrieve PseudoTop"); + } else { + top::check(evtStore()->retrieve(pseudoTopResultContainer, topConfig()->sgKeyPseudoTopLoose(event.m_hashValue)), "Failed to retrieve PseudoTop"); } - if(m_config->doPseudoTop()){ + pseudoTopResult = pseudoTopResultContainer->at(0); - const xAOD::PseudoTopResultContainer* pseudoTopResultContainer(nullptr); - const xAOD::PseudoTopResult* pseudoTopResult(nullptr); + m_PseudoTop_Reco_ttbar_pt = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_ttbar_pt"); + m_PseudoTop_Reco_ttbar_eta = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_ttbar_eta"); + m_PseudoTop_Reco_ttbar_phi = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_ttbar_phi"); + m_PseudoTop_Reco_ttbar_m = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_ttbar_m"); - if (evtStore()->contains<xAOD::PseudoTopResultContainer>(m_config->sgKeyPseudoTop(0))) { - top::check(evtStore()->retrieve(pseudoTopResultContainer, m_config->sgKeyPseudoTop(0)), "Failed to retrieve PseudoTop"); + m_PseudoTop_Reco_top_lep_pt = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_lep_pt"); + m_PseudoTop_Reco_top_lep_eta = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_lep_eta"); + m_PseudoTop_Reco_top_lep_phi = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_lep_phi"); + m_PseudoTop_Reco_top_lep_m = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_lep_m"); - pseudoTopResult = pseudoTopResultContainer->at(0); + m_PseudoTop_Reco_top_had_pt = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_had_pt"); + m_PseudoTop_Reco_top_had_eta = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_had_eta"); + m_PseudoTop_Reco_top_had_phi = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_had_phi"); + m_PseudoTop_Reco_top_had_m = pseudoTopResult->auxdecor<float>("PseudoTop_Reco_top_had_m"); + } + } + } + + void EventSaverFlatNtuple::fillEvent(const top::Event& event) { + //do it! + m_treeManagers[event.m_ttreeIndex]->fill(); + } + + void EventSaverFlatNtuple::saveTruthEvent() { + this->cleanTruthEvent(); + this->calculateTruthEvent(); + this->fillTruthEvent(); + } + + void EventSaverFlatNtuple::cleanTruthEvent() { + /* Doing nothing for now, but we should put here the (re-)initialisation to dummy values + * of all variables later calculated in cleanTruthEvent() + * For example all weights set to 1, all vectors cleaned, all kinematic or angular variables set to -99999. + */ + } + + void EventSaverFlatNtuple::calculateTruthEvent() { + + const xAOD::EventInfo* eventInfo(nullptr); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + + m_weight_mc = eventInfo->auxdataConst<float>("AnalysisTop_eventWeight"); + m_eventNumber = eventInfo->eventNumber(); + m_runNumber = eventInfo->runNumber(); + m_mcChannelNumber = eventInfo->mcChannelNumber(); + m_mu = eventInfo->averageInteractionsPerCrossing(); + m_mu_actual = eventInfo->actualInteractionsPerCrossing(); + + if (m_config->doPileupReweighting() && !m_config->isTruthDxAOD()) { + m_weight_pileup = eventInfo->auxdataConst<float>("PileupWeight"); + m_randomRunNumber = eventInfo->auxdataConst<unsigned int>("RandomRunNumber"); + } else { + m_weight_pileup = NAN; + m_randomRunNumber = 0; + } - m_PseudoTop_Particle_ttbar_pt = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_ttbar_pt"); - m_PseudoTop_Particle_ttbar_eta = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_ttbar_eta"); - m_PseudoTop_Particle_ttbar_phi = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_ttbar_phi"); - m_PseudoTop_Particle_ttbar_m = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_ttbar_m"); + //MC particle + if (m_config->useTruthParticles() && m_config->doTruthBlockInfo()) { + const xAOD::TruthParticleContainer* truth(nullptr); + top::check(evtStore()->retrieve(truth, m_config->sgKeyMCParticle()), "Failed to retrieve TruthParticleContainer"); + + if (truth != nullptr) { + unsigned int i(0); + unsigned int truthSize = truth->size(); + m_mc_pt.resize(truthSize); + m_mc_eta.resize(truthSize); + m_mc_phi.resize(truthSize); + m_mc_e.resize(truthSize); + m_mc_pdgId.resize(truthSize); + m_mc_charge.resize(truthSize); + m_mc_status.resize(truthSize); + m_mc_barcode.resize(truthSize); + + for (const auto* const mcPtr : *truth) { + // Fix for + // Warning in <TVector3::PseudoRapidity>: transvers momentum = 0! return +/- 10e10 + + float eta(-999.9); + + if (!(mcPtr->p4().CosTheta() * mcPtr->p4().CosTheta() >= 1 && mcPtr->p4().Pz() != 0)) { + eta = mcPtr->eta(); + } - m_PseudoTop_Particle_top_lep_pt = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_lep_pt"); - m_PseudoTop_Particle_top_lep_eta = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_lep_eta"); - m_PseudoTop_Particle_top_lep_phi = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_lep_phi"); - m_PseudoTop_Particle_top_lep_m = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_lep_m"); + m_mc_pt[i] = mcPtr->pt(); + m_mc_eta[i] = eta; + m_mc_phi[i] = mcPtr->phi(); + m_mc_e[i] = mcPtr->e(); + m_mc_pdgId[i] = mcPtr->pdgId(); + m_mc_charge[i] = mcPtr->charge(); + m_mc_status[i] = mcPtr->status(); + m_mc_barcode[i] = mcPtr->barcode(); - m_PseudoTop_Particle_top_had_pt = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_had_pt"); - m_PseudoTop_Particle_top_had_eta = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_had_eta"); - m_PseudoTop_Particle_top_had_phi = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_had_phi"); - m_PseudoTop_Particle_top_had_m = pseudoTopResult -> auxdecor<float>("PseudoTop_Particle_top_had_m"); + ++i; + } + } + } + if (m_config->doTopPartonHistory()) { + const xAOD::PartonHistoryContainer* partonHistoryContainer(nullptr); + const xAOD::PartonHistory* partonHistory(nullptr); + if (evtStore()->contains<xAOD::PartonHistoryContainer>(m_config->sgKeyTopPartonHistory())) { + top::check(evtStore()->retrieve(partonHistoryContainer, m_config->sgKeyTopPartonHistory()), "Failed to retrieve Top Parton History"); + if (partonHistoryContainer->size() == 1) { + partonHistory = partonHistoryContainer->at(0); + } + } - } - } + if (partonHistory != nullptr) { + if (!m_config->isTopPartonHistoryRegisteredInNtuple()) { + registerObjectIntoTruthTree(*(partonHistory)); + m_config->setTopPartonHistoryRegisteredInNtuple(); + } + saveObjectIntoTruthTree(*(partonHistory)); + } + } + } + + void EventSaverFlatNtuple::fillTruthEvent() { + if(m_config->doTopPartonLevel()) m_truthTreeManager->fill(); + } + void EventSaverFlatNtuple::saveParticleLevelEvent(const top::ParticleLevelEvent& plEvent) { + // Quick return if particle level is disabled. + if (not m_config->doTopParticleLevel()) { + return; + } + // No need to attempt to write out anything for non-MC data. + if (!m_config->isMC()) { + return; + } + this->cleanParticleLevelEvent(); + this->calculateParticleLevelEvent(plEvent); + this->fillParticleLevelEvent(); + } + + void EventSaverFlatNtuple::cleanParticleLevelEvent() { + /* Doing nothing for now, but we should put here the (re-)initialisation to dummy values + * of all variables later calculated in calculateParticleLevelEvent(const top::ParticleLevelEvent& plEvent) + * For example all weights set to 1, all vectors cleaned, all kinematic or angular variables set to -99999. + */ + } + + void EventSaverFlatNtuple::calculateParticleLevelEvent(const top::ParticleLevelEvent& plEvent) { + for (auto& selectionDecision : m_particleLevel_SelectionDecisions) { + selectionDecision.second = plEvent.m_selectionDecisions[ selectionDecision.first ]; + } + m_weight_mc = plEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); - //do it! - m_particleLevelTreeManager->fill(); + m_eventNumber = plEvent.m_info->eventNumber(); + m_runNumber = plEvent.m_info->runNumber(); + m_mcChannelNumber = plEvent.m_info->mcChannelNumber(); + + m_mu = plEvent.m_info->averageInteractionsPerCrossing(); + m_mu_actual = plEvent.m_info->actualInteractionsPerCrossing(); + + if (m_config->doPileupReweighting() && !m_config->isTruthDxAOD()) { + m_weight_pileup = plEvent.m_info->auxdataConst<float>("PileupWeight"); + m_randomRunNumber = plEvent.m_info->auxdataConst<unsigned int>("RandomRunNumber"); + } else { + m_weight_pileup = NAN; + m_randomRunNumber = 0; } - void EventSaverFlatNtuple::saveUpgradeEvent(const top::ParticleLevelEvent& upgradeEvent){ - // Quick return if upgrade is disabled. No tree will be created! - if ( not m_config->HLLHC() ){ - return; - } + //electrons + if (m_config->useTruthElectrons()) { + unsigned int i = 0; + + m_el_pt.resize(plEvent.m_electrons->size()); + m_el_eta.resize(plEvent.m_electrons->size()); + m_el_phi.resize(plEvent.m_electrons->size()); + m_el_e.resize(plEvent.m_electrons->size()); + m_el_charge.resize(plEvent.m_electrons->size()); + + m_el_pt_bare.resize(plEvent.m_electrons->size()); + m_el_eta_bare.resize(plEvent.m_electrons->size()); + m_el_phi_bare.resize(plEvent.m_electrons->size()); + m_el_e_bare.resize(plEvent.m_electrons->size()); + + m_el_true_type.resize(plEvent.m_electrons->size()); + m_el_true_origin.resize(plEvent.m_electrons->size()); + + for (const auto& elPtr : *plEvent.m_electrons) { + m_el_pt[i] = elPtr->pt(); + m_el_eta[i] = elPtr->eta(); + m_el_phi[i] = elPtr->phi(); + m_el_e[i] = elPtr->e(); + m_el_charge[i] = elPtr->charge(); + + m_el_pt_bare[i] = elPtr->auxdata<float>("pt_bare"); + m_el_eta_bare[i] = elPtr->auxdata<float>("eta_bare"); + m_el_phi_bare[i] = elPtr->auxdata<float>("phi_bare"); + m_el_e_bare[i] = elPtr->auxdata<float>("e_bare"); + + if(elPtr->isAvailable<unsigned int>("particleType")) m_el_true_type[i] = elPtr->auxdata<unsigned int>("particleType"); + else if(elPtr->isAvailable<unsigned int>("classifierParticleType")) m_el_true_type[i] = elPtr->auxdata<unsigned int>("classifierParticleType"); + else m_el_true_type[i] = 0; + + if(elPtr->isAvailable<unsigned int>("particleOrigin")) m_el_true_origin[i] = elPtr->auxdata<unsigned int>("particleOrigin"); + else if(elPtr->isAvailable<unsigned int>("classifierParticleOrigin")) m_el_true_origin[i] = elPtr->auxdata<unsigned int>("classifierParticleOrigin"); + else m_el_true_origin[i] = 0; + + ++i; + } + } - // Setup the TTree. This should come at the very top in order to make sure - // that event for non-MC data, the TTree will be created (but remains empty). - setupUpgradeTreeManager( /*upgradeEvent*/ ); + //muons + if (m_config->useTruthMuons()) { + unsigned int i = 0; + + m_mu_pt.resize(plEvent.m_muons->size()); + m_mu_eta.resize(plEvent.m_muons->size()); + m_mu_phi.resize(plEvent.m_muons->size()); + m_mu_e.resize(plEvent.m_muons->size()); + m_mu_charge.resize(plEvent.m_muons->size()); + + m_mu_pt_bare.resize(plEvent.m_muons->size()); + m_mu_eta_bare.resize(plEvent.m_muons->size()); + m_mu_phi_bare.resize(plEvent.m_muons->size()); + m_mu_e_bare.resize(plEvent.m_muons->size()); + + m_mu_true_type.resize(plEvent.m_muons->size()); + m_mu_true_origin.resize(plEvent.m_muons->size()); + + for (const auto& muPtr : *plEvent.m_muons) { + m_mu_pt[i] = muPtr->pt(); + m_mu_eta[i] = muPtr->eta(); + m_mu_phi[i] = muPtr->phi(); + m_mu_e[i] = muPtr->e(); + m_mu_charge[i] = muPtr->charge(); + + m_mu_pt_bare[i] = muPtr->auxdata<float>("pt_bare"); + m_mu_eta_bare[i] = muPtr->auxdata<float>("eta_bare"); + m_mu_phi_bare[i] = muPtr->auxdata<float>("phi_bare"); + m_mu_e_bare[i] = muPtr->auxdata<float>("e_bare"); + + if(muPtr->isAvailable<unsigned int>("particleType")) m_mu_true_type[i] = muPtr->auxdata<unsigned int>("particleType"); + else if(muPtr->isAvailable<unsigned int>("classifierParticleType")) m_mu_true_type[i] = muPtr->auxdata<unsigned int>("classifierParticleType"); + else m_mu_true_type[i] = 0; + + if(muPtr->isAvailable<unsigned int>("particleOrigin")) m_mu_true_origin[i] = muPtr->auxdata<unsigned int>("particleOrigin"); + else if(muPtr->isAvailable<unsigned int>("classifierParticleOrigin")) m_mu_true_origin[i] = muPtr->auxdata<unsigned int>("classifierParticleOrigin"); + else m_mu_true_origin[i] = 0; - // No need to attempt to write out anything for non-MC data. - if ( ! m_config->isMC() ){ - return; + ++i; + } + + i=0; + if(m_config->useSoftMuons()) { + + m_softmu_pt.resize(plEvent.m_softmuons->size()); + m_softmu_eta.resize(plEvent.m_softmuons->size()); + m_softmu_phi.resize(plEvent.m_softmuons->size()); + m_softmu_e.resize(plEvent.m_softmuons->size()); + m_softmu_charge.resize(plEvent.m_softmuons->size()); + + m_softmu_true_type.resize(plEvent.m_softmuons->size()); + m_softmu_true_origin.resize(plEvent.m_softmuons->size()); + + if(m_config->softmuonAdditionalTruthInfo()) + { + m_softmu_parton_origin_flag.resize(plEvent.m_softmuons->size()); + m_softmu_particle_origin_flag.resize(plEvent.m_softmuons->size()); + m_softmu_parent_pdgid.resize(plEvent.m_softmuons->size()); + m_softmu_b_hadron_parent_pdgid.resize(plEvent.m_softmuons->size()); + m_softmu_c_hadron_parent_pdgid.resize(plEvent.m_softmuons->size()); } - // to get the fixed mc weight - const xAOD::TruthEventContainer * truthEvent(nullptr); - top::check( evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth event container" ); - unsigned int truthEventSize = truthEvent->size(); - top::check( truthEventSize==1 , "Failed to retrieve truth PDF info - truth event container size is different from 1 (strange)" ); - -// m_weight_mc = plEvent.m_info->mcEventWeight(); - m_weight_mc = truthEvent->at(0)->weights()[0];// FIXME temporary bugfix - - m_eventNumber = upgradeEvent.m_info->eventNumber(); - m_runNumber = upgradeEvent.m_info->runNumber(); - m_mcChannelNumber = upgradeEvent.m_info->mcChannelNumber(); - - m_mu = upgradeEvent.m_info->averageInteractionsPerCrossing(); - - // save electrons - unsigned int i = 0; - m_el_pt.resize(upgradeEvent.m_electrons->size()); - m_el_eta.resize(upgradeEvent.m_electrons->size()); - m_el_phi.resize(upgradeEvent.m_electrons->size()); - m_el_e.resize(upgradeEvent.m_electrons->size()); - m_el_charge.resize(upgradeEvent.m_electrons->size()); - - for (const auto elPtr : * upgradeEvent.m_electrons) { - m_el_pt[i] = elPtr->pt(); - m_el_eta[i] = elPtr->eta(); - m_el_phi[i] = elPtr->phi(); - m_el_e[i] = elPtr->e(); - m_el_charge[i] = elPtr->charge(); - ++i; - } - - // save muons - i = 0; - m_mu_pt.resize(upgradeEvent.m_muons->size()); - m_mu_eta.resize(upgradeEvent.m_muons->size()); - m_mu_phi.resize(upgradeEvent.m_muons->size()); - m_mu_e.resize(upgradeEvent.m_muons->size()); - m_mu_charge.resize(upgradeEvent.m_muons->size()); - - for (const auto muPtr : * upgradeEvent.m_muons) { - m_mu_pt[i] = muPtr->pt(); - m_mu_eta[i] = muPtr->eta(); - m_mu_phi[i] = muPtr->phi(); - m_mu_e[i] = muPtr->e(); - m_mu_charge[i] = muPtr->charge(); - ++i; - } - - // save jets - i = 0; - m_jet_pt.resize(upgradeEvent.m_jets->size()); - m_jet_eta.resize(upgradeEvent.m_jets->size()); - m_jet_phi.resize(upgradeEvent.m_jets->size()); - m_jet_e.resize(upgradeEvent.m_jets->size()); - m_jet_mv1eff.resize(upgradeEvent.m_jets->size()); - m_jet_isPileup.resize(upgradeEvent.m_jets->size()); - m_jet_Ghosts_BHadron_Final_Count.resize(upgradeEvent.m_jets->size()); - m_jet_Ghosts_CHadron_Final_Count.resize(upgradeEvent.m_jets->size()); - for (const auto & jetPtr : * upgradeEvent.m_jets) { - m_jet_pt[i] = jetPtr->pt(); - m_jet_eta[i] = jetPtr->eta(); - m_jet_phi[i] = jetPtr->phi(); - m_jet_e[i] = jetPtr->e(); - - m_jet_mv1eff[i] = jetPtr->auxdata<float>("mv1TagEff"); - - if(jetPtr->auxdata<int>("pileUp")==0) { - m_jet_isPileup[i]=0; - m_jet_Ghosts_BHadron_Final_Count[i] = jetPtr->auxdata<int>( "GhostBHadronsFinalCount" ); - m_jet_Ghosts_CHadron_Final_Count[i] = jetPtr->auxdata<int>( "GhostCHadronsFinalCount" ); - } else { - m_jet_isPileup[i]=1; - m_jet_Ghosts_BHadron_Final_Count[i] = 0; - m_jet_Ghosts_CHadron_Final_Count[i] = 0; - } - - ++i; - } - - // MET - m_met_met = upgradeEvent.m_met->met(); - m_met_phi = upgradeEvent.m_met->phi(); - - // fill the tree - m_upgradeTreeManager->fill(); - - }//saveUpgradeEvent - - void EventSaverFlatNtuple::finalize() - { - m_outputFile->Write(); - } - - void EventSaverFlatNtuple::loadPdfInfo(){ - const xAOD::TruthEventContainer * truthEvent(nullptr); - top::check( evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth PDF info" ); - - if (truthEvent != nullptr) { - unsigned int i(0); - unsigned int truthEventSize = truthEvent->size(); - m_PDFinfo_X1.resize(truthEventSize); - m_PDFinfo_X2.resize(truthEventSize); - m_PDFinfo_PDGID1.resize(truthEventSize); - m_PDFinfo_PDGID2.resize(truthEventSize); - m_PDFinfo_Q.resize(truthEventSize); - m_PDFinfo_XF1.resize(truthEventSize); - m_PDFinfo_XF2.resize(truthEventSize); - - for (const auto * const tePtr : * truthEvent) { - // LMTODO: ASG tools/pdfInfo() can't be used yet, since scale Q is not available - // xAOD::TruthEvent::PdfInfo _pdfInfo=tePtr->pdfInfo(); - // if _pdfInfo.valid() { m_PDFinfo_X1[i] = _pdfInfo.x1; //etc. } - std::string PDFinfoVarName="X1"; - if (truthEvent->isAvailable<float>(PDFinfoVarName)) - m_PDFinfo_X1[i] = (*tePtr).auxdataConst< float >( PDFinfoVarName ); - PDFinfoVarName="X2"; - if (truthEvent->isAvailable<float>(PDFinfoVarName)) - m_PDFinfo_X2[i] = (*tePtr).auxdataConst< float >( PDFinfoVarName ); - PDFinfoVarName="PDGID1"; - if (truthEvent->isAvailable<int>(PDFinfoVarName)) - m_PDFinfo_PDGID1[i] = (*tePtr).auxdataConst< int >( PDFinfoVarName ); - PDFinfoVarName="PDGID2"; - if (truthEvent->isAvailable<int>(PDFinfoVarName)) - m_PDFinfo_PDGID2[i] = (*tePtr).auxdataConst< int >( PDFinfoVarName ); - PDFinfoVarName="XF1"; - if (truthEvent->isAvailable<float>(PDFinfoVarName)) - m_PDFinfo_XF1[i] = (*tePtr).auxdataConst< float >( PDFinfoVarName ); - PDFinfoVarName="XF2"; - if (truthEvent->isAvailable<float>(PDFinfoVarName)) - m_PDFinfo_XF2[i] = (*tePtr).auxdataConst< float >( PDFinfoVarName ); - PDFinfoVarName="Q"; - if (truthEvent->isAvailable<float>(PDFinfoVarName)) - m_PDFinfo_Q[i] = (*tePtr).auxdataConst< float >( PDFinfoVarName ); - ++i; + for (const auto& muPtr : *plEvent.m_softmuons) { + m_softmu_pt[i] = muPtr->pt(); + m_softmu_eta[i] = muPtr->eta(); + m_softmu_phi[i] = muPtr->phi(); + m_softmu_e[i] = muPtr->e(); + m_softmu_charge[i] = muPtr->charge(); + + if(muPtr->isAvailable<unsigned int>("particleType")) m_softmu_true_type[i] = muPtr->auxdata<unsigned int>("particleType"); + else if(muPtr->isAvailable<unsigned int>("classifierParticleType")) m_softmu_true_type[i] = muPtr->auxdata<unsigned int>("classifierParticleType"); + else m_softmu_true_type[i] = 0; + + if(muPtr->isAvailable<unsigned int>("particleOrigin")) m_softmu_true_origin[i] = muPtr->auxdata<unsigned int>("particleOrigin"); + else if(muPtr->isAvailable<unsigned int>("classifierParticleOrigin")) m_softmu_true_origin[i] = muPtr->auxdata<unsigned int>("classifierParticleOrigin"); + else m_softmu_true_origin[i] = 0; + + if(m_config->softmuonAdditionalTruthInfo()) + { + + m_softmu_parton_origin_flag[i]=0; + if(m_config->softmuonAdditionalTruthInfoCheckPartonOrigin()) + { + static const SG::AuxElement::Accessor<top::LepPartonOriginFlag> leppartonoriginflag("LepPartonOriginFlag"); + if(leppartonoriginflag.isAvailable(*muPtr)) m_softmu_parton_origin_flag[i]=static_cast<int>(leppartonoriginflag(*muPtr)); } - } + m_softmu_particle_origin_flag[i]=0; + m_softmu_parent_pdgid[i]=0; + m_softmu_b_hadron_parent_pdgid[i]=0; + m_softmu_c_hadron_parent_pdgid[i]=0; + static const SG::AuxElement::Accessor<top::LepParticleOriginFlag> lepparticleoriginflag("LepParticleOriginFlag"); + if(lepparticleoriginflag.isAvailable(*muPtr)) m_softmu_particle_origin_flag[i]=static_cast<int>(lepparticleoriginflag(*muPtr)); + + static const SG::AuxElement::Accessor<const xAOD::TruthParticle*> Mother("truthMotherLink"); + const xAOD::TruthParticle* mother = 0; + if(Mother.isAvailable(*muPtr)) mother=Mother(*muPtr); + if(mother) m_softmu_parent_pdgid[i]=mother->pdgId(); + + static const SG::AuxElement::Accessor<const xAOD::TruthParticle*> BMother("truthBMotherLink"); + const xAOD::TruthParticle* Bmother = 0; + if(BMother.isAvailable(*muPtr)) Bmother=BMother(*muPtr); + if(Bmother) m_softmu_b_hadron_parent_pdgid[i]=Bmother->pdgId(); + + static const SG::AuxElement::Accessor<const xAOD::TruthParticle*> CMother("truthCMotherLink"); + const xAOD::TruthParticle* Cmother = 0; + if(CMother.isAvailable(*muPtr)) Cmother=CMother(*muPtr); + if(Cmother) m_softmu_c_hadron_parent_pdgid[i]=Cmother->pdgId(); + + if(m_config->softmuonAdditionalTruthInfoDoVerbose()) asg::msgUserCode::ATH_MSG_INFO("writing truth soft muon with pt="<<m_softmu_pt[i] <<" parton_origin_flag="<<m_softmu_parton_origin_flag[i]<<" particle_origin_flag="<<m_softmu_particle_origin_flag[i]<<" parent_pdg_id="<<m_softmu_parent_pdgid[i]<<" b_hadron_parent_pdg_id="<<m_softmu_b_hadron_parent_pdgid[i]<<" c_hadron_parent_pdg_id="<<m_softmu_c_hadron_parent_pdgid[i]); + } + + ++i; + } + }//end of soft muons part + }//end of muons part + + //photons + if (m_config->useTruthPhotons()) { + unsigned int i(0); + m_ph_pt.resize(plEvent.m_photons->size()); + m_ph_eta.resize(plEvent.m_photons->size()); + m_ph_phi.resize(plEvent.m_photons->size()); + m_ph_e.resize(plEvent.m_photons->size()); + for (const auto* const phPtr : *plEvent.m_photons) { + m_ph_pt[i] = phPtr->pt(); + m_ph_eta[i] = phPtr->eta(); + m_ph_phi[i] = phPtr->phi(); + m_ph_e[i] = phPtr->e(); + + ++i; + } + } + + static const SG::AuxElement::ConstAccessor<int> ghostBHadronsFinalCount("GhostBHadronsFinalCount"); + static const SG::AuxElement::ConstAccessor<int> ghostCHadronsFinalCount("GhostCHadronsFinalCount"); + + //jets + if (m_config->useTruthJets()) { + unsigned int i = 0; + + m_jet_pt.resize(plEvent.m_jets->size()); + m_jet_eta.resize(plEvent.m_jets->size()); + m_jet_phi.resize(plEvent.m_jets->size()); + m_jet_e.resize(plEvent.m_jets->size()); + m_jet_Ghosts_BHadron_Final_Count.resize(plEvent.m_jets->size()); + m_jet_Ghosts_CHadron_Final_Count.resize(plEvent.m_jets->size()); + for (const auto& jetPtr : *plEvent.m_jets) { + m_jet_pt[i] = jetPtr->pt(); + m_jet_eta[i] = jetPtr->eta(); + m_jet_phi[i] = jetPtr->phi(); + m_jet_e[i] = jetPtr->e(); + + if(ghostBHadronsFinalCount.isAvailable(*jetPtr)) { + m_jet_Ghosts_BHadron_Final_Count[i] = ghostBHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostBHadronFinalCount auxdata"); + m_jet_Ghosts_BHadron_Final_Count[i] = 0; + } + + if(ghostCHadronsFinalCount.isAvailable(*jetPtr)) { + m_jet_Ghosts_CHadron_Final_Count[i] = ghostCHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostCHadronFinalCount auxdata"); + m_jet_Ghosts_CHadron_Final_Count[i] = 0; + } + + ++i; + } } - void EventSaverFlatNtuple::loadPdfWeights(){ - const xAOD::TruthEventContainer * truthEvent(nullptr); - top::check( evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth PDF info" ); + //large R jets + if (m_config->useTruthLargeRJets()) { + unsigned int i = 0; + + m_ljet_pt.resize(plEvent.m_largeRJets->size()); + m_ljet_eta.resize(plEvent.m_largeRJets->size()); + m_ljet_phi.resize(plEvent.m_largeRJets->size()); + m_ljet_e.resize(plEvent.m_largeRJets->size()); + m_ljet_Ghosts_BHadron_Final_Count.resize(plEvent.m_largeRJets->size()); + m_ljet_Ghosts_CHadron_Final_Count.resize(plEvent.m_largeRJets->size()); + for (const auto& jetPtr : *plEvent.m_largeRJets) { + m_ljet_pt[i] = jetPtr->pt(); + m_ljet_eta[i] = jetPtr->eta(); + m_ljet_phi[i] = jetPtr->phi(); + m_ljet_e[i] = jetPtr->e(); + + if(ghostBHadronsFinalCount.isAvailable(*jetPtr)) { + m_ljet_Ghosts_BHadron_Final_Count[i] = ghostBHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostBHadronFinalCount auxdata"); + m_ljet_Ghosts_BHadron_Final_Count[i] = 0; + } + + if(ghostCHadronsFinalCount.isAvailable(*jetPtr)) { + m_ljet_Ghosts_CHadron_Final_Count[i] = ghostCHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostCHadronFinalCount auxdata"); + m_ljet_Ghosts_CHadron_Final_Count[i] = 0; + } - for( auto tePtr : * truthEvent ){ - for( const std::string & pdf_name : m_config->LHAPDFSets() ){ - if( tePtr->isAvailable<std::vector<float> >( "AnalysisTop_" + pdf_name + "_Weights") ){ - m_PDF_eventWeights[ pdf_name ] = tePtr->auxdata<std::vector<float> >("AnalysisTop_" + pdf_name + "_Weights"); - } - } + ++i; + } + } + + //Taus + if (m_config->useTruthTaus()) { + unsigned int i = 0; + + m_tau_pt.resize(plEvent.m_taus->size()); + m_tau_eta.resize(plEvent.m_taus->size()); + m_tau_phi.resize(plEvent.m_taus->size()); + m_tau_e.resize(plEvent.m_taus->size()); + m_tau_charge.resize(plEvent.m_taus->size()); + m_tau_isHadronic.resize(plEvent.m_taus->size()); + + for (const auto& tauPtr : *plEvent.m_taus) { + m_tau_pt[i] = tauPtr->pt(); + m_tau_eta[i] = tauPtr->eta(); + m_tau_phi[i] = tauPtr->phi(); + m_tau_e[i] = tauPtr->e(); + m_tau_charge[i] = tauPtr->charge(); + if (tauPtr->isAvailable<char>("IsHadronicTau")) { + m_tau_isHadronic[i] = tauPtr->auxdata<char>("IsHadronicTau"); } + + ++i; + } } - void EventSaverFlatNtuple::loadMCGeneratorWeights(){ - const xAOD::TruthEventContainer * truthEvent(nullptr); - top::check( evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()) , "Failed to retrieve MC Generator weights - impossible to retrieve truth event container" ); - unsigned int truthEventSize = truthEvent->size(); - top::check( truthEventSize==1 , "Failed to retrieve truth PDF info - truth event container size is different from 1 (strange)" ); - m_mc_generator_weights = truthEvent->at(0)->weights(); + if (m_makeRCJets) { + // re-clustered jet substructure + static const SG::AuxElement::ConstAccessor<float> RCSplit12("Split12"); + static const SG::AuxElement::ConstAccessor<float> RCSplit23("Split23"); + + // re-clustered jet substructure from clusters + static const SG::AuxElement::ConstAccessor<float> Tau21_clstr("Tau21_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau32_clstr("Tau32_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau3_clstr("Tau3_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau2_clstr("Tau2_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau1_clstr("Tau1_clstr"); + static const SG::AuxElement::ConstAccessor<float> D2_clstr("D2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF1_clstr("ECF1_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF2_clstr("ECF2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF3_clstr("ECF3_clstr"); + static const SG::AuxElement::ConstAccessor<float> d12_clstr("d12_clstr"); + static const SG::AuxElement::ConstAccessor<float> d23_clstr("d23_clstr"); + static const SG::AuxElement::ConstAccessor<float> Qw_clstr("Qw_clstr"); + static const SG::AuxElement::ConstAccessor<float> nconstituent_clstr("nconstituent_clstr"); + + static const SG::AuxElement::ConstAccessor<float> gECF332_clstr("gECF332_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF461_clstr("gECF461_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF322_clstr("gECF322_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF331_clstr("gECF331_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF422_clstr("gECF422_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF441_clstr("gECF441_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF212_clstr("gECF212_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF321_clstr("gECF321_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF311_clstr("gECF311_clstr"); + static const SG::AuxElement::ConstAccessor<float> L1_clstr("L1_clstr"); + static const SG::AuxElement::ConstAccessor<float> L2_clstr("L2_clstr"); + static const SG::AuxElement::ConstAccessor<float> L3_clstr("L3_clstr"); + static const SG::AuxElement::ConstAccessor<float> L4_clstr("L4_clstr"); + static const SG::AuxElement::ConstAccessor<float> L5_clstr("L5_clstr"); + // store also the jet that is rebuilt to calculate the JSS + static const SG::AuxElement::ConstAccessor<float> RRCJet_pt("RRCJet_pt"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_eta("RRCJet_eta"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_phi("RRCJet_phi"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_e("RRCJet_e"); + + + // Initialize the vectors to be saved as branches + unsigned int sizeOfRCjets(plEvent.m_RCJets.size()); + + m_rcjet_pt.clear(); + m_rcjet_eta.clear(); + m_rcjet_phi.clear(); + m_rcjet_e.clear(); + m_rcjet_d12.clear(); + m_rcjet_d23.clear(); + m_rcjetsub_pt.clear(); + m_rcjetsub_eta.clear(); + m_rcjetsub_phi.clear(); + m_rcjetsub_e.clear(); + m_rcjetsub_Ghosts_BHadron_Final_Count.clear(); + m_rcjetsub_Ghosts_CHadron_Final_Count.clear(); + + + m_rcjet_tau32_clstr.clear(); + m_rcjet_tau21_clstr.clear(); + m_rcjet_tau3_clstr.clear(); + m_rcjet_tau2_clstr.clear(); + m_rcjet_tau1_clstr.clear(); + m_rcjet_D2_clstr.clear(); + m_rcjet_ECF1_clstr.clear(); + m_rcjet_ECF2_clstr.clear(); + m_rcjet_ECF3_clstr.clear(); + m_rcjet_d12_clstr.clear(); + m_rcjet_d23_clstr.clear(); + m_rcjet_Qw_clstr.clear(); + m_rcjet_nconstituent_clstr.clear(); + + m_rcjet_gECF332_clstr.clear(); + m_rcjet_gECF461_clstr.clear(); + m_rcjet_gECF322_clstr.clear(); + m_rcjet_gECF331_clstr.clear(); + m_rcjet_gECF422_clstr.clear(); + m_rcjet_gECF441_clstr.clear(); + m_rcjet_gECF212_clstr.clear(); + m_rcjet_gECF321_clstr.clear(); + m_rcjet_gECF311_clstr.clear(); + m_rcjet_L1_clstr.clear(); + m_rcjet_L2_clstr.clear(); + m_rcjet_L3_clstr.clear(); + m_rcjet_L4_clstr.clear(); + m_rcjet_L5_clstr.clear(); + + m_rcjet_pt.resize(sizeOfRCjets, -999.); + m_rcjet_eta.resize(sizeOfRCjets, -999.); + m_rcjet_phi.resize(sizeOfRCjets, -999.); + m_rcjet_e.resize(sizeOfRCjets, -999.); + m_rcjet_d12.resize(sizeOfRCjets, -999.); + m_rcjet_d23.resize(sizeOfRCjets, -999.); + m_rcjetsub_pt.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_eta.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_phi.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_e.resize(sizeOfRCjets, std::vector<float>()); + m_rcjetsub_Ghosts_BHadron_Final_Count.resize(sizeOfRCjets, std::vector<int>()); + m_rcjetsub_Ghosts_CHadron_Final_Count.resize(sizeOfRCjets, std::vector<int>()); + + if (m_useRCJSS || m_useRCAdditionalJSS) { + m_rrcjet_pt.resize(sizeOfRCjets, -999.); + m_rrcjet_eta.resize(sizeOfRCjets, -999.); + m_rrcjet_phi.resize(sizeOfRCjets, -999.); + m_rrcjet_e.resize(sizeOfRCjets, -999.); + } + if (m_useRCJSS) { + m_rcjet_tau32_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau21_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau1_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_tau3_clstr.resize(sizeOfRCjets, -999.); + + m_rcjet_d12_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_d23_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_Qw_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_nconstituent_clstr.resize(sizeOfRCjets, -999.); + + m_rcjet_D2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_ECF1_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_ECF2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_ECF3_clstr.resize(sizeOfRCjets, -999.); + } + if (m_useRCAdditionalJSS) { + m_rcjet_gECF332_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF461_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF322_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF331_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF422_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF441_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF212_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF321_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_gECF311_clstr.resize(sizeOfRCjets, -999.); + + m_rcjet_L1_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L2_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L3_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L4_clstr.resize(sizeOfRCjets, -999.); + m_rcjet_L5_clstr.resize(sizeOfRCjets, -999.); + } + unsigned int i = 0; + for (auto rc_jet : plEvent.m_RCJets) { + m_rcjet_pt[i] = rc_jet->pt(); + m_rcjet_eta[i] = rc_jet->eta(); + m_rcjet_phi[i] = rc_jet->phi(); + m_rcjet_e[i] = rc_jet->e(); + + m_rcjet_d12[i] = (RCSplit12.isAvailable(*rc_jet)) ? RCSplit12(*rc_jet) : -999.; + m_rcjet_d23[i] = (RCSplit23.isAvailable(*rc_jet)) ? RCSplit23(*rc_jet) : -999.; + + if (m_useRCJSS || m_useRCAdditionalJSS) { + m_rrcjet_pt[i] = (RRCJet_pt.isAvailable(*rc_jet)) ? RRCJet_pt(*rc_jet) : -999.; + m_rrcjet_eta[i] = (RRCJet_eta.isAvailable(*rc_jet)) ? RRCJet_eta(*rc_jet) : -999.; + m_rrcjet_phi[i] = (RRCJet_phi.isAvailable(*rc_jet)) ? RRCJet_phi(*rc_jet) : -999.; + m_rrcjet_e[i] = (RRCJet_e.isAvailable(*rc_jet)) ? RRCJet_e(*rc_jet) : -999.; + } + if (m_useRCJSS) { + m_rcjet_tau32_clstr[i] = (Tau32_clstr.isAvailable(*rc_jet)) ? Tau32_clstr(*rc_jet) : -999.; + m_rcjet_tau21_clstr[i] = (Tau21_clstr.isAvailable(*rc_jet)) ? Tau21_clstr(*rc_jet) : -999.; + m_rcjet_tau3_clstr[i] = (Tau3_clstr.isAvailable(*rc_jet)) ? Tau3_clstr(*rc_jet) : -999.; + m_rcjet_tau2_clstr[i] = (Tau2_clstr.isAvailable(*rc_jet)) ? Tau2_clstr(*rc_jet) : -999.; + m_rcjet_tau1_clstr[i] = (Tau1_clstr.isAvailable(*rc_jet)) ? Tau1_clstr(*rc_jet) : -999.; + + m_rcjet_d12_clstr[i] = (d12_clstr.isAvailable(*rc_jet)) ? d12_clstr(*rc_jet) : -999.; + m_rcjet_d23_clstr[i] = (d23_clstr.isAvailable(*rc_jet)) ? d23_clstr(*rc_jet) : -999.; + m_rcjet_Qw_clstr[i] = (Qw_clstr.isAvailable(*rc_jet)) ? Qw_clstr(*rc_jet) : -999.; + m_rcjet_nconstituent_clstr[i] = (nconstituent_clstr.isAvailable(*rc_jet)) ? nconstituent_clstr(*rc_jet) : -999.; + + m_rcjet_D2_clstr[i] = (D2_clstr.isAvailable(*rc_jet)) ? D2_clstr(*rc_jet) : -999.; + m_rcjet_ECF1_clstr[i] = (ECF1_clstr.isAvailable(*rc_jet)) ? ECF1_clstr(*rc_jet) : -999.; + m_rcjet_ECF2_clstr[i] = (ECF2_clstr.isAvailable(*rc_jet)) ? ECF2_clstr(*rc_jet) : -999.; + m_rcjet_ECF3_clstr[i] = (ECF3_clstr.isAvailable(*rc_jet)) ? ECF3_clstr(*rc_jet) : -999.; + } + if (m_useRCAdditionalJSS) { + m_rcjet_gECF332_clstr[i] = (gECF332_clstr.isAvailable(*rc_jet)) ? gECF332_clstr(*rc_jet) : -999.; + m_rcjet_gECF461_clstr[i] = (gECF461_clstr.isAvailable(*rc_jet)) ? gECF461_clstr(*rc_jet) : -999.; + m_rcjet_gECF322_clstr[i] = (gECF322_clstr.isAvailable(*rc_jet)) ? gECF322_clstr(*rc_jet) : -999.; + m_rcjet_gECF331_clstr[i] = (gECF331_clstr.isAvailable(*rc_jet)) ? gECF331_clstr(*rc_jet) : -999.; + m_rcjet_gECF422_clstr[i] = (gECF422_clstr.isAvailable(*rc_jet)) ? gECF422_clstr(*rc_jet) : -999.; + m_rcjet_gECF441_clstr[i] = (gECF441_clstr.isAvailable(*rc_jet)) ? gECF441_clstr(*rc_jet) : -999.; + m_rcjet_gECF212_clstr[i] = (gECF212_clstr.isAvailable(*rc_jet)) ? gECF212_clstr(*rc_jet) : -999.; + m_rcjet_gECF321_clstr[i] = (gECF321_clstr.isAvailable(*rc_jet)) ? gECF321_clstr(*rc_jet) : -999.; + m_rcjet_gECF311_clstr[i] = (gECF311_clstr.isAvailable(*rc_jet)) ? gECF311_clstr(*rc_jet) : -999.; + + m_rcjet_L1_clstr[i] = (L1_clstr.isAvailable(*rc_jet)) ? L1_clstr(*rc_jet) : -999.; + m_rcjet_L2_clstr[i] = (L2_clstr.isAvailable(*rc_jet)) ? L2_clstr(*rc_jet) : -999.; + m_rcjet_L3_clstr[i] = (L3_clstr.isAvailable(*rc_jet)) ? L3_clstr(*rc_jet) : -999.; + m_rcjet_L4_clstr[i] = (L4_clstr.isAvailable(*rc_jet)) ? L4_clstr(*rc_jet) : -999.; + m_rcjet_L5_clstr[i] = (L5_clstr.isAvailable(*rc_jet)) ? L5_clstr(*rc_jet) : -999.; + } + + // loop over subjets + m_rcjetsub_pt[i].clear(); // clear the vector size (otherwise it grows out of control!) + m_rcjetsub_eta[i].clear(); + m_rcjetsub_phi[i].clear(); + m_rcjetsub_e[i].clear(); + + const xAOD::Jet* subjet(nullptr); + for (auto rc_jet_subjet : rc_jet->getConstituents()) { + subjet = static_cast<const xAOD::Jet*>(rc_jet_subjet->rawConstituent()); + m_rcjetsub_pt[i].push_back(subjet->pt()); + m_rcjetsub_eta[i].push_back(subjet->eta()); + m_rcjetsub_phi[i].push_back(subjet->phi()); + m_rcjetsub_e[i].push_back(subjet->e()); + + if(ghostBHadronsFinalCount.isAvailable(*subjet)) { + m_rcjetsub_Ghosts_BHadron_Final_Count[i].push_back(ghostBHadronsFinalCount(*subjet)); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostBHadronFinalCount auxdata"); + m_rcjetsub_Ghosts_BHadron_Final_Count[i].push_back(0); + } + + if(ghostCHadronsFinalCount.isAvailable(*subjet)) { + m_rcjetsub_Ghosts_CHadron_Final_Count[i].push_back(ghostCHadronsFinalCount(*subjet)); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostCHadronFinalCount auxdata"); + m_rcjetsub_Ghosts_CHadron_Final_Count[i].push_back(0); + } + + } // end for-loop over subjets + ++i; + } // end for-loop over re-clustered jets } + // VarRC jets + if (m_makeVarRCJets) { + std::string VarRC = "vrcjet"; + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + + // re-clustered jet substructure + static const SG::AuxElement::ConstAccessor<float> VarRCSplit12("Split12"); + static const SG::AuxElement::ConstAccessor<float> VarRCSplit23("Split23"); + // re-clustered jet substructure from clusters + static const SG::AuxElement::ConstAccessor<float> Tau21_clstr("Tau21_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau32_clstr("Tau32_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau3_clstr("Tau3_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau2_clstr("Tau2_clstr"); + static const SG::AuxElement::ConstAccessor<float> Tau1_clstr("Tau1_clstr"); + static const SG::AuxElement::ConstAccessor<float> D2_clstr("D2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF1_clstr("ECF1_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF2_clstr("ECF2_clstr"); + static const SG::AuxElement::ConstAccessor<float> ECF3_clstr("ECF3_clstr"); + static const SG::AuxElement::ConstAccessor<float> d12_clstr("d12_clstr"); + static const SG::AuxElement::ConstAccessor<float> d23_clstr("d23_clstr"); + static const SG::AuxElement::ConstAccessor<float> Qw_clstr("Qw_clstr"); + + static const SG::AuxElement::ConstAccessor<float> gECF332_clstr("gECF332_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF461_clstr("gECF461_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF322_clstr("gECF322_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF331_clstr("gECF331_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF422_clstr("gECF422_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF441_clstr("gECF441_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF212_clstr("gECF212_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF321_clstr("gECF321_clstr"); + static const SG::AuxElement::ConstAccessor<float> gECF311_clstr("gECF311_clstr"); + static const SG::AuxElement::ConstAccessor<float> L1_clstr("L1_clstr"); + static const SG::AuxElement::ConstAccessor<float> L2_clstr("L2_clstr"); + static const SG::AuxElement::ConstAccessor<float> L3_clstr("L3_clstr"); + static const SG::AuxElement::ConstAccessor<float> L4_clstr("L4_clstr"); + static const SG::AuxElement::ConstAccessor<float> L5_clstr("L5_clstr"); + // store also the jet that is rebuilt to calculate the JSS + static const SG::AuxElement::ConstAccessor<float> RRCJet_pt("RRCJet_pt"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_eta("RRCJet_eta"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_phi("RRCJet_phi"); + static const SG::AuxElement::ConstAccessor<float> RRCJet_e("RRCJet_e"); + + // Initialize the vectors to be saved as branches + + xAOD::JetContainer* vrc_jets = plEvent.m_VarRCJets[name].get(); + unsigned int sizeOfRCjets = vrc_jets->size(); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_pt"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_eta"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_phi"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_e"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d12"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d23"].resize(sizeOfRCjets, -999.); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_pt"].resize(sizeOfRCjets, std::vector<float>()); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_eta"].resize(sizeOfRCjets, std::vector<float>()); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_phi"].resize(sizeOfRCjets, std::vector<float>()); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_e"].resize(sizeOfRCjets, std::vector<float>()); + if (m_useVarRCJSS || m_useVarRCAdditionalJSS) { + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_pt"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_eta"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_phi"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_e"].resize(sizeOfRCjets, -999.); + } + if (m_useVarRCJSS) { + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau32_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau21_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau1_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau3_clstr"].resize(sizeOfRCjets, -999.); + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d12_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d23_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_Qw_clstr"].resize(sizeOfRCjets, -999.); + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_D2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_ECF1_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_ECF2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_ECF3_clstr"].resize(sizeOfRCjets, -999.); + } + if (m_useVarRCAdditionalJSS) { + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF332_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF461_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF322_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF331_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF422_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF441_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF212_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF321_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF311_clstr"].resize(sizeOfRCjets, -999.); + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L1_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L2_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L3_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L4_clstr"].resize(sizeOfRCjets, -999.); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L5_clstr"].resize(sizeOfRCjets, -999.); + } - // This bit is new - // It is not optimal and can do with a lot of improvement - // Consider it a first pass - // - // We can save xAOD objects into flat ntuple by looking at their SG::AuxElement data - // - // inspired by: - // https://svnweb.cern.ch/trac/atlasoff/browser/Event/xAOD/xAODCore/tags/xAODCore-00-00-93/Root/PrintHelpers.cxx + unsigned int i = 0; - void EventSaverFlatNtuple::registerObjectIntoTruthTree(const SG::AuxElement& obj) - { - // If the container doesn't have an auxiliary store, bail now: - if (!obj.container()->getConstStore()) - return; - - // Get a convenience pointer to the aux type registry: - SG::AuxTypeRegistry& reg = SG::AuxTypeRegistry::instance(); - - // Get the auxiliary IDs of the object: - const SG::auxid_set_t& auxids = - ( obj.container()->getConstStore() ? - obj.container()->getConstStore()->getAuxIDs() : - obj.getConstStore()->getAuxIDs() ); - - // find the variables and fill them - for (SG::auxid_t auxid : auxids) { - // get the type of the variable - const std::type_info* ti = reg.getType( auxid ); - // get the name of the variable - const std::string name = reg.getName( auxid ); - - // Add variable - if (*ti == typeid( int ) ){ - m_extraTruthVars_int.insert( std::make_pair( name , new int ) ); + for (auto jet_ptr : *vrc_jets) { + const xAOD::Jet* rc_jet = jet_ptr; + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_pt"][i] = rc_jet->pt(); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_eta"][i] = rc_jet->eta(); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_phi"][i] = rc_jet->phi(); + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_e"][i] = rc_jet->e(); + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d12"][i] = (VarRCSplit12.isAvailable(*rc_jet)) ? VarRCSplit12(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d23"][i] = (VarRCSplit23.isAvailable(*rc_jet)) ? VarRCSplit23(*rc_jet) : -999.; + + if (m_useVarRCJSS || m_useVarRCAdditionalJSS) { + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_pt"][i] = (RRCJet_pt.isAvailable(*rc_jet)) ? RRCJet_pt(*rc_jet) : -999.; + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_eta"][i] = (RRCJet_eta.isAvailable(*rc_jet)) ? RRCJet_eta(*rc_jet) : -999.; + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_phi"][i] = (RRCJet_phi.isAvailable(*rc_jet)) ? RRCJet_phi(*rc_jet) : -999.; + m_VarRCjetBranchesParticle["vrrcjet_" + name + "_e"][i] = (RRCJet_e.isAvailable(*rc_jet)) ? RRCJet_e(*rc_jet) : -999.; } - else if (*ti == typeid( float ) ){ - m_extraTruthVars_float.insert( std::make_pair( name , new float ) ); + if (m_useVarRCJSS) { + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau32_clstr"][i] = (Tau32_clstr.isAvailable(*rc_jet)) ? Tau32_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau21_clstr"][i] = (Tau21_clstr.isAvailable(*rc_jet)) ? Tau21_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau3_clstr"][i] = (Tau3_clstr.isAvailable(*rc_jet)) ? Tau3_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau2_clstr"][i] = (Tau2_clstr.isAvailable(*rc_jet)) ? Tau2_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_tau1_clstr"][i] = (Tau1_clstr.isAvailable(*rc_jet)) ? Tau1_clstr(*rc_jet) : -999.; + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d12_clstr"][i] = (d12_clstr.isAvailable(*rc_jet)) ? d12_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_d23_clstr"][i] = (d23_clstr.isAvailable(*rc_jet)) ? d23_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_Qw_clstr"][i] = (Qw_clstr.isAvailable(*rc_jet)) ? Qw_clstr(*rc_jet) : -999.; + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_D2_clstr"][i] = (D2_clstr.isAvailable(*rc_jet)) ? D2_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_ECF1_clstr"][i] = (ECF1_clstr.isAvailable(*rc_jet)) ? ECF1_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_ECF2_clstr"][i] = (ECF2_clstr.isAvailable(*rc_jet)) ? ECF2_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_ECF3_clstr"][i] = (ECF3_clstr.isAvailable(*rc_jet)) ? ECF3_clstr(*rc_jet) : -999.; } - else { - ATH_MSG_INFO("insertObjectIntoTruthTree - you need another variable map for more types!"); + if (m_useVarRCAdditionalJSS) { + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF332_clstr"][i] = (gECF332_clstr.isAvailable(*rc_jet)) ? gECF332_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF461_clstr"][i] = (gECF461_clstr.isAvailable(*rc_jet)) ? gECF461_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF322_clstr"][i] = (gECF322_clstr.isAvailable(*rc_jet)) ? gECF322_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF331_clstr"][i] = (gECF331_clstr.isAvailable(*rc_jet)) ? gECF331_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF422_clstr"][i] = (gECF422_clstr.isAvailable(*rc_jet)) ? gECF422_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF441_clstr"][i] = (gECF441_clstr.isAvailable(*rc_jet)) ? gECF441_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF212_clstr"][i] = (gECF212_clstr.isAvailable(*rc_jet)) ? gECF212_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF321_clstr"][i] = (gECF321_clstr.isAvailable(*rc_jet)) ? gECF321_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_gECF311_clstr"][i] = (gECF311_clstr.isAvailable(*rc_jet)) ? gECF311_clstr(*rc_jet) : -999.; + + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L1_clstr"][i] = (L1_clstr.isAvailable(*rc_jet)) ? L1_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L2_clstr"][i] = (L2_clstr.isAvailable(*rc_jet)) ? L2_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L3_clstr"][i] = (L3_clstr.isAvailable(*rc_jet)) ? L3_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L4_clstr"][i] = (L4_clstr.isAvailable(*rc_jet)) ? L4_clstr(*rc_jet) : -999.; + m_VarRCjetBranchesParticle[VarRC + "_" + name + "_L5_clstr"][i] = (L5_clstr.isAvailable(*rc_jet)) ? L5_clstr(*rc_jet) : -999.; } - } - // add the variables to the truthTreeManager - for (std::unordered_map<std::string,int*>::const_iterator i=m_extraTruthVars_int.begin();i!=m_extraTruthVars_int.end();++i) { - m_truthTreeManager->makeOutputVariable(*(*i).second,(*i).first); + // loop over subjets + const xAOD::Jet* subjet(nullptr); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_pt"][i].clear(); // clear the vector size + // (otherwise it grows out of + // control!) + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_eta"][i].clear(); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_phi"][i].clear(); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_e"][i].clear(); + for (auto rc_jet_subjet : rc_jet->getConstituents()) { + subjet = static_cast<const xAOD::Jet*>(rc_jet_subjet->rawConstituent()); + + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_pt"][i].push_back(subjet->pt()); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_eta"][i].push_back(subjet->eta()); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_phi"][i].push_back(subjet->phi()); + m_VarRCjetsubBranchesParticle[VarRC + "_" + name + "_sub_e"][i].push_back(subjet->e()); + } // end for-loop over subjets + ++i; + } // end for-loop over re-clustered jets + } // end loop over mass parameters + } // end loop over multipliers for mass scale + } // end if make VarRC jets + // end VarRC jets + + + + //met + if (m_config->useTruthMET()) { + m_met_met = plEvent.m_met->met(); + m_met_phi = plEvent.m_met->phi(); + } + + if (m_config->doPseudoTop()) { + const xAOD::PseudoTopResultContainer* pseudoTopResultContainer(nullptr); + const xAOD::PseudoTopResult* pseudoTopResult(nullptr); + + if (evtStore()->contains<xAOD::PseudoTopResultContainer>(m_config->sgKeyPseudoTop(0))) { + top::check(evtStore()->retrieve(pseudoTopResultContainer, m_config->sgKeyPseudoTop(0)), "Failed to retrieve PseudoTop"); + + pseudoTopResult = pseudoTopResultContainer->at(0); + + m_PseudoTop_Particle_ttbar_pt = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_ttbar_pt"); + m_PseudoTop_Particle_ttbar_eta = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_ttbar_eta"); + m_PseudoTop_Particle_ttbar_phi = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_ttbar_phi"); + m_PseudoTop_Particle_ttbar_m = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_ttbar_m"); + + m_PseudoTop_Particle_top_lep_pt = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_lep_pt"); + m_PseudoTop_Particle_top_lep_eta = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_lep_eta"); + m_PseudoTop_Particle_top_lep_phi = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_lep_phi"); + m_PseudoTop_Particle_top_lep_m = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_lep_m"); + + m_PseudoTop_Particle_top_had_pt = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_had_pt"); + m_PseudoTop_Particle_top_had_eta = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_had_eta"); + m_PseudoTop_Particle_top_had_phi = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_had_phi"); + m_PseudoTop_Particle_top_had_m = pseudoTopResult->auxdecor<float>("PseudoTop_Particle_top_had_m"); + } + } + } + + void EventSaverFlatNtuple::fillParticleLevelEvent() { + //do it! + m_particleLevelTreeManager->fill(); + } + + void EventSaverFlatNtuple::saveUpgradeEvent(const top::ParticleLevelEvent& upgradeEvent) { + // Quick return if upgrade is disabled. + if (not m_config->HLLHC()) { + return; + } + // No need to attempt to write out anything for non-MC data. + if (!m_config->isMC()) { + return; + } + this->cleanUpgradeEvent(); + this->calculateUpgradeEvent(upgradeEvent); + this->fillUpgradeEvent(); + } + + void EventSaverFlatNtuple::cleanUpgradeEvent() { + /* Doing nothing for now, but we should put here the (re-)initialisation to dummy values + * of all variables later calculated in calculateParticleLevelEvent(const top::ParticleLevelEvent& plEvent) + * For example all weights set to 1, all vectors cleaned, all kinematic or angular variables set to -99999. + */ + } + + void EventSaverFlatNtuple::calculateUpgradeEvent(const top::ParticleLevelEvent& upgradeEvent) { + for (auto& selectionDecision : m_upgrade_SelectionDecisions) { + selectionDecision.second = upgradeEvent.m_selectionDecisions[ selectionDecision.first ]; + } + + m_weight_mc = upgradeEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); + + m_eventNumber = upgradeEvent.m_info->eventNumber(); + m_runNumber = upgradeEvent.m_info->runNumber(); + m_mcChannelNumber = upgradeEvent.m_info->mcChannelNumber(); + + m_mu = upgradeEvent.m_info->averageInteractionsPerCrossing(); + m_mu_actual = upgradeEvent.m_info->actualInteractionsPerCrossing(); + + // save electrons + unsigned int i = 0; + m_el_pt.resize(upgradeEvent.m_electrons->size()); + m_el_eta.resize(upgradeEvent.m_electrons->size()); + m_el_phi.resize(upgradeEvent.m_electrons->size()); + m_el_e.resize(upgradeEvent.m_electrons->size()); + m_el_etcone20.resize(upgradeEvent.m_electrons->size()); + m_el_ptcone30.resize(upgradeEvent.m_electrons->size()); + m_el_charge.resize(upgradeEvent.m_electrons->size()); + m_el_true_type.resize(upgradeEvent.m_electrons->size()); + m_el_true_origin.resize(upgradeEvent.m_electrons->size()); + //m_el_true_firstEgMotherTruthOrigin.resize(upgradeEvent.m_electrons->size()); + //m_el_true_firstEgMotherTruthType.resize(upgradeEvent.m_electrons->size()); + //m_el_true_isPrompt.resize(upgradeEvent.m_electrons->size()); + if (m_config->HLLHCFakes()) m_el_faketype.resize(upgradeEvent.m_electrons->size()); + + for (const auto elPtr : *upgradeEvent.m_electrons) { + m_el_pt[i] = elPtr->pt(); + m_el_eta[i] = elPtr->eta(); + m_el_phi[i] = elPtr->phi(); + m_el_e[i] = elPtr->e(); + m_el_charge[i] = elPtr->charge(); + + m_el_true_type[i] = 0; + m_el_true_origin[i] = 0; + //m_el_true_firstEgMotherTruthType[i] = 0; + //m_el_true_firstEgMotherTruthOrigin[i] = 0; + //m_el_true_isPrompt[i] = 0; + + if (elPtr->isAvailable<float>("etcone20")) { + m_el_etcone20[i] = elPtr->auxdata<float>("etcone20"); + } else { + m_el_etcone20[i] = -999; + } + if (elPtr->isAvailable<float>("ptcone30")) { + m_el_ptcone30[i] = elPtr->auxdata<float>("ptcone30"); + } else { + m_el_ptcone30[i] = -999; + } + + if (!m_config->HLLHCFakes()) { + if (elPtr->isAvailable<unsigned int>("particleType")) { + m_el_true_type[i] = elPtr->auxdata<unsigned int>("particleType"); + } else if (elPtr->isAvailable<unsigned int>("classifierParticleType")) { + m_el_true_type[i] = elPtr->auxdata<unsigned int>("classifierParticleType"); + } else { + top::check(false, "Could not obtain truth Type decoration for electron!"); } - for (std::unordered_map<std::string,float*>::const_iterator i=m_extraTruthVars_float.begin();i!=m_extraTruthVars_float.end();++i) { - m_truthTreeManager->makeOutputVariable(*(*i).second,(*i).first); + if (elPtr->isAvailable<unsigned int>("particleOrigin")) { + m_el_true_origin[i] = elPtr->auxdata<unsigned int>("particleOrigin"); + } else if (elPtr->isAvailable<unsigned int>("classifierParticleOrigin")) { + m_el_true_origin[i] = elPtr->auxdata<unsigned int>("classifierParticleOrigin"); + } else { + top::check(false, "Could not obtain truth Origin decoration for electron!"); } + //if (elPtr->isAvailable<unsigned int>("firstEgMotherTruthType")) { + // m_el_true_firstEgMotherTruthType[i] = elPtr->auxdata<unsigned int>("firstEgMotherTruthType"); + //} else { + // top::check(false, "Could not obtain mother's truth Type decoration for electron!"); + //} + //if (elPtr->isAvailable<unsigned int>("firstEgMotherTruthOrigin")) { + // m_el_true_firstEgMotherTruthOrigin[i] = elPtr->auxdata<unsigned int>("firstEgMotherTruthOrigin"); + //} else { + // top::check(false, "Could not obtain mother's truth Origin decoration for electron!"); + //} + //m_el_true_isPrompt[i] = isPromptElectron(m_el_true_type[i], m_el_true_origin[i], + // m_el_true_firstEgMotherTruthType[i], m_el_true_firstEgMotherTruthOrigin[i]); + } else { + if (elPtr->isAvailable<int>("FakeType")) { + m_el_faketype[i] = elPtr->auxdata<int>("FakeType"); + } else { + top::check(false, "Could not obtain FakeType decoration for electron!"); + } + if (m_el_faketype[i] == 0) { // truthType/Origin only available for true electron (also for electron fake, but + // we are not interested in its truth info) + if (elPtr->isAvailable<unsigned int>("particleType")) { + m_el_true_type[i] = elPtr->auxdata<unsigned int>("particleType"); + } else if (elPtr->isAvailable<unsigned int>("classifierParticleType")) { + m_el_true_type[i] = elPtr->auxdata<unsigned int>("classifierParticleType"); + } else { + top::check(false, "Could not obtain truth Type decoration for electron!"); + } + if (elPtr->isAvailable<unsigned int>("particleOrigin")) { + m_el_true_origin[i] = elPtr->auxdata<unsigned int>("particleOrigin"); + } else if (elPtr->isAvailable<unsigned int>("classifierParticleOrigin")) { + m_el_true_origin[i] = elPtr->auxdata<unsigned int>("classifierParticleOrigin"); + } else { + top::check(false, "Could not obtain truth Origin decoration for electron!"); + } + //if (elPtr->isAvailable<unsigned int>("firstEgMotherTruthType")) { + // m_el_true_firstEgMotherTruthType[i] = elPtr->auxdata<unsigned int>("firstEgMotherTruthType"); + //} else { + // top::check(false, "Could not obtain mother's truth Type decoration for electron!"); + //} + //if (elPtr->isAvailable<unsigned int>("firstEgMotherTruthOrigin")) { + // m_el_true_firstEgMotherTruthOrigin[i] = elPtr->auxdata<unsigned int>("firstEgMotherTruthOrigin"); + //} else { + // top::check(false, "Could not obtain mother's truth Origin decoration for electron!"); + //} + //m_el_true_isPrompt[i] = isPromptElectron(m_el_true_type[i], m_el_true_origin[i], + // m_el_true_firstEgMotherTruthType[i], m_el_true_firstEgMotherTruthOrigin[i]); + } + } + + ++i; } - void EventSaverFlatNtuple::saveObjectIntoTruthTree(const SG::AuxElement& obj) - { - // If the container doesn't have an auxiliary store, bail now: - if (!obj.container()->getConstStore()) - return; - - // Get a convenience pointer to the aux type registry: - SG::AuxTypeRegistry& reg = SG::AuxTypeRegistry::instance(); - // Get the auxiliary IDs of the object: - const SG::auxid_set_t& auxids = - ( obj.container()->getConstStore() ? - obj.container()->getConstStore()->getAuxIDs() : - obj.getConstStore()->getAuxIDs() ); - - // setup new variables - for (SG::auxid_t auxid : auxids) { - // get the type of the variable - const std::type_info* ti = reg.getType( auxid ); - // get the name of the variable - const std::string name = reg.getName( auxid ); - - // Add variable - if (*ti == typeid( int ) ){ - std::unordered_map<std::string,int*>::iterator itr = m_extraTruthVars_int.find( name ); - if (itr != m_extraTruthVars_int.end()) { - *((*itr).second) = obj.auxdataConst<int> (name); - } - } - else if (*ti == typeid( float ) ){ - std::unordered_map<std::string,float*>::iterator itr = m_extraTruthVars_float.find( name ); - if (itr != m_extraTruthVars_float.end()) { - *((*itr).second) = obj.auxdataConst<float> (name); - } + // save muons + i = 0; + m_mu_pt.resize(upgradeEvent.m_muons->size()); + m_mu_eta.resize(upgradeEvent.m_muons->size()); + m_mu_phi.resize(upgradeEvent.m_muons->size()); + m_mu_e.resize(upgradeEvent.m_muons->size()); + m_mu_etcone20.resize(upgradeEvent.m_muons->size()); + m_mu_ptcone30.resize(upgradeEvent.m_muons->size()); + m_mu_charge.resize(upgradeEvent.m_muons->size()); + m_mu_true_type.resize(upgradeEvent.m_muons->size()); + m_mu_true_origin.resize(upgradeEvent.m_muons->size()); + m_mu_true_isPrompt.resize(upgradeEvent.m_muons->size()); + m_mu_prodVtx_z.resize(upgradeEvent.m_muons->size()); + m_mu_prodVtx_perp.resize(upgradeEvent.m_muons->size()); + m_mu_prodVtx_phi.resize(upgradeEvent.m_muons->size()); + + for (const auto muPtr : *upgradeEvent.m_muons) { + m_mu_pt[i] = muPtr->pt(); + m_mu_eta[i] = muPtr->eta(); + m_mu_phi[i] = muPtr->phi(); + m_mu_e[i] = muPtr->e(); + m_mu_charge[i] = muPtr->charge(); + + m_mu_true_type[i] = 0; + m_mu_true_origin[i] = 0; + m_mu_true_isPrompt[i] = 0; + m_mu_prodVtx_z[i] = -999; + m_mu_prodVtx_perp[i] = -999; + m_mu_prodVtx_phi[i] = -999; + if (muPtr->isAvailable<unsigned int>("particleType")) { + m_mu_true_type[i] = muPtr->auxdata<unsigned int>("particleType"); + } else if (muPtr->isAvailable<unsigned int>("classifierParticleType")) { + m_mu_true_type[i] = muPtr->auxdata<unsigned int>("classifierParticleType"); + } else { + top::check(false, "Could not obtain truth Type decoration for muon!"); + } + if (muPtr->isAvailable<unsigned int>("particleOrigin")) { + m_mu_true_origin[i] = muPtr->auxdata<unsigned int>("particleOrigin"); + } else if (muPtr->isAvailable<unsigned int>("classifierParticleOrigin")) { + m_mu_true_origin[i] = muPtr->auxdata<unsigned int>("classifierParticleOrigin"); + } else { + top::check(false, "Could not obtain truth Origin decoration for muon!"); + } + m_mu_true_isPrompt[i] = isPromptMuon(m_mu_true_type[i], m_mu_true_origin[i]); + if (muPtr->isAvailable<float>("prodVtx_z")) { + m_mu_prodVtx_z[i] = muPtr->auxdata<float>("prodVtx_z"); + } + if (muPtr->isAvailable<float>("prodVtx_perp")) { + m_mu_prodVtx_perp[i] = muPtr->auxdata<float>("prodVtx_perp"); + } + if (muPtr->isAvailable<float>("etcone20")) { + m_mu_etcone20[i] = muPtr->auxdata<float>("etcone20"); + } else { + m_mu_etcone20[i] = -999; + } + if (muPtr->isAvailable<float>("ptcone30")) { + m_mu_ptcone30[i] = muPtr->auxdata<float>("ptcone30"); + } else { + m_mu_ptcone30[i] = -999; + } + if (muPtr->isAvailable<float>("prodVtx_phi")) { + m_mu_prodVtx_phi[i] = muPtr->auxdata<float>("prodVtx_phi"); + } + + ++i; + } + + static const SG::AuxElement::ConstAccessor<int> ghostBHadronsFinalCount("GhostBHadronsFinalCount"); + static const SG::AuxElement::ConstAccessor<int> ghostCHadronsFinalCount("GhostCHadronsFinalCount"); + + // save jets + i = 0; + m_jet_pt.resize(upgradeEvent.m_jets->size()); + m_jet_eta.resize(upgradeEvent.m_jets->size()); + m_jet_phi.resize(upgradeEvent.m_jets->size()); + m_jet_e.resize(upgradeEvent.m_jets->size()); + m_jet_mv1eff.resize(upgradeEvent.m_jets->size()); + m_jet_isPileup.resize(upgradeEvent.m_jets->size()); + m_jet_Ghosts_BHadron_Final_Count.resize(upgradeEvent.m_jets->size()); + m_jet_Ghosts_CHadron_Final_Count.resize(upgradeEvent.m_jets->size()); + for (const auto& jetPtr : *upgradeEvent.m_jets) { + m_jet_pt[i] = jetPtr->pt(); + m_jet_eta[i] = jetPtr->eta(); + m_jet_phi[i] = jetPtr->phi(); + m_jet_e[i] = jetPtr->e(); + + m_jet_mv1eff[i] = jetPtr->auxdata<float>("mv1TagEff"); + + if (jetPtr->auxdata<int>("pileUp") == 0) { + m_jet_isPileup[i] = 0; + + if(ghostBHadronsFinalCount.isAvailable(*jetPtr)) { + m_jet_Ghosts_BHadron_Final_Count[i] = ghostBHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostBHadronFinalCount auxdata"); + m_jet_Ghosts_BHadron_Final_Count[i] = 0; + } + + if(ghostCHadronsFinalCount.isAvailable(*jetPtr)) { + m_jet_Ghosts_CHadron_Final_Count[i] = ghostCHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostCHadronFinalCount auxdata"); + m_jet_Ghosts_CHadron_Final_Count[i] = 0; + } + + } else { + m_jet_isPileup[i] = 1; + m_jet_Ghosts_BHadron_Final_Count[i] = 0; + m_jet_Ghosts_CHadron_Final_Count[i] = 0; + } + + ++i; + } + + //large R jets + if (m_config->useTruthLargeRJets()) { + unsigned int i = 0; + + m_ljet_pt.resize(upgradeEvent.m_largeRJets->size()); + m_ljet_eta.resize(upgradeEvent.m_largeRJets->size()); + m_ljet_phi.resize(upgradeEvent.m_largeRJets->size()); + m_ljet_e.resize(upgradeEvent.m_largeRJets->size()); + m_ljet_Ghosts_BHadron_Final_Count.resize(upgradeEvent.m_largeRJets->size()); + m_ljet_Ghosts_CHadron_Final_Count.resize(upgradeEvent.m_largeRJets->size()); + for (const auto& jetPtr : *upgradeEvent.m_largeRJets) { + m_ljet_pt[i] = jetPtr->pt(); + m_ljet_eta[i] = jetPtr->eta(); + m_ljet_phi[i] = jetPtr->phi(); + m_ljet_e[i] = jetPtr->e(); + + if(ghostBHadronsFinalCount.isAvailable(*jetPtr)) { + m_ljet_Ghosts_BHadron_Final_Count[i] = ghostBHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostBHadronFinalCount auxdata"); + m_ljet_Ghosts_BHadron_Final_Count[i] = 0; + } + + if(ghostCHadronsFinalCount.isAvailable(*jetPtr)) { + m_ljet_Ghosts_CHadron_Final_Count[i] = ghostCHadronsFinalCount(*jetPtr); + } + else { + ATH_MSG_DEBUG("Found a jet with no GhostCHadronFinalCount auxdata"); + m_ljet_Ghosts_CHadron_Final_Count[i] = 0; + } + + ++i; + } + } + + //photons + if (m_config->useTruthPhotons()) { + unsigned int i(0); + m_ph_pt.resize(upgradeEvent.m_photons->size()); + m_ph_eta.resize(upgradeEvent.m_photons->size()); + m_ph_phi.resize(upgradeEvent.m_photons->size()); + m_ph_e.resize(upgradeEvent.m_photons->size()); + m_ph_true_type.resize(upgradeEvent.m_photons->size()); + m_ph_true_origin.resize(upgradeEvent.m_photons->size()); + if (m_config->HLLHCFakes()) m_ph_faketype.resize(upgradeEvent.m_photons->size()); + + for (const auto* const phPtr : *upgradeEvent.m_photons) { + m_ph_pt[i] = phPtr->pt(); + m_ph_eta[i] = phPtr->eta(); + m_ph_phi[i] = phPtr->phi(); + m_ph_e[i] = phPtr->e(); + if (!m_config->HLLHCFakes()) { + if (phPtr->isAvailable<unsigned int>("particleType")) { + m_ph_true_type[i] = phPtr->auxdata<unsigned int>("particleType"); + } else if (phPtr->isAvailable<unsigned int>("classifierParticleType")) { + m_ph_true_type[i] = phPtr->auxdata<unsigned int>("classifierParticleType"); + } else { + top::check(false, "Could not obtain truth Type decoration for photon!"); + } + if (phPtr->isAvailable<unsigned int>("particleOrigin")) { + m_ph_true_origin[i] = phPtr->auxdata<unsigned int>("particleOrigin"); + } else if (phPtr->isAvailable<unsigned int>("classifierParticleOrigin")) { + m_ph_true_origin[i] = phPtr->auxdata<unsigned int>("classifierParticleOrigin"); + } else { + top::check(false, "Could not obtain truth Origin decoration for photon!"); + } + } else { + if (phPtr->isAvailable<int>("FakeType")) { + m_ph_faketype[i] = phPtr->auxdata<int>("FakeType"); + } else { + top::check(false, "Could not obtain FakeType decoration for photon!"); + } + if (m_ph_faketype[i] == 0) { // truthType/Origin only available for true photon (also for electron fake, but + // we are not interested in its truth info) + if (phPtr->isAvailable<unsigned int>("particleType")) { + m_ph_true_type[i] = phPtr->auxdata<unsigned int>("particleType"); + } else if (phPtr->isAvailable<unsigned int>("classifierParticleType")) { + m_ph_true_type[i] = phPtr->auxdata<unsigned int>("classifierParticleType"); + } else { + top::check(false, "Could not obtain truth Type decoration for photon!"); } - else { - ATH_MSG_INFO("saveObjectIntoTruthTree - you need another variable map for more types!"); + if (phPtr->isAvailable<unsigned int>("particleOrigin")) { + m_ph_true_origin[i] = phPtr->auxdata<unsigned int>("particleOrigin"); + } else if (phPtr->isAvailable<unsigned int>("classifierParticleOrigin")) { + m_ph_true_origin[i] = phPtr->auxdata<unsigned int>("classifierParticleOrigin"); + } else { + top::check(false, "Could not obtain truth Origin decoration for photon!"); } + } } + + ++i; + } } - // get short name for FixedCutBEff_* WPs - std::string EventSaverFlatNtuple::shortBtagWP(std::string const & WP) const { - std::string str = "FixedCutBEff_"; - std::string out = WP; - if (out.find(str) != std::string::npos) { - out.replace(out.find(str),str.length(),""); + // MET + m_met_met = upgradeEvent.m_met->met(); + m_met_phi = upgradeEvent.m_met->phi(); + + if (m_config->doMCGeneratorWeights()) { + // delegate to helper function. + loadMCGeneratorWeights(); + } + } + + void EventSaverFlatNtuple::fillUpgradeEvent() { + // fill the tree + m_upgradeTreeManager->fill(); + }//saveUpgradeEvent + + void EventSaverFlatNtuple::finalize() { + m_outputFile->Write(); + } + + void EventSaverFlatNtuple::loadPdfInfo() { + const xAOD::TruthEventContainer* truthEvent(nullptr); + + top::check(evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()), "Failed to retrieve truth PDF info"); + + if (truthEvent != nullptr) { + unsigned int i(0); + unsigned int truthEventSize = truthEvent->size(); + m_PDFinfo_X1.resize(truthEventSize); + m_PDFinfo_X2.resize(truthEventSize); + m_PDFinfo_PDGID1.resize(truthEventSize); + m_PDFinfo_PDGID2.resize(truthEventSize); + m_PDFinfo_Q.resize(truthEventSize); + m_PDFinfo_XF1.resize(truthEventSize); + m_PDFinfo_XF2.resize(truthEventSize); + + for (const auto* const tePtr : *truthEvent) { + // LMTODO: ASG tools/pdfInfo() can't be used yet, since scale Q is not available + // xAOD::TruthEvent::PdfInfo _pdfInfo=tePtr->pdfInfo(); + // if _pdfInfo.valid() { m_PDFinfo_X1[i] = _pdfInfo.x1; //etc. } + std::string PDFinfoVarName = "X1"; + if (truthEvent->isAvailable<float>(PDFinfoVarName)) m_PDFinfo_X1[i] = (*tePtr).auxdataConst< float >(PDFinfoVarName); + PDFinfoVarName = "X2"; + if (truthEvent->isAvailable<float>(PDFinfoVarName)) m_PDFinfo_X2[i] = (*tePtr).auxdataConst< float >(PDFinfoVarName); + PDFinfoVarName = "PDGID1"; + if (truthEvent->isAvailable<int>(PDFinfoVarName)) m_PDFinfo_PDGID1[i] = (*tePtr).auxdataConst< int >(PDFinfoVarName); + PDFinfoVarName = "PDGID2"; + if (truthEvent->isAvailable<int>(PDFinfoVarName)) m_PDFinfo_PDGID2[i] = (*tePtr).auxdataConst< int >(PDFinfoVarName); + PDFinfoVarName = "XF1"; + if (truthEvent->isAvailable<float>(PDFinfoVarName)) m_PDFinfo_XF1[i] = (*tePtr).auxdataConst< float >(PDFinfoVarName); + PDFinfoVarName = "XF2"; + if (truthEvent->isAvailable<float>(PDFinfoVarName)) m_PDFinfo_XF2[i] = (*tePtr).auxdataConst< float >(PDFinfoVarName); + PDFinfoVarName = "Q"; + if (truthEvent->isAvailable<float>(PDFinfoVarName)) m_PDFinfo_Q[i] = (*tePtr).auxdataConst< float >(PDFinfoVarName); + ++i; } - return out; } + } - // remove "FT_EFF_", spaces, and "-" in named systematics - std::string EventSaverFlatNtuple::betterBtagNamedSyst (const std::string name) { - std::string str = "FT_EFF_"; - std::string out = name; - if (out.find(str) != std::string::npos) { - out.replace(out.find(str),str.length(),""); + void EventSaverFlatNtuple::loadPdfWeights() { + const xAOD::TruthEventContainer* truthEvent(nullptr); + + top::check(evtStore()->retrieve(truthEvent, m_config->sgKeyTruthEvent()), "Failed to retrieve truth PDF info"); + + for (auto tePtr : *truthEvent) { + for (const std::string& pdf_name : m_config->LHAPDFSets()) { + if (tePtr->isAvailable<std::vector<float> >("AnalysisTop_" + pdf_name + "_Weights")) { + m_PDF_eventWeights[ pdf_name ] = tePtr->auxdata<std::vector<float> >("AnalysisTop_" + pdf_name + "_Weights"); + } } - str = " "; - while (out.find(str) != std::string::npos) { - out.replace(out.find(str),str.length(),"_"); + } + } + + void EventSaverFlatNtuple::loadMCGeneratorWeights() { + const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo for loading of MCGenWeights!"); + m_mc_generator_weights = eventInfo->mcEventWeights(); + } + + // This bit is new + // It is not optimal and can do with a lot of improvement + // Consider it a first pass + // + // We can save xAOD objects into flat ntuple by looking at their SG::AuxElement data + // + // inspired by: + // https://svnweb.cern.ch/trac/atlasoff/browser/Event/xAOD/xAODCore/tags/xAODCore-00-00-93/Root/PrintHelpers.cxx + + void EventSaverFlatNtuple::registerObjectIntoTruthTree(const SG::AuxElement& obj) { + // If the container doesn't have an auxiliary store, bail now: + if (!obj.container()->getConstStore()) return; + + // Get a convenience pointer to the aux type registry: + SG::AuxTypeRegistry& reg = SG::AuxTypeRegistry::instance(); + + // Get the auxiliary IDs of the object: + const SG::auxid_set_t& auxids = + (obj.container()->getConstStore() ? + obj.container()->getConstStore()->getAuxIDs() : + obj.getConstStore()->getAuxIDs()); + + // find the variables and fill them + for (SG::auxid_t auxid : auxids) { + // get the type of the variable + const std::type_info* ti = reg.getType(auxid); + // get the name of the variable + const std::string name = reg.getName(auxid); + + // Add variable + if (*ti == typeid(int)) { + m_extraTruthVars_int.insert(std::make_pair(name, new int)); + } else if (*ti == typeid(float)) { + m_extraTruthVars_float.insert(std::make_pair(name, new float)); + } else { + ATH_MSG_INFO("insertObjectIntoTruthTree - you need another variable map for more types!"); } - str = "-"; - while (out.find(str) != std::string::npos) { - out.replace(out.find(str),str.length(),"_"); + } + + // add the variables to the truthTreeManager + for (std::unordered_map<std::string, int*>::const_iterator i = m_extraTruthVars_int.begin(); i != m_extraTruthVars_int.end(); ++i) { + m_truthTreeManager->makeOutputVariable(*(*i).second, (*i).first); + } + for (std::unordered_map<std::string, float*>::const_iterator i = m_extraTruthVars_float.begin(); i != m_extraTruthVars_float.end(); ++i) { + m_truthTreeManager->makeOutputVariable(*(*i).second, (*i).first); + } + } + + void EventSaverFlatNtuple::saveObjectIntoTruthTree(const SG::AuxElement& obj) { + // If the container doesn't have an auxiliary store, bail now: + if (!obj.container()->getConstStore()) return; + + // Get a convenience pointer to the aux type registry: + SG::AuxTypeRegistry& reg = SG::AuxTypeRegistry::instance(); + // Get the auxiliary IDs of the object: + const SG::auxid_set_t& auxids = + (obj.container()->getConstStore() ? + obj.container()->getConstStore()->getAuxIDs() : + obj.getConstStore()->getAuxIDs()); + + // setup new variables + for (SG::auxid_t auxid : auxids) { + // get the type of the variable + const std::type_info* ti = reg.getType(auxid); + // get the name of the variable + const std::string name = reg.getName(auxid); + + // Add variable + if (*ti == typeid(int)) { + std::unordered_map<std::string, int*>::iterator itr = m_extraTruthVars_int.find(name); + if (itr != m_extraTruthVars_int.end()) { + *((*itr).second) = obj.auxdataConst<int> (name); + } + } else if (*ti == typeid(float)) { + std::unordered_map<std::string, float*>::iterator itr = m_extraTruthVars_float.find(name); + if (itr != m_extraTruthVars_float.end()) { + *((*itr).second) = obj.auxdataConst<float> (name); + } + } else { + ATH_MSG_INFO("saveObjectIntoTruthTree - you need another variable map for more types!"); } - return out; + } + } + + // get short name for FixedCutBEff_* WPs + std::string EventSaverFlatNtuple::shortBtagWP(std::string const& WP) const { + std::string str = "FixedCutBEff_"; + std::string out = WP; + if (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), ""); + } + return out; + } + + // remove "FT_EFF_", spaces, and "-" in named systematics + std::string EventSaverFlatNtuple::betterBtagNamedSyst(const std::string name) { + std::string str = "FT_EFF_"; + std::string out = name; + if (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), ""); + } + str = " "; + while (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), "_"); + } + str = "-"; + while (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), "_"); + } + return out; + } + + //new prompt lepton classification below based on + // https://twiki.cern.ch/twiki/pub/AtlasProtected/IsolationFakeForum/MakeTruthClassification.hxx + //these represent the latest IFF recommendations + std::pair<bool, bool> EventSaverFlatNtuple::isPromptElectron(int type, int origin, int egMotherType, int egMotherOrigin, int egMotherPdgId, int RecoCharge) { + // 43 is "diboson" origin, but is needed due to buggy origin flags in Sherpa ttbar + bool isprompt = (type == 2 || + (type == 4 && origin == 5 && fabs(egMotherPdgId) == 11) || + // bkg electrons from ElMagDecay with origin top, W or Z, higgs, diBoson + (type == 4 && origin == 7 && egMotherType == 2 && (egMotherOrigin == 10 || egMotherOrigin == 12 || egMotherOrigin == 13 || egMotherOrigin == 14 || egMotherOrigin == 43) && fabs(egMotherPdgId) == 11) || + // unknown electrons from multi-boson (sherpa 222, di-boson) + (type == 1 && egMotherType == 2 && egMotherOrigin == 47 && fabs(egMotherPdgId) == 11)); + + bool isChargeFl = false; + + if (egMotherPdgId * RecoCharge > 0) isChargeFl = true; + if (isprompt) return std::make_pair(true, isChargeFl); //charge flipped electrons are also considered prompt + + // bkg photons from photon conv from FSR (must check!!) + if (type == 4 && origin == 5 && egMotherOrigin == 40) return std::make_pair(true, false); + + // non-iso photons from FSR for the moment but we must check!! (must check!!) + if (type == 15 && origin == 40) return std::make_pair(true, false); + + // mainly in Sherpa Zee, but some also in Zmumu + if (type == 4 && origin == 7 && egMotherType == 15 && egMotherOrigin == 40) return std::make_pair(true, false); + + return std::make_pair(false, false); + } + + bool EventSaverFlatNtuple::isPromptMuon(int type, int origin) { + // 43 is "diboson" origin, but is needed due to buggy origin flags in Sherpa ttbar + bool prompt = (type == 6 && + (origin == 10 || origin == 12 || origin == 13 || origin == 14 || origin == 15 || origin == 22 || origin == 43)); + + return prompt; + } + + int EventSaverFlatNtuple::filterBranches(const top::TreeManager* treeManager, const std::string& variable) { + std::vector<std::string> filteredBranches; + if(treeManager->name() == "truth") filteredBranches= m_config->filterPartonLevelBranches(); + else if(treeManager->name() == "particleLevel") filteredBranches= m_config->filterParticleLevelBranches(); + else if(treeManager->name() == "nominal_Loose") filteredBranches= m_config->filterNominalLooseBranches(); + else filteredBranches= m_config->filterBranches(); + + // lambda to test a wildcard on the variable + auto matches_wildcard = [&variable] (const std::string& wildcard) { + std::smatch match; + std::regex_search(variable, match, std::regex(wildcard)); + if (!match.empty()) return true; + + return false; + }; + + for (std::string filter : filteredBranches) { + // replace "*" with ".*" + filter = regex_replace(filter, std::regex("\\*"), ".*"); + // check for a match + if (matches_wildcard(("^" + filter).c_str())) return 0; } + return -1; + } } // namespace diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAOD.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAOD.cxx index 34fb1578fa3d234198ab7317a65d466903cd962a..767cc1d7ed393f310432924b98cdec381747b7ff 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAOD.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAOD.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/EventSaverxAOD.h" @@ -17,40 +17,38 @@ #include "TFile.h" namespace top { - -EventSaverxAOD::EventSaverxAOD() : - asg::AsgTool( "top::EventSaverxAOD" ), - m_prefix("CorrectedSelected"), - m_config(nullptr), - m_outputFile(nullptr) { -} - -EventSaverxAOD::~EventSaverxAOD() -{ -} - -void EventSaverxAOD::initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches) { + EventSaverxAOD::EventSaverxAOD() : + asg::AsgTool("top::EventSaverxAOD"), + m_prefix("CorrectedSelected"), + m_config(nullptr), + m_outputFile(nullptr) { + } + + EventSaverxAOD::~EventSaverxAOD() { + } + + void EventSaverxAOD::initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches) { m_config = config; m_outputFile = file; top::check(evtStore()->event()->writeTo(m_outputFile), "EventSaverxAOD trying to call writeTo on output file"); //EventInfo std::string eventInfoList = "runNumber.eventNumber.eventTypeBitmask.averageInteractionsPerCrossing"; - if (config->isMC()) - eventInfoList += ".mcChannelNumber.mcEventWeights.PileupWeight"; + if (config->isMC()) eventInfoList += ".mcChannelNumber.mcEventWeights.PileupWeight"; //Add extra branches - e.g. if it passed the ee / mumu / emu selection per event for (const auto& branchName : extraBranches) - eventInfoList += "." + branchName; + eventInfoList += "." + branchName; - //std::cout << "EventLoaderCorrectSelect::branchesToSave - EventInfo " << eventInfoList << std::endl; evtStore()->event()->setAuxItemList("EventInfoAux.", eventInfoList); //Electrons evtStore()->event()->setAuxItemList(m_prefix + m_config->sgKeyElectrons() + "Aux.", "pt.eta.phi.m.charge"); //Muons - evtStore()->event()->setAuxItemList(m_prefix + m_config->sgKeyMuons() + "Aux.", "pt.eta.phi.m.charge.muonType.combinedTrackParticleLink"); + evtStore()->event()->setAuxItemList( + m_prefix + m_config->sgKeyMuons() + "Aux.", "pt.eta.phi.m.charge.muonType.combinedTrackParticleLink"); //Once mu has a built-in charge we can get rid of this //Muon charge is a property of the associated track - e.g. d0.z0.phi.theta.qOverP @@ -66,137 +64,153 @@ void EventSaverxAOD::initialize(std::shared_ptr<top::TopConfig> config, TFile* f evtStore()->event()->setAuxItemList(btagName + "Aux.", "MV1_discriminant"); //MET seems to be pretty small already -} + } -void EventSaverxAOD::saveEvent(const top::Event& event) { + void EventSaverxAOD::saveEvent(const top::Event& event) { //only save the nominal variation for now - speak to Attila about TEvent.fill not taking a tree name - if (event.m_hashValue != m_config->nominalHashValue()) - return; - + if (event.m_hashValue != m_config->nominalHashValue()) return; + // record the event? - if (m_config->saveOnlySelectedEvents() && !event.m_saveEvent) - return; - - // Systematic Event + if (m_config->saveOnlySelectedEvents() && !event.m_saveEvent) return; + + // Systematic Event const xAOD::SystematicEventContainer* allSystematics(nullptr); - top::check(evtStore()->retrieve(allSystematics,m_config->sgKeyTopSystematicEvents()) , "Failed to retrieve xAOD::SystematicEventContainer" ); - - xAOD::SystematicEventContainer* allSystematics_output = new xAOD::SystematicEventContainer{}; - SG::IAuxStore* allSystematics_aux = evtStore()->event()->recordAux( m_config->sgKeyTopSystematicEvents() + "Aux." ); - allSystematics_output->setStore( allSystematics_aux ); + top::check(evtStore()->retrieve(allSystematics, + m_config->sgKeyTopSystematicEvents()), + "Failed to retrieve xAOD::SystematicEventContainer"); + + xAOD::SystematicEventContainer* allSystematics_output = new xAOD::SystematicEventContainer {}; + SG::IAuxStore* allSystematics_aux = evtStore()->event()->recordAux(m_config->sgKeyTopSystematicEvents() + "Aux."); + allSystematics_output->setStore(allSystematics_aux); for (auto currentSystematic : *allSystematics) { - xAOD::SystematicEvent* out = new xAOD::SystematicEvent{}; - out->makePrivateStore( *currentSystematic ); - allSystematics_output->push_back( out ); + xAOD::SystematicEvent* out = new xAOD::SystematicEvent {}; + out->makePrivateStore(*currentSystematic); + allSystematics_output->push_back(out); } - top::check(evtStore()->event()->record(allSystematics_output,m_config->sgKeyTopSystematicEvents()),"Failed to record xAOD::SystematicEventContainer" ); - - - // Top Parton History + top::check(evtStore()->event()->record(allSystematics_output, + m_config->sgKeyTopSystematicEvents()), + "Failed to record xAOD::SystematicEventContainer"); + + + // Top Parton History if (m_config->doTopPartonHistory()) { if (evtStore()->contains<xAOD::PartonHistoryContainer>(m_config->sgKeyTopPartonHistory())) { const xAOD::PartonHistoryContainer* partonHistory(nullptr); - top::check(evtStore()->retrieve(partonHistory, m_config->sgKeyTopPartonHistory()),"Failed to retrieve Top Parton History"); - - xAOD::PartonHistoryContainer* partonHistory_output = new xAOD::PartonHistoryContainer{}; - SG::IAuxStore* partonHistory_aux = evtStore()->event()->recordAux( m_config->sgKeyTopPartonHistory() + "Aux." ); - partonHistory_output->setStore( partonHistory_aux ); + top::check(evtStore()->retrieve(partonHistory, + m_config->sgKeyTopPartonHistory()), "Failed to retrieve Top Parton History"); + + xAOD::PartonHistoryContainer* partonHistory_output = new xAOD::PartonHistoryContainer {}; + SG::IAuxStore* partonHistory_aux = evtStore()->event()->recordAux(m_config->sgKeyTopPartonHistory() + "Aux."); + partonHistory_output->setStore(partonHistory_aux); for (auto x : *partonHistory) { - xAOD::PartonHistory* out = new xAOD::PartonHistory{}; - out->makePrivateStore( *x ); - partonHistory_output->push_back( out ); + xAOD::PartonHistory* out = new xAOD::PartonHistory {}; + out->makePrivateStore(*x); + partonHistory_output->push_back(out); } - top::check(evtStore()->event()->record(partonHistory_output,m_config->sgKeyTopPartonHistory()),"Failed to record Parton History" ); + top::check(evtStore()->event()->record(partonHistory_output, + m_config->sgKeyTopPartonHistory()), "Failed to record Parton History"); } } - - + + //Event Info top::check(evtStore()->event()->copy("EventInfo"), "copying event info failed"); //Electrons if (m_config->useElectrons()) { - xAOD::ElectronContainer* electrons_output = new xAOD::ElectronContainer(); - SG::IAuxStore* electrons_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyElectrons() + "Aux."); - electrons_output->setStore(electrons_aux); - - for (const auto* const elPtr : event.m_electrons) { - xAOD::Electron* outputElPtr = new xAOD::Electron(); - outputElPtr->makePrivateStore(*elPtr); - electrons_output->push_back(outputElPtr); - } + xAOD::ElectronContainer* electrons_output = new xAOD::ElectronContainer(); + SG::IAuxStore* electrons_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyElectrons() + "Aux."); + electrons_output->setStore(electrons_aux); + + for (const auto* const elPtr : event.m_electrons) { + xAOD::Electron* outputElPtr = new xAOD::Electron(); + outputElPtr->makePrivateStore(*elPtr); + electrons_output->push_back(outputElPtr); + } - top::check(evtStore()->event()->record(electrons_output, m_prefix + m_config->sgKeyElectrons()), "xAOD::TEvent record " + m_prefix + m_config->sgKeyElectrons() + " failed"); + top::check(evtStore()->event()->record(electrons_output, + m_prefix + m_config->sgKeyElectrons()), + "xAOD::TEvent record " + m_prefix + m_config->sgKeyElectrons() + " failed"); } //Muons if (m_config->useMuons()) { - xAOD::MuonContainer* muons_output = new xAOD::MuonContainer(); - SG::IAuxStore* muons_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyMuons() + "Aux."); - muons_output->setStore(muons_aux); - - for (const auto* const muPtr : event.m_muons) { - xAOD::Muon* outputMuPtr = new xAOD::Muon(); - outputMuPtr->makePrivateStore(*muPtr); - muons_output->push_back(outputMuPtr); - } - - top::check(evtStore()->event()->record(muons_output, m_prefix + m_config->sgKeyMuons()), "xAOD::TEvent record " + m_prefix + m_config->sgKeyMuons() + " failed"); + xAOD::MuonContainer* muons_output = new xAOD::MuonContainer(); + SG::IAuxStore* muons_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyMuons() + "Aux."); + muons_output->setStore(muons_aux); + + for (const auto* const muPtr : event.m_muons) { + xAOD::Muon* outputMuPtr = new xAOD::Muon(); + outputMuPtr->makePrivateStore(*muPtr); + muons_output->push_back(outputMuPtr); + } - //for now... - //Muon charge is a property of the associated track - //Copy tracks (for muon charge) - check(evtStore()->event()->copy("InDetTrackParticles"), "xAOD::TEvent copy InDetTrackParticles failed"); - check(evtStore()->event()->copy("ExtrapolatedMuonTrackParticles"), "xAOD::TEvent copy InDetTrackParticles ExtrapolatedMuonTrackParticles"); - check(evtStore()->event()->copy("CombinedMuonTrackParticles"), "xAOD::TEvent copy InDetTrackParticles CombinedMuonTrackParticles"); + top::check(evtStore()->event()->record(muons_output, + m_prefix + m_config->sgKeyMuons()), + "xAOD::TEvent record " + m_prefix + m_config->sgKeyMuons() + " failed"); + + //for now... + //Muon charge is a property of the associated track + //Copy tracks (for muon charge) + check(evtStore()->event()->copy("InDetTrackParticles"), "xAOD::TEvent copy InDetTrackParticles failed"); + check(evtStore()->event()->copy( + "ExtrapolatedMuonTrackParticles"), + "xAOD::TEvent copy InDetTrackParticles ExtrapolatedMuonTrackParticles"); + check(evtStore()->event()->copy( + "CombinedMuonTrackParticles"), "xAOD::TEvent copy InDetTrackParticles CombinedMuonTrackParticles"); } //Jets if (m_config->useJets()) { - xAOD::JetContainer* jets_output = new xAOD::JetContainer(); - SG::IAuxStore* jets_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyJets() + "Aux."); - jets_output->setStore(jets_aux); - - for (const auto* const jetPtr : event.m_jets) { - xAOD::Jet* outputJetPtr = new xAOD::Jet(); - outputJetPtr->makePrivateStore(*jetPtr); - jets_output->push_back(outputJetPtr); - } + xAOD::JetContainer* jets_output = new xAOD::JetContainer(); + SG::IAuxStore* jets_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyJets() + "Aux."); + jets_output->setStore(jets_aux); + + for (const auto* const jetPtr : event.m_jets) { + xAOD::Jet* outputJetPtr = new xAOD::Jet(); + outputJetPtr->makePrivateStore(*jetPtr); + jets_output->push_back(outputJetPtr); + } - top::check(evtStore()->event()->record(jets_output, m_prefix + m_config->sgKeyJets()), "xAOD::TEvent record " + m_prefix + m_config->sgKeyJets() + " failed"); + top::check(evtStore()->event()->record(jets_output, + m_prefix + m_config->sgKeyJets()), + "xAOD::TEvent record " + m_prefix + m_config->sgKeyJets() + " failed"); - //b-tagging variables need the BTagging_JetNameWithoutJetsOnTheEnd container - //remove Jets from the end of the container name and add BTagging_ - const std::string btagName = "BTagging_" + m_config->sgKeyJets().substr(0, m_config->sgKeyJets().size() - 4); - check(evtStore()->event()->copy(btagName), "xAOD::TEvent copy " + btagName + " failed"); + //b-tagging variables need the BTagging_JetNameWithoutJetsOnTheEnd container + //remove Jets from the end of the container name and add BTagging_ + const std::string btagName = "BTagging_" + m_config->sgKeyJets().substr(0, m_config->sgKeyJets().size() - 4); + check(evtStore()->event()->copy(btagName), "xAOD::TEvent copy " + btagName + " failed"); } //Large Jets if (m_config->useLargeRJets()) { - xAOD::JetContainer* largeJets_output = new xAOD::JetContainer(); - SG::IAuxStore* largeJets_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyLargeRJets() + "Aux."); - largeJets_output->setStore(largeJets_aux); - - for (const auto* const jetPtr : event.m_largeJets) { - xAOD::Jet* outputJetPtr = new xAOD::Jet(); - outputJetPtr->makePrivateStore(*jetPtr); - largeJets_output->push_back(outputJetPtr); - } + xAOD::JetContainer* largeJets_output = new xAOD::JetContainer(); + SG::IAuxStore* largeJets_aux = evtStore()->event()->recordAux(m_prefix + m_config->sgKeyLargeRJets() + "Aux."); + largeJets_output->setStore(largeJets_aux); + + for (const auto* const jetPtr : event.m_largeJets) { + xAOD::Jet* outputJetPtr = new xAOD::Jet(); + outputJetPtr->makePrivateStore(*jetPtr); + largeJets_output->push_back(outputJetPtr); + } - check(evtStore()->event()->record(largeJets_output, m_prefix + m_config->sgKeyLargeRJets()), "xAOD::TEvent record " + m_prefix + m_config->sgKeyLargeRJets() + " failed"); + check(evtStore()->event()->record(largeJets_output, + m_prefix + m_config->sgKeyLargeRJets()), + "xAOD::TEvent record " + m_prefix + m_config->sgKeyLargeRJets() + " failed"); } //MET - top::check(evtStore()->event()->copy(m_config->sgKeyMissingEt()), "xAOD::TEvent copy " + m_config->sgKeyMissingEt() + " failed"); + top::check(evtStore()->event()->copy(m_config->sgKeyMissingEt()), + "xAOD::TEvent copy " + m_config->sgKeyMissingEt() + " failed"); //do it! top::check(evtStore()->event()->fill(), "xAOD::TEvent fill failed"); -} + } -void EventSaverxAOD::finalize() { + void EventSaverxAOD::finalize() { m_outputFile->Write(); - top::check(evtStore()->event()->finishWritingTo(m_outputFile), "EventSaverxAOD::finalise trying to call finishWritingTo"); -} - + top::check(evtStore()->event()->finishWritingTo( + m_outputFile), "EventSaverxAOD::finalise trying to call finishWritingTo"); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAODNext.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAODNext.cxx index 7845c85afc7953d81140d0ae78851131d8379deb..dd6cd0e2a145dd8d52a910a1c4d84a640da87390 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAODNext.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSaverxAODNext.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/EventSaverxAODNext.h" @@ -27,52 +27,50 @@ #include "TFile.h" namespace top { - - EventSaverxAODNext::EventSaverxAODNext() : - asg::AsgMetadataTool( "top::EventSaverxAODNext" ), - m_config(nullptr), + EventSaverxAODNext::EventSaverxAODNext() : + asg::AsgMetadataTool("top::EventSaverxAODNext"), + m_config(nullptr), m_outputFile(nullptr), - m_saveAllObjects(false) - { + m_saveAllObjects(false) { } - - EventSaverxAODNext::~EventSaverxAODNext() - { + + EventSaverxAODNext::~EventSaverxAODNext() { } - void EventSaverxAODNext::initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches) { + void EventSaverxAODNext::initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches) { m_config = config; m_outputFile = file; top::check(evtStore()->event()->writeTo(m_outputFile), "EventSaverxAODNext trying to call writeTo on output file"); - // Persist the top::TopConfig settings - we'll need this to make sense of the output when reading it back - top::check( outputMetaStore()->record( m_config->createPersistentSettings() , "TopPersistentSettings" ) , "Failed to save TopPersistentSettings" ); + // Persist the top::TopConfig settings - we'll need this to make sense of the output when reading it back + top::check(outputMetaStore()->record( + m_config->createPersistentSettings(), "TopPersistentSettings"), + "Failed to save TopPersistentSettings"); auto* const settings = top::ConfigurationSettings::get(); - + //EventInfo std::string eventInfoList = settings->value("EventVariableSaveList"); - if (config->isMC()) - eventInfoList += ".mcChannelNumber.mcEventWeights"; + if (config->isMC()) eventInfoList += ".mcChannelNumber.mcEventWeights"; //Add extra branches - e.g. if it passed the ee / mumu / emu selection per event for (const auto& branchName : extraBranches) - eventInfoList += "." + branchName; + eventInfoList += "." + branchName; - //std::cout << "EventLoaderCorrectSelect::branchesToSave - EventInfo " << eventInfoList << std::endl; evtStore()->event()->setAuxItemList("EventInfoAux.", eventInfoList); - + // Photons if (m_config->usePhotons()) { std::string photonVariableSaveList = settings->value("PhotonVariableSaveList"); if (config->isMC()) { photonVariableSaveList += ".truthType.truthOrigin"; } - + for (auto currentSystematic : *m_config->systSgKeyMapPhotons()) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , photonVariableSaveList ); + evtStore()->event()->setAuxItemList(sgKey + "Aux.", photonVariableSaveList); } - } // Photons + } // Photons // Electrons if (m_config->useElectrons()) { @@ -80,13 +78,13 @@ namespace top { if (config->isMC()) { electronVariableSaveList += ".truthType.truthOrigin"; } - + for (auto currentSystematic : *m_config->systSgKeyMapElectrons()) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , electronVariableSaveList ); + evtStore()->event()->setAuxItemList(sgKey + "Aux.", electronVariableSaveList); } } // Electrons - + // Muons if (m_config->useMuons()) { std::string muonVariableSaveList = settings->value("MuonVariableSaveList"); @@ -95,71 +93,71 @@ namespace top { // if (config->isMC()) { // muonVariableSaveList += ".truthType.truthOrigin"; // } - + for (auto currentSystematic : *m_config->systSgKeyMapMuons()) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , muonVariableSaveList ); + evtStore()->event()->setAuxItemList(sgKey + "Aux.", muonVariableSaveList); } - } // Muons - + } // Muons + // Taus if (m_config->useTaus()) { std::string tauVariableSaveList = settings->value("TauVariableSaveList"); - + for (auto currentSystematic : *m_config->systSgKeyMapTaus()) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , tauVariableSaveList ); + evtStore()->event()->setAuxItemList(sgKey + "Aux.", tauVariableSaveList); } - } // Taus - - + } // Taus + + // Jets if (m_config->useJets()) { std::string jetVariableSaveList = settings->value("JetVariableSaveList"); - + for (auto currentSystematic : *m_config->systSgKeyMapJets(false)) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , jetVariableSaveList ); - } + evtStore()->event()->setAuxItemList(sgKey + "Aux.", jetVariableSaveList); + } } - + if (m_config->useLargeRJets()) { std::string jetVariableSaveList = settings->value("JetVariableSaveList"); - + for (auto currentSystematic : *m_config->systSgKeyMapLargeRJets()) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , jetVariableSaveList ); - } - } - + evtStore()->event()->setAuxItemList(sgKey + "Aux.", jetVariableSaveList); + } + } + if (m_config->useTrackJets()) { std::string jetVariableSaveList = settings->value("JetVariableSaveList"); - + for (auto currentSystematic : *m_config->systSgKeyMapTrackJets()) { std::string sgKey = currentSystematic.second; - evtStore()->event()->setAuxItemList(sgKey + "Aux." , jetVariableSaveList ); - } - } - + evtStore()->event()->setAuxItemList(sgKey + "Aux.", jetVariableSaveList); + } + } + if (m_config->useJets() || m_config->useLargeRJets() || m_config->useTrackJets()) { // B-tagging std::string bTagVariableSaveList = settings->value("BTagVariableSaveList"); - evtStore()->event()->setAuxItemList("BTagging_AntiKt4EMTopoAux.",bTagVariableSaveList); - } // B-tagging - - + evtStore()->event()->setAuxItemList("BTagging_AntiKt4EMTopoAux.", bTagVariableSaveList); + } // B-tagging } - void EventSaverxAODNext::saveEventToxAOD() - { - // Systematic Event + void EventSaverxAODNext::saveEventToxAOD() { + // Systematic Event const xAOD::SystematicEventContainer* allSystematics(nullptr); - top::check(evtStore()->retrieve(allSystematics,m_config->sgKeyTopSystematicEvents()) , "Failed to retrieve xAOD::SystematicEventContainer" ); - + + top::check(evtStore()->retrieve(allSystematics, + m_config->sgKeyTopSystematicEvents()), + "Failed to retrieve xAOD::SystematicEventContainer"); + // Save all reco event objects? // If no systematic in the event passes the event selection // We don't fill the collections - this saves a lot of disk space - bool saveEvent(false),saveEventObjects(false); + bool saveEvent(false), saveEventObjects(false); if (!m_config->saveOnlySelectedEvents()) { saveEvent = true; } @@ -172,143 +170,148 @@ namespace top { } } } // Save reco event? - - if (saveEvent) { + if (saveEvent) { //Event Info - top::check(evtStore()->event()->copy("EventInfo"), "copying event info failed"); - - // BTagging - can consider thinning this at some point. + top::check(evtStore()->event()->copy("EventInfo"), "copying event info failed"); + + // BTagging - can consider thinning this at some point. // Tricky computation as all jet collections need updated ElementLinks - top::check(evtStore()->event()->copy("BTagging_AntiKt4EMTopo") , "copying btagging failed" ); + top::check(evtStore()->event()->copy("BTagging_AntiKt4EMTopo"), "copying btagging failed"); top::check(evtStore()->event()->copy("egammaClusters"), "copying egamma clusters failed"); - - // Object Thinning maps - std::shared_ptr<ThinningMap_t> photonThinningMap = savePhotons(saveEventObjects); + + // Object Thinning maps + std::shared_ptr<ThinningMap_t> photonThinningMap = savePhotons(saveEventObjects); std::shared_ptr<ThinningMap_t> electronThinningMap = saveElectrons(saveEventObjects); - std::shared_ptr<ThinningMap_t> muonThinningMap = saveMuons(saveEventObjects); + std::shared_ptr<ThinningMap_t> muonThinningMap = saveMuons(saveEventObjects); std::shared_ptr<ThinningMap_t> tauThinningMap = saveTaus(saveEventObjects); - std::shared_ptr<ThinningMap_t> jetThinningMap = saveJets(saveEventObjects); - std::shared_ptr<ThinningMap_t> largeRJetThinningMap = saveLargeRJets(saveEventObjects); + std::shared_ptr<ThinningMap_t> jetThinningMap = saveJets(saveEventObjects); + std::shared_ptr<ThinningMap_t> largeRJetThinningMap = saveLargeRJets(saveEventObjects); std::shared_ptr<ThinningMap_t> trackJetThinningMap = saveTrackJets(saveEventObjects); - + // Save SystematicEventContainer - xAOD::SystematicEventContainer* allSystematics_output = new xAOD::SystematicEventContainer{}; - SG::IAuxStore* allSystematics_output_aux = evtStore()->event()->recordAux( m_config->sgKeyTopSystematicEvents() + "Aux." ); - allSystematics_output->setStore( allSystematics_output_aux ); + xAOD::SystematicEventContainer* allSystematics_output = new xAOD::SystematicEventContainer {}; + SG::IAuxStore* allSystematics_output_aux = evtStore()->event()->recordAux( + m_config->sgKeyTopSystematicEvents() + "Aux."); + allSystematics_output->setStore(allSystematics_output_aux); if (saveEventObjects) { for (auto systematicPtr : *allSystematics) { - xAOD::SystematicEvent* out = new xAOD::SystematicEvent{}; - out->makePrivateStore( *systematicPtr ); - out->setGoodPhotons ( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodPhotons() , photonThinningMap ) ); - out->setGoodElectrons ( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodElectrons() , electronThinningMap ) ); - out->setGoodMuons ( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodMuons() , muonThinningMap ) ); - out->setGoodTaus ( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodTaus() , tauThinningMap ) ); - out->setGoodJets ( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodJets() , jetThinningMap ) ); - out->setGoodLargeRJets( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodLargeRJets() , largeRJetThinningMap ) ); - out->setGoodTrackJets ( thinObjectSelection( systematicPtr->hashValue() , systematicPtr->goodTrackJets() , trackJetThinningMap ) ); - allSystematics_output->push_back( out ); - - // Missing ET + if (!(systematicPtr->hashValue() == m_config->nominalHashValue() || m_config->doTightSysts() || + m_config->doLooseSysts())) continue; + xAOD::SystematicEvent* out = new xAOD::SystematicEvent {}; + out->makePrivateStore(*systematicPtr); + out->setGoodPhotons(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodPhotons(), + photonThinningMap)); + out->setGoodElectrons(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodElectrons(), + electronThinningMap)); + out->setGoodMuons(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodMuons(), + muonThinningMap)); + out->setGoodTaus(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodTaus(), tauThinningMap)); + out->setGoodJets(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodJets(), jetThinningMap)); + out->setGoodLargeRJets(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodLargeRJets(), + largeRJetThinningMap)); + out->setGoodTrackJets(thinObjectSelection(systematicPtr->hashValue(), systematicPtr->goodTrackJets(), + trackJetThinningMap)); + allSystematics_output->push_back(out); + + // Missing ET xAOD::MissingETContainer* met(nullptr); - top::check( evtStore()->retrieve(met,m_config->sgKeyMissingEt( systematicPtr->hashValue() ) ) , "Failed to retrieve MET" ); - - xAOD::MissingETContainer* output_met = new xAOD::MissingETContainer{}; - SG::IAuxStore* output_met_aux = evtStore()->event()->recordAux( m_config->sgKeyMissingEt( systematicPtr->hashValue() ) + "Aux." ); - output_met->setStore( output_met_aux ); + top::check(evtStore()->retrieve(met, m_config->sgKeyMissingEt( + systematicPtr->hashValue())), "Failed to retrieve MET"); + + xAOD::MissingETContainer* output_met = new xAOD::MissingETContainer {}; + SG::IAuxStore* output_met_aux = + evtStore()->event()->recordAux(m_config->sgKeyMissingEt(systematicPtr->hashValue()) + "Aux."); + output_met->setStore(output_met_aux); for (auto x : *met) { - xAOD::MissingET* out = new xAOD::MissingET{}; - out->makePrivateStore( *x ); - output_met->push_back( out ); + xAOD::MissingET* out = new xAOD::MissingET {}; + out->makePrivateStore(*x); + output_met->push_back(out); } - top::check( evtStore()->event()->record(output_met,m_config->sgKeyMissingEt( systematicPtr->hashValue() )) , "Failed to save MET" ); - - + top::check(evtStore()->event()->record(output_met, m_config->sgKeyMissingEt( + systematicPtr->hashValue())), "Failed to save MET"); } } - top::check(evtStore()->event()->record(allSystematics_output,m_config->sgKeyTopSystematicEvents()),"Failed to record xAOD::SystematicEventContainer" ); - + top::check(evtStore()->event()->record(allSystematics_output, + m_config->sgKeyTopSystematicEvents()), + "Failed to record xAOD::SystematicEventContainer"); + // Write to disk top::check(evtStore()->event()->fill(), "xAOD::TEvent fill failed"); } } - - - std::vector<unsigned int> EventSaverxAODNext::thinObjectSelection(const std::size_t hashValue , - const std::vector<unsigned int>& objectList , - const std::shared_ptr<ThinningMap_t> thinningMap) const - { + std::vector<unsigned int> EventSaverxAODNext::thinObjectSelection(const std::size_t hashValue, + const std::vector<unsigned int>& objectList, + const std::shared_ptr<ThinningMap_t> thinningMap) + const { // reduced output std::vector<unsigned int> out; - + // Find the correct systematic in the thinningMap - ThinningMap_Itr Itr = thinningMap->find( hashValue ); + ThinningMap_Itr Itr = thinningMap->find(hashValue); // If the systematic is not in the map, then we use the nominal hashValue // This happens, for example, when we look at a jet systematic and are looping over electrons if (Itr == thinningMap->end()) { - Itr = thinningMap->find( m_config->nominalHashValue() ); + Itr = thinningMap->find(m_config->nominalHashValue()); } - + // double check that we have a valid systematic if (Itr != thinningMap->end()) { - // Get the relevant thinningMap for this specific systematic - std::map<unsigned int,unsigned int> currentSystematicThinningMap = (*Itr).second; - + std::map<unsigned int, unsigned int> currentSystematicThinningMap = (*Itr).second; + // Loop over the original good object list, this contains information about objects we are not going to save // Use the thinningMap to build a new good object list based on the objects we are saving for (auto i : objectList) { - std::map<unsigned int,unsigned int>::const_iterator Itr2 = currentSystematicThinningMap.find( i ); + std::map<unsigned int, unsigned int>::const_iterator Itr2 = currentSystematicThinningMap.find(i); if (Itr2 != currentSystematicThinningMap.end()) { - out.push_back( (*Itr2).second ); + out.push_back((*Itr2).second); } - } + } } - + return out; } /** - * All the saveObject functions work the same way - * - we should probably turn this into a template method at some point - * - * We only save objects that pass the pre overlap removal selection - * - This throws away a lot of objects and saves a lot of disk space - * - * We need to consider every calibration systematic variation - * - Each calibration systematic contains a vector of goodIndices used to form top::Event's - * - We need to re-map these vectors if we throw away objects - * - For example, lets consider a dummy jet systematic: - * - calibrated JetContainer has objects [0,1,2,3,4,5,6,7,8] - * - The pre OR selection cuts keep objects [3,4,7] - * - We only want to save objects [3,4,7], objects [0,1,2,5,6,8] are a waste of disk space - * - The saved objects in the output mini-xAOD become [0,1,2] - * - We need to map [ 3->0 , 4->1 , 7->2 ] - * - This needs to be done for each xAOD::SystematicEvent - * - */ - - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::savePhotons(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + * All the saveObject functions work the same way + * - we should probably turn this into a template method at some point + * + * We only save objects that pass the pre overlap removal selection + * - This throws away a lot of objects and saves a lot of disk space + * + * We need to consider every calibration systematic variation + * - Each calibration systematic contains a vector of goodIndices used to form top::Event's + * - We need to re-map these vectors if we throw away objects + * - For example, lets consider a dummy jet systematic: + * - calibrated JetContainer has objects [0,1,2,3,4,5,6,7,8] + * - The pre OR selection cuts keep objects [3,4,7] + * - We only want to save objects [3,4,7], objects [0,1,2,5,6,8] are a waste of disk space + * - The saved objects in the output mini-xAOD become [0,1,2] + * - We need to map [ 3->0 , 4->1 , 7->2 ] + * - This needs to be done for each xAOD::SystematicEvent + * + */ + + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::savePhotons( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->usePhotons()) { - for (auto currentSystematic : *m_config->systSgKeyMapPhotons()) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::PhotonContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve photons"); - - xAOD::PhotonContainer* output = new xAOD::PhotonContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve photons"); + + xAOD::PhotonContainer* output = new xAOD::PhotonContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -320,44 +323,42 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::Photon* out = new xAOD::Photon{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::Photon* out = new xAOD::Photon {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container - } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::PhotonContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); + } // saveEventObjects + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::PhotonContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); } // Loop over all systematics; } // use object type - - return thinningMap; + + return thinningMap; } - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::saveElectrons(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::saveElectrons( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->useElectrons()) { - for (auto currentSystematic : *m_config->systSgKeyMapElectrons()) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::ElectronContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve electrons"); - - xAOD::ElectronContainer* output = new xAOD::ElectronContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve electrons"); + + xAOD::ElectronContainer* output = new xAOD::ElectronContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -369,50 +370,47 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::Electron* out = new xAOD::Electron{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::Electron* out = new xAOD::Electron {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container - // Reset calo cluster links - for (std::map<unsigned int,unsigned int>::const_iterator i=currentSystematicThinningMap.begin();i!=currentSystematicThinningMap.end();++i) { - output->at((*i).second)->setCaloClusterLinks( xaod->at((*i).first)->caloClusterLinks() ); - } - } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::ElectronContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); - } // Loop over all systematics + // Reset calo cluster links + for (std::map<unsigned int, unsigned int>::const_iterator i = currentSystematicThinningMap.begin(); + i != currentSystematicThinningMap.end(); ++i) { + output->at((*i).second)->setCaloClusterLinks(xaod->at((*i).first)->caloClusterLinks()); + } + } // saveEventObjects + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::ElectronContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); + } // Loop over all systematics } // use object type - - return thinningMap; - } - + return thinningMap; + } - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::saveMuons(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::saveMuons( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->useMuons()) { - for (auto currentSystematic : *m_config->systSgKeyMapMuons()) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::MuonContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve muons"); - - xAOD::MuonContainer* output = new xAOD::MuonContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve muons"); + + xAOD::MuonContainer* output = new xAOD::MuonContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -424,44 +422,42 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::Muon* out = new xAOD::Muon{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::Muon* out = new xAOD::Muon {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container - } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::MuonContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); - } // Loop over all systematics + } // saveEventObjects + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::MuonContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); + } // Loop over all systematics } // use object type - - return thinningMap; + + return thinningMap; } - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::saveTaus(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::saveTaus( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->useTaus()) { - for (auto currentSystematic : *m_config->systSgKeyMapTaus()) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::TauJetContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve taus"); - - xAOD::TauJetContainer* output = new xAOD::TauJetContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve taus"); + + xAOD::TauJetContainer* output = new xAOD::TauJetContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -473,44 +469,42 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::TauJet* out = new xAOD::TauJet{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::TauJet* out = new xAOD::TauJet {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::TauJetContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); - } // Loop over all systematics + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::TauJetContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); + } // Loop over all systematics } // use object type - - return thinningMap; + + return thinningMap; } - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::saveJets(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::saveJets( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->useJets()) { - for (auto currentSystematic : *m_config->systSgKeyMapJets(false)) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::JetContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve electrons"); - - xAOD::JetContainer* output = new xAOD::JetContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve electrons"); + + xAOD::JetContainer* output = new xAOD::JetContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -522,50 +516,48 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::Jet* out = new xAOD::Jet{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::Jet* out = new xAOD::Jet {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container - + // Reset b-tagging links - for (std::map<unsigned int,unsigned int>::const_iterator i=currentSystematicThinningMap.begin();i!=currentSystematicThinningMap.end();++i) { - output->at((*i).second)->setBTaggingLink ( xaod->at((*i).first)->btaggingLink() ); - } - - } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::JetContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); - } // Loop over all systematics + //for (std::map<unsigned int, unsigned int>::const_iterator i = currentSystematicThinningMap.begin(); + // i != currentSystematicThinningMap.end(); ++i) { + // output->at((*i).second)->setBTaggingLink(xaod->at((*i).first)->btaggingLink()); + //} + } // saveEventObjects + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::JetContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); + } // Loop over all systematics } // use object type - - return thinningMap; + + return thinningMap; } - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::saveLargeRJets(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::saveLargeRJets( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->useLargeRJets()) { - for (auto currentSystematic : *m_config->systSgKeyMapLargeRJets()) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::JetContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve electrons"); - - xAOD::JetContainer* output = new xAOD::JetContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve electrons"); + + xAOD::JetContainer* output = new xAOD::JetContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -577,50 +569,48 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::Jet* out = new xAOD::Jet{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::Jet* out = new xAOD::Jet {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container - + // Reset b-tagging links - for (std::map<unsigned int,unsigned int>::const_iterator i=currentSystematicThinningMap.begin();i!=currentSystematicThinningMap.end();++i) { - output->at((*i).second)->setBTaggingLink ( xaod->at((*i).first)->btaggingLink() ); - } - + //for (std::map<unsigned int, unsigned int>::const_iterator i = currentSystematicThinningMap.begin(); + // i != currentSystematicThinningMap.end(); ++i) { + // output->at((*i).second)->setBTaggingLink(xaod->at((*i).first)->btaggingLink()); + //} } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::JetContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); - } // Loop over all systematics + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::JetContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); + } // Loop over all systematics } // use object type - - return thinningMap; - } - - std::shared_ptr<std::map<std::size_t,std::map<unsigned int,unsigned int>>> EventSaverxAODNext::saveTrackJets(const bool saveEventObjects) - { - std::shared_ptr<ThinningMap_t> thinningMap( new ThinningMap_t ); + + return thinningMap; + } + + std::shared_ptr<std::map<std::size_t, std::map<unsigned int, unsigned int> > > EventSaverxAODNext::saveTrackJets( + const bool saveEventObjects) { + std::shared_ptr<ThinningMap_t> thinningMap(new ThinningMap_t); if (m_config->useTrackJets()) { - for (auto currentSystematic : *m_config->systSgKeyMapTrackJets()) { - std::map<unsigned int,unsigned int> currentSystematicThinningMap; + std::map<unsigned int, unsigned int> currentSystematicThinningMap; std::string sgKey = currentSystematic.second; const xAOD::JetContainer* xaod(nullptr); - top::check(evtStore()->retrieve(xaod,sgKey),"Failed to retrieve electrons"); - - xAOD::JetContainer* output = new xAOD::JetContainer{}; - SG::IAuxStore* output_aux = evtStore()->event()->recordAux( sgKey + "Aux." ); - output->setStore( output_aux ); - - if( saveEventObjects ) { - unsigned int index(0),indexReduced(0); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve electrons"); + + xAOD::JetContainer* output = new xAOD::JetContainer {}; + SG::IAuxStore* output_aux = evtStore()->event()->recordAux(sgKey + "Aux."); + output->setStore(output_aux); + + if (saveEventObjects) { + unsigned int index(0), indexReduced(0); for (auto x : *xaod) { - bool save(m_saveAllObjects); if (x->isAvailable<char>("passPreORSelection")) { if (x->auxdataConst<char>("passPreORSelection") == 1) { @@ -632,34 +622,34 @@ namespace top { save = true; } } - + if (save) { - currentSystematicThinningMap.insert( std::make_pair( index , indexReduced ) ); - xAOD::Jet* out = new xAOD::Jet{}; - out->makePrivateStore( *x ); - output->push_back( out ); + currentSystematicThinningMap.insert(std::make_pair(index, indexReduced)); + xAOD::Jet* out = new xAOD::Jet {}; + out->makePrivateStore(*x); + output->push_back(out); ++indexReduced; } ++index; } // Loop over container - + // Reset b-tagging links - for (std::map<unsigned int,unsigned int>::const_iterator i=currentSystematicThinningMap.begin();i!=currentSystematicThinningMap.end();++i) { - output->at((*i).second)->setBTaggingLink ( xaod->at((*i).first)->btaggingLink() ); - } - + //for (std::map<unsigned int, unsigned int>::const_iterator i = currentSystematicThinningMap.begin(); + // i != currentSystematicThinningMap.end(); ++i) { + // output->at((*i).second)->setBTaggingLink(xaod->at((*i).first)->btaggingLink()); + //} } // saveEventObjects - top::check(evtStore()->event()->record(output,sgKey),"Failed to record xAOD::JetContainer"); - thinningMap->insert( std::make_pair(currentSystematic.first, currentSystematicThinningMap) ); - } // Loop over all systematics + top::check(evtStore()->event()->record(output, sgKey), "Failed to record xAOD::JetContainer"); + thinningMap->insert(std::make_pair(currentSystematic.first, currentSystematicThinningMap)); + } // Loop over all systematics } // use object type - - return thinningMap; - } - void EventSaverxAODNext::finalize() { - m_outputFile->Write(); - top::check(evtStore()->event()->finishWritingTo(m_outputFile), "EventSaverxAODNext::finalise trying to call finishWritingTo"); + return thinningMap; } + void EventSaverxAODNext::finalize() { + m_outputFile->Write(); + top::check(evtStore()->event()->finishWritingTo( + m_outputFile), "EventSaverxAODNext::finalise trying to call finishWritingTo"); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelection.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelection.cxx index 90f4fbf746877273a0533e09840dd28392d4c0d2..2206953a410a48a24bca0ca922a179063ec4a9bb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelection.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelection.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/EventSelection.h" #include "TopAnalysis/Tools.h" @@ -25,408 +25,494 @@ #include "TopParticleLevel/ParticleLevelEvent.h" #include "TopEventSelectionTools/FakesMMConfigs.h" +#include "TopEventSelectionTools/NJetBtagSelector.h" -namespace top { - -EventSelection::EventSelection(const std::string& name, const std::vector<std::string>& cutNames, TFile* outputFile, const std::vector<std::unique_ptr<top::ToolLoaderBase>>& toolLoaders,std::shared_ptr<top::TopConfig> config, EL::Worker* wk) : - m_cutflow(nullptr), - m_cutflow_Loose(nullptr), - m_cutflowMCWeights(nullptr), - m_cutflowMCWeights_Loose(nullptr), - m_cutflowPUWeights(nullptr), - m_cutflowPUWeights_Loose(nullptr), - m_cutflowZVtxWeights(nullptr), - m_cutflowZVtxWeights_Loose(nullptr), - m_cutflowMCPUWeights(nullptr), - m_cutflowMCPUWeights_Loose(nullptr), - m_cutflowMCPUZVtxWeights(nullptr), - m_cutflowMCPUZVtxWeights_Loose(nullptr), - m_cutflowScaleFactors(nullptr), - m_cutflowScaleFactors_Loose(nullptr), - m_cutflowBScaleFactors(nullptr), - m_cutflowBScaleFactors_Loose(nullptr), - m_cutflowParticleLevel(nullptr), - m_cutflowUpgradeLevel(nullptr), - m_name(name), - m_isMC(false), - m_sfRetriever(nullptr), - m_nominalHashValue(0), - m_containsInitial(false), - m_containsGRL(false), - m_containsGoodCalo(false), - m_containsPrimaryVertex(false), - m_positionInitial(0), - m_positionGRL(0), - m_positionGoodCalo(0), - m_positionPrimaryVertex(0), - m_toBeSaved(false) -{ +#include "TopAnalysis/MsgCategory.h" +using namespace TopAnalysis; +namespace top { + EventSelection::EventSelection(const std::string& name, const std::vector<std::string>& cutNames, TFile* outputFile, + const std::vector<std::unique_ptr<top::ToolLoaderBase> >& toolLoaders, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk) : + m_cutflow(nullptr), + m_cutflow_Loose(nullptr), + m_cutflowMCWeights(nullptr), + m_cutflowMCWeights_Loose(nullptr), + m_cutflowPUWeights(nullptr), + m_cutflowPUWeights_Loose(nullptr), + m_cutflowZVtxWeights(nullptr), + m_cutflowZVtxWeights_Loose(nullptr), + m_cutflowMCPUWeights(nullptr), + m_cutflowMCPUWeights_Loose(nullptr), + m_cutflowMCPUZVtxWeights(nullptr), + m_cutflowMCPUZVtxWeights_Loose(nullptr), + m_cutflowScaleFactors(nullptr), + m_cutflowScaleFactors_Loose(nullptr), + m_cutflowBScaleFactors(nullptr), + m_cutflowBScaleFactors_Loose(nullptr), + m_cutflowParticleLevel(nullptr), + m_cutflowParticleLevelMCWeights(nullptr), + m_cutflowUpgradeLevel(nullptr), + m_name(name), + m_isMC(false), + m_sfRetriever(nullptr), + m_nominalHashValue(0), + m_containsInitial(false), + m_containsGRL(false), + m_containsGoodCalo(false), + m_containsPrimaryVertex(false), + m_positionInitial(0), + m_positionGRL(0), + m_positionGoodCalo(0), + m_positionPrimaryVertex(0), + m_toBeSaved(false) { // We use the nominal hash value so we don't do // string comparisions during the event loop CP::SystematicSet nominal; m_nominalHashValue = nominal.hash(); - + // need that later for the sf in the cutflow, not especially elegant but works for now m_config = config; - m_isMC = config->isMC(); + m_isMC = config->isMC(); - if(m_isMC) - m_sfRetriever = std::unique_ptr<top::ScaleFactorRetriever> ( new top::ScaleFactorRetriever( config) ); + if (m_isMC) { + this->initialiseTopScaleFactorRetriever(m_config); + } TDirectory* plotDir = outputFile->mkdir(m_name.c_str()); plotDir->cd(); - if (!config->doLooseTreeOnly()) { + if (config->doTightEvents()) { m_cutflow = new TH1D("cutflow", (name + " cutflow").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowMCWeights = new TH1D("cutflow_mc", (name + " cutflow MC weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowPUWeights = new TH1D("cutflow_pu", (name + " cutflow PU weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowZVtxWeights = new TH1D("cutflow_zvtx", (name + " cutflow ZVtx weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowMCPUWeights = new TH1D("cutflow_mc_pu", (name + " cutflow MC*PU weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowMCPUZVtxWeights = new TH1D("cutflow_mc_pu_zvtx", (name + " cutflow MC*PU*ZVtx weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowScaleFactors = new TH1D("cutflow_scale_factors", (name + " cutflow ScaleFactors").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowBScaleFactors = new TH1D("cutflow_btag_scale_factors", (name + " cutflow b-tag ScaleFactors").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowMCWeights = new TH1D("cutflow_mc", (name + " cutflow MC weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowPUWeights = new TH1D("cutflow_pu", (name + " cutflow PU weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowZVtxWeights = new TH1D("cutflow_zvtx", (name + " cutflow ZVtx weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowMCPUWeights = new TH1D("cutflow_mc_pu", (name + " cutflow MC*PU weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowMCPUZVtxWeights = new TH1D("cutflow_mc_pu_zvtx", + (name + " cutflow MC*PU*ZVtx weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowScaleFactors = new TH1D("cutflow_scale_factors", (name + " cutflow ScaleFactors").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowBScaleFactors = new TH1D("cutflow_btag_scale_factors", + (name + " cutflow b-tag ScaleFactors").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); } if (config->doLooseEvents()) { - m_cutflow_Loose = new TH1D("cutflow_Loose", (name + " cutflow_Loose").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowMCWeights_Loose = new TH1D("cutflow_mc_Loose", (name + " cutflow_Loose MC weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowPUWeights_Loose = new TH1D("cutflow_pu_Loose", (name + " cutflow_Loose PU weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowZVtxWeights_Loose = new TH1D("cutflow_zvtx_Loose", (name + " cutflow_Loose ZVtx weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowMCPUWeights_Loose = new TH1D("cutflow_mc_pu_Loose", (name + " cutflow_Loose MC*PU weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowMCPUZVtxWeights_Loose = new TH1D("cutflow_mc_pu_zvtx_Loose", (name + " cutflow_Loose MC*PU*ZVtx weights").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowScaleFactors_Loose = new TH1D("cutflow_scale_factors_Loose", (name + " cutflow_Loose ScaleFactors").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); - m_cutflowBScaleFactors_Loose = new TH1D("cutflow_btag_scale_factors_Loose", (name + " cutflow_Loose b-tag ScaleFactors").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflow_Loose = new TH1D("cutflow_Loose", (name + " cutflow_Loose").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowMCWeights_Loose = new TH1D("cutflow_mc_Loose", + (name + " cutflow_Loose MC weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowPUWeights_Loose = new TH1D("cutflow_pu_Loose", + (name + " cutflow_Loose PU weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowZVtxWeights_Loose = new TH1D("cutflow_zvtx_Loose", + (name + " cutflow_Loose ZVtx weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowMCPUWeights_Loose = new TH1D("cutflow_mc_pu_Loose", + (name + " cutflow_Loose MC*PU weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowMCPUZVtxWeights_Loose = new TH1D("cutflow_mc_pu_zvtx_Loose", + (name + " cutflow_Loose MC*PU*ZVtx weights").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowScaleFactors_Loose = new TH1D("cutflow_scale_factors_Loose", + (name + " cutflow_Loose ScaleFactors").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowBScaleFactors_Loose = + new TH1D("cutflow_btag_scale_factors_Loose", (name + " cutflow_Loose b-tag ScaleFactors").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); } - if ( config->doTopParticleLevel() ){ - m_cutflowParticleLevel = new TH1D("cutflow_particle_level", (name + " cutflow_particle_level").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); + if (config->doTopParticleLevel()) { + m_cutflowParticleLevel = new TH1D("cutflow_particle_level", + (name + " cutflow_particle_level").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); + m_cutflowParticleLevelMCWeights = new TH1D("cutflow_particle_level_mc", + (name + " cutflow_particle_level_mc").c_str(), + cutNames.size(), -0.5, cutNames.size() - 0.5); } - if ( config->HLLHC() ){ - m_cutflowUpgradeLevel = new TH1D("cutflow_upgrade_level", (name + " cutflow_upgrade_level").c_str(), cutNames.size(), -0.5, cutNames.size() - 0.5); + if (config->HLLHC()) { + m_cutflowUpgradeLevel = new TH1D("cutflow_upgrade_level", + (name + " cutflow_upgrade_level").c_str(), cutNames.size(), -0.5, + cutNames.size() - 0.5); } unsigned int i(0); for (const auto& currentCutName : cutNames) { + //look through all the libraries and load any tools + top::EventSelectorBase* tool = nullptr; + for (auto& libraryPtr : toolLoaders) { + tool = libraryPtr->initTool(m_name, currentCutName, outputFile, config, wk); + if (tool) break; + } - //look through all the libraries and load any tools - top::EventSelectorBase* tool = nullptr; - for (auto& libraryPtr : toolLoaders) { - tool = libraryPtr->initTool(m_name, currentCutName, outputFile, config, wk); - if (tool) - break; - } + if (tool != nullptr) { + m_allCuts.emplace_back(std::move(tool)); + } else { + throw std::runtime_error("Could not find " + currentCutName); + } - if (tool != nullptr) { - m_allCuts.emplace_back(std::move(tool)); - } else { - std::cout << "Could not find " << currentCutName << std::endl; - exit(1); - } - - // Initlal and GRL - if (currentCutName == "INITIAL") { - m_containsInitial = true; - m_positionInitial = i; - } - - if (currentCutName == "GRL") { - m_containsGRL = true; - m_positionGRL = i; - } - - if (currentCutName == "GOODCALO") { - m_containsGoodCalo = true; - m_positionGoodCalo = i; - } - - if (currentCutName == "PRIVTX") { - m_containsPrimaryVertex = true; - m_positionPrimaryVertex = i; - } - - //some cutflow histograms - if (!config->doLooseTreeOnly()) { - m_cutflow->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowMCWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowPUWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowZVtxWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowMCPUWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowMCPUZVtxWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowScaleFactors->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowBScaleFactors->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - } - if (config->doLooseEvents()) { - m_cutflow_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowMCWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowPUWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowZVtxWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowMCPUWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowMCPUZVtxWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowScaleFactors_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - m_cutflowBScaleFactors_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - } + // Initlal and GRL + if (currentCutName == "INITIAL") { + m_containsInitial = true; + m_positionInitial = i; + } - if ( m_cutflowParticleLevel ){ - m_cutflowParticleLevel->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - } + if (currentCutName == "GRL") { + m_containsGRL = true; + m_positionGRL = i; + } - if ( m_cutflowUpgradeLevel ){ - m_cutflowUpgradeLevel->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); - } - - if (currentCutName == "SAVE") { - m_toBeSaved = true; - } + if (currentCutName == "GOODCALO") { + m_containsGoodCalo = true; + m_positionGoodCalo = i; + } + + if (currentCutName == "PRIVTX") { + m_containsPrimaryVertex = true; + m_positionPrimaryVertex = i; + } + + //some cutflow histograms + if (config->doTightEvents()) { + m_cutflow->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowMCWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowPUWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowZVtxWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowMCPUWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowMCPUZVtxWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowScaleFactors->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowBScaleFactors->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + } + if (config->doLooseEvents()) { + m_cutflow_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowMCWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowPUWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowZVtxWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowMCPUWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowMCPUZVtxWeights_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowScaleFactors_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + m_cutflowBScaleFactors_Loose->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + } + + if (m_cutflowParticleLevel) { + m_cutflowParticleLevel->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + } + + if (m_cutflowParticleLevelMCWeights) { + m_cutflowParticleLevelMCWeights->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + } + + if (m_cutflowUpgradeLevel) { + m_cutflowUpgradeLevel->GetXaxis()->SetBinLabel(i + 1, m_allCuts[i]->name().c_str()); + } + + if (currentCutName == "SAVE") { + m_toBeSaved = true; + } - ++i; + ++i; } //be nice to the user and tell them what they enabled //at the very start of the run. It allows them to quit the program //if they notice a problem. printCuts(); -} - -EventSelection::EventSelection(EventSelection&& other) : - m_allCuts(std::move(other.m_allCuts)), - m_cutflow(std::move(other.m_cutflow)), - m_cutflow_Loose(std::move(other.m_cutflow_Loose)), - m_cutflowMCWeights(std::move(other.m_cutflowMCWeights)), - m_cutflowMCWeights_Loose(std::move(other.m_cutflowMCWeights_Loose)), - m_cutflowPUWeights(std::move(other.m_cutflowPUWeights)), - m_cutflowPUWeights_Loose(std::move(other.m_cutflowPUWeights_Loose)), - m_cutflowZVtxWeights(std::move(other.m_cutflowZVtxWeights)), - m_cutflowZVtxWeights_Loose(std::move(other.m_cutflowZVtxWeights_Loose)), - m_cutflowMCPUWeights(std::move(other.m_cutflowMCPUWeights)), - m_cutflowMCPUWeights_Loose(std::move(other.m_cutflowMCPUWeights_Loose)), - m_cutflowMCPUZVtxWeights(std::move(other.m_cutflowMCPUZVtxWeights)), - m_cutflowMCPUZVtxWeights_Loose(std::move(other.m_cutflowMCPUZVtxWeights_Loose)), - m_cutflowScaleFactors(std::move(other.m_cutflowScaleFactors)), - m_cutflowScaleFactors_Loose(std::move(other.m_cutflowScaleFactors_Loose)), - m_cutflowBScaleFactors(std::move(other.m_cutflowBScaleFactors)), - m_cutflowBScaleFactors_Loose(std::move(other.m_cutflowBScaleFactors_Loose)), - m_cutflowParticleLevel(std::move(other.m_cutflowParticleLevel)), - m_cutflowUpgradeLevel(std::move(other.m_cutflowUpgradeLevel)), - m_name(std::move(other.m_name)), - m_isMC(std::move(other.m_isMC)), - m_config(std::move(other.m_config)), - m_sfRetriever(nullptr), - m_nominalHashValue(std::move(other.m_nominalHashValue)), - m_containsInitial(std::move(other.m_containsInitial)), - m_containsGRL(std::move(other.m_containsGRL)), - m_containsGoodCalo(std::move(other.m_containsGoodCalo)), - m_containsPrimaryVertex(std::move(other.m_containsPrimaryVertex)), - m_positionInitial(std::move(other.m_positionInitial)), - m_positionGRL(std::move(other.m_positionGRL)), - m_positionGoodCalo(std::move(other.m_positionGoodCalo)), - m_positionPrimaryVertex(std::move(other.m_positionPrimaryVertex)), - m_toBeSaved(std::move(other.m_toBeSaved)) -{ - - // need this to calculate the lepton SF for the cutflow - if(m_isMC) - m_sfRetriever = std::unique_ptr<top::ScaleFactorRetriever> ( new top::ScaleFactorRetriever( m_config ) ); - -} + } -void EventSelection::countInitial(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const -{ - if (m_containsInitial) { - if (!m_config->doLooseTreeOnly()) { - m_cutflow->Fill(m_positionInitial); - m_cutflowMCWeights->Fill(m_positionInitial,mcEventWeight); - m_cutflowPUWeights->Fill(m_positionInitial,pileupWeight); - m_cutflowZVtxWeights->Fill(m_positionInitial,zvtxWeight); - m_cutflowMCPUWeights->Fill(m_positionInitial,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights->Fill(m_positionInitial,mcEventWeight*pileupWeight*zvtxWeight); - } - if (m_config->doLooseEvents()) { - m_cutflow_Loose->Fill(m_positionInitial); - m_cutflowMCWeights_Loose->Fill(m_positionInitial,mcEventWeight); - m_cutflowPUWeights_Loose->Fill(m_positionInitial,pileupWeight); - m_cutflowZVtxWeights_Loose->Fill(m_positionInitial,zvtxWeight); - m_cutflowMCPUWeights_Loose->Fill(m_positionInitial,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionInitial,mcEventWeight*pileupWeight*zvtxWeight); + EventSelection::EventSelection(EventSelection&& other) : + m_allCuts(std::move(other.m_allCuts)), + m_cutflow(std::move(other.m_cutflow)), + m_cutflow_Loose(std::move(other.m_cutflow_Loose)), + m_cutflowMCWeights(std::move(other.m_cutflowMCWeights)), + m_cutflowMCWeights_Loose(std::move(other.m_cutflowMCWeights_Loose)), + m_cutflowPUWeights(std::move(other.m_cutflowPUWeights)), + m_cutflowPUWeights_Loose(std::move(other.m_cutflowPUWeights_Loose)), + m_cutflowZVtxWeights(std::move(other.m_cutflowZVtxWeights)), + m_cutflowZVtxWeights_Loose(std::move(other.m_cutflowZVtxWeights_Loose)), + m_cutflowMCPUWeights(std::move(other.m_cutflowMCPUWeights)), + m_cutflowMCPUWeights_Loose(std::move(other.m_cutflowMCPUWeights_Loose)), + m_cutflowMCPUZVtxWeights(std::move(other.m_cutflowMCPUZVtxWeights)), + m_cutflowMCPUZVtxWeights_Loose(std::move(other.m_cutflowMCPUZVtxWeights_Loose)), + m_cutflowScaleFactors(std::move(other.m_cutflowScaleFactors)), + m_cutflowScaleFactors_Loose(std::move(other.m_cutflowScaleFactors_Loose)), + m_cutflowBScaleFactors(std::move(other.m_cutflowBScaleFactors)), + m_cutflowBScaleFactors_Loose(std::move(other.m_cutflowBScaleFactors_Loose)), + m_cutflowParticleLevel(std::move(other.m_cutflowParticleLevel)), + m_cutflowParticleLevelMCWeights(std::move(other.m_cutflowParticleLevelMCWeights)), + m_cutflowUpgradeLevel(std::move(other.m_cutflowUpgradeLevel)), + m_name(std::move(other.m_name)), + m_isMC(std::move(other.m_isMC)), + m_config(std::move(other.m_config)), + m_sfRetriever(nullptr), + m_nominalHashValue(std::move(other.m_nominalHashValue)), + m_containsInitial(std::move(other.m_containsInitial)), + m_containsGRL(std::move(other.m_containsGRL)), + m_containsGoodCalo(std::move(other.m_containsGoodCalo)), + m_containsPrimaryVertex(std::move(other.m_containsPrimaryVertex)), + m_positionInitial(std::move(other.m_positionInitial)), + m_positionGRL(std::move(other.m_positionGRL)), + m_positionGoodCalo(std::move(other.m_positionGoodCalo)), + m_positionPrimaryVertex(std::move(other.m_positionPrimaryVertex)), + m_toBeSaved(std::move(other.m_toBeSaved)) { + // need this to calculate the lepton SF for the cutflow + if (m_isMC) { + this->initialiseTopScaleFactorRetriever(m_config); } } -} -void EventSelection::countGRL(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const -{ - if (m_containsGRL) { - if (!m_config->doLooseTreeOnly()) { - m_cutflow->Fill(m_positionGRL); - m_cutflowMCWeights->Fill(m_positionGRL,mcEventWeight); - m_cutflowPUWeights->Fill(m_positionGRL,pileupWeight); - m_cutflowZVtxWeights->Fill(m_positionGRL,zvtxWeight); - m_cutflowMCPUWeights->Fill(m_positionGRL,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights->Fill(m_positionGRL,mcEventWeight*pileupWeight*zvtxWeight); - } - if (m_config->doLooseEvents()) { - m_cutflow_Loose->Fill(m_positionGRL); - m_cutflowMCWeights_Loose->Fill(m_positionGRL,mcEventWeight); - m_cutflowPUWeights_Loose->Fill(m_positionGRL,pileupWeight); - m_cutflowZVtxWeights_Loose->Fill(m_positionGRL,zvtxWeight); - m_cutflowMCPUWeights_Loose->Fill(m_positionGRL,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionGRL,mcEventWeight*pileupWeight*zvtxWeight); + void EventSelection::initialiseTopScaleFactorRetriever(std::shared_ptr<TopConfig> config) { + // Define this once, and then use it when needed + if (asg::ToolStore::contains<ScaleFactorRetriever>("top::ScaleFactorRetriever")) { + m_sfRetriever = asg::ToolStore::get<ScaleFactorRetriever>("top::ScaleFactorRetriever"); + } else { + top::ScaleFactorRetriever* topSFR = new top::ScaleFactorRetriever("top::ScaleFactorRetriever"); + top::check(asg::setProperty(topSFR, "config", config), "Failed to set config"); + top::check(topSFR->initialize(), "Failed to initalialise"); + m_sfRetriever = topSFR; } } -} -void EventSelection::countGoodCalo(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const -{ - if (m_containsGoodCalo) { - if (!m_config->doLooseTreeOnly()) { - m_cutflow->Fill(m_positionGoodCalo); - m_cutflowMCWeights->Fill(m_positionGoodCalo,mcEventWeight); - m_cutflowPUWeights->Fill(m_positionGoodCalo,pileupWeight); - m_cutflowZVtxWeights->Fill(m_positionGoodCalo,zvtxWeight); - m_cutflowMCPUWeights->Fill(m_positionGoodCalo,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights->Fill(m_positionGoodCalo,mcEventWeight*pileupWeight*zvtxWeight); + void EventSelection::countInitial(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) const { + if (m_containsInitial) { + if (m_config->doTightEvents()) { + m_cutflow->Fill(m_positionInitial); + m_cutflowMCWeights->Fill(m_positionInitial, mcEventWeight); + m_cutflowPUWeights->Fill(m_positionInitial, pileupWeight); + m_cutflowZVtxWeights->Fill(m_positionInitial, zvtxWeight); + m_cutflowMCPUWeights->Fill(m_positionInitial, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights->Fill(m_positionInitial, mcEventWeight * pileupWeight * zvtxWeight); + } + if (m_config->doLooseEvents()) { + m_cutflow_Loose->Fill(m_positionInitial); + m_cutflowMCWeights_Loose->Fill(m_positionInitial, mcEventWeight); + m_cutflowPUWeights_Loose->Fill(m_positionInitial, pileupWeight); + m_cutflowZVtxWeights_Loose->Fill(m_positionInitial, zvtxWeight); + m_cutflowMCPUWeights_Loose->Fill(m_positionInitial, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionInitial, mcEventWeight * pileupWeight * zvtxWeight); + } } - if (m_config->doLooseEvents()) { - m_cutflow_Loose->Fill(m_positionGoodCalo); - m_cutflowMCWeights_Loose->Fill(m_positionGoodCalo,mcEventWeight); - m_cutflowPUWeights_Loose->Fill(m_positionGoodCalo,pileupWeight); - m_cutflowZVtxWeights_Loose->Fill(m_positionGoodCalo,zvtxWeight); - m_cutflowMCPUWeights_Loose->Fill(m_positionGoodCalo,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionGoodCalo,mcEventWeight*pileupWeight*zvtxWeight); + } + + void EventSelection::countGRL(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) const { + if (m_containsGRL) { + if (m_config->doTightEvents()) { + m_cutflow->Fill(m_positionGRL); + m_cutflowMCWeights->Fill(m_positionGRL, mcEventWeight); + m_cutflowPUWeights->Fill(m_positionGRL, pileupWeight); + m_cutflowZVtxWeights->Fill(m_positionGRL, zvtxWeight); + m_cutflowMCPUWeights->Fill(m_positionGRL, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights->Fill(m_positionGRL, mcEventWeight * pileupWeight * zvtxWeight); + } + if (m_config->doLooseEvents()) { + m_cutflow_Loose->Fill(m_positionGRL); + m_cutflowMCWeights_Loose->Fill(m_positionGRL, mcEventWeight); + m_cutflowPUWeights_Loose->Fill(m_positionGRL, pileupWeight); + m_cutflowZVtxWeights_Loose->Fill(m_positionGRL, zvtxWeight); + m_cutflowMCPUWeights_Loose->Fill(m_positionGRL, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionGRL, mcEventWeight * pileupWeight * zvtxWeight); + } } } -} -void EventSelection::countPrimaryVertex(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const -{ - if (m_containsPrimaryVertex) { - if (!m_config->doLooseTreeOnly()) { - m_cutflow->Fill(m_positionPrimaryVertex); - m_cutflowMCWeights->Fill(m_positionPrimaryVertex,mcEventWeight); - m_cutflowPUWeights->Fill(m_positionPrimaryVertex,pileupWeight); - m_cutflowZVtxWeights->Fill(m_positionPrimaryVertex,zvtxWeight); - m_cutflowMCPUWeights->Fill(m_positionPrimaryVertex,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights->Fill(m_positionPrimaryVertex,mcEventWeight*pileupWeight*zvtxWeight); + void EventSelection::countGoodCalo(const float mcEventWeight, const float pileupWeight, + const float zvtxWeight) const { + if (m_containsGoodCalo) { + if (m_config->doTightEvents()) { + m_cutflow->Fill(m_positionGoodCalo); + m_cutflowMCWeights->Fill(m_positionGoodCalo, mcEventWeight); + m_cutflowPUWeights->Fill(m_positionGoodCalo, pileupWeight); + m_cutflowZVtxWeights->Fill(m_positionGoodCalo, zvtxWeight); + m_cutflowMCPUWeights->Fill(m_positionGoodCalo, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights->Fill(m_positionGoodCalo, mcEventWeight * pileupWeight * zvtxWeight); + } + if (m_config->doLooseEvents()) { + m_cutflow_Loose->Fill(m_positionGoodCalo); + m_cutflowMCWeights_Loose->Fill(m_positionGoodCalo, mcEventWeight); + m_cutflowPUWeights_Loose->Fill(m_positionGoodCalo, pileupWeight); + m_cutflowZVtxWeights_Loose->Fill(m_positionGoodCalo, zvtxWeight); + m_cutflowMCPUWeights_Loose->Fill(m_positionGoodCalo, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionGoodCalo, mcEventWeight * pileupWeight * zvtxWeight); + } } - if (m_config->doLooseEvents()) { - m_cutflow_Loose->Fill(m_positionPrimaryVertex); - m_cutflowMCWeights_Loose->Fill(m_positionPrimaryVertex,mcEventWeight); - m_cutflowPUWeights_Loose->Fill(m_positionPrimaryVertex,pileupWeight); - m_cutflowZVtxWeights_Loose->Fill(m_positionPrimaryVertex,zvtxWeight); - m_cutflowMCPUWeights_Loose->Fill(m_positionPrimaryVertex,mcEventWeight*pileupWeight); - m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionPrimaryVertex,mcEventWeight*pileupWeight*zvtxWeight); + } + + void EventSelection::countPrimaryVertex(const float mcEventWeight, const float pileupWeight, + const float zvtxWeight) const { + if (m_containsPrimaryVertex) { + if (m_config->doTightEvents()) { + m_cutflow->Fill(m_positionPrimaryVertex); + m_cutflowMCWeights->Fill(m_positionPrimaryVertex, mcEventWeight); + m_cutflowPUWeights->Fill(m_positionPrimaryVertex, pileupWeight); + m_cutflowZVtxWeights->Fill(m_positionPrimaryVertex, zvtxWeight); + m_cutflowMCPUWeights->Fill(m_positionPrimaryVertex, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights->Fill(m_positionPrimaryVertex, mcEventWeight * pileupWeight * zvtxWeight); + } + if (m_config->doLooseEvents()) { + m_cutflow_Loose->Fill(m_positionPrimaryVertex); + m_cutflowMCWeights_Loose->Fill(m_positionPrimaryVertex, mcEventWeight); + m_cutflowPUWeights_Loose->Fill(m_positionPrimaryVertex, pileupWeight); + m_cutflowZVtxWeights_Loose->Fill(m_positionPrimaryVertex, zvtxWeight); + m_cutflowMCPUWeights_Loose->Fill(m_positionPrimaryVertex, mcEventWeight * pileupWeight); + m_cutflowMCPUZVtxWeights_Loose->Fill(m_positionPrimaryVertex, mcEventWeight * pileupWeight * zvtxWeight); + } } } -} -bool EventSelection::apply(const top::Event& event) const { + bool EventSelection::apply(const top::Event& event) const { unsigned int i(0); bool passEvent(false); - for (const auto& currentCut : m_allCuts) { - const bool passed = currentCut->apply(event); - //std::cout << (*it)->name() << " " << passed << std::endl; + std::string btag_string = ""; + std::string nBtagCutName = "JET_N_BTAG"; + std::string nBtagCutName_tjet = "TJET_N_BTAG"; + + // Find if this cutflow uses JET_N_BTAG or TJET_N_BTAG to identify appropriate b-tagging WP SF (if available) + // Implicitly assumes you only apply one n-btag condition (and is only for cutflow use) + auto foundBtagSelection = std::find_if(m_allCuts.begin(), m_allCuts.end(), + [&nBtagCutName](const auto& thisCut) { + return(thisCut->name() == nBtagCutName); + }); + auto foundBtagSelection_tjet = std::find_if(m_allCuts.begin(), m_allCuts.end(), + [&nBtagCutName_tjet](const auto& thisCut) { + return(thisCut->name() == nBtagCutName_tjet); + }); + if (foundBtagSelection_tjet != m_allCuts.end()) { + NJetBtagSelector* nJetBtagSelection = dynamic_cast<NJetBtagSelector*>((*foundBtagSelection_tjet).get()); + btag_string = nJetBtagSelection->getFullCutName(); + } else if (foundBtagSelection != m_allCuts.end()) { + NJetBtagSelector* nJetBtagSelection = dynamic_cast<NJetBtagSelector*>((*foundBtagSelection).get()); + btag_string = nJetBtagSelection->getFullCutName(); + } - if (!passed) - break; + for (const auto& currentCut : m_allCuts) { + const bool passed = currentCut->apply(event); - double mcweight = 1.; - double puweight = 1.; - double zvtxweight = 1.; - double leptonSF = 1.; - double btagSF = 1.; + if (!passed) break; - if (m_isMC) { -// mcweight = event.m_info->mcEventWeight(); - mcweight = event.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + double mcweight = 1.; + double puweight = 1.; + double zvtxweight = 1.; + double leptonSF = 1.; + double btagSF = 1.; - if (top::ScaleFactorRetriever::hasPileupSF(event)) - puweight = top::ScaleFactorRetriever::pileupSF(event); + if (m_isMC) { + mcweight = event.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); - leptonSF = m_sfRetriever -> leptonSF(event, top::topSFSyst::nominal); + if (top::ScaleFactorRetriever::hasPileupSF(event)) puweight = top::ScaleFactorRetriever::pileupSF(event); - for (auto& tag : ( m_config->useTrackJets() ? m_config->bTagWP_available_trkJet() : m_config->bTagWP_available())){ - btagSF = m_sfRetriever -> btagSF(event, top::topSFSyst::nominal, tag, m_config->useTrackJets()); - } + leptonSF = m_sfRetriever->leptonSF(event, top::topSFSyst::nominal); + // Need to be careful with b-tagging. Can now load multiple taggers/calibrated or not. + // Can only retrieve SF for cutflow if its calibrated + if ((m_config->useTrackJets() && + std::find(m_config->bTagWP_calibrated_trkJet().begin(), m_config->bTagWP_calibrated_trkJet().end(), + btag_string) != m_config->bTagWP_calibrated_trkJet().end()) || + (!m_config->useTrackJets() && + std::find(m_config->bTagWP_calibrated().begin(), m_config->bTagWP_calibrated().end(), + btag_string) != m_config->bTagWP_calibrated().end())) { + btagSF = m_sfRetriever->btagSF(event, top::topSFSyst::nominal, btag_string, m_config->useTrackJets()); } + } - //add cutflow information for the nominal (not systematic) selection - //For data we have (sometimes) the same event with loose and tight - //The cutflow is just the "analysis" -> tight to avoid double counting - if (event.m_hashValue == m_nominalHashValue) { - bool countThisCut(true); - if ( m_containsInitial && i == m_positionInitial) {countThisCut = false;} - if ( m_containsGRL && i == m_positionGRL) {countThisCut = false;} - if ( m_containsGoodCalo && i == m_positionGoodCalo) {countThisCut = false;} - if ( m_containsPrimaryVertex && i == m_positionPrimaryVertex) {countThisCut = false;} - if (countThisCut) { - if (!m_config->doLooseTreeOnly() && !event.m_isLoose) { - m_cutflow->Fill(i); - m_cutflowMCWeights->Fill(i, mcweight); - m_cutflowPUWeights->Fill(i, puweight); - m_cutflowZVtxWeights->Fill(i, zvtxweight); - m_cutflowMCPUWeights->Fill(i, mcweight * puweight); - m_cutflowMCPUZVtxWeights->Fill(i, mcweight * puweight * zvtxweight); - m_cutflowScaleFactors->Fill(i, leptonSF); - m_cutflowBScaleFactors->Fill(i, btagSF); - } - if (m_config->doLooseEvents() && event.m_isLoose) { - m_cutflow_Loose->Fill(i); - m_cutflowMCWeights_Loose->Fill(i, mcweight); - m_cutflowPUWeights_Loose->Fill(i, puweight); - m_cutflowZVtxWeights_Loose->Fill(i, zvtxweight); - m_cutflowMCPUWeights_Loose->Fill(i, mcweight * puweight); - m_cutflowMCPUZVtxWeights_Loose->Fill(i, mcweight * puweight * zvtxweight); - m_cutflowScaleFactors_Loose->Fill(i, leptonSF); - m_cutflowBScaleFactors_Loose->Fill(i, btagSF); - } + //add cutflow information for the nominal (not systematic) selection + //For data we have (sometimes) the same event with loose and tight + //The cutflow is just the "analysis" -> tight to avoid double counting + if (event.m_hashValue == m_nominalHashValue) { + bool countThisCut(true); + if (m_containsInitial && i == m_positionInitial) { + countThisCut = false; + } + if (m_containsGRL && i == m_positionGRL) { + countThisCut = false; + } + if (m_containsGoodCalo && i == m_positionGoodCalo) { + countThisCut = false; + } + if (m_containsPrimaryVertex && i == m_positionPrimaryVertex) { + countThisCut = false; + } + if (countThisCut) { + if (m_config->doTightEvents() && !event.m_isLoose) { + m_cutflow->Fill(i); + m_cutflowMCWeights->Fill(i, mcweight); + m_cutflowPUWeights->Fill(i, puweight); + m_cutflowZVtxWeights->Fill(i, zvtxweight); + m_cutflowMCPUWeights->Fill(i, mcweight * puweight); + m_cutflowMCPUZVtxWeights->Fill(i, mcweight * puweight * zvtxweight); + m_cutflowScaleFactors->Fill(i, leptonSF); + m_cutflowBScaleFactors->Fill(i, btagSF); + } + if (m_config->doLooseEvents() && event.m_isLoose) { + m_cutflow_Loose->Fill(i); + m_cutflowMCWeights_Loose->Fill(i, mcweight); + m_cutflowPUWeights_Loose->Fill(i, puweight); + m_cutflowZVtxWeights_Loose->Fill(i, zvtxweight); + m_cutflowMCPUWeights_Loose->Fill(i, mcweight * puweight); + m_cutflowMCPUZVtxWeights_Loose->Fill(i, mcweight * puweight * zvtxweight); + m_cutflowScaleFactors_Loose->Fill(i, leptonSF); + m_cutflowBScaleFactors_Loose->Fill(i, btagSF); } } + } - passEvent |= (currentCut->name() == "SAVE"); - ++i; + passEvent |= (currentCut->name() == "SAVE"); + ++i; } // If "SAVE" wasn't found but event passes all cuts, event passes the selection passEvent |= (i == m_allCuts.size()); return passEvent; -} + } -bool EventSelection::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const { + bool EventSelection::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const { // In principle, this function should never be called for non-active // particle level. However, for code safetly, include a null pointer // check. Return false here because "do-not-do-particle-level" is equivalent // to "do-no-save-particle-level". - if ( not m_cutflowParticleLevel ){ return false; } + if (not m_cutflowParticleLevel) { + return false; + } + if (not m_cutflowParticleLevelMCWeights) { + return false; + } unsigned int i(0); bool passEvent(false); for (const auto& currentCut : m_allCuts) { - const bool passed = currentCut->applyParticleLevel( plEvent ); - //std::cout << (*it)->name() << " " << passed << std::endl; + const bool passed = currentCut->applyParticleLevel(plEvent); - if (!passed) - break; + if (!passed) break; - m_cutflowParticleLevel->Fill(i); + m_cutflowParticleLevel->Fill(i); - passEvent |= (currentCut->name() == "SAVE"); - ++i; + double mcweight = plEvent.m_info->mcEventWeight(0); + m_cutflowParticleLevelMCWeights->Fill(i, mcweight); + + passEvent |= (currentCut->name() == "SAVE"); + ++i; } // If "SAVE" wasn't found but event passes all cuts, event passes the selection passEvent |= (i == m_allCuts.size()); return passEvent; -} + } -bool EventSelection::applyUpgradeLevel(const top::ParticleLevelEvent& upgradeEvent) const { + bool EventSelection::applyUpgradeLevel(const top::ParticleLevelEvent& upgradeEvent) const { // In principle, this function should never be called for non-active // upgrade level. However, for code safetly, include a null pointer // check. Return false here because "do-not-do-particle-level" is equivalent // to "do-no-save-particle-level". - if ( not m_cutflowUpgradeLevel ){ return false; } + if (not m_cutflowUpgradeLevel) { + return false; + } unsigned int i(0); bool passEvent(false); @@ -434,11 +520,9 @@ bool EventSelection::applyUpgradeLevel(const top::ParticleLevelEvent& upgradeEve for (const auto& currentCut : m_allCuts) { // we use applyParticleLevel, because in the end upgrade events are smeared // truth level, so we can just re-use this function - const bool passed = currentCut->applyParticleLevel( upgradeEvent ); - //std::cout << (*it)->name() << " " << passed << std::endl; + const bool passed = currentCut->applyParticleLevel(upgradeEvent); - if (!passed) - break; + if (!passed) break; m_cutflowUpgradeLevel->Fill(i); @@ -450,149 +534,163 @@ bool EventSelection::applyUpgradeLevel(const top::ParticleLevelEvent& upgradeEve passEvent |= (i == m_allCuts.size()); return passEvent; -} + } -void EventSelection::finalise() const { + void EventSelection::finalise() const { //2dp, neater output for numbers - std::cout << std::right; - if (m_isMC) - std::cout << std::fixed << std::setprecision(2); - - if (!m_config->doLooseTreeOnly()) { - //channel name - std::cout << " - " << m_name << " cutflow:\n"; - - //some headings - std::cout << std::setw(7) << "" << - std::setw(30) << "cut" << - std::setw(15) << "events"; - - if (m_isMC) - std::cout << std::setw(15) << "mc weights" << - std::setw(15) << "mc*pu weights" << - std::setw(15) << "lepton SF" << - std::setw(15) << "b-tag SF" ; - - if( m_cutflowParticleLevel ) { - std::cout << std::setw(15) << "particle level"; - } - - if( m_cutflowUpgradeLevel ) { - std::cout << std::setw(15) << "upgrade level"; - } + std::ostream& msgInfo = msg(MSG::Level::INFO); + msgInfo << std::right; + if (m_isMC) msgInfo << std::fixed << std::setprecision(2); + + if (m_config->doTightEvents()) { + //channel name + msgInfo << " - " << m_name << " cutflow:\n"; + + //some headings + msgInfo << std::setw(7) << "" << + std::setw(30) << "cut" << + std::setw(15) << "events"; + + if (m_isMC) + msgInfo << std::setw(15) << "mc weights" << + std::setw(15) << "mc*pu weights" << + std::setw(15) << "lepton SF" << + std::setw(15) << "b-tag SF"; + + if (m_cutflowParticleLevel) { + msgInfo << std::setw(15) << "particle level"; + } + + if (m_cutflowParticleLevelMCWeights) { + msgInfo << std::setw(15) << "particle level mc"; + } - std::cout << "\n"; + if (m_cutflowUpgradeLevel) { + msgInfo << std::setw(15) << "upgrade level"; + } + + msgInfo << "\n"; - //cutflow table content - for (int i = 1; i <= m_cutflow->GetNbinsX(); ++i) { - std::cout << " " << std::setw(3) << i - << std::setw(30) << m_cutflow->GetXaxis()->GetBinLabel(i) - << std::setw(15) << m_cutflow->GetBinContent(i); + //cutflow table content + for (int i = 1; i <= m_cutflow->GetNbinsX(); ++i) { + msgInfo << " " << std::setw(3) << i + << std::setw(30) << m_cutflow->GetXaxis()->GetBinLabel(i) + << std::setw(15) << m_cutflow->GetBinContent(i); if (m_isMC) - std::cout << std::setw(15) << m_cutflowMCWeights->GetBinContent(i) - << std::setw(15) << m_cutflowMCPUWeights->GetBinContent(i) - << std::setw(15) << m_cutflowScaleFactors->GetBinContent(i) - << std::setw(15) << m_cutflowBScaleFactors->GetBinContent(i); - - if ( m_cutflowParticleLevel ){ - std::cout << std::setw(15) << m_cutflowParticleLevel->GetBinContent(i); - } - - if ( m_cutflowUpgradeLevel ){ - std::cout << std::setw(15) << m_cutflowUpgradeLevel->GetBinContent(i); + msgInfo << std::setw(15) << m_cutflowMCWeights->GetBinContent(i) + << std::setw(15) << m_cutflowMCPUWeights->GetBinContent(i) + << std::setw(15) << m_cutflowScaleFactors->GetBinContent(i) + << std::setw(15) << m_cutflowBScaleFactors->GetBinContent(i); + + if (m_cutflowParticleLevel) { + msgInfo << std::setw(15) << m_cutflowParticleLevel->GetBinContent(i); + } + + if (m_cutflowParticleLevelMCWeights) { + msgInfo << std::setw(15) << m_cutflowParticleLevelMCWeights->GetBinContent(i); + } + + if (m_cutflowUpgradeLevel) { + msgInfo << std::setw(15) << m_cutflowUpgradeLevel->GetBinContent(i); } - std::cout << "\n"; + msgInfo << "\n"; + } } - } - if (m_config->doLooseEvents()) { - //channel name - std::cout << " - " << m_name << " cutflow (Loose):\n"; + if (m_config->doLooseEvents()) { + //channel name + msgInfo << " - " << m_name << " cutflow (Loose):\n"; - //some headings - std::cout << std::setw(7) << "" << - std::setw(30) << "cut" << - std::setw(15) << "events"; + //some headings + msgInfo << std::setw(7) << "" << + std::setw(30) << "cut" << + std::setw(15) << "events"; - if (m_isMC) - std::cout << std::setw(15) << "mc weights" << + if (m_isMC) + msgInfo << std::setw(15) << "mc weights" << std::setw(15) << "mc*pu weights" << std::setw(15) << "lepton SF" << - std::setw(15) << "b-tag SF" ; + std::setw(15) << "b-tag SF"; - if( m_cutflowParticleLevel ) { - std::cout << std::setw(15) << "particle level"; - } + if (m_cutflowParticleLevel) { + msgInfo << std::setw(15) << "particle level"; + } - if( m_cutflowUpgradeLevel ) { - std::cout << std::setw(15) << "upgrade level"; - } + if (m_cutflowParticleLevelMCWeights) { + msgInfo << std::setw(15) << "particle level mc"; + } + if (m_cutflowUpgradeLevel) { + msgInfo << std::setw(15) << "upgrade level"; + } - std::cout << "\n"; - //cutflow table content - for (int i = 1; i <= m_cutflow_Loose->GetNbinsX(); ++i) { - std::cout << " " << std::setw(3) << i - << std::setw(30) << m_cutflow_Loose->GetXaxis()->GetBinLabel(i) - << std::setw(15) << m_cutflow_Loose->GetBinContent(i); + msgInfo << "\n"; + + //cutflow table content + for (int i = 1; i <= m_cutflow_Loose->GetNbinsX(); ++i) { + msgInfo << " " << std::setw(3) << i + << std::setw(30) << m_cutflow_Loose->GetXaxis()->GetBinLabel(i) + << std::setw(15) << m_cutflow_Loose->GetBinContent(i); if (m_isMC) - std::cout << std::setw(15) << m_cutflowMCWeights_Loose->GetBinContent(i) - << std::setw(15) << m_cutflowMCPUWeights_Loose->GetBinContent(i) - << std::setw(15) << m_cutflowScaleFactors_Loose->GetBinContent(i) - << std::setw(15) << m_cutflowBScaleFactors_Loose->GetBinContent(i); + msgInfo << std::setw(15) << m_cutflowMCWeights_Loose->GetBinContent(i) + << std::setw(15) << m_cutflowMCPUWeights_Loose->GetBinContent(i) + << std::setw(15) << m_cutflowScaleFactors_Loose->GetBinContent(i) + << std::setw(15) << m_cutflowBScaleFactors_Loose->GetBinContent(i); + + if (m_cutflowParticleLevel) { + msgInfo << std::setw(15) << m_cutflowParticleLevel->GetBinContent(i); + } - if ( m_cutflowParticleLevel ){ - std::cout << std::setw(15) << m_cutflowParticleLevel->GetBinContent(i); + if (m_cutflowParticleLevelMCWeights) { + msgInfo << std::setw(15) << m_cutflowParticleLevelMCWeights->GetBinContent(i); } - if ( m_cutflowUpgradeLevel ){ - std::cout << std::setw(15) << m_cutflowUpgradeLevel->GetBinContent(i); + if (m_cutflowUpgradeLevel) { + msgInfo << std::setw(15) << m_cutflowUpgradeLevel->GetBinContent(i); } - std::cout << "\n"; + msgInfo << "\n"; + } } + msgInfo << "\n"; } - std::cout << "\n"; -} -const std::string EventSelection::name() const { + const std::string EventSelection::name() const { return m_name; -} + } -std::vector<std::string> EventSelection::GetFakesMMConfigs() const { + std::vector<std::string> EventSelection::GetFakesMMConfigs() const { std::vector<std::string> configs; for (const auto& currentCutName : m_allCuts) { - if (currentCutName->name()!="FAKESMMCONFIGS") continue; + if (currentCutName->name() != "FAKESMMCONFIGS") continue; else { - FakesMMConfigs* conf = dynamic_cast<FakesMMConfigs*>(currentCutName.get()); - for (std::string s : conf->configurations()) - configs.push_back(s); + FakesMMConfigs* conf = dynamic_cast<FakesMMConfigs*>(currentCutName.get()); + for (std::string s : conf->configurations()) + configs.push_back(s); } } return configs; -} + } -void EventSelection::printCuts() { - std::cout << " - " << m_name << ":\n"; - if (!m_config->doLooseTreeOnly()) { + void EventSelection::printCuts() { + std::ostream& msgInfo = msg(MSG::Level::INFO); + msgInfo << "\n - " << m_name << ":\n"; + if (m_config->doTightEvents()) { for (int i = 1; i <= m_cutflow->GetNbinsX(); ++i) { - std::cout << " " << std::setw(3) << i - << std::setw(30) << m_cutflow->GetXaxis()->GetBinLabel(i) - << "\n"; + msgInfo << " " << std::setw(3) << i + << std::setw(30) << m_cutflow->GetXaxis()->GetBinLabel(i) + << "\n"; } - } - else if (m_config->doLooseEvents()) { + } else if (m_config->doLooseEvents()) { for (int i = 1; i <= m_cutflow_Loose->GetNbinsX(); ++i) { - std::cout << " " << std::setw(3) << i - << std::setw(30) << m_cutflow_Loose->GetXaxis()->GetBinLabel(i) - << "\n"; + msgInfo << " " << std::setw(3) << i + << std::setw(30) << m_cutflow_Loose->GetXaxis()->GetBinLabel(i) + << "\n"; } } - - std::cout << "\n"; -} - + msgInfo << std::endl; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelectionManager.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelectionManager.cxx index f7168b5489d59ce31f2b80b863139b407faf5d77..c86529a2033de28b2e3763fc1bf329228eb0893d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelectionManager.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/EventSelectionManager.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/EventSelectionManager.h" @@ -23,145 +23,151 @@ #include "TopParticleLevel/ParticleLevelEvent.h" -namespace top { +#include "TopAnalysis/MsgCategory.h" +// use ATH_MSG macros defined in the namespace TopAnalysis +using namespace TopAnalysis; -EventSelectionManager::EventSelectionManager(const std::vector<SelectionConfigurationData>& selectionConfigData, TFile* outputFile, const std::string& toolLoaderNames, std::shared_ptr<top::TopConfig> config, EL::Worker* wk) { +namespace top { + EventSelectionManager::EventSelectionManager(const std::vector<SelectionConfigurationData>& selectionConfigData, + TFile* outputFile, const std::string& toolLoaderNames, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk) { std::vector<std::string> tokens; std::stringstream ss(toolLoaderNames); std::string item; char delim = ' '; while (std::getline(ss, item, delim)) - tokens.push_back(item); + tokens.push_back(item); - std::vector<std::unique_ptr<top::ToolLoaderBase>> toolLoaders; + std::vector<std::unique_ptr<top::ToolLoaderBase> > toolLoaders; for (const auto& toolLoaderName : tokens) { - //remove the lib and add namespace and Loader to the class name - std::string className = "top::" + toolLoaderName.substr(3) + "Loader"; - - std::cout << "Attempting to load Tools from this class: " << className << "\n"; - TClass* c = ::TClass::GetClass(className.c_str()); - - //okay, so that failed - //maybe the user didn't put it in the top namespace - try again without top::? - if (c == nullptr) { - className = toolLoaderName.substr(3) + "Loader"; - std::cout << "Attempting to load Tools from this class: " << className << "\n"; - c = ::TClass::GetClass(className.c_str()); - } - - //okay, so that worked! - if (c != nullptr) { - std::cout << " Success part 1 of 2" << "\n"; - top::ToolLoaderBase* bc = static_cast<top::ToolLoaderBase*> (c->New()); - - if (bc) { - std::cout << " Success part 2 of 2" << "\n"; - toolLoaders.push_back(std::unique_ptr<top::ToolLoaderBase>(bc)); - } else - std::cout << " Failure converting to ToolLoaderBase\n"; - } else - std::cout << " Class " << className << " in library " << toolLoaderName << " not found - this is only a problem if you wrote one in your library\n"; + //remove the lib and add namespace and Loader to the class name + std::string className = "top::" + toolLoaderName.substr(3) + "Loader"; + + ATH_MSG_INFO("Attempting to load Tools from this class: " << className); + TClass* c = ::TClass::GetClass(className.c_str()); + + //okay, so that failed + //maybe the user didn't put it in the top namespace - try again without top::? + if (c == nullptr) { + className = toolLoaderName.substr(3) + "Loader"; + ATH_MSG_INFO("Attempting to load Tools from this class: " << className); + c = ::TClass::GetClass(className.c_str()); + } + + //okay, so that worked! + if (c != nullptr) { + ATH_MSG_INFO(" Success part 1 of 2"); + top::ToolLoaderBase* bc = static_cast<top::ToolLoaderBase*> (c->New()); + + if (bc) { + ATH_MSG_INFO(" Success part 2 of 2"); + toolLoaders.push_back(std::unique_ptr<top::ToolLoaderBase>(bc)); + } else ATH_MSG_ERROR(" Failure converting to ToolLoaderBase"); + } else ATH_MSG_WARNING(" Class " << className << " in library " << toolLoaderName << + " not found - this is only a problem if you wrote one in your library"); } - std::cout << "\nTelling you how I'm configured, before I do anything:\n"; + ATH_MSG_INFO("Telling you how I'm configured, before I do anything:"); for (const auto& currentConfig : selectionConfigData) - m_selections.emplace_back(currentConfig.m_name, currentConfig.m_cutnames, outputFile, toolLoaders,config,wk); -} + m_selections.emplace_back(currentConfig.m_name, currentConfig.m_cutnames, outputFile, toolLoaders, config, wk); + } -EventSelectionManager::EventSelectionManager(EventSelectionManager&& other) : + EventSelectionManager::EventSelectionManager(EventSelectionManager&& other) : m_selections(std::move(other.m_selections)) { -} - -void EventSelectionManager::countInitial(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) -{ - for (const auto& currentSelection : m_selections) - currentSelection.countInitial(mcEventWeight,pileupWeight,zvtxWeight); -} + } -void EventSelectionManager::countGRL(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) -{ - for (const auto& currentSelection : m_selections) - currentSelection.countGRL(mcEventWeight,pileupWeight,zvtxWeight); -} + void EventSelectionManager::countInitial(const float mcEventWeight, const float pileupWeight, + const float zvtxWeight) { + for (const auto& currentSelection : m_selections) + currentSelection.countInitial(mcEventWeight, pileupWeight, zvtxWeight); + } -void EventSelectionManager::countGoodCalo(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) -{ - for (const auto& currentSelection : m_selections) - currentSelection.countGoodCalo(mcEventWeight,pileupWeight,zvtxWeight); -} + void EventSelectionManager::countGRL(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) { + for (const auto& currentSelection : m_selections) + currentSelection.countGRL(mcEventWeight, pileupWeight, zvtxWeight); + } -void EventSelectionManager::countPrimaryVertex(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) -{ - for (const auto& currentSelection : m_selections) - currentSelection.countPrimaryVertex(mcEventWeight,pileupWeight,zvtxWeight); -} + void EventSelectionManager::countGoodCalo(const float mcEventWeight, const float pileupWeight, + const float zvtxWeight) { + for (const auto& currentSelection : m_selections) + currentSelection.countGoodCalo(mcEventWeight, pileupWeight, zvtxWeight); + } -bool EventSelectionManager::apply(top::Event& event,const xAOD::SystematicEvent& currentSystematic) { + void EventSelectionManager::countPrimaryVertex(const float mcEventWeight, const float pileupWeight, + const float zvtxWeight) { + for (const auto& currentSelection : m_selections) + currentSelection.countPrimaryVertex(mcEventWeight, pileupWeight, zvtxWeight); + } + + bool EventSelectionManager::apply(top::Event& event, const xAOD::SystematicEvent& currentSystematic) { bool save(false); + for (const auto& currentSelection : m_selections) { - const bool passedThisSelection = currentSelection.apply(event); + const bool passedThisSelection = currentSelection.apply(event); - //save result as new branch (int) - event.m_info->auxdecor<int>(currentSelection.name()) = passedThisSelection; - //save result as decoration - currentSystematic.auxdecor<int>(currentSelection.name()) = passedThisSelection ? 1 : 0; + //save result as new branch (int) + event.m_info->auxdecor<int>(currentSelection.name()) = passedThisSelection; + //save result as decoration + currentSystematic.auxdecor<int>(currentSelection.name()) = passedThisSelection ? 1 : 0; - //Did any of the selections with SAVE specified pass for this event (if so we might want to keep the event) - save |= (passedThisSelection && currentSelection.ToBeSaved()); + //Did any of the selections with SAVE specified pass for this event (if so we might want to keep the event) + save |= (passedThisSelection && currentSelection.ToBeSaved()); } return save; -} + } -bool EventSelectionManager::applyParticleLevel(const top::ParticleLevelEvent& plEvent) { + bool EventSelectionManager::applyParticleLevel(const top::ParticleLevelEvent& plEvent) { bool save(false); + for (const auto& currentSelection : m_selections) { - const bool passedThisSelection = currentSelection.applyParticleLevel( plEvent ); + const bool passedThisSelection = currentSelection.applyParticleLevel(plEvent); - //save result as new branch (int) - plEvent.m_selectionDecisions[ currentSelection.name() ] = passedThisSelection; + //save result as new branch (int) + plEvent.m_selectionDecisions[ currentSelection.name() ] = passedThisSelection; - //Did any of the selections with SAVE specified pass for this event (if so we might want to keep the event) - save |= (passedThisSelection && currentSelection.ToBeSaved()); + //Did any of the selections with SAVE specified pass for this event (if so we might want to keep the event) + save |= (passedThisSelection && currentSelection.ToBeSaved()); } return save; -} + } -bool EventSelectionManager::applyUpgradeLevel(const top::ParticleLevelEvent& upgradeEvent) { + bool EventSelectionManager::applyUpgradeLevel(const top::ParticleLevelEvent& upgradeEvent) { bool save(false); + for (const auto& currentSelection : m_selections) { - const bool passedThisSelection = currentSelection.applyUpgradeLevel( upgradeEvent ); + const bool passedThisSelection = currentSelection.applyUpgradeLevel(upgradeEvent); - //save result as new branch (int) - upgradeEvent.m_selectionDecisions[ currentSelection.name() ] = passedThisSelection; + //save result as new branch (int) + upgradeEvent.m_selectionDecisions[ currentSelection.name() ] = passedThisSelection; - //Did any of the selections with SAVE specified pass for this event (if so we might want to keep the event) - save |= (passedThisSelection && currentSelection.ToBeSaved()); + //Did any of the selections with SAVE specified pass for this event (if so we might want to keep the event) + save |= (passedThisSelection && currentSelection.ToBeSaved()); } return save; -} + } -void EventSelectionManager::finalise() { - std::cout << "Final yields:\n"; + void EventSelectionManager::finalise() { + ATH_MSG_INFO("Final yields:"); for (const auto& currentSelection : m_selections) - currentSelection.finalise(); -} + currentSelection.finalise(); + } -void EventSelectionManager::addExtraBranches(std::vector<std::string>& extraBranchList) { + void EventSelectionManager::addExtraBranches(std::vector<std::string>& extraBranchList) { for (const auto& currentSelection : m_selections) - extraBranchList.push_back(currentSelection.name()); -} + extraBranchList.push_back(currentSelection.name()); + } -std::vector<std::string> EventSelectionManager::GetFakesMMConfigs(std::string selection) const { - for (const auto& currentSelection : m_selections) - if (currentSelection.name() == selection) return currentSelection.GetFakesMMConfigs(); - std::cout << "WARNING: Attempt to retrieve the FakesMMConfigs for non-existing selection " << selection << std::endl; - std::cout << " This is nonense - returning empty list" << std::endl; - std::vector<std::string> empty; - return empty; -} + std::vector<std::string> EventSelectionManager::GetFakesMMConfigs(std::string selection) const { + for (const auto& currentSelection : m_selections) + if (currentSelection.name() == selection) return currentSelection.GetFakesMMConfigs(); + ATH_MSG_WARNING("Attempt to retrieve the FakesMMConfigs for non-existing selection " << selection + << "\n This is nonense - returning empty list"); + std::vector<std::string> empty; + return empty; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/LinkDef.h index 656be7428b15ac326a2ed72334b73359b0574efc..3533b95ab49289368ac78efcb077228bd4574cb3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/LinkDef.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/ObjectLoaderStandardCuts.h" diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/MsgCategory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/MsgCategory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..a81b4d6b4d42ac9c6b5525cb6d50ef9b17e88b6c --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/MsgCategory.cxx @@ -0,0 +1,6 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#include "TopAnalysis/MsgCategory.h" + +ANA_MSG_SOURCE(TopAnalysis, "TopAnalysis") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/ObjectLoaderStandardCuts.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/ObjectLoaderStandardCuts.cxx index a8797c37c3493db48ba26910ef37de2c6269b5aa..facd9d7573205eff47da7eabf960615d4091a2a4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/ObjectLoaderStandardCuts.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/ObjectLoaderStandardCuts.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/ObjectLoaderStandardCuts.h" #include "TopEvent/EventTools.h" @@ -9,81 +9,102 @@ #include "TopObjectSelectionTools/TopObjectSelection.h" #include "TopObjectSelectionTools/ElectronLikelihoodMC15.h" #include "TopObjectSelectionTools/ElectronCutBasedMC15.h" +//#include "TopObjectSelectionTools/FwdElectronMC15.h" #include "TopObjectSelectionTools/IsolationTools.h" #include "TopObjectSelectionTools/MuonMC15.h" +#include "TopObjectSelectionTools/SoftMuonMC15.h" #include "TopObjectSelectionTools/AntiMuonMC15.h" #include "TopObjectSelectionTools/TauMC15.h" #include "TopObjectSelectionTools/JetMC15.h" #include "TopObjectSelectionTools/TrackJetMC15.h" -#include "TopObjectSelectionTools/PhotonMC15.h" +#include "TopObjectSelectionTools/JetGhostTrackSelection.h" +#include "TopObjectSelectionTools/TrackSelection.h" #include "TopObjectSelectionTools/OverlapRemovalASG.h" +// R21 specific +#include "TopObjectSelectionTools/PhotonMC16.h" -namespace top { +#include "TopAnalysis/MsgCategory.h" +// use ATH_MSG macros defined in the namespace TopAnalysis +using namespace TopAnalysis; - top::TopObjectSelection* ObjectLoaderStandardCuts::init(std::shared_ptr<top::TopConfig> topConfig) - { +namespace top { + top::TopObjectSelection* ObjectLoaderStandardCuts::init(std::shared_ptr<top::TopConfig> topConfig) { top::TopObjectSelection* objectSelection = new top::TopObjectSelection(topConfig->objectSelectionName()); - top::check(objectSelection->setProperty( "config" , topConfig ) , "Failed to setProperty for top::TopObjectSelection" ); - top::check(objectSelection->initialize() , "Failed to initialize top::TopObjectSelection" ); + top::check(objectSelection->setProperty("config", topConfig), "Failed to setProperty for top::TopObjectSelection"); + top::check(objectSelection->initialize(), "Failed to initialize top::TopObjectSelection"); // Debug messages? // objectSelection->msg().setLevel(MSG::DEBUG); ///-- Photons --// - if(topConfig->usePhotons()) { - objectSelection->photonSelection(new top::PhotonMC15(topConfig->photonPtcut(), - topConfig->photonEtacut(), - topConfig->photonIdentification(), - topConfig->photonIdentificationLoose(), - new top::StandardIsolation( - topConfig->photonIsolation(), - topConfig->photonIsolationLoose() )) ); + if (topConfig->usePhotons()) { + ATH_MSG_INFO("top::ObjectLoaderStandardCuts::init - Using new photon object for Release 21 - PhotonMC16"); + objectSelection->photonSelection(new top::PhotonMC16(topConfig->photonPtcut(), + topConfig->photonEtacut(), + topConfig->photonIdentification(), + topConfig->photonIdentificationLoose(), + new top::StandardIsolation(topConfig->photonIsolation(), + topConfig->photonIsolationLoose()), + topConfig->recomputeCPvars())); } ///-- Electrons --/// if (topConfig->useElectrons()) { - if (topConfig->electronID().find("LH") == std::string::npos && topConfig->electronIDLoose().find("LH") == std::string::npos) { - //both the tight and loose user settings do not contain LH -> cut based + if (topConfig->electronID().find("LH") == std::string::npos && + topConfig->electronIDLoose().find("LH") == std::string::npos) { + //both the tight and loose user settings do not contain LH -> cut based objectSelection->electronSelection(new top::ElectronCutBasedMC15(topConfig->electronPtcut(), topConfig->electronVetoLArCrack(), topConfig->electronID(), topConfig->electronIDLoose(), new top::StandardIsolation( - topConfig->electronIsolation() , - topConfig->electronIsolationLoose() )) ); - - } else if (topConfig->electronID().find("LH") != std::string::npos && topConfig->electronIDLoose().find("LH") != std::string::npos) { - //user wants likelihood electrons - objectSelection->electronSelection(new top::ElectronLikelihoodMC15(topConfig->isPrimaryxAOD(), - topConfig->electronPtcut(), - topConfig->electronVetoLArCrack(), - topConfig->electronID(), - topConfig->electronIDLoose(), - new top::StandardIsolation( - topConfig->electronIsolation() , - topConfig->electronIsolationLoose() ), - topConfig->applyTTVACut() - ) ); - + topConfig->electronIsolation(), + topConfig->electronIsolationLoose()))); + } else if (topConfig->electronID().find("LH") != std::string::npos && + topConfig->electronIDLoose().find("LH") != std::string::npos) { + //user wants likelihood electrons + objectSelection->electronSelection(new top::ElectronLikelihoodMC15(topConfig->isPrimaryxAOD(), + topConfig->electronPtcut(), + topConfig->electronVetoLArCrack(), + topConfig->electronID(), + topConfig->electronIDLoose(), + new top::StandardIsolation( + topConfig->electronIsolation(), + topConfig->electronIsolationLoose()), + topConfig->applyTTVACut(), + topConfig->useElectronChargeIDSelection() + )); } else { - std::cout << "\nHo hum\n"; - std::cout << "Not sure it makes sense to use a mix of LH and cut-based electrons for the tight/loose definitions\n"; - std::cout << "Tight electron definition is " << topConfig->electronID() << "\n"; - std::cout << "Loose electron definition is " << topConfig->electronIDLoose() << "\n"; - std::cout << "If it does make sense, feel free to fix this\n"; - exit(1); + ATH_MSG_ERROR("Not sure it makes sense to use a mix of LH and cut-based electrons for the tight/loose definitions\n" + << "Tight electron definition is " << topConfig->electronID() << "\n" + << "Loose electron definition is " << topConfig->electronIDLoose() << "\n" + << "If it does make sense, feel free to fix this"); + throw std::runtime_error("Mixing LH and cut-based electron definitions for tight/loose"); } } + ///-- Fwd Electrons --/// + //if (topConfig->useFwdElectrons()) { + // objectSelection->fwdElectronSelection(new top::FwdElectronMC15(topConfig->fwdElectronPtcut(), + // topConfig->fwdElectronMinEtacut(), + // topConfig->fwdElectronMaxEtacut(), topConfig)); + //} ///-- Muons --/// if (topConfig->useMuons()) { + if (topConfig->useAntiMuons()) objectSelection->muonSelection(new top::AntiMuonMC15(topConfig->muonPtcut(), + new top::StandardIsolation( + topConfig->muonIsolation(), + topConfig-> + muonIsolationLoose()))); + else objectSelection->muonSelection(new top::MuonMC15(topConfig->muonPtcut(), + new top::StandardIsolation(topConfig->muonIsolation(), + topConfig->muonIsolationLoose()), + topConfig->applyTTVACut())); + } - - if (topConfig->useAntiMuons()) - objectSelection -> muonSelection(new top::AntiMuonMC15(topConfig->muonPtcut(), new top::StandardIsolation(topConfig->muonIsolation(), topConfig->muonIsolationLoose()) )); - else - objectSelection -> muonSelection(new top::MuonMC15(topConfig->muonPtcut(), new top::StandardIsolation(topConfig->muonIsolation(), topConfig->muonIsolationLoose()), topConfig->applyTTVACut()) ); - + ///-- Soft Muons --/// + if (topConfig->useSoftMuons()) { + objectSelection->softmuonSelection(new top::SoftMuonMC15(topConfig->softmuonPtcut())); } @@ -94,24 +115,39 @@ namespace top { ///-- Jets --/// if (topConfig->useJets()) { - objectSelection -> jetSelection(new top::JetMC15(topConfig->jetPtcut(), topConfig->jetEtacut(), topConfig->fwdJetAndMET())); + objectSelection->jetSelection(new top::JetMC15(topConfig->jetPtcut(), topConfig->jetEtacut())); } ///-- Large R Jets --/// if (topConfig->useLargeRJets()) {// not doing JVT cut for large-R jets - objectSelection -> largeJetSelection(new top::JetMC15(topConfig->largeRJetPtcut(), topConfig->largeRJetEtacut(), false)); + objectSelection->largeJetSelection(new top::JetMC15(topConfig->largeRJetPtcut(), topConfig->largeRJetEtacut(), + false)); } ///-- Track Jets --/// if (topConfig->useTrackJets()) { - objectSelection -> trackJetSelection(new top::TrackJetMC15(topConfig->trackJetPtcut(), topConfig->trackJetEtacut())); + objectSelection->trackJetSelection(new top::TrackJetMC15(topConfig->trackJetPtcut(), + topConfig->trackJetEtacut())); + } + + ///-- Ghost Track Jets --/// + if (topConfig->useJetGhostTrack()) { + objectSelection->jetGhostTrackSelection(new top::JetGhostTrackSelection(topConfig->ghostTrackspT(), + 2.5,topConfig->ghostTracksVertexAssociation(),topConfig->jetPtGhostTracks(), 2.5)); + } + + ///-- Tracks --/// + if (topConfig->useTracks()) { + objectSelection->trackSelection(new top::TrackSelection(topConfig->trackPtcut(), topConfig->trackEtacut())); } ///-- Overlap removal --/// /// single parameter: boolean to do OR with large-R jets - objectSelection->overlapRemovalPostSelection(new top::OverlapRemovalASG( (topConfig->doLargeJetOverlapRemoval() && topConfig->useLargeRJets())) ); + if (!topConfig->isTruthDxAOD()) { + objectSelection->overlapRemovalPostSelection(new top::OverlapRemovalASG((topConfig->doLargeJetOverlapRemoval() && + topConfig->useLargeRJets()))); + } return objectSelection; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/Tools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/Tools.cxx index 6c1de11684c086b940995a55fa95d8cb3a7081c5..d8942ca71a37060924f06a17d31b09ff5b24d915 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/Tools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/Root/Tools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopAnalysis/Tools.h" @@ -26,147 +26,237 @@ #include "TROOT.h" #include "xAODRootAccess/Init.h" +//#include "xAODRootAccess/LoadDictionaries.h" #include "PATInterfaces/SystematicCode.h" #include "PATInterfaces/CorrectionCode.h" +#include "AsgTools/AsgMetadataTool.h" +#include "xAODTruth/TruthMetaData.h" +#include "xAODTruth/TruthMetaDataContainer.h" + #ifndef ROOTCORE #include "AthAnalysisBaseComps/AthAnalysisHelper.h" #endif -namespace top { +#include "TopAnalysis/MsgCategory.h" +using namespace TopAnalysis; -void xAODInit(bool failOnUnchecked) { +namespace top { + void xAODInit(bool failOnUnchecked) { if (!xAOD::Init()) { - std::cout << "Failed xAOD::Init - no idea what to do, exiting\n"; - exit(1); + throw std::runtime_error("Failed xAOD::Init - no idea what to do, exiting"); } + //if (xAOD::LoadDictionaries().isFailure()) { + // ATH_MSG_WARNING("Failiure in xAOD::LoadDictionaries(). The job will " + // "likely not run correctly."); + //} //fail on unchecked error codes if (failOnUnchecked) { - xAOD::TReturnCode::enableFailure(); - CP::SystematicCode::enableFailure(); - CP::CorrectionCode::enableFailure(); - //StatusCode::enableFailure(); + xAOD::TReturnCode::enableFailure(); + CP::SystematicCode::enableFailure(); + CP::CorrectionCode::enableFailure(); + //StatusCode::enableFailure(); } -} + } -bool isFilePrimaryxAOD(TFile* inputFile) { + bool isFilePrimaryxAOD(TFile* inputFile) { TTree* metaData = dynamic_cast<TTree*> (inputFile->Get("MetaData")); if (metaData) { - metaData->LoadTree(0); - - TObjArray* ar = metaData->GetListOfBranches(); - for (int i = 0; i < ar->GetEntries(); ++i) { - TBranch* b = (TBranch*) ar->At(i); - std::string name = std::string(b->GetName()); - // std::cout << name << std::endl; - if (name == "StreamAOD") - return true; - } + metaData->LoadTree(0); + + TObjArray* ar = metaData->GetListOfBranches(); + for (int i = 0; i < ar->GetEntries(); ++i) { + TBranch* b = (TBranch*) ar->At(i); + std::string name = std::string(b->GetName()); + if (name == "StreamAOD") return true; + } } else { - std::cout << "isFilePrimaryxAOD says MetaData tree missing from input file.\n Weird" << std::endl; - exit(1); + throw std::runtime_error("Tools::isFilePrimaryxAOD: MetaData tree missing from input file."); } return false; -} + } -bool isFileSimulation(TFile* inputFile, const std::string& eventInfoName) { + bool isFileSimulation(TFile* inputFile, const std::string& eventInfoName) { xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); top::check(xaodEvent.readFrom(inputFile), "Tools::isFileSimulation Failed to read file in"); xaodEvent.getEntry(0); const xAOD::EventInfo* eventInfo(0); - top::check(xaodEvent.retrieve(eventInfo, eventInfoName) , "Tools::isFileSimulation Failed to get " + eventInfoName); - return eventInfo->eventType(xAOD::EventInfo::IS_SIMULATION); -} + top::check(xaodEvent.retrieve(eventInfo, eventInfoName), "Tools::isFileSimulation Failed to get " + eventInfoName); -bool isTruthDxAOD(TFile* inputFile) { - TTree* metaData = dynamic_cast<TTree*> (inputFile->Get("MetaData")); - - if (metaData) { - metaData->LoadTree(0); - - TObjArray* ar = metaData->GetListOfBranches(); - for (int i = 0; i < ar->GetEntries(); ++i) { - TBranch* b = (TBranch*) ar->At(i); - std::string name = std::string(b->GetName()); - // std::cout << name << std::endl; - if (name.find("DAOD_TRUTH") != std::string::npos) - return true; - } - } else { - throw std::runtime_error("isTruthDxAOD says MetaData tree" - " missing from input file.\n Weird"); + return eventInfo->eventType(xAOD::EventInfo::IS_SIMULATION); } - - return false; -} + size_t MCweightsSize(TFile* inputFile, const std::string& eventInfoName) { + xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); + top::check(xaodEvent.readFrom(inputFile), "Tools::MCweightsSize Failed to read file in"); -unsigned int getDSID(TFile* inputFile, const std::string& eventInfoName){ + xaodEvent.getEntry(0); + const xAOD::EventInfo* eventInfo(0); + top::check(xaodEvent.retrieve(eventInfo, eventInfoName), "Tools::isFileSimulation Failed to get " + eventInfoName); - xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); - top::check(xaodEvent.readFrom(inputFile), "Tools::isFileSimulation Failed to read file in"); - - xaodEvent.getEntry(0); - const xAOD::EventInfo* eventInfo(0); - top::check(xaodEvent.retrieve(eventInfo, eventInfoName) , "Tools::isFileSimulation Failed to get " + eventInfoName); - - return eventInfo-> mcChannelNumber(); + return eventInfo->mcEventWeights().size(); + } -} + bool isTruthDxAOD(TFile* inputFile) { + TTree* metaData = dynamic_cast<TTree*> (inputFile->Get("MetaData")); + if (metaData) { + metaData->LoadTree(0); + + TObjArray* ar = metaData->GetListOfBranches(); + for (int i = 0; i < ar->GetEntries(); ++i) { + TBranch* b = (TBranch*) ar->At(i); + std::string name = std::string(b->GetName()); + if (name.find("DAOD_TRUTH") != std::string::npos) return true; + } + } else { + throw std::runtime_error("isTruthDxAOD says MetaData tree" + " missing from input file.\n Weird"); + } -bool isFileFastSim(TFile* /*inputFile*/) { + return false; + } - - return false; - -} + unsigned int getDSID(TFile* inputFile, const std::string& eventInfoName) { + xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); + top::check(xaodEvent.readFrom(inputFile), "Tools::isFileSimulation Failed to read file in"); + xaodEvent.getEntry(0); + const xAOD::EventInfo* eventInfo(0); + top::check(xaodEvent.retrieve(eventInfo, eventInfoName), "Tools::isFileSimulation Failed to get " + eventInfoName); -std::string getDerivationStream(TFile* inputFile){ + return eventInfo->mcChannelNumber(); + } - TTree* metaData = dynamic_cast<TTree*> (inputFile->Get("MetaData")); + bool isFileFastSim(TFile* /*inputFile*/) { + return false; + } - if (metaData) { - metaData->LoadTree(0); + std::string getDerivationStream(TFile* inputFile) { + TTree* metaData = dynamic_cast<TTree*> (inputFile->Get("MetaData")); - TObjArray* ar = metaData->GetListOfBranches(); - for (int i = 0; i < ar->GetEntries(); ++i) { - TBranch* b = (TBranch*) ar->At(i); - std::string name = std::string(b->GetName()); - // Find a variable name with Stream, then split off from DAOD - // If we only need TOPQX, we just find "_", add 1 and substring from there instead - if (name.find("Stream") != std::string::npos){ - auto cursor = name.find("_"); - std::string stream = name.substr(cursor+1); - return stream; - } + if (metaData) { + metaData->LoadTree(0); + + TObjArray* ar = metaData->GetListOfBranches(); + for (int i = 0; i < ar->GetEntries(); ++i) { + TBranch* b = (TBranch*) ar->At(i); + std::string name = std::string(b->GetName()); + // Find a variable name with Stream, then split off from DAOD + // If we only need TOPQX, we just find "_", add 1 and substring from there instead + if (name.find("Stream") != std::string::npos) { + auto cursor = name.find("_"); + std::string stream = name.substr(cursor + 1); + return stream; + } + } + } else { + throw std::runtime_error("getDerivationStream says MetaData tree" + " missing from input file.\n Weird"); } - } - else { - throw std::runtime_error("getDerivationStream says MetaData tree" - " missing from input file.\n Weird"); + + // If we don't already return, something unexpected has happened and we need to fix it! + throw std::runtime_error("Cannot determine the derivation stream. Please report."); } - // If we don't already return, something unexpected has happened and we need to fix it! - throw std::runtime_error("Cannot determine the derivation stream. Please report."); + void parseCutBookkeepers(const xAOD::CutBookkeeperContainer *cutBookKeepers, + std::vector<std::string> &names, std::vector<float>& sumW, const bool isHLLHC) { + std::vector<int> maxCycle; + for (const xAOD::CutBookkeeper *cbk : *cutBookKeepers) { + // skip RDO and ESD numbers, which are nonsense; and + // skip the derivation number, which is the one after skimming + // we want the primary xAOD numbers + if ((cbk->inputStream() != "StreamAOD") && !(isHLLHC && cbk->inputStream() == "StreamDAOD_TRUTH1")) + continue; + // only accept "AllExecutedEvents" bookkeeper (0th MC weight) + // or "AllExecutedEvents_NonNominalMCWeight_XYZ" where XYZ is the MC weight index + if (!((cbk->name() == "AllExecutedEvents") + || (cbk->name().find("AllExecutedEvents_NonNominalMCWeight_") != std::string::npos))) + continue; + const std::string name = cbk->name(); + auto pos_name = std::find(names.begin(), names.end(), name); + // is it a previously unencountered bookkeeper? If yes append its name to the vector of names + // if not no need, but we must check the corresponding entry for the sum of weights exist + if (pos_name == names.end()) { + names.push_back(name); + maxCycle.push_back(cbk->cycle()); + sumW.push_back(cbk->sumOfEventWeights()); + } else if (cbk->cycle() > maxCycle.at(pos_name - names.begin())) { + maxCycle.at(pos_name - names.begin()) = cbk->cycle(); + sumW.at(pos_name - names.begin()) = cbk->sumOfEventWeights(); + } else { + continue; + } + } + } -} - + ULong64_t getRawEventsBookkeeper(const xAOD::CutBookkeeperContainer *cutBookKeepers, const bool isHLLHC) { + int maxCycle = -1; + ULong64_t rawEntries = 0; + // search for "AllExecutedEvents" bookkeeper -- this one should always exist + for (const xAOD::CutBookkeeper *cbk : *cutBookKeepers) { + if ((cbk->inputStream() != "StreamAOD") && !(isHLLHC && cbk->inputStream() == "StreamDAOD_TRUTH1")) + continue; + if (cbk->name() != "AllExecutedEvents") + continue; + if (cbk->cycle() > maxCycle) { + rawEntries = cbk->nAcceptedEvents(); + maxCycle = cbk->cycle(); + } + } + return rawEntries; + } -xAOD::TEvent::EAuxMode guessAccessMode(const std::string& filename, const std::string& electronCollectionName) { + void renameCutBookkeepers(std::vector<std::string>& bookkeeper_names, + const std::vector<std::string>& pmg_weight_names) { + + // prefix in the bookkeeper names to remove + static const std::string name_prefix = "AllExecutedEvents_NonNominalMCWeight_"; + + // check if we have more than one MC generator weight, in that case we have to do the renaming + if (pmg_weight_names.size() > 1) { + if (bookkeeper_names.size() != pmg_weight_names.size()) { + // The number of AllExecutedEvents_ bookkeepers does not match the number of weights retrieved by PMGTool + // we cannot match the bookkeepers to weights by indices in this case + throw std::runtime_error("ERROR: The number of CutBookkeepers does not match the number of MC generator weights in metadata! Cannot match nominal MC weight to nominal sum of weights!"); + } + + // rename the bookkeepers based on the weight names from PMGTool + // this names are then also written into the sumWeights TTree in output files + for (std::string &name : bookkeeper_names) { + if (name == "AllExecutedEvents") { + name = pmg_weight_names.at(0); + } else { + // erase "AllExecutedEvents_NonNominalMCWeight_" prefix + int index = std::stoi(name.erase(0, name_prefix.size())); + name = pmg_weight_names.at(index); + } + } + } else { + // expect only one MC weight in this sample, hence only one AllExecutedEvents* bookeeeper + if (bookkeeper_names.size() == 1) { + bookkeeper_names[0] = "nominal"; + } else { + ATH_MSG_INFO("WARNING: PMGTruthWeightTool reports no extra MC generator weight variations, " + << "but this sample does not have exactly one AllExecutedEvents* bookkeeper!\n" + << "Expect trouble, because this means we can't guarantee that proper CutBookkeeper " + << "is used for the sum of weights!"); + } + } + } + xAOD::TEvent::EAuxMode guessAccessMode(const std::string& filename, const std::string& electronCollectionName) { //there must be a better way than this std::unique_ptr<TFile> inputFile(TFile::Open(filename.c_str())); xAOD::TEvent xaodEvent(xAOD::TEvent::kBranchAccess); - top::check( xaodEvent.readFrom(inputFile.get()) , "Failed to guessAccessMode" ); + top::check(xaodEvent.readFrom(inputFile.get()), "Failed to guessAccessMode"); //if we're unlucky and none of the events have electrons we can't //tell which mode we need -> use ClassAccess @@ -174,128 +264,116 @@ xAOD::TEvent::EAuxMode guessAccessMode(const std::string& filename, const std::s xAOD::TEvent::EAuxMode mode = xAOD::TEvent::kBranchAccess; if (electronCollectionName != "None") { - //look at the first n events - unsigned int entries = xaodEvent.getEntries(); - - for (unsigned int i = 0; i < entries; ++i) { - xaodEvent.getEntry(i); - - const xAOD::ElectronContainer* electrons(0); - top::check( xaodEvent.retrieve(electrons, electronCollectionName) , "Failed to guessAccessMode" ); - - try { - //loading the electron pt only works for class access for the first - //round of xAODs made for DC14 8 TeV - //class access doesn't let us make out mini-xAOD super small though - - //branch access is available for the xAOD->xAOD reprocessing, - //derivations and 13 TeV DC14 MC samples - if (!electrons->empty()) { - fallback = false; - electrons->at(0)->pt(); - break; - } - } catch(...) { - mode = xAOD::TEvent::kClassAccess; - break; - } + //look at the first n events + unsigned int entries = xaodEvent.getEntries(); + + for (unsigned int i = 0; i < entries; ++i) { + xaodEvent.getEntry(i); + + const xAOD::ElectronContainer* electrons(0); + top::check(xaodEvent.retrieve(electrons, electronCollectionName), "Failed to guessAccessMode"); + + try { + //loading the electron pt only works for class access for the first + //round of xAODs made for DC14 8 TeV + //class access doesn't let us make out mini-xAOD super small though + + //branch access is available for the xAOD->xAOD reprocessing, + //derivations and 13 TeV DC14 MC samples + if (!electrons->empty()) { + fallback = false; + electrons->at(0)->pt(); + break; + } + } catch (...) { + mode = xAOD::TEvent::kClassAccess; + break; } + } } if (fallback) { - std::cout << "Falling back to kClassAccess" << std::endl; - mode = xAOD::TEvent::kClassAccess; + ATH_MSG_WARNING("Falling back to kClassAccess"); + mode = xAOD::TEvent::kClassAccess; } //useful message if (mode == xAOD::TEvent::kClassAccess) - std::cout << "guessAccessMode: Using kClassAccess\n"; + ATH_MSG_INFO("guessAccessMode: Using kClassAccess"); else if (mode == xAOD::TEvent::kBranchAccess) - std::cout << "guessAccessMode: Using kBranchAccess\n"; + ATH_MSG_INFO("guessAccessMode: Using kBranchAccess"); return mode; -} + } -std::vector<std::string> loadCuts(const std::string& filename) { + std::vector<std::string> loadCuts(const std::string& filename) { std::vector<std::string> v; std::fstream in(filename.c_str()); if (!in.is_open()) { - std::cout << "Problem opening " << filename << "\n"; - exit(1); + throw std::runtime_error("Problem opening " + filename); } std::string str; while (std::getline(in, str)) { - std::string newstring(str); + std::string newstring(str); - if (str.find("#") != std::string::npos) - newstring = str.substr(0, str.find("#")); + if (str.find("#") != std::string::npos) newstring = str.substr(0, str.find("#")); - //leading and trailing white space removal - while (std::isspace(*newstring.begin())) - newstring.erase(newstring.begin()); + //leading and trailing white space removal + while (std::isspace(*newstring.begin())) + newstring.erase(newstring.begin()); - while (std::isspace(*newstring.rbegin())) - newstring.erase(newstring.length() - 1); + while (std::isspace(*newstring.rbegin())) + newstring.erase(newstring.length() - 1); - //make sure it contains something - if (newstring.size() > 0) - v.push_back(newstring); + //make sure it contains something + if (newstring.size() > 0) v.push_back(newstring); } return v; -} + } -unsigned int checkFiles(const std::vector<std::string>& filenames) { - std::cout << "Input filenames:\n"; - unsigned int i = 0; - unsigned int totalYield = 0; + size_t checkFiles(const std::vector<std::string>& filenames) { + ATH_MSG_INFO("Input filenames:\n"); + size_t i = 0; + size_t totalYield = 0; for (const auto& filename : filenames) { - std::unique_ptr<TFile> f(TFile::Open(filename.c_str())); - std::cout << " " << i + 1 << "/" << filenames.size() << " File: " << filename; + std::unique_ptr<TFile> f(TFile::Open(filename.c_str())); + ATH_MSG_INFO(i + 1 << "/" << filenames.size() << " File: " << filename); - if (!f.get()) { - std::cout << "\nDid not manage to open " << filename << std::endl; - std::cout << "Can't continue" << std::endl; - exit(1); - } + if (!f.get()) { + throw std::runtime_error("Did not manage to open " + filename); + } - const TTree* const t = dynamic_cast<TTree* > (f->Get("CollectionTree")); + const TTree* const t = dynamic_cast<TTree* > (f->Get("CollectionTree")); - //some files made by the derivation framework have no events passing the - //cuts -> which means no collection tree. - //the old behaviour was to end execution on this problem - //not any more! - int entries = 0; - std::string note; - if (t) - entries = t->GetEntries(); - else - note = " (No CollectionTree)"; + //some files made by the derivation framework have no events passing the + //cuts -> which means no collection tree. + //the old behaviour was to end execution on this problem + //not any more! + int entries = 0; + std::string note; + if (t) entries = t->GetEntries(); + else note = " (No CollectionTree)"; - std::cout << " Entries: " << entries << note << "\n"; - totalYield += entries; + ATH_MSG_INFO("Entries: " << entries << note); + totalYield += entries; - ++i; + ++i; } - std::cout << "\n"; - return totalYield; -} + } -std::vector<std::string> fileList(const std::string& filename) { + std::vector<std::string> fileList(const std::string& filename) { std::ifstream ifs(filename.c_str()); if (!ifs) { - std::cout << "File does not exist " << filename << std::endl; - std::cout << "This should contain a list - comma separated list of" << std::endl; - std::cout << "input files" << std::endl; - std::cout << "Can't continue" << std::endl; - exit(1); + throw std::runtime_error("File does not exist " + filename + + "\nThis should contain a list - comma separated list of input files."); } //loop over the lines in the file @@ -306,8 +384,8 @@ std::vector<std::string> fileList(const std::string& filename) { //these will be included automagically. std::string line; while (!ifs.eof()) { - std::getline(ifs, line); - wholefile << line << ','; + std::getline(ifs, line); + wholefile << line << ','; } //somewhere to save the filenames @@ -316,78 +394,172 @@ std::vector<std::string> fileList(const std::string& filename) { //now zoom through the whole file string and split at the comma std::string to; while (std::getline(wholefile, to, ',')) { - if (to.size() > 0) - fileList.push_back(to); + if (to.size() > 0) fileList.push_back(to); } if (fileList.size() == 0) { - std::cout << "Could not get a list of input files from " << filename << std::endl; - std::cout << "Can't continue" << std::endl; - exit(1); + throw std::runtime_error("Could not get a list of input files from " + filename); } return fileList; -} + } -void loadLibraries(const std::string& libraryNames) { + void loadLibraries(const std::string& libraryNames) { std::vector<std::string> tokens; std::stringstream ss(libraryNames); std::string item; char delim = ' '; while (std::getline(ss, item, delim)) - tokens.push_back(item); + tokens.push_back(item); - std::vector<std::unique_ptr<top::ToolLoaderBase>> toolLoaders; + std::vector<std::unique_ptr<top::ToolLoaderBase> > toolLoaders; for (const auto& toolLoaderName : tokens) { - std::cout << "Attempting to load library: " << toolLoaderName << ".so\n"; - gSystem->Load((toolLoaderName + ".so").c_str()); + ATH_MSG_INFO("Attempting to load library: " << toolLoaderName << ".so"); + gSystem->Load((toolLoaderName + ".so").c_str()); } -} + } -top::TopObjectSelection* loadObjectSelection(std::shared_ptr<top::TopConfig> config) { - std::cout << "Attempting to load ObjectSelection: " << config->objectSelectionName() << std::endl; - TClass* c = ::TClass::GetClass( config->objectSelectionName().c_str() ); + top::TopObjectSelection* loadObjectSelection(std::shared_ptr<top::TopConfig> config) { + ATH_MSG_INFO("Attempting to load ObjectSelection: " << config->objectSelectionName()); + TClass* c = ::TClass::GetClass(config->objectSelectionName().c_str()); if (c == nullptr) { - std::cout << "Didn't manage to load " << config->objectSelectionName() << std::endl; - exit(1); + throw std::runtime_error("Didn't manage to load " + config->objectSelectionName()); } top::ObjectLoaderBase* bc = static_cast<top::ObjectLoaderBase*> (c->New()); if (bc == nullptr) { - std::cout << "Didn't manage to cast it to top::ObjectLoaderBase " << std::endl; - exit(1); + throw std::runtime_error("Didn't manage to cast it to top::ObjectLoaderBase"); } top::TopObjectSelection* objectSelection = bc->init(config); if (objectSelection == nullptr) { - std::cout << "Didn't manage to make a top::ObjectSelection class" << std::endl; - exit(1); + throw std::runtime_error("Didn't manage to make a top::ObjectSelection class"); } return objectSelection; -} + } -top::EventSaverBase* loadEventSaver(std::shared_ptr<top::TopConfig> config) { - std::cout << "Attempting to load OutputFormat: " << config->outputFormat() << std::endl; - TClass* c = ::TClass::GetClass( config->outputFormat().c_str() ); + top::EventSaverBase* loadEventSaver(std::shared_ptr<top::TopConfig> config) { + ATH_MSG_INFO("Attempting to load OutputFormat: " << config->outputFormat()); + TClass* c = ::TClass::GetClass(config->outputFormat().c_str()); if (c == nullptr) { - std::cout << "Didn't manage to load " << config->outputFormat() << std::endl; - exit(1); + throw std::runtime_error("Didn't manage to load " + config->outputFormat()); } top::EventSaverBase* bc = static_cast<top::EventSaverBase*> (c->New()); if (bc == nullptr) { - std::cout << "Didn't manage to cast it to top::EventSaverBase " << std::endl; - exit(1); + throw std::runtime_error("Didn't manage to cast it to top::EventSaverBase "); } return bc; -} + } + bool readMetaData(TFile* inputFile, std::shared_ptr<top::TopConfig> config) { + // Load the file into a TEvent + xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); + top::check(xaodEvent.readFrom(inputFile), "Cannot load inputFile"); + xaodEvent.getEntry(0); + + bool gotDSID=false; + unsigned int mcChannelNumber = ((unsigned int) -1); + + std::string productionRelease="?", amiTag="?", AODFixVersion="?", AODCalibVersion="?", dataType="?", geometryVersion="?", conditionsTag="?", + beamType="?", simFlavour="?"; + float beamEnergy = 0, mcProcID = -1; + + // Magical metadata tool to access FileMetaData object + asg::AsgMetadataTool ATMetaData("OurNewMetaDataObject"); + bool readFMD=false; + + // Check it exists, and if it does we will work with it + if (ATMetaData.inputMetaStore()->contains<xAOD::FileMetaData>("FileMetaData")) { + + ATH_MSG_INFO("Trying to read FileMetaData"); + + // Create pointer for FileMetaData which we will load + const xAOD::FileMetaData* FMD = 0; + top::check(ATMetaData.inputMetaStore()->retrieve(FMD, + "FileMetaData"), + "Failed to retrieve metadata from AsgMetadataTool"); + // Let's get all the info we can... + // https://gitlab.cern.ch/atlas/athena/blob/21.2/Event/xAOD/xAODMetaData/xAODMetaData/versions/FileMetaData_v1.h#L47 + /// Release that was used to make the file [string] + FMD->value(xAOD::FileMetaData::productionRelease, productionRelease); + /// AMI tag used to process the file the last time [string] + FMD->value(xAOD::FileMetaData::amiTag, amiTag); + /// Version of AODFix that was used on the file last [string] + FMD->value(xAOD::FileMetaData::AODFixVersion, AODFixVersion); + /// Version of AODCalib that was used on the file last [string] + FMD->value(xAOD::FileMetaData::AODCalibVersion, AODCalibVersion); + /// Data type that's in the file [string] + FMD->value(xAOD::FileMetaData::dataType, dataType); + /// Geometry version [string] + FMD->value(xAOD::FileMetaData::geometryVersion, geometryVersion); + /// Conditions version used for simulation/reconstruction [string] + FMD->value(xAOD::FileMetaData::conditionsTag, conditionsTag); + /// Beam energy [float] + FMD->value(xAOD::FileMetaData::beamEnergy, beamEnergy); + /// Beam type [string] + FMD->value(xAOD::FileMetaData::beamType, beamType); + /// Same as mc_channel_number [float] + gotDSID = FMD->value(xAOD::FileMetaData::mcProcID, mcProcID); + mcChannelNumber = mcProcID; + /// Fast or Full sim [string] + FMD->value(xAOD::FileMetaData::simFlavour, simFlavour); + /// It is also possible to access any other info in metadata with + /// FMD->value("SomeMetaInfo", someObject); + readFMD=true; + } + if (!readFMD || !gotDSID || mcChannelNumber == ((unsigned int) -1)){ // in case FileMetaData is bugged and does not have DSID properly stored happens for example for files with 0 events in CollectionTree after skimming + + ATH_MSG_INFO("FileMetaData not found or not readable, trying to read TruthMetaData"); + + bool gotTruthMetaData = true; + const xAOD::TruthMetaDataContainer *truthMetadata = nullptr; + if (ATMetaData.inputMetaStore()->contains<xAOD::TruthMetaDataContainer>("TruthMetaData")) { + if (ATMetaData.inputMetaStore()->retrieve(truthMetadata, "TruthMetaData")) { + if (truthMetadata->size() == 1) { + mcChannelNumber = truthMetadata->at(0)->mcChannelNumber(); + } else { + ATH_MSG_WARNING("TruthMetaData does not have exactly one entry. Cannot reliably determine DSID"); + } + } else { + gotTruthMetaData = false; + } + } else { + gotTruthMetaData = false; + } + if (!gotTruthMetaData) + { + ATH_MSG_ERROR("We cannot retrieve even TruthMetaData to determine DSID"); + return false; + } + } + + /// Print out this information as a cross-check + ATH_MSG_INFO("Using AsgMetadataTool to access the following information\n" + << "productionRelease -> " << productionRelease << "\n" + << "amiTag -> " << amiTag << "\n" + << "AODFixVersion -> " << AODFixVersion << "\n" + << "AODCalibVersion -> " << AODCalibVersion << "\n" + << "dataType -> " << dataType << "\n" + << "geometryVersion -> " << geometryVersion << "\n" + << "conditionsTag -> " << conditionsTag << "\n" + << "beamEnergy -> " << beamEnergy << "\n" + << "beamType -> " << beamType << "\n" + << "mcProcID -> " << int(mcChannelNumber) << "\n" + << "simFlavour -> " << simFlavour << "\n" + << "Not all of this information is propagated to TopConfig"); + + config->setAmiTag(amiTag); + config->setDSID(mcChannelNumber); + + return true; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/AnalysisTrackingHelper.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/AnalysisTrackingHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..13b848776983ca64194707eeabac13a1ae15d404 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/AnalysisTrackingHelper.h @@ -0,0 +1,69 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef _TOPANALYSIS_ANALYSISTRACKINGHELPER_H_ +#define _TOPANALYSIS_ANALYSISTRACKINGHELPER_H_ + +#include <memory> +#include <string> +#include <vector> + +namespace top { + class TopConfig; +} + +namespace top { +/** + * @brief Helper for collecting data for analysis tracking. + */ + class AnalysisTrackingHelper { + public: + AnalysisTrackingHelper(); + ~AnalysisTrackingHelper(); + + /** + * @brief Notify helper that an input file was processed. + * + * @param path Path to the input file. + * @param entriesProcessed Number of entries that were processed. + */ + void addInputFile(std::string const& path, unsigned long long entriesProcessed); + + /** + * @brief Notify helper about configuration options. + * + * @param topConfig Pointer to the TopConfig object. + */ + void setTopConfig(std::shared_ptr<TopConfig> const& topConfig); + + /** + * @brief Store tracking data in current TFile. + * + * @param treename Name of the TTree used to store the data. + * + * @remarks + * It's your responsibility to call TFile::cd() before this function. + */ + void writeTree(std::string const& treename); + private: + struct InputFileInfo { + InputFileInfo(std::string const& path, unsigned long long const entriesProcessed) : + path(path), + entriesProcessed(entriesProcessed) { + } + + std::string const path; + unsigned long long const entriesProcessed; + }; + + void finish(); + + std::string m_json; + bool m_finished; + std::shared_ptr<TopConfig> m_topConfig; + std::vector<InputFileInfo> m_inputFiles; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverBase.h index 31887cf8f13807fb80a9e6a8512bcd45c42f5814..97426dc94c3870164aade93468d694cfda02ebe6 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSAVERBASE_H_ #define EVENTSAVERBASE_H_ @@ -20,18 +20,17 @@ namespace top { class ParticleLevelEvent; /** - * @brief A base class so users can write their own event saving stuff. Some - * people, for some reason, prefer flat ntuples to xAODs. - */ - class EventSaverBase{ - + * @brief A base class so users can write their own event saving stuff. Some + * people, for some reason, prefer flat ntuples to xAODs. + */ + class EventSaverBase { public: - /** + /** * @brief Default ctor/dtor - ROOT wants to use these, don't use fancy ctors */ - EventSaverBase(){} - virtual ~EventSaverBase(){} - + EventSaverBase() {} + virtual ~EventSaverBase() {} + /** * @brief Called once at the start of the job after the file has been opened. * @@ -39,7 +38,14 @@ namespace top { * @param file You probably need the file if you're going to write to it. * @param extraBranches So you can write extra branches (only for xAOD). */ - virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches) = 0; + virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches) = 0; + + /** + * @brief Method to execute any calculations common for + * reco/particle/parton level. + */ + virtual void execute() {return;} /** * @brief I guess you want to save an event sometimes to. @@ -50,18 +56,18 @@ namespace top { * * @param event The event in question, in the format used internally. */ - virtual void saveEvent(const top::Event& /*event*/){return;} - virtual void saveEventToxAOD(){return;} - - /** + virtual void saveEvent(const top::Event& /*event*/) {return;} + virtual void saveEventToxAOD() {return;} + + /** * @breif Run for every event - * + * * This fills, if requested, the: - * MC truth record + * MC truth record * PDF info * TopPartons */ - virtual void saveTruthEvent(){return;} + virtual void saveTruthEvent() {return;} /*! * @brief Function to save the particle level event. @@ -71,8 +77,8 @@ namespace top { * @param plEvent The particle level event whose contents will be saved. */ virtual void saveParticleLevelEvent(const top::ParticleLevelEvent& /* plEvent */) { - /* Deliberately No-Op */ - return; + /* Deliberately No-Op */ + return; } /*! @@ -83,18 +89,17 @@ namespace top { * @param upgradeEvent The upgrade event whose contents will be saved. */ virtual void saveUpgradeEvent(const top::ParticleLevelEvent& /* plEvent */) { - /* Deliberately No-Op */ - return; + /* Deliberately No-Op */ + return; } /** * @brief So you can write something at the end of the job (like metadata). */ - virtual void finalize(){return;} + virtual void finalize() {return;} ClassDef(top::EventSaverBase, 0); }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverFlatNtuple.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverFlatNtuple.h index 82ab1d577f1bc5dcf76c84268726d8f03ee6127e..38e80327578c12dd997dd93e3b691aca956da5ec 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverFlatNtuple.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverFlatNtuple.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSAVERFLATNTUPLE_H_ #define EVENTSAVERFLATNTUPLE_H_ @@ -8,7 +8,6 @@ #include "TopAnalysis/EventSaverBase.h" #include "TopCorrections/ScaleFactorRetriever.h" #include "TopEventSelectionTools/TreeManager.h" -#include "TopObjectSelectionTools/RCJetMC15.h" // Framework include(s): #include "AsgTools/AsgTool.h" @@ -16,19 +15,18 @@ #include "AthContainers/DataVector.h" #include <unordered_map> -namespace top { +namespace top { // fwd declare upgrade class -class UpgradeEvent; + class UpgradeEvent; /** * @brief Some code that writes out a 'standard' flat ntuple. This can be * extended if the user wants to inherit from this and implement the functions * themselves. */ -class EventSaverFlatNtuple : public top::EventSaverBase , public asg::AsgTool { - -public: + class EventSaverFlatNtuple: public top::EventSaverBase, public asg::AsgTool { + public: /** * @brief A default constructor so that this class can be created at * run-time by ROOT. @@ -49,10 +47,17 @@ public: * @param extraBranches Extra info requested (like which selections are * passed). */ - virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches); + virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches) override; + + /** + * @brief Execute stuff common for reco/particle/parton level, + * e.g. loading of weights, PDF sets, etc. + */ + virtual void execute() override; //Keep the asg::AsgTool happy - virtual StatusCode initialize(){return StatusCode::SUCCESS;} + virtual StatusCode initialize() override {return StatusCode::SUCCESS;} /** * @brief Run for every event (actually every systematic for every event). @@ -62,7 +67,10 @@ public: * @param event The top::Event which has had object selection and overlap * removal (if requested) applied to it. */ - virtual void saveEvent(const top::Event& event); + virtual void saveEvent(const top::Event& event) override; // calls the three next functions + virtual void cleanEvent(); // (re-)initialise all relevant variables to default (dummy) values + virtual void calculateEvent(const top::Event& event); // calculate the relevant variables + virtual void fillEvent(const top::Event& event); // calls tree->Fill /** * @breif Run for every event @@ -72,7 +80,10 @@ public: * PDF info * TopPartons */ - virtual void saveTruthEvent(); + virtual void saveTruthEvent() override; // calls the three next functions + virtual void cleanTruthEvent(); // (re-)initialise all relevant variables to default (dummy) values + virtual void calculateTruthEvent(); // calculate the relevant variables + virtual void fillTruthEvent(); // calls tree->Fill /*! * @brief Store the particle level event's content in the particle level @@ -85,7 +96,11 @@ public: * @param plEvent The particle level event whose data content will be * written to the output. */ - virtual void saveParticleLevelEvent(const top::ParticleLevelEvent& plEvent); + virtual void saveParticleLevelEvent(const top::ParticleLevelEvent& plEvent) override; // calls the three next functions + virtual void cleanParticleLevelEvent(); // (re-)initialise all relevant variables to default (dummy) values + virtual void calculateParticleLevelEvent(const top::ParticleLevelEvent& plEvent); // calculate the relevant + // variables + virtual void fillParticleLevelEvent(); // calls tree->Fill /*! * @brief Store the upgrade event's content in the upgrade @@ -98,19 +113,21 @@ public: * @param upgradeEvent The upgrade event whose data content will be * written to the output. */ - virtual void saveUpgradeEvent(const top::ParticleLevelEvent& plEvent); + virtual void saveUpgradeEvent(const top::ParticleLevelEvent& plEvent) override; // calls the three next functions + virtual void cleanUpgradeEvent(); // (re-)initialise all relevant variables to default (dummy) values + virtual void calculateUpgradeEvent(const top::ParticleLevelEvent& plEvent); // calculate the relevant variables + virtual void fillUpgradeEvent(); // calls tree->Fill /** * @brief Not used by the flat ntuple code yet, but needed by the xAOD code. */ - virtual void finalize(); + virtual void finalize() override; /** * @brief shorten name of b-tagging working point (FixedCutBEff_*) */ - std::string shortBtagWP(std::string const & WP) const; - -protected: + std::string shortBtagWP(std::string const& WP) const; + protected: /** * @brief Allow child classes to access the configuration object. */ @@ -124,7 +141,7 @@ protected: * * @return A vector of the treeManagers (one for each systematic). */ - std::vector<std::shared_ptr<top::TreeManager>> treeManagers(); + std::vector<std::shared_ptr<top::TreeManager> > treeManagers(); std::shared_ptr<top::TreeManager> truthTreeManager(); /*! @@ -135,32 +152,40 @@ protected: */ std::shared_ptr<top::TreeManager> particleLevelTreeManager(); + /*! + * @brief Return a shared pointer to the top::TreeManager object that is + * used for the upgrade level output tree. + * @returns A shared pointer to the top::TreeManager object that is used to + * write out the upgrade level event data. + */ + std::shared_ptr<top::TreeManager> upgradeTreeManager(); - /** - * @brief Return a shared pointer to the top::ScaleFactorRetriever object - * which allows us to easily access the SF decorations - * @returns A shared pointer to the top::ScaleFactorRetriever object - */ - std::shared_ptr<top::ScaleFactorRetriever> scaleFactorRetriever(); + /** + * @brief Return a shared pointer to the top::ScaleFactorRetriever object + * which allows us to easily access the SF decorations + * @returns A shared pointer to the top::ScaleFactorRetriever object + */ + //std::shared_ptr<top::ScaleFactorRetriever> scaleFactorRetriever(); + top::ScaleFactorRetriever* scaleFactorRetriever(); /*! * @brief Function to access the branch filters - cf ANALYSISTO-61 * @returns A shared pointer to the m_branchFilters object */ - std::vector<top::TreeManager::BranchFilter> & branchFilters(); - + std::vector<top::TreeManager::BranchFilter>& branchFilters(); + /*! * @brief Internal function which configures the particle level tree * manager. It does branch setup etc. */ - void setupParticleLevelTreeManager(const top::ParticleLevelEvent& plEvent); + void setupParticleLevelTreeManager(/*const top::ParticleLevelEvent& plEvent*/); /*! * @brief Internal function which configures the upgrade tree manager. * It does branch setup etc. */ void setupUpgradeTreeManager(/*const top::UpgradeEvent& upgradeEvent*/); -private: + private: /** * @brief For each selection that we run in the top-xaod code, we "decorate" * event info with a variable saying if this event passed or failed it. @@ -205,13 +230,14 @@ private: std::shared_ptr<top::TopConfig> m_config; ///Scale factors - std::shared_ptr<top::ScaleFactorRetriever> m_sfRetriever; + //std::shared_ptr<top::ScaleFactorRetriever> m_sfRetriever; + top::ScaleFactorRetriever* m_sfRetriever; ///The file where everything goes TFile* m_outputFile; ///A simple way to write out branches, without having to worry about the type. - std::vector<std::shared_ptr<top::TreeManager>> m_treeManagers; + std::vector<std::shared_ptr<top::TreeManager> > m_treeManagers; std::shared_ptr<top::TreeManager> m_truthTreeManager; /// The top::TreeManager used for the particle level data output. @@ -220,7 +246,8 @@ private: /// decisions. The std::pair contains: /// .first --- The name of the selection /// .second --- The variable used for storing into the TTree - std::vector< std::pair<std::string,int> > m_particleLevel_SelectionDecisions; + std::vector< std::pair<std::string, int> > m_particleLevel_SelectionDecisions; + std::vector< std::pair<std::string, int> > m_upgrade_SelectionDecisions; /// TreeManager for upgrade analysis data output std::shared_ptr<top::TreeManager> m_upgradeTreeManager; @@ -231,6 +258,13 @@ private: /// branch filters - cf ANALYSISTO-61 std::vector<top::TreeManager::BranchFilter> m_branchFilters; + /// remove "FT_EFF_" and spaces in named systematics + std::string betterBtagNamedSyst(const std::string WP); + + ///////////////////////////////////// + /// Definition of event variables + ///////////////////////////////////// + ///Decisions on if the event passed / failed a particular selection. std::vector<int> m_selectionDecisions; @@ -243,12 +277,21 @@ private: //Store output PDF weights from LHAPDF std::unordered_map<std::string, std::vector<float> > m_PDF_eventWeights; + // Store boosted jet tagger names + std::vector<std::string> m_boostedJetTaggersNames; + std::vector<std::string> m_boostedJetTaggersNamesCalibrated; + //some event weights float m_weight_mc; float m_weight_pileup; ///-- Pileup SF systematics --/// float m_weight_pileup_UP; float m_weight_pileup_DOWN; + ///---Fwd electrons --/// + float m_weight_fwdElSF; + float m_weight_fwdElSF_FWDEL_SF_ID_UP; + float m_weight_fwdElSF_FWDEL_SF_ID_DOWN; + ///-- Lepton SF --/// float m_weight_leptonSF; ///-- Lepton SF - electron SF systematics --/// @@ -260,6 +303,14 @@ private: float m_weight_leptonSF_EL_SF_ID_DOWN; float m_weight_leptonSF_EL_SF_Isol_UP; float m_weight_leptonSF_EL_SF_Isol_DOWN; + ///-- electron SF advanded correlation model systematics --/// + std::vector<float> m_weight_leptonSF_EL_SF_CorrModel_Reco_UP; + std::vector<float> m_weight_leptonSF_EL_SF_CorrModel_Reco_DOWN; + std::vector<float> m_weight_leptonSF_EL_SF_CorrModel_ID_UP; + std::vector<float> m_weight_leptonSF_EL_SF_CorrModel_ID_DOWN; + std::vector<float> m_weight_leptonSF_EL_SF_CorrModel_Iso_UP; + std::vector<float> m_weight_leptonSF_EL_SF_CorrModel_Iso_DOWN; + ///-- Lepton SF - muon SF systematics --/// float m_weight_leptonSF_MU_SF_Trigger_STAT_UP; float m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN; @@ -284,11 +335,24 @@ private: float m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN; float m_weight_leptonSF_MU_SF_TTVA_SYST_UP; float m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN; + // Additional global event calculated trigger SF + systematics + float m_weight_globalLeptonTriggerSF; + float m_weight_globalLeptonTriggerSF_EL_Trigger_UP; + float m_weight_globalLeptonTriggerSF_EL_Trigger_DOWN; + float m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP; + float m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN; + float m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP; + float m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN; + // Old trigger SFs + float m_weight_oldTriggerSF; + float m_weight_oldTriggerSF_EL_Trigger_UP; + float m_weight_oldTriggerSF_EL_Trigger_DOWN; + float m_weight_oldTriggerSF_MU_Trigger_STAT_UP; + float m_weight_oldTriggerSF_MU_Trigger_STAT_DOWN; + float m_weight_oldTriggerSF_MU_Trigger_SYST_UP; + float m_weight_oldTriggerSF_MU_Trigger_SYST_DOWN; ///-- individual components for lepton SF --/// - float m_weight_indiv_SF_EL_Trigger; - float m_weight_indiv_SF_EL_Trigger_UP; - float m_weight_indiv_SF_EL_Trigger_DOWN; float m_weight_indiv_SF_EL_Reco; float m_weight_indiv_SF_EL_Reco_UP; float m_weight_indiv_SF_EL_Reco_DOWN; @@ -306,11 +370,6 @@ private: float m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN; float m_weight_indiv_SF_EL_ChargeMisID_SYST_UP; float m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN; - float m_weight_indiv_SF_MU_Trigger; - float m_weight_indiv_SF_MU_Trigger_STAT_UP; - float m_weight_indiv_SF_MU_Trigger_STAT_DOWN; - float m_weight_indiv_SF_MU_Trigger_SYST_UP; - float m_weight_indiv_SF_MU_Trigger_SYST_DOWN; float m_weight_indiv_SF_MU_ID; // Muon ID SF systematics (regular) float m_weight_indiv_SF_MU_ID_STAT_UP; @@ -336,68 +395,92 @@ private: // Taus float m_weight_tauSF; - float m_weight_tauSF_ELEOLR_UP; - float m_weight_tauSF_ELEOLR_DOWN; - float m_weight_tauSF_JETID_UP; - float m_weight_tauSF_JETID_DOWN; - float m_weight_tauSF_RECO_UP; - float m_weight_tauSF_RECO_DOWN; + std::map<top::topSFSyst, float> m_weight_tauSF_variations; // Photons float m_weight_photonSF = 0.; float m_weight_photonSF_ID_UP = 0.; float m_weight_photonSF_ID_DOWN = 0.; - float m_weight_photonSF_effIso = 0.; - float m_weight_photonSF_effLowPtIso_UP = 0.; - float m_weight_photonSF_effLowPtIso_DOWN = 0.; - float m_weight_photonSF_effTrkIso_UP = 0.; - float m_weight_photonSF_effTrkIso_DOWN = 0.; - float m_weight_photonSF_isoDDonoff_UP = 0.; - float m_weight_photonSF_isoDDonoff_DOWN = 0.; + float m_weight_photonSF_effIso_UP = 0.; + float m_weight_photonSF_effIso_DOWN = 0.; // nominal b-tagging SF [WP] std::unordered_map<std::string, float> m_weight_bTagSF; std::unordered_map<std::string, float> m_weight_trackjet_bTagSF; + // per-jet nominal btag SF + std::unordered_map<std::string, std::vector<float> > m_perjet_weight_bTagSF; + std::unordered_map<std::string, std::vector<float> > m_perjet_weight_trackjet_bTagSF; + // JVT (c++11 initialization for fun) float m_weight_jvt = 0.0; float m_weight_jvt_up = 0.0; float m_weight_jvt_down = 0.0; + // fJVT + float m_weight_forwardjvt = 0.0; + float m_weight_forwardjvt_up = 0.0; + float m_weight_forwardjvt_down = 0.0; - // Sherpa 2.2 weight + // Sherpa 2.2 weight float m_weight_sherpa_22_vjets = 0.; // eigen variations affecting b-jets [WP] - std::unordered_map<std::string, std::vector<float>> m_weight_bTagSF_eigen_B_up; - std::unordered_map<std::string, std::vector<float>> m_weight_bTagSF_eigen_B_down; - std::unordered_map<std::string, std::vector<float>> m_weight_trackjet_bTagSF_eigen_B_up; - std::unordered_map<std::string, std::vector<float>> m_weight_trackjet_bTagSF_eigen_B_down; + std::unordered_map<std::string, std::vector<float> > m_weight_bTagSF_eigen_B_up; + std::unordered_map<std::string, std::vector<float> > m_weight_bTagSF_eigen_B_down; + std::unordered_map<std::string, std::vector<float> > m_weight_trackjet_bTagSF_eigen_B_up; + std::unordered_map<std::string, std::vector<float> > m_weight_trackjet_bTagSF_eigen_B_down; + + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_bTagSF_eigen_B_up; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_bTagSF_eigen_B_down; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_trackjet_bTagSF_eigen_B_up; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_trackjet_bTagSF_eigen_B_down; // eigen variations affecting c-jets [WP] - std::unordered_map<std::string, std::vector<float>> m_weight_bTagSF_eigen_C_up; - std::unordered_map<std::string, std::vector<float>> m_weight_bTagSF_eigen_C_down; - std::unordered_map<std::string, std::vector<float>> m_weight_trackjet_bTagSF_eigen_C_up; - std::unordered_map<std::string, std::vector<float>> m_weight_trackjet_bTagSF_eigen_C_down; + std::unordered_map<std::string, std::vector<float> > m_weight_bTagSF_eigen_C_up; + std::unordered_map<std::string, std::vector<float> > m_weight_bTagSF_eigen_C_down; + std::unordered_map<std::string, std::vector<float> > m_weight_trackjet_bTagSF_eigen_C_up; + std::unordered_map<std::string, std::vector<float> > m_weight_trackjet_bTagSF_eigen_C_down; + + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_bTagSF_eigen_C_up; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_bTagSF_eigen_C_down; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_trackjet_bTagSF_eigen_C_up; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_trackjet_bTagSF_eigen_C_down; // eigen variations affecting light jets [WP] - std::unordered_map<std::string, std::vector<float>> m_weight_bTagSF_eigen_Light_up; - std::unordered_map<std::string, std::vector<float>> m_weight_bTagSF_eigen_Light_down; - std::unordered_map<std::string, std::vector<float>> m_weight_trackjet_bTagSF_eigen_Light_up; - std::unordered_map<std::string, std::vector<float>> m_weight_trackjet_bTagSF_eigen_Light_down; + std::unordered_map<std::string, std::vector<float> > m_weight_bTagSF_eigen_Light_up; + std::unordered_map<std::string, std::vector<float> > m_weight_bTagSF_eigen_Light_down; + std::unordered_map<std::string, std::vector<float> > m_weight_trackjet_bTagSF_eigen_Light_up; + std::unordered_map<std::string, std::vector<float> > m_weight_trackjet_bTagSF_eigen_Light_down; - // named systematics [WP][name] - std::unordered_map<std::string, std::unordered_map<std::string, float>> m_weight_bTagSF_named_up; - std::unordered_map<std::string, std::unordered_map<std::string, float>> m_weight_bTagSF_named_down; - std::unordered_map<std::string, std::unordered_map<std::string, float>> m_weight_trackjet_bTagSF_named_up; - std::unordered_map<std::string, std::unordered_map<std::string, float>> m_weight_trackjet_bTagSF_named_down; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_bTagSF_eigen_Light_up; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_bTagSF_eigen_Light_down; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_trackjet_bTagSF_eigen_Light_up; + std::unordered_map<std::string, std::vector<std::vector<float> > > m_perjet_weight_trackjet_bTagSF_eigen_Light_down; - // remove "FT_EFF_" and spaces in named systematics - std::string betterBtagNamedSyst (const std::string WP); + // named systematics [WP][name] + std::unordered_map<std::string, std::unordered_map<std::string, float> > m_weight_bTagSF_named_up; + std::unordered_map<std::string, std::unordered_map<std::string, float> > m_weight_bTagSF_named_down; + std::unordered_map<std::string, std::unordered_map<std::string, float> > m_weight_trackjet_bTagSF_named_up; + std::unordered_map<std::string, std::unordered_map<std::string, float> > m_weight_trackjet_bTagSF_named_down; + + std::unordered_map<std::string, + std::unordered_map<std::string, std::vector<float> > > m_perjet_weight_bTagSF_named_up; + std::unordered_map<std::string, + std::unordered_map<std::string, std::vector<float> > > m_perjet_weight_bTagSF_named_down; + std::unordered_map<std::string, + std::unordered_map<std::string, std::vector<float> > > m_perjet_weight_trackjet_bTagSF_named_up; + std::unordered_map<std::string, + std::unordered_map<std::string, + std::vector<float> > > m_perjet_weight_trackjet_bTagSF_named_down; ///-- weights for matrix-method fakes estimate, for each selection and configuration --/// - /// m_fakesMM_weights[selection][configuration] - std::unordered_map<std::string,std::unordered_map<std::string, float>> m_fakesMM_weights; + int m_ASMsize; + std::vector<float> m_ASMweights; + std::vector<std::vector<float> > m_ASMweights_Syst; + std::vector<std::vector<std::string> > m_ASMweights_Systname; + /// Weights for bootstrapping + std::vector<int> m_weight_poisson; //event info unsigned long long m_eventNumber; @@ -406,9 +489,13 @@ private: unsigned int m_mcChannelNumber; float m_mu_original; float m_mu; - // non-collision background flag - usage: https://twiki.cern.ch/twiki/bin/view/Atlas/NonCollisionBackgroundsRunTwo#Recommend_cuts_tools_and_procedu + float m_mu_actual_original; + float m_mu_actual; + // non-collision background flag - usage: + // https://twiki.cern.ch/twiki/bin/view/Atlas/NonCollisionBackgroundsRunTwo#Recommend_cuts_tools_and_procedu unsigned int m_backgroundFlags; - // hasBadMuon flag - see: https://twiki.cern.ch/twiki/bin/viewauth/Atlas/MuonSelectionTool#is_BadMuon_Flag_Event_Veto + // hasBadMuon flag - see: + // https://twiki.cern.ch/twiki/bin/viewauth/Atlas/MuonSelectionTool#is_BadMuon_Flag_Event_Veto unsigned int m_hasBadMuon; //electrons @@ -418,8 +505,11 @@ private: std::vector<float> m_el_phi; std::vector<float> m_el_e; std::vector<float> m_el_charge; + std::vector<float> m_el_faketype; std::vector<float> m_el_topoetcone20; std::vector<float> m_el_ptvarcone20; + std::vector<float> m_el_etcone20; + std::vector<float> m_el_ptcone30; std::vector<char> m_el_isTight; std::vector<char> m_el_CF; // pass charge ID selector (has no charge flip) std::unordered_map<std::string, std::vector<char> > m_el_trigMatched; @@ -427,8 +517,23 @@ private: std::vector<float> m_el_delta_z0_sintheta; std::vector<int> m_el_true_type; std::vector<int> m_el_true_origin; - std::vector<int> m_el_true_typebkg; - std::vector<int> m_el_true_originbkg; + std::vector<int> m_el_true_firstEgMotherTruthType; + std::vector<int> m_el_true_firstEgMotherTruthOrigin; + std::vector<int> m_el_true_firstEgMotherPdgId; + std::vector<char> m_el_true_isPrompt; + std::vector<char> m_el_true_isChargeFl; + std::vector<char> m_el_ECIDS; + std::vector<double> m_el_ECIDSResult; + + //forward electrons + std::vector<float> m_fwdel_pt; + std::vector<float> m_fwdel_eta; + std::vector<float> m_fwdel_phi; + std::vector<float> m_fwdel_e; + std::vector<float> m_fwdel_etcone20; + std::vector<float> m_fwdel_etcone30; + std::vector<float> m_fwdel_etcone40; + std::vector<char> m_fwdel_isTight; //muons std::vector<float> m_mu_pt; @@ -438,41 +543,180 @@ private: std::vector<float> m_mu_charge; std::vector<float> m_mu_topoetcone20; std::vector<float> m_mu_ptvarcone30; + std::vector<float> m_mu_etcone20; + std::vector<float> m_mu_ptcone30; std::vector<char> m_mu_isTight; std::unordered_map<std::string, std::vector<char> > m_mu_trigMatched; std::vector<float> m_mu_d0sig; std::vector<float> m_mu_delta_z0_sintheta; std::vector<int> m_mu_true_type; std::vector<int> m_mu_true_origin; + std::vector<char> m_mu_true_isPrompt; + std::vector<float> m_mu_prodVtx_z; + std::vector<float> m_mu_prodVtx_perp; + std::vector<float> m_mu_prodVtx_phi; + + //soft muons + std::vector<float> m_softmu_pt; + std::vector<float> m_softmu_eta; + std::vector<float> m_softmu_phi; + std::vector<float> m_softmu_e; + std::vector<float> m_softmu_charge; + std::vector<float> m_softmu_d0; + std::vector<float> m_softmu_d0sig; + std::vector<float> m_softmu_delta_z0_sintheta; + std::vector<int> m_softmu_true_type; + std::vector<int> m_softmu_true_origin; + std::vector<int> m_softmu_true_isPrompt; + std::vector<float> m_softmu_SF_ID; + std::vector<float> m_softmu_SF_ID_STAT_UP; + std::vector<float> m_softmu_SF_ID_STAT_DOWN; + std::vector<float> m_softmu_SF_ID_SYST_UP; + std::vector<float> m_softmu_SF_ID_SYST_DOWN; + std::vector<float> m_softmu_SF_ID_STAT_LOWPT_UP; + std::vector<float> m_softmu_SF_ID_STAT_LOWPT_DOWN; + std::vector<float> m_softmu_SF_ID_SYST_LOWPT_UP; + std::vector<float> m_softmu_SF_ID_SYST_LOWPT_DOWN; + std::vector<int> m_softmu_parton_origin_flag; + std::vector<int> m_softmu_particle_origin_flag; + std::vector<int> m_softmu_parent_pdgid; + std::vector<int> m_softmu_b_hadron_parent_pdgid; + std::vector<int> m_softmu_c_hadron_parent_pdgid; + + //temporary: PLIV for electrons+muons + std::vector<float> m_PLIV_el_PromptLeptonRNN_conversion; + std::vector<float> m_PLIV_el_PromptLeptonRNN_non_prompt_b; + std::vector<float> m_PLIV_el_PromptLeptonRNN_non_prompt_c; + std::vector<float> m_PLIV_el_PromptLeptonRNN_prompt; + std::vector<short> m_PLIV_el_PromptLeptonImprovedInput_MVAXBin; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_TrackJetNTrack; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_topoetcone30rel; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_ptvarcone30rel; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_PtFrac; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_DRlj; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_CaloClusterSumEtRel; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_PtRel; + std::vector<float> m_PLIV_el_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest_ThetaCutVtx; + std::vector<float> m_PLIV_el_PromptLeptonImprovedVetoBARR; + std::vector<float> m_PLIV_el_PromptLeptonImprovedVetoECAP; + std::vector<float> m_PLIV_mu_PromptLeptonRNN_non_prompt_b; + std::vector<float> m_PLIV_mu_PromptLeptonRNN_non_prompt_c; + std::vector<float> m_PLIV_mu_PromptLeptonRNN_prompt; + std::vector<short> m_PLIV_mu_PromptLeptonImprovedInput_MVAXBin; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedInput_topoetcone30rel; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedInput_PtFrac; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedInput_DRlj; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedInput_ptvarcone30_TightTTVA_pt500rel; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedInput_CaloClusterERel; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedInput_CandVertex_normDistToPriVtxLongitudinalBest; + std::vector<float> m_PLIV_mu_PromptLeptonImprovedVeto; + //photons std::vector<float> m_ph_pt; std::vector<float> m_ph_eta; std::vector<float> m_ph_phi; std::vector<float> m_ph_e; + std::vector<float> m_ph_true_type; + std::vector<float> m_ph_true_origin; + std::vector<float> m_ph_faketype; std::vector<float> m_ph_iso; //taus std::vector<float> m_tau_pt; std::vector<float> m_tau_eta; std::vector<float> m_tau_phi; + std::vector<float> m_tau_e; std::vector<float> m_tau_charge; + std::vector<char> m_tau_isHadronic; //jets std::vector<float> m_jet_pt; std::vector<float> m_jet_eta; std::vector<float> m_jet_phi; std::vector<float> m_jet_e; - std::vector<float> m_jet_mv2c00; std::vector<float> m_jet_mv2c10; - std::vector<float> m_jet_mv2c20; std::vector<float> m_jet_jvt; - std::vector<char> m_jet_passfjvt; + std::vector<float> m_jet_fjvt; + std::vector<char> m_jet_passfjvt; //Could be useful to check pass/fail when fJVT only used in MET std::vector<float> m_jet_ip3dsv1; std::vector<int> m_jet_truthflav; std::vector<int> m_jet_truthPartonLabel; std::vector<char> m_jet_isTrueHS; - std::unordered_map<std::string, std::vector<char>> m_jet_isbtagged;//one vector per jet per WP - std::vector<int> m_jet_tagWeightBin;//tag-weight bin in case Continuous WP is used + std::vector<int> m_jet_HadronConeExclExtendedTruthLabelID; // Newer jet truth flavour label + std::unordered_map<std::string, std::vector<char> > m_jet_isbtagged;//one vector per jet per WP + std::unordered_map<std::string, std::vector<int> > m_jet_tagWeightBin;// one vector per jet per tag-weight bin in + // case Continuous WP is used + + // ghost tracks + std::vector<std::vector<float> > m_jet_ghostTrack_pt; + std::vector<std::vector<float> > m_jet_ghostTrack_eta; + std::vector<std::vector<float> > m_jet_ghostTrack_phi; + std::vector<std::vector<float> > m_jet_ghostTrack_e; + std::vector<std::vector<float> > m_jet_ghostTrack_d0; + std::vector<std::vector<float> > m_jet_ghostTrack_z0; + std::vector<std::vector<float> > m_jet_ghostTrack_qOverP; + + // tracks + std::vector<float> m_track_pt; + std::vector<float> m_track_eta; + std::vector<float> m_track_phi; + std::vector<float> m_track_e; + std::vector<float> m_track_d0; + std::vector<float> m_track_z0; + std::vector<float> m_track_qOverP; + std::vector<float> m_track_charge; + std::vector<float> m_track_d0_significance; + std::vector<float> m_track_z0_significance; + std::vector<float> m_track_phi0; + std::vector<float> m_track_theta; + std::vector<float> m_track_chiSquared; + std::vector<uint8_t> m_track_numberDoF; + + // R21 b-tagging + std::unordered_map<std::string, std::vector<float>> m_jet_DLx; + std::unordered_map<std::string, std::vector<float>> m_jet_DLx_pb; + std::unordered_map<std::string, std::vector<float>> m_jet_DLx_pc; + std::unordered_map<std::string, std::vector<float>> m_jet_DLx_pu; + + // fail-JVT jets + std::vector<float> m_failJvt_jet_pt; + std::vector<float> m_failJvt_jet_eta; + std::vector<float> m_failJvt_jet_phi; + std::vector<float> m_failJvt_jet_e; + std::vector<float> m_failJvt_jet_jvt; + std::vector<float> m_failJvt_jet_fjvt; + std::vector<char> m_failJvt_jet_passfjvt; + std::vector<int> m_failJvt_jet_truthflav; + std::vector<int> m_failJvt_jet_truthPartonLabel; + std::vector<char> m_failJvt_jet_isTrueHS; + std::vector<int> m_failJvt_jet_HadronConeExclExtendedTruthLabelID; // Newer jet truth flavour label + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_pt; + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_eta; + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_phi; + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_e; + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_d0; + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_z0; + std::vector<std::vector<float> > m_failJvt_jet_ghostTrack_qOverP; + + // fail-FJVT jets + std::vector<float> m_failFJvt_jet_pt; + std::vector<float> m_failFJvt_jet_eta; + std::vector<float> m_failFJvt_jet_phi; + std::vector<float> m_failFJvt_jet_e; + std::vector<float> m_failFJvt_jet_jvt; + std::vector<float> m_failFJvt_jet_fjvt; + std::vector<char> m_failFJvt_jet_passjvt; + std::vector<int> m_failFJvt_jet_truthflav; + std::vector<int> m_failFJvt_jet_truthPartonLabel; + std::vector<char> m_failFJvt_jet_isTrueHS; + std::vector<int> m_failFJvt_jet_HadronConeExclExtendedTruthLabelID; // Newer jet truth flavour label + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_pt; + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_eta; + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_phi; + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_e; + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_d0; + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_z0; + std::vector<std::vector<float> > m_failFJvt_jet_ghostTrack_qOverP; // for upgrade, we store the tagging efficiency per jet & whether it is from pileup std::vector<float> m_jet_mv1eff; @@ -484,34 +728,47 @@ private: std::vector<float> m_ljet_phi; std::vector<float> m_ljet_e; std::vector<float> m_ljet_m; - std::vector<float> m_ljet_sd12; + std::vector<int> m_ljet_truthLabel; + + std::unordered_map<std::string, std::vector<float> > m_ljet_substructure; + std::unordered_map<std::string, std::vector<char> > m_ljet_isTagged; + std::unordered_map<std::string, std::vector<float> > m_ljet_tagSF; //track jets std::vector<float> m_tjet_pt; std::vector<float> m_tjet_eta; std::vector<float> m_tjet_phi; std::vector<float> m_tjet_e; - std::vector<float> m_tjet_mv2c00; std::vector<float> m_tjet_mv2c10; - std::vector<float> m_tjet_mv2c20; - std::unordered_map<std::string, std::vector<char>> m_tjet_isbtagged;//one vector per jet per WP - std::vector<int> m_tjet_tagWeightBin;//tag-weight bin in case Continuous WP is used + std::unordered_map<std::string, SG::AuxElement::ConstAccessor<float>> DLx; + std::unordered_map<std::string, std::vector<float>> m_tjet_DLx; + std::unordered_map<std::string, std::vector<float>> m_tjet_DLx_pb; + std::unordered_map<std::string, std::vector<float>> m_tjet_DLx_pc; + std::unordered_map<std::string, std::vector<float>> m_tjet_DLx_pu; + std::unordered_map<std::string, std::vector<char> > m_tjet_isbtagged;//one vector per jet per WP + std::unordered_map<std::string, std::vector<int> > m_tjet_tagWeightBin;//one vector per jet tag-weight bin in case + // Continuous WP is used //re-clustered jets // -> need unordered map for systematics bool m_makeRCJets; // making re-clustered jets bool m_makeVarRCJets; // making VarRC jets + bool m_useRCJSS; // write RCJSS variables + bool m_useRCAdditionalJSS; // write RCJSS additional variables + bool m_useVarRCJSS; // write Variable-R RCJSS variables + bool m_useVarRCAdditionalJSS; // write Variable-R RCJSS additional variables + bool m_useElectronChargeIDSelection; // write ECID tool output variables std::string m_RCJetContainer; // name for RC jets container in TStore std::vector<std::string> m_VarRCJetRho; std::vector<std::string> m_VarRCJetMassScale; - std::unique_ptr<RCJetMC15> m_rc; - std::map<std::string,std::unique_ptr<RCJetMC15> > m_VarRC; std::string m_egamma; // egamma systematic naming scheme std::string m_muonsyst; // muon systematic naming scheme + std::string m_softmuonsyst; // soft muon systematic naming scheme std::string m_jetsyst; // jet systematic naming scheme - std::unordered_map<std::size_t, JetReclusteringTool*> m_jetReclusteringTool; - std::map<std::string,std::vector<float>> m_VarRCjetBranches; - std::map<std::string,std::vector<std::vector<float>>> m_VarRCjetsubBranches; + std::map<std::string, std::vector<float> > m_VarRCjetBranches; + std::map<std::string, std::vector<std::vector<float> > > m_VarRCjetsubBranches; + std::map<std::string, std::vector<float> > m_VarRCjetBranchesParticle; + std::map<std::string, std::vector<std::vector<float> > > m_VarRCjetsubBranchesParticle; std::vector<int> m_rcjet_nsub; std::vector<float> m_rcjet_pt; std::vector<float> m_rcjet_eta; @@ -525,12 +782,54 @@ private: std::vector<std::vector<float> > m_rcjetsub_e; std::vector<std::vector<float> > m_rcjetsub_mv2c10; + std::vector<float> m_rrcjet_pt; + std::vector<float> m_rrcjet_eta; + std::vector<float> m_rrcjet_phi; + std::vector<float> m_rrcjet_e; + + std::vector<float> m_rcjet_tau32_clstr; + std::vector<float> m_rcjet_tau21_clstr; + std::vector<float> m_rcjet_tau3_clstr; + std::vector<float> m_rcjet_tau2_clstr; + std::vector<float> m_rcjet_tau1_clstr; + + std::vector<float> m_rcjet_D2_clstr; + std::vector<float> m_rcjet_ECF1_clstr; + std::vector<float> m_rcjet_ECF2_clstr; + std::vector<float> m_rcjet_ECF3_clstr; + + std::vector<float> m_rcjet_d12_clstr; + std::vector<float> m_rcjet_d23_clstr; + std::vector<float> m_rcjet_Qw_clstr; + std::vector<float> m_rcjet_nconstituent_clstr; + + std::vector<float> m_rcjet_gECF332_clstr; + std::vector<float> m_rcjet_gECF461_clstr; + std::vector<float> m_rcjet_gECF322_clstr; + std::vector<float> m_rcjet_gECF331_clstr; + std::vector<float> m_rcjet_gECF422_clstr; + std::vector<float> m_rcjet_gECF441_clstr; + std::vector<float> m_rcjet_gECF212_clstr; + std::vector<float> m_rcjet_gECF321_clstr; + std::vector<float> m_rcjet_gECF311_clstr; + std::vector<float> m_rcjet_L1_clstr; + std::vector<float> m_rcjet_L2_clstr; + std::vector<float> m_rcjet_L3_clstr; + std::vector<float> m_rcjet_L4_clstr; + std::vector<float> m_rcjet_L5_clstr; + + //met float m_met_met; float m_met_phi; + //these are for specific studies on the met, turned off by default, and turned on with the WriteMETBuiltWithLooseObjects option + float m_met_met_withLooseObjects; + float m_met_phi_withLooseObjects; //KLFitter short m_klfitter_selected; + /// Selection + std::vector<std::string> m_klfitter_selection; /// Error flags std::vector<short> m_klfitter_minuitDidNotConverge; std::vector<short> m_klfitter_fitAbortedDueToNaN; @@ -541,8 +840,9 @@ private: std::vector<unsigned int> m_klfitter_bestPermutation; std::vector<float> m_klfitter_logLikelihood; std::vector<float> m_klfitter_eventProbability; - std::vector<std::vector<double>> m_klfitter_parameters; - std::vector<std::vector<double>> m_klfitter_parameterErrors; + std::vector<unsigned int> m_klfitter_parameters_size; + std::vector<std::vector<double> > m_klfitter_parameters; + std::vector<std::vector<double> > m_klfitter_parameterErrors; /// Model std::vector<float> m_klfitter_model_bhad_pt; @@ -585,12 +885,61 @@ private: std::vector<float> m_klfitter_model_lep_eta; std::vector<float> m_klfitter_model_lep_phi; std::vector<float> m_klfitter_model_lep_E; + std::vector<unsigned int> m_klfitter_model_lep_index; + + std::vector<float> m_klfitter_model_lepZ1_pt; + std::vector<float> m_klfitter_model_lepZ1_eta; + std::vector<float> m_klfitter_model_lepZ1_phi; + std::vector<float> m_klfitter_model_lepZ1_E; + std::vector<unsigned int> m_klfitter_model_lepZ1_index; + + std::vector<float> m_klfitter_model_lepZ2_pt; + std::vector<float> m_klfitter_model_lepZ2_eta; + std::vector<float> m_klfitter_model_lepZ2_phi; + std::vector<float> m_klfitter_model_lepZ2_E; + std::vector<unsigned int> m_klfitter_model_lepZ2_index; std::vector<float> m_klfitter_model_nu_pt; std::vector<float> m_klfitter_model_nu_eta; std::vector<float> m_klfitter_model_nu_phi; std::vector<float> m_klfitter_model_nu_E; + std::vector<float> m_klfitter_model_b_from_top1_pt; + std::vector<float> m_klfitter_model_b_from_top1_eta; + std::vector<float> m_klfitter_model_b_from_top1_phi; + std::vector<float> m_klfitter_model_b_from_top1_E; + std::vector<unsigned int> m_klfitter_model_b_from_top1_jetIndex; + + std::vector<float> m_klfitter_model_b_from_top2_pt; + std::vector<float> m_klfitter_model_b_from_top2_eta; + std::vector<float> m_klfitter_model_b_from_top2_phi; + std::vector<float> m_klfitter_model_b_from_top2_E; + std::vector<unsigned int> m_klfitter_model_b_from_top2_jetIndex; + + std::vector<float> m_klfitter_model_lj1_from_top1_pt; + std::vector<float> m_klfitter_model_lj1_from_top1_eta; + std::vector<float> m_klfitter_model_lj1_from_top1_phi; + std::vector<float> m_klfitter_model_lj1_from_top1_E; + std::vector<unsigned int> m_klfitter_model_lj1_from_top1_jetIndex; + + std::vector<float> m_klfitter_model_lj2_from_top1_pt; + std::vector<float> m_klfitter_model_lj2_from_top1_eta; + std::vector<float> m_klfitter_model_lj2_from_top1_phi; + std::vector<float> m_klfitter_model_lj2_from_top1_E; + std::vector<unsigned int> m_klfitter_model_lj2_from_top1_jetIndex; + + std::vector<float> m_klfitter_model_lj1_from_top2_pt; + std::vector<float> m_klfitter_model_lj1_from_top2_eta; + std::vector<float> m_klfitter_model_lj1_from_top2_phi; + std::vector<float> m_klfitter_model_lj1_from_top2_E; + std::vector<unsigned int> m_klfitter_model_lj1_from_top2_jetIndex; + + std::vector<float> m_klfitter_model_lj2_from_top2_pt; + std::vector<float> m_klfitter_model_lj2_from_top2_eta; + std::vector<float> m_klfitter_model_lj2_from_top2_phi; + std::vector<float> m_klfitter_model_lj2_from_top2_E; + std::vector<unsigned int> m_klfitter_model_lj2_from_top2_jetIndex; + // calculated KLFitter variables for best perm float m_klfitter_bestPerm_topLep_pt; float m_klfitter_bestPerm_topLep_eta; @@ -643,7 +992,10 @@ private: std::vector<float> m_mc_eta; std::vector<float> m_mc_phi; std::vector<float> m_mc_e; + std::vector<double> m_mc_charge; std::vector<int> m_mc_pdgId; + std::vector<int> m_mc_status; + std::vector<int> m_mc_barcode; //PDFInfo std::vector<float> m_PDFinfo_X1; @@ -653,9 +1005,8 @@ private: std::vector<float> m_PDFinfo_Q; std::vector<float> m_PDFinfo_XF1; std::vector<float> m_PDFinfo_XF2; - - //the on-the-fly computed generator weights - //there is one vector of float per entry in the trutheventcontainer (which should have only 1 entry) + + //the on-the-fly computed generator weights stored in EventInfo std::vector<float> m_mc_generator_weights; //Extra variables for Particle Level (bare lepton kinematics and b-Hadron @@ -674,17 +1025,643 @@ private: std::vector<int> m_jet_Ghosts_CHadron_Final_Count; std::vector<int> m_ljet_Ghosts_BHadron_Final_Count; std::vector<int> m_ljet_Ghosts_CHadron_Final_Count; + std::vector<std::vector<int> > m_rcjetsub_Ghosts_BHadron_Final_Count; + std::vector<std::vector<int> > m_rcjetsub_Ghosts_CHadron_Final_Count; + + // Truth tree inserted variables + // This can be expanded as required + // This is just a first pass at doing this sort of thing + std::unordered_map<std::string, int*> m_extraTruthVars_int; + std::unordered_map<std::string, float*> m_extraTruthVars_float; + protected: + ///////////////////////////////////// + /// const getters for the event variables + ///////////////////////////////////// + + ///Decisions on if the event passed / failed a particular selection. + const std::vector<int>& selectionDecisions() const {return m_selectionDecisions;} + + ///Decisions on if the event passed / failed a particular trigger. + const std::unordered_map<std::string, char>& triggerDecisions() const {return m_triggerDecisions;} + + ///Pre-scale of the trigger menu for each event. + const std::unordered_map<std::string, float>& triggerPrescales() const {return m_triggerPrescales;} + //Store output PDF weights from LHAPDF + const std::unordered_map<std::string, std::vector<float> >& PDF_eventWeights() const {return m_PDF_eventWeights;} + + //some event weights + const float& weight_mc() const {return m_weight_mc;} + const float& weight_pileup() const {return m_weight_pileup;} + + ///-- Pileup SF systematics --/// + const float& weight_pileup_UP() const {return m_weight_pileup_UP;} + const float& weight_pileup_DOWN() const {return m_weight_pileup_DOWN;} + + ///-- Lepton SF --/// + const float& weight_leptonSF() const {return m_weight_leptonSF;} + + ///-- Lepton SF - electron SF systematics --/// + const float& weight_leptonSF_EL_SF_Trigger_UP() const {return m_weight_leptonSF_EL_SF_Trigger_UP;} + const float& weight_leptonSF_EL_SF_Trigger_DOWN() const {return m_weight_leptonSF_EL_SF_Trigger_DOWN;} + const float& weight_leptonSF_EL_SF_Reco_UP() const {return m_weight_leptonSF_EL_SF_Reco_UP;} + const float& weight_leptonSF_EL_SF_Reco_DOWN() const {return m_weight_leptonSF_EL_SF_Reco_DOWN;} + const float& weight_leptonSF_EL_SF_ID_UP() const {return m_weight_leptonSF_EL_SF_ID_UP;} + const float& weight_leptonSF_EL_SF_ID_DOWN() const {return m_weight_leptonSF_EL_SF_ID_DOWN;} + const float& weight_leptonSF_EL_SF_Isol_UP() const {return m_weight_leptonSF_EL_SF_Isol_UP;} + const float& weight_leptonSF_EL_SF_Isol_DOWN() const {return m_weight_leptonSF_EL_SF_Isol_DOWN;} + + ///-- Lepton SF - muon SF systematics --/// + const float& weight_leptonSF_MU_SF_Trigger_STAT_UP() const {return m_weight_leptonSF_MU_SF_Trigger_STAT_UP;} + const float& weight_leptonSF_MU_SF_Trigger_STAT_DOWN() const {return m_weight_leptonSF_MU_SF_Trigger_STAT_DOWN;} + const float& weight_leptonSF_MU_SF_Trigger_SYST_UP() const {return m_weight_leptonSF_MU_SF_Trigger_SYST_UP;} + const float& weight_leptonSF_MU_SF_Trigger_SYST_DOWN() const {return m_weight_leptonSF_MU_SF_Trigger_SYST_DOWN;} + // Muon ID SF systematics (regular) + const float& weight_leptonSF_MU_SF_ID_STAT_UP() const {return m_weight_leptonSF_MU_SF_ID_STAT_UP;} + const float& weight_leptonSF_MU_SF_ID_STAT_DOWN() const {return m_weight_leptonSF_MU_SF_ID_STAT_DOWN;} + const float& weight_leptonSF_MU_SF_ID_SYST_UP() const {return m_weight_leptonSF_MU_SF_ID_SYST_UP;} + const float& weight_leptonSF_MU_SF_ID_SYST_DOWN() const {return m_weight_leptonSF_MU_SF_ID_SYST_DOWN;} + // Muon ID SF systematics (low pT) + const float& weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP() const {return m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_UP;} + const float& weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN() const {return m_weight_leptonSF_MU_SF_ID_STAT_LOWPT_DOWN;} + const float& weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP() const {return m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_UP;} + const float& weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN() const {return m_weight_leptonSF_MU_SF_ID_SYST_LOWPT_DOWN;} + // Muon isolation SF systematics + const float& weight_leptonSF_MU_SF_Isol_STAT_UP() const {return m_weight_leptonSF_MU_SF_Isol_STAT_UP;} + const float& weight_leptonSF_MU_SF_Isol_STAT_DOWN() const {return m_weight_leptonSF_MU_SF_Isol_STAT_DOWN;} + const float& weight_leptonSF_MU_SF_Isol_SYST_UP() const {return m_weight_leptonSF_MU_SF_Isol_SYST_UP;} + const float& weight_leptonSF_MU_SF_Isol_SYST_DOWN() const {return m_weight_leptonSF_MU_SF_Isol_SYST_DOWN;} + const float& weight_leptonSF_MU_SF_TTVA_STAT_UP() const {return m_weight_leptonSF_MU_SF_TTVA_STAT_UP;} + const float& weight_leptonSF_MU_SF_TTVA_STAT_DOWN() const {return m_weight_leptonSF_MU_SF_TTVA_STAT_DOWN;} + const float& weight_leptonSF_MU_SF_TTVA_SYST_UP() const {return m_weight_leptonSF_MU_SF_TTVA_SYST_UP;} + const float& weight_leptonSF_MU_SF_TTVA_SYST_DOWN() const {return m_weight_leptonSF_MU_SF_TTVA_SYST_DOWN;} + // Special global lepton trigger SF + systematics + const float& weight_globalLeptonTriggerSF() const {return m_weight_globalLeptonTriggerSF;} + const float& weight_globalLeptonTriggerSF_EL_Trigger_UP() const { + return m_weight_globalLeptonTriggerSF_EL_Trigger_UP; + } + const float& weight_globalLeptonTriggerSF_EL_Trigger_DOWN() const { + return m_weight_globalLeptonTriggerSF_EL_Trigger_DOWN; + } + const float& weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP() const { + return m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_UP; + } + const float& weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN() const { + return m_weight_globalLeptonTriggerSF_MU_Trigger_STAT_DOWN; + } + const float& weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP() const {return m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_UP;} + const float& weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN() const {return m_weight_globalLeptonTriggerSF_MU_Trigger_SYST_DOWN;} + // Old trigger SFs + const float& weight_oldTriggerSF() const {return m_weight_oldTriggerSF;} + const float& weight_oldTriggerSF_EL_Trigger_UP() const {return m_weight_oldTriggerSF_EL_Trigger_UP;} + const float& weight_oldTriggerSF_EL_Trigger_DOWN() const {return m_weight_oldTriggerSF_EL_Trigger_DOWN;} + const float& weight_oldTriggerSF_MU_Trigger_STAT_UP() const {return m_weight_oldTriggerSF_MU_Trigger_STAT_UP;} + const float& weight_oldTriggerSF_MU_Trigger_STAT_DOWN() const {return m_weight_oldTriggerSF_MU_Trigger_STAT_DOWN;} + const float& weight_oldTriggerSF_MU_Trigger_SYST_UP() const {return m_weight_oldTriggerSF_MU_Trigger_SYST_UP;} + const float& weight_oldTriggerSF_MU_Trigger_SYST_DOWN() const {return m_weight_oldTriggerSF_MU_Trigger_SYST_DOWN;} + + ///-- individual components for lepton SF --/// + const float& weight_indiv_SF_EL_Trigger() const {return weight_oldTriggerSF();} + const float& weight_indiv_SF_EL_Trigger_UP() const {return weight_oldTriggerSF_EL_Trigger_UP();} + const float& weight_indiv_SF_EL_Trigger_DOWN() const {return weight_oldTriggerSF_EL_Trigger_DOWN();} + const float& weight_indiv_SF_EL_Reco() const {return m_weight_indiv_SF_EL_Reco;} + const float& weight_indiv_SF_EL_Reco_UP() const {return m_weight_indiv_SF_EL_Reco_UP;} + const float& weight_indiv_SF_EL_Reco_DOWN() const {return m_weight_indiv_SF_EL_Reco_DOWN;} + const float& weight_indiv_SF_EL_ID() const {return m_weight_indiv_SF_EL_ID;} + const float& weight_indiv_SF_EL_ID_UP() const {return m_weight_indiv_SF_EL_ID_UP;} + const float& weight_indiv_SF_EL_ID_DOWN() const {return m_weight_indiv_SF_EL_ID_DOWN;} + const float& weight_indiv_SF_EL_Isol() const {return m_weight_indiv_SF_EL_Isol;} + const float& weight_indiv_SF_EL_Isol_UP() const {return m_weight_indiv_SF_EL_Isol_UP;} + const float& weight_indiv_SF_EL_Isol_DOWN() const {return m_weight_indiv_SF_EL_Isol_DOWN;} + const float& weight_indiv_SF_EL_ChargeID() const {return m_weight_indiv_SF_EL_ChargeID;} + const float& weight_indiv_SF_EL_ChargeID_UP() const {return m_weight_indiv_SF_EL_ChargeID_UP;} + const float& weight_indiv_SF_EL_ChargeID_DOWN() const {return m_weight_indiv_SF_EL_ChargeID_DOWN;} + const float& weight_indiv_SF_EL_ChargeMisID() const {return m_weight_indiv_SF_EL_ChargeMisID;} + const float& weight_indiv_SF_EL_ChargeMisID_STAT_UP() const {return m_weight_indiv_SF_EL_ChargeMisID_STAT_UP;} + const float& weight_indiv_SF_EL_ChargeMisID_STAT_DOWN() const {return m_weight_indiv_SF_EL_ChargeMisID_STAT_DOWN;} + const float& weight_indiv_SF_EL_ChargeMisID_SYST_UP() const {return m_weight_indiv_SF_EL_ChargeMisID_SYST_UP;} + const float& weight_indiv_SF_EL_ChargeMisID_SYST_DOWN() const {return m_weight_indiv_SF_EL_ChargeMisID_SYST_DOWN;} + const float& weight_indiv_SF_MU_Trigger() const {return weight_oldTriggerSF();} + const float& weight_indiv_SF_MU_Trigger_STAT_UP() const {return weight_oldTriggerSF_MU_Trigger_STAT_UP();} + const float& weight_indiv_SF_MU_Trigger_STAT_DOWN() const {return weight_oldTriggerSF_MU_Trigger_STAT_DOWN();} + const float& weight_indiv_SF_MU_Trigger_SYST_UP() const {return weight_oldTriggerSF_MU_Trigger_SYST_UP();} + const float& weight_indiv_SF_MU_Trigger_SYST_DOWN() const {return weight_oldTriggerSF_MU_Trigger_SYST_DOWN();} + const float& weight_indiv_SF_MU_ID() const {return m_weight_indiv_SF_MU_ID;} + // Muon ID SF systematics (regular) + const float& weight_indiv_SF_MU_ID_STAT_UP() const {return m_weight_indiv_SF_MU_ID_STAT_UP;} + const float& weight_indiv_SF_MU_ID_STAT_DOWN() const {return m_weight_indiv_SF_MU_ID_STAT_DOWN;} + const float& weight_indiv_SF_MU_ID_SYST_UP() const {return m_weight_indiv_SF_MU_ID_SYST_UP;} + const float& weight_indiv_SF_MU_ID_SYST_DOWN() const {return m_weight_indiv_SF_MU_ID_SYST_DOWN;} + // Muon ID SF systematics (low pt) + const float& weight_indiv_SF_MU_ID_STAT_LOWPT_UP() const {return m_weight_indiv_SF_MU_ID_STAT_LOWPT_UP;} + const float& weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN() const {return m_weight_indiv_SF_MU_ID_STAT_LOWPT_DOWN;} + const float& weight_indiv_SF_MU_ID_SYST_LOWPT_UP() const {return m_weight_indiv_SF_MU_ID_SYST_LOWPT_UP;} + const float& weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN() const {return m_weight_indiv_SF_MU_ID_SYST_LOWPT_DOWN;} + // Muon isolation systematics + const float& weight_indiv_SF_MU_Isol() const {return m_weight_indiv_SF_MU_Isol;} + const float& weight_indiv_SF_MU_Isol_SYST_UP() const {return m_weight_indiv_SF_MU_Isol_SYST_UP;} + const float& weight_indiv_SF_MU_Isol_SYST_DOWN() const {return m_weight_indiv_SF_MU_Isol_SYST_DOWN;} + const float& weight_indiv_SF_MU_Isol_STAT_UP() const {return m_weight_indiv_SF_MU_Isol_STAT_UP;} + const float& weight_indiv_SF_MU_Isol_STAT_DOWN() const {return m_weight_indiv_SF_MU_Isol_STAT_DOWN;} + const float& weight_indiv_SF_MU_TTVA() const {return m_weight_indiv_SF_MU_TTVA;} + const float& weight_indiv_SF_MU_TTVA_SYST_UP() const {return m_weight_indiv_SF_MU_TTVA_SYST_UP;} + const float& weight_indiv_SF_MU_TTVA_SYST_DOWN() const {return m_weight_indiv_SF_MU_TTVA_SYST_DOWN;} + const float& weight_indiv_SF_MU_TTVA_STAT_UP() const {return m_weight_indiv_SF_MU_TTVA_STAT_UP;} + const float& weight_indiv_SF_MU_TTVA_STAT_DOWN() const {return m_weight_indiv_SF_MU_TTVA_STAT_DOWN;} + + // Photons + const float& weight_photonSF() const {return m_weight_photonSF;} + const float& weight_photonSF_ID_UP() const {return m_weight_photonSF_ID_UP;} + const float& weight_photonSF_ID_DOWN() const {return m_weight_photonSF_ID_DOWN;} + const float& weight_photonSF_effIso_UP() const {return m_weight_photonSF_effIso_UP;} + const float& weight_photonSF_effIso_DOWN() const {return m_weight_photonSF_effIso_DOWN;} + + // nominal b-tagging SF [WP] + const std::unordered_map<std::string, float>& weight_bTagSF() const {return m_weight_bTagSF;} + const std::unordered_map<std::string, std::vector<float> >& perjet_weight_bTagSF() const {return m_perjet_weight_bTagSF;} + const std::unordered_map<std::string, float>& weight_trackjet_bTagSF() const {return m_weight_trackjet_bTagSF;} + const std::unordered_map<std::string, std::vector<float> >& perjet_weight_trackjet_bTagSF() const {return m_perjet_weight_trackjet_bTagSF;} + + // JVT (c++11 initialization for fun) + const float& weight_jvt() const {return m_weight_jvt;} + const float& weight_jvt_up() const {return m_weight_jvt_up;} + const float& weight_jvt_down() const {return m_weight_jvt_down;} + + // FJVT + const float& weight_forwardjvt() const {return m_weight_forwardjvt;} + const float& weight_forwardjvt_up() const {return m_weight_forwardjvt_up;} + const float& weight_forwardjvt_down() const {return m_weight_forwardjvt_down;} + + // Sherpa 2.2 weight + const float& weight_sherpa_22_vjets() const {return m_weight_sherpa_22_vjets;} + + // eigen variations affecting b-jets [WP] + const std::unordered_map<std::string, std::vector<float> >& weight_bTagSF_eigen_B_up() const {return m_weight_bTagSF_eigen_B_up;} + const std::unordered_map<std::string, std::vector<float> >& weight_bTagSF_eigen_B_down() const {return m_weight_bTagSF_eigen_B_down;} + const std::unordered_map<std::string, std::vector<float> >& weight_trackjet_bTagSF_eigen_B_up() const {return m_weight_trackjet_bTagSF_eigen_B_up;} + const std::unordered_map<std::string, std::vector<float> >& weight_trackjet_bTagSF_eigen_B_down() const {return m_weight_trackjet_bTagSF_eigen_B_down;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_bTagSF_eigen_B_up() const {return m_perjet_weight_bTagSF_eigen_B_up;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_bTagSF_eigen_B_down() const {return m_perjet_weight_bTagSF_eigen_B_down;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_trackjet_bTagSF_eigen_B_up() const {return m_perjet_weight_trackjet_bTagSF_eigen_B_up;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_trackjet_bTagSF_eigen_B_down() const {return m_perjet_weight_trackjet_bTagSF_eigen_B_down;} + // eigen variations affecting c-jets [WP] + const std::unordered_map<std::string, std::vector<float> >& weight_bTagSF_eigen_C_up() const {return m_weight_bTagSF_eigen_C_up;} + const std::unordered_map<std::string, std::vector<float> >& weight_bTagSF_eigen_C_down() const {return m_weight_bTagSF_eigen_C_down;} + const std::unordered_map<std::string, std::vector<float> >& weight_trackjet_bTagSF_eigen_C_up() const {return m_weight_trackjet_bTagSF_eigen_C_up;} + const std::unordered_map<std::string, std::vector<float> >& weight_trackjet_bTagSF_eigen_C_down() const {return m_weight_trackjet_bTagSF_eigen_C_down;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_bTagSF_eigen_C_up() const {return m_perjet_weight_bTagSF_eigen_C_up;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_bTagSF_eigen_C_down() const {return m_perjet_weight_bTagSF_eigen_C_down;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_trackjet_bTagSF_eigen_C_up() const {return m_perjet_weight_trackjet_bTagSF_eigen_C_up;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_trackjet_bTagSF_eigen_C_down() const {return m_perjet_weight_trackjet_bTagSF_eigen_C_down;} + // eigen variations affecting light jets [WP] + const std::unordered_map<std::string, std::vector<float> >& weight_bTagSF_eigen_Light_up() const {return m_weight_bTagSF_eigen_Light_up;} + const std::unordered_map<std::string, std::vector<float> >& weight_bTagSF_eigen_Light_down() const {return m_weight_bTagSF_eigen_Light_down;} + const std::unordered_map<std::string, std::vector<float> >& weight_trackjet_bTagSF_eigen_Light_up() const {return m_weight_trackjet_bTagSF_eigen_Light_up;} + const std::unordered_map<std::string, std::vector<float> >& weight_trackjet_bTagSF_eigen_Light_down() const {return m_weight_trackjet_bTagSF_eigen_Light_down;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_bTagSF_eigen_Light_up() const {return m_perjet_weight_bTagSF_eigen_C_up;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_bTagSF_eigen_Light_down() const {return m_perjet_weight_bTagSF_eigen_C_down;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_trackjet_bTagSF_eigen_Light_up() const {return m_perjet_weight_trackjet_bTagSF_eigen_Light_up;} + const std::unordered_map<std::string, std::vector<std::vector<float> > >& perjet_weight_trackjet_bTagSF_eigen_Light_down() const {return m_perjet_weight_trackjet_bTagSF_eigen_Light_down;} + // named systematics [WP][name] + const std::unordered_map<std::string, std::unordered_map<std::string, float> >& weight_bTagSF_named_up() const {return m_weight_bTagSF_named_up;} + const std::unordered_map<std::string, std::unordered_map<std::string, float> >& weight_bTagSF_named_down() const {return m_weight_bTagSF_named_down;} + const std::unordered_map<std::string, std::unordered_map<std::string, float> >& weight_trackjet_bTagSF_named_up() const {return m_weight_trackjet_bTagSF_named_up;} + const std::unordered_map<std::string, std::unordered_map<std::string, float> >& weight_trackjet_bTagSF_named_down() const {return m_weight_trackjet_bTagSF_named_down;} + const std::unordered_map<std::string, std::unordered_map<std::string, std::vector<float> > >& perjet_weight_bTagSF_named_up() const {return m_perjet_weight_bTagSF_named_up;} + const std::unordered_map<std::string, std::unordered_map<std::string, std::vector<float> > >& perjet_weight_bTagSF_named_down() const {return m_perjet_weight_bTagSF_named_down;} + const std::unordered_map<std::string, std::unordered_map<std::string, std::vector<float> > >& perjet_weight_trackjet_bTagSF_named_up() const {return m_perjet_weight_trackjet_bTagSF_named_up;} + const std::unordered_map<std::string, std::unordered_map<std::string, std::vector<float> > >& perjet_weight_trackjet_bTagSF_named_down() const {return m_perjet_weight_trackjet_bTagSF_named_down;} + + /// Weights for bootstrapping + const std::vector<int>& weight_poisson() const {return m_weight_poisson;} + + //event info + const unsigned long long& eventNumber() const {return m_eventNumber;} + const unsigned int& runNumber() const {return m_runNumber;} + const unsigned int& randomRunNumber() const {return m_randomRunNumber;} + const unsigned int& mcChannelNumber() const {return m_mcChannelNumber;} + const float& mu_original() const {return m_mu_original;} + const float& mu() const {return m_mu;} + + // non-collision background flag - usage: + // https://twiki.cern.ch/twiki/bin/view/Atlas/NonCollisionBackgroundsRunTwo#Recommend_cuts_tools_and_procedu + const unsigned int& backgroundFlags() const {return m_backgroundFlags;} + + // hasBadMuon flag - see: + // https://twiki.cern.ch/twiki/bin/viewauth/Atlas/MuonSelectionTool#is_BadMuon_Flag_Event_Veto + const unsigned int& hasBadMuon() const {return m_hasBadMuon;} + + //electrons + const std::vector<float>& el_pt() const {return m_el_pt;} + const std::vector<float>& el_eta() const {return m_el_eta;} + const std::vector<float>& el_cl_eta() const {return m_el_cl_eta;} + const std::vector<float>& el_phi() const {return m_el_phi;} + const std::vector<float>& el_e() const {return m_el_e;} + const std::vector<float>& el_faketype() const {return m_el_faketype;} + const std::vector<float>& el_charge() const {return m_el_charge;} + const std::vector<float>& el_topoetcone20() const {return m_el_topoetcone20;} + const std::vector<float>& el_ptvarcone20() const {return m_el_ptvarcone20;} + const std::vector<char>& el_isTight() const {return m_el_isTight;} + const std::vector<char>& el_CF() const {return m_el_CF;} // pass charge ID selector (has no charge flip) + const std::unordered_map<std::string, std::vector<char> >& el_trigMatched() const {return m_el_trigMatched;} + const std::vector<float>& el_d0sig() const {return m_el_d0sig;} + const std::vector<float>& el_delta_z0_sintheta() const {return m_el_delta_z0_sintheta;} + const std::vector<int>& el_true_type() const {return m_el_true_type;} + const std::vector<int>& el_true_origin() const {return m_el_true_origin;} + const std::vector<int>& el_true_firstEgMotherTruthType() const {return m_el_true_firstEgMotherTruthType;} + const std::vector<int>& el_true_firstEgMotherTruthOrigin() const {return m_el_true_firstEgMotherTruthOrigin;} + const std::vector<int>& el_true_firstEgMotherPdgId() const {return m_el_true_firstEgMotherPdgId;} + const std::vector<char>& el_true_isPrompt() const {return m_el_true_isPrompt;} + const std::vector<char>& el_true_isChargeFl() const {return m_el_true_isChargeFl;} + + //forward electrons + const std::vector<float>& fwdel_pt() const {return m_fwdel_pt;} + const std::vector<float>& fwdel_eta() const {return m_fwdel_eta;} + const std::vector<float>& fwdel_phi() const {return m_fwdel_phi;} + const std::vector<float>& fwdel_e() const {return m_fwdel_e;} + const std::vector<float>& fwdel_etcone20() const {return m_fwdel_etcone20;} + const std::vector<float>& fwdel_etcone30() const {return m_fwdel_etcone30;} + const std::vector<float>& fwdel_etcone40() const {return m_fwdel_etcone40;} + + //muons + const std::vector<float>& mu_pt() const {return m_mu_pt;} + const std::vector<float>& mu_eta() const {return m_mu_eta;} + const std::vector<float>& mu_phi() const {return m_mu_phi;} + const std::vector<float>& mu_e() const {return m_mu_e;} + const std::vector<float>& mu_charge() const {return m_mu_charge;} + const std::vector<float>& mu_topoetcone20() const {return m_mu_topoetcone20;} + const std::vector<float>& mu_ptvarcone30() const {return m_mu_ptvarcone30;} + const std::vector<char>& mu_isTight() const {return m_mu_isTight;} + const std::unordered_map<std::string, std::vector<char> >& mu_trigMatched() const {return m_mu_trigMatched;} + const std::vector<float>& mu_d0sig() const {return m_mu_d0sig;} + const std::vector<float>& mu_delta_z0_sintheta() const {return m_mu_delta_z0_sintheta;} + const std::vector<int>& mu_true_type() const {return m_mu_true_type;} + const std::vector<int>& mu_true_origin() const {return m_mu_true_origin;} + const std::vector<char>& mu_true_isPrompt() const {return m_mu_true_isPrompt;} + + //soft muons + const std::vector<float>& softmu_pt() const {return m_softmu_pt;} + const std::vector<float>& softmu_eta() const {return m_softmu_eta;} + const std::vector<float>& softmu_phi() const {return m_softmu_phi;} + const std::vector<float>& softmu_e() const {return m_softmu_e;} + const std::vector<float>& softmu_charge() const {return m_softmu_charge;} + const std::vector<float>& softmu_d0() const {return m_softmu_d0;} + const std::vector<float>& softmu_d0sig() const {return m_softmu_d0sig;} + const std::vector<float>& softmu_delta_z0_sintheta() const {return m_softmu_delta_z0_sintheta;} + const std::vector<int>& softmu_true_type() const {return m_softmu_true_type;} + const std::vector<int>& softmu_true_origin() const {return m_softmu_true_origin;} + const std::vector<int>& softmu_true_isPrompt() const {return m_softmu_true_isPrompt;} + + //photons + const std::vector<float>& ph_pt() const {return m_ph_pt;} + const std::vector<float>& ph_eta() const {return m_ph_eta;} + const std::vector<float>& ph_phi() const {return m_ph_phi;} + const std::vector<float>& ph_e() const {return m_ph_e;} + const std::vector<float>& ph_true_type() const {return m_ph_true_type;} + const std::vector<float>& ph_true_origin() const {return m_ph_true_origin;} + const std::vector<float>& ph_faketype() const {return m_ph_faketype;} + const std::vector<float>& ph_iso() const {return m_ph_iso;} + + //taus + const std::vector<float>& tau_pt() const {return m_tau_pt;} + const std::vector<float>& tau_eta() const {return m_tau_eta;} + const std::vector<float>& tau_phi() const {return m_tau_phi;} + const std::vector<float>& tau_charge() const {return m_tau_charge;} + + //jets + const std::vector<float>& jet_pt() const {return m_jet_pt;} + const std::vector<float>& jet_eta() const {return m_jet_eta;} + const std::vector<float>& jet_phi() const {return m_jet_phi;} + const std::vector<float>& jet_e() const {return m_jet_e;} + const std::vector<float>& jet_mv2c10() const {return m_jet_mv2c10;} + const std::vector<float>& jet_jvt() const {return m_jet_jvt;} + const std::vector<float>& jet_forwardjvt() const {return m_jet_fjvt;} + const std::vector<char>& jet_passforwardjvt() const {return m_jet_passfjvt;} + const std::vector<int>& jet_truthflav() const {return m_jet_truthflav;} + const std::vector<int>& jet_truthPartonLabel() const {return m_jet_truthPartonLabel;} + const std::vector<char>& jet_isTrueHS() const {return m_jet_isTrueHS;} + const std::vector<int>& jet_truthflavExtended() const {return m_jet_HadronConeExclExtendedTruthLabelID;} + const std::unordered_map<std::string, std::vector<char> >& jet_isbtagged() const {return m_jet_isbtagged;}//one + // vector + // per jet + // per WP + const std::unordered_map<std::string, std::vector<int> >& jet_tagWeightBin() const {return m_jet_tagWeightBin;}//one + // vector + // per + // jet + // tag-weight + // bin + // in + // case + // Continuous + // WP + // is + // used + // for upgrade, we store the tagging efficiency per jet & whether it is from pileup + const std::vector<float>& jet_mv1eff() const {return m_jet_mv1eff;} + const std::vector<float>& jet_isPileup() const {return m_jet_isPileup;} + + // fail-JVT jets + const std::vector<float>& failJvt_jet_pt() const {return m_failJvt_jet_pt;} + const std::vector<float>& failJvt_jet_eta() const {return m_failJvt_jet_eta;} + const std::vector<float>& failJvt_jet_phi() const {return m_failJvt_jet_phi;} + const std::vector<float>& failJvt_jet_e() const {return m_failJvt_jet_e;} + const std::vector<float>& failJvt_jet_jvt() const {return m_failJvt_jet_jvt;} + const std::vector<float>& failJvt_jet_forwardjvt() const {return m_failJvt_jet_fjvt;} + const std::vector<char>& failJvt_jet_passforwardjvt() const {return m_failJvt_jet_passfjvt;} + const std::vector<int>& failJvt_jet_truthflav() const {return m_failJvt_jet_truthflav;} + const std::vector<int>& failJvt_jet_truthPartonLabel() const {return m_failJvt_jet_truthPartonLabel;} + const std::vector<char>& failJvt_jet_isTrueHS() const {return m_failJvt_jet_isTrueHS;} + const std::vector<int>& failJvt_jet_truthflavExtended() const {return m_failJvt_jet_HadronConeExclExtendedTruthLabelID;} + + // fail-FJVT jets + const std::vector<float>& failFJvt_jet_pt() const {return m_failFJvt_jet_pt;} + const std::vector<float>& failFJvt_jet_eta() const {return m_failFJvt_jet_eta;} + const std::vector<float>& failFJvt_jet_phi() const {return m_failFJvt_jet_phi;} + const std::vector<float>& failFJvt_jet_e() const {return m_failFJvt_jet_e;} + const std::vector<float>& failFJvt_jet_jvt() const {return m_failFJvt_jet_jvt;} + const std::vector<float>& failFJvt_jet_forwardjvt() const {return m_failFJvt_jet_fjvt;} + const std::vector<char>& failFJvt_jet_passjvt() const {return m_failFJvt_jet_passjvt;} + const std::vector<int>& failFJvt_jet_truthflav() const {return m_failFJvt_jet_truthflav;} + const std::vector<int>& failFJvt_jet_truthPartonLabel() const {return m_failFJvt_jet_truthPartonLabel;} + const std::vector<char>& failFJvt_jet_isTrueHS() const {return m_failFJvt_jet_isTrueHS;} + const std::vector<int>& failFJvt_jet_truthflavExtended() const {return m_failFJvt_jet_HadronConeExclExtendedTruthLabelID;} + + //large-R jets + const std::vector<float>& ljet_pt() const {return m_ljet_pt;} + const std::vector<float>& ljet_eta() const {return m_ljet_eta;} + const std::vector<float>& ljet_phi() const {return m_ljet_phi;} + const std::vector<float>& ljet_e() const {return m_ljet_e;} + const std::vector<float>& ljet_m() const {return m_ljet_m;} + const std::vector<int>& ljet_truthLabel() const {return m_ljet_truthLabel;} + + const std::unordered_map<std::string, std::vector<float> >& ljet_substructure() const {return m_ljet_substructure;} + const std::unordered_map<std::string, std::vector<char> >& ljet_isTagged() const {return m_ljet_isTagged;} + const std::vector<char>& ljet_isTagged(const std::string& taggerName) {return m_ljet_isTagged[taggerName];} + + //track jets + const std::vector<float>& tjet_pt() const {return m_tjet_pt;} + const std::vector<float>& tjet_eta() const {return m_tjet_eta;} + const std::vector<float>& tjet_phi() const {return m_tjet_phi;} + const std::vector<float>& tjet_e() const {return m_tjet_e;} + const std::vector<float>& tjet_mv2c10() const {return m_tjet_mv2c10;} + const std::unordered_map<std::string, std::vector<char> >& tjet_isbtagged() const {return m_tjet_isbtagged;}//one + // vector + // per + // jet + // per + // WP + const std::unordered_map<std::string, std::vector<int> >& tjet_tagWeightBin() const {return m_tjet_tagWeightBin;}//one + // vector + // per + // jet + // tag-weight + // bin + // in + // case + // Continuous + // WP + // is + // used + + //re-clustered jets + // -> need unordered map for systematics + const bool& makeRCJets() const {return m_makeRCJets;} // making re-clustered jets + const bool& makeVarRCJets() const {return m_makeVarRCJets;} // making VarRC jets + const std::string& RCJetContainer() const {return m_RCJetContainer;} // name for RC jets container in TStore + const std::vector<std::string>& VarRCJetRho() const {return m_VarRCJetRho;} + const std::vector<std::string>& VarRCJetMassScale() const {return m_VarRCJetMassScale;} + const std::string& egamma() const {return m_egamma;} // egamma systematic naming scheme + const std::string& muonsyst() const {return m_muonsyst;} // muon systematic naming scheme + const std::string& softmuonsyst() const {return m_softmuonsyst;} // soft muon systematic naming scheme + const std::string& jetsyst() const {return m_jetsyst;} // jet systematic naming scheme + const std::map<std::string, std::vector<float> >& VarRCjetBranches() const {return m_VarRCjetBranches;} + const std::map<std::string, std::vector<std::vector<float> > >& VarRCjetsubBranches() const {return m_VarRCjetsubBranches;} + const std::vector<int>& rcjet_nsub() const {return m_rcjet_nsub;} + const std::vector<float>& rcjet_pt() const {return m_rcjet_pt;} + const std::vector<float>& rcjet_eta() const {return m_rcjet_eta;} + const std::vector<float>& rcjet_phi() const {return m_rcjet_phi;} + const std::vector<float>& rcjet_e() const {return m_rcjet_e;} + const std::vector<float>& rcjet_d12() const {return m_rcjet_d12;} + const std::vector<float>& rcjet_d23() const {return m_rcjet_d23;} + const std::vector<std::vector<float> >& rcjetsub_pt() const {return m_rcjetsub_pt;} + const std::vector<std::vector<float> >& rcjetsub_eta() const {return m_rcjetsub_eta;} + const std::vector<std::vector<float> >& rcjetsub_phi() const {return m_rcjetsub_phi;} + const std::vector<std::vector<float> >& rcjetsub_e() const {return m_rcjetsub_e;} + const std::vector<std::vector<float> >& rcjetsub_mv2c10() const {return m_rcjetsub_mv2c10;} + const std::vector<float>& rcjet_tau32_clstr() const {return m_rcjet_tau32_clstr;} + const std::vector<float>& rcjet_tau21_clstr() const {return m_rcjet_tau21_clstr;} + const std::vector<float>& rcjet_tau3_clstr() const {return m_rcjet_tau3_clstr;} + const std::vector<float>& rcjet_tau2_clstr() const {return m_rcjet_tau2_clstr;} + const std::vector<float>& rcjet_tau1_clstr() const {return m_rcjet_tau1_clstr;} + const std::vector<float>& rcjet_D2_clstr() const {return m_rcjet_D2_clstr;} + const std::vector<float>& rcjet_ECF1_clstr() const {return m_rcjet_ECF1_clstr;} + const std::vector<float>& rcjet_ECF2_clstr() const {return m_rcjet_ECF2_clstr;} + const std::vector<float>& rcjet_ECF3_clstr() const {return m_rcjet_ECF3_clstr;} + const std::vector<float>& rcjet_d12_clstr() const {return m_rcjet_d12_clstr;} + const std::vector<float>& rcjet_d23_clstr() const {return m_rcjet_d23_clstr;} + const std::vector<float>& rcjet_Qw_clstr() const {return m_rcjet_Qw_clstr;} + const std::vector<float>& rcjet_nconstituent_clstr() const {return m_rcjet_nconstituent_clstr;} + const std::vector<float>& rcjet_gECF332_clstr() const {return m_rcjet_gECF332_clstr;} + const std::vector<float>& rcjet_gECF461_clstr() const {return m_rcjet_gECF461_clstr;} + const std::vector<float>& rcjet_gECF322_clstr() const {return m_rcjet_gECF322_clstr;} + const std::vector<float>& rcjet_gECF331_clstr() const {return m_rcjet_gECF331_clstr;} + const std::vector<float>& rcjet_gECF422_clstr() const {return m_rcjet_gECF422_clstr;} + const std::vector<float>& rcjet_gECF441_clstr() const {return m_rcjet_gECF441_clstr;} + const std::vector<float>& rcjet_gECF212_clstr() const {return m_rcjet_gECF212_clstr;} + const std::vector<float>& rcjet_gECF321_clstr() const {return m_rcjet_gECF321_clstr;} + const std::vector<float>& rcjet_gECF311_clstr() const {return m_rcjet_gECF311_clstr;} + + const std::vector<float>& rcjet_L1_clstr() const {return m_rcjet_L1_clstr;} + const std::vector<float>& rcjet_L2_clstr() const {return m_rcjet_L2_clstr;} + const std::vector<float>& rcjet_L3_clstr() const {return m_rcjet_L3_clstr;} + const std::vector<float>& rcjet_L4_clstr() const {return m_rcjet_L4_clstr;} + const std::vector<float>& rcjet_L5_clstr() const {return m_rcjet_L5_clstr;} + + //met + const float& met_met() const {return m_met_met;} + const float& met_phi() const {return m_met_phi;} + + ///KLFitter + const short& klfitter_selected() const {return m_klfitter_selected;} + /// Selection + const std::vector<std::string> klfitter_selection() const {return m_klfitter_selection;} + /// Error flags + const std::vector<short>& klfitter_minuitDidNotConverge() const {return m_klfitter_minuitDidNotConverge;} + const std::vector<short>& klfitter_fitAbortedDueToNaN() const {return m_klfitter_fitAbortedDueToNaN;} + const std::vector<short>& klfitter_atLeastOneFitParameterAtItsLimit() const {return m_klfitter_atLeastOneFitParameterAtItsLimit;} + const std::vector<short>& klfitter_invalidTransferFunctionAtConvergence() const {return m_klfitter_invalidTransferFunctionAtConvergence;} + /// Global result + const std::vector<unsigned int>& klfitter_bestPermutation() const {return m_klfitter_bestPermutation;} + const std::vector<float>& klfitter_logLikelihood() const {return m_klfitter_logLikelihood;} + const std::vector<float>& klfitter_eventProbability() const {return m_klfitter_eventProbability;} + const std::vector<unsigned int>& klfitter_parameters_size() const {return m_klfitter_parameters_size;} + const std::vector<std::vector<double> >& klfitter_parameters() const {return m_klfitter_parameters;} + const std::vector<std::vector<double> >& klfitter_parameterErrors() const {return m_klfitter_parameterErrors;} + /// Model + const std::vector<float>& klfitter_model_bhad_pt() const {return m_klfitter_model_bhad_pt;} + const std::vector<float>& klfitter_model_bhad_eta() const {return m_klfitter_model_bhad_eta;} + const std::vector<float>& klfitter_model_bhad_phi() const {return m_klfitter_model_bhad_phi;} + const std::vector<float>& klfitter_model_bhad_E() const {return m_klfitter_model_bhad_E;} + const std::vector<unsigned int>& klfitter_model_bhad_jetIndex() const {return m_klfitter_model_bhad_jetIndex;} + const std::vector<float>& klfitter_model_blep_pt() const {return m_klfitter_model_blep_pt;} + const std::vector<float>& klfitter_model_blep_eta() const {return m_klfitter_model_blep_eta;} + const std::vector<float>& klfitter_model_blep_phi() const {return m_klfitter_model_blep_phi;} + const std::vector<float>& klfitter_model_blep_E() const {return m_klfitter_model_blep_E;} + const std::vector<unsigned int>& klfitter_model_blep_jetIndex() const {return m_klfitter_model_blep_jetIndex;} + const std::vector<float>& klfitter_model_lq1_pt() const {return m_klfitter_model_lq1_pt;} + const std::vector<float>& klfitter_model_lq1_eta() const {return m_klfitter_model_lq1_eta;} + const std::vector<float>& klfitter_model_lq1_phi() const {return m_klfitter_model_lq1_phi;} + const std::vector<float>& klfitter_model_lq1_E() const {return m_klfitter_model_lq1_E;} + const std::vector<unsigned int>& klfitter_model_lq1_jetIndex() const {return m_klfitter_model_lq1_jetIndex;} + const std::vector<float>& klfitter_model_lq2_pt() const {return m_klfitter_model_lq2_pt;} + const std::vector<float>& klfitter_model_lq2_eta() const {return m_klfitter_model_lq2_eta;} + const std::vector<float>& klfitter_model_lq2_phi() const {return m_klfitter_model_lq2_phi;} + const std::vector<float>& klfitter_model_lq2_E() const {return m_klfitter_model_lq2_E;} + const std::vector<unsigned int>& klfitter_model_lq2_jetIndex() const {return m_klfitter_model_lq2_jetIndex;} + const std::vector<float>& klfitter_model_Higgs_b1_pt() const {return m_klfitter_model_Higgs_b1_pt;} + const std::vector<float>& klfitter_model_Higgs_b1_eta() const {return m_klfitter_model_Higgs_b1_eta;} + const std::vector<float>& klfitter_model_Higgs_b1_phi() const {return m_klfitter_model_Higgs_b1_phi;} + const std::vector<float>& klfitter_model_Higgs_b1_E() const {return m_klfitter_model_Higgs_b1_E;} + const std::vector<unsigned int>& klfitter_model_Higgs_b1_jetIndex() const {return m_klfitter_model_Higgs_b1_jetIndex;} + const std::vector<float>& klfitter_model_Higgs_b2_pt() const {return m_klfitter_model_Higgs_b2_pt;} + const std::vector<float>& klfitter_model_Higgs_b2_eta() const {return m_klfitter_model_Higgs_b2_eta;} + const std::vector<float>& klfitter_model_Higgs_b2_phi() const {return m_klfitter_model_Higgs_b2_phi;} + const std::vector<float>& klfitter_model_Higgs_b2_E() const {return m_klfitter_model_Higgs_b2_E;} + const std::vector<unsigned int>& klfitter_model_Higgs_b2_jetIndex() const {return m_klfitter_model_Higgs_b2_jetIndex;} + const std::vector<float>& klfitter_model_lep_pt() const {return m_klfitter_model_lep_pt;} + const std::vector<float>& klfitter_model_lep_eta() const {return m_klfitter_model_lep_eta;} + const std::vector<float>& klfitter_model_lep_phi() const {return m_klfitter_model_lep_phi;} + const std::vector<float>& klfitter_model_lep_E() const {return m_klfitter_model_lep_E;} + const std::vector<float>& klfitter_model_nu_pt() const {return m_klfitter_model_nu_pt;} + const std::vector<float>& klfitter_model_nu_eta() const {return m_klfitter_model_nu_eta;} + const std::vector<float>& klfitter_model_nu_phi() const {return m_klfitter_model_nu_phi;} + const std::vector<float>& klfitter_model_nu_E() const {return m_klfitter_model_nu_E;} + const std::vector<float>& klfitter_model_b_from_top1_pt() const {return m_klfitter_model_b_from_top1_pt;} + const std::vector<float>& klfitter_model_b_from_top1_eta() const {return m_klfitter_model_b_from_top1_eta;} + const std::vector<float>& klfitter_model_b_from_top1_phi() const {return m_klfitter_model_b_from_top1_phi;} + const std::vector<float>& klfitter_model_b_from_top1_E() const {return m_klfitter_model_b_from_top1_E;} + const std::vector<unsigned int>& klfitter_model_b_from_top1_jetIndex() const {return m_klfitter_model_b_from_top1_jetIndex;} + const std::vector<float>& klfitter_model_b_from_top2_pt() const {return m_klfitter_model_b_from_top2_pt;} + const std::vector<float>& klfitter_model_b_from_top2_eta() const {return m_klfitter_model_b_from_top2_eta;} + const std::vector<float>& klfitter_model_b_from_top2_phi() const {return m_klfitter_model_b_from_top2_phi;} + const std::vector<float>& klfitter_model_b_from_top2_E() const {return m_klfitter_model_b_from_top2_E;} + const std::vector<unsigned int>& klfitter_model_b_from_top2_jetIndex() const {return m_klfitter_model_b_from_top2_jetIndex;} + const std::vector<float>& klfitter_model_lj1_from_top1_pt() const {return m_klfitter_model_lj1_from_top1_pt;} + const std::vector<float>& klfitter_model_lj1_from_top1_eta() const {return m_klfitter_model_lj1_from_top1_eta;} + const std::vector<float>& klfitter_model_lj1_from_top1_phi() const {return m_klfitter_model_lj1_from_top1_phi;} + const std::vector<float>& klfitter_model_lj1_from_top1_E() const {return m_klfitter_model_lj1_from_top1_E;} + const std::vector<unsigned int>& klfitter_model_lj1_from_top1_jetIndex() const {return m_klfitter_model_lj1_from_top1_jetIndex;} + const std::vector<float>& klfitter_model_lj2_from_top1_pt() const {return m_klfitter_model_lj2_from_top1_pt;} + const std::vector<float>& klfitter_model_lj2_from_top1_eta() const {return m_klfitter_model_lj2_from_top1_eta;} + const std::vector<float>& klfitter_model_lj2_from_top1_phi() const {return m_klfitter_model_lj2_from_top1_phi;} + const std::vector<float>& klfitter_model_lj2_from_top1_E() const {return m_klfitter_model_lj2_from_top1_E;} + const std::vector<unsigned int>& klfitter_model_lj2_from_top1_jetIndex() const {return m_klfitter_model_lj2_from_top1_jetIndex;} + const std::vector<float>& klfitter_model_lj1_from_top2_pt() const {return m_klfitter_model_lj1_from_top2_pt;} + const std::vector<float>& klfitter_model_lj1_from_top2_eta() const {return m_klfitter_model_lj1_from_top2_eta;} + const std::vector<float>& klfitter_model_lj1_from_top2_phi() const {return m_klfitter_model_lj1_from_top2_phi;} + const std::vector<float>& klfitter_model_lj1_from_top2_E() const {return m_klfitter_model_lj1_from_top2_E;} + const std::vector<unsigned int>& klfitter_model_lj1_from_top2_jetIndex() const {return m_klfitter_model_lj1_from_top2_jetIndex;} + const std::vector<float>& klfitter_model_lj2_from_top2_pt() const {return m_klfitter_model_lj2_from_top2_pt;} + const std::vector<float>& klfitter_model_lj2_from_top2_eta() const {return m_klfitter_model_lj2_from_top2_eta;} + const std::vector<float>& klfitter_model_lj2_from_top2_phi() const {return m_klfitter_model_lj2_from_top2_phi;} + const std::vector<float>& klfitter_model_lj2_from_top2_E() const {return m_klfitter_model_lj2_from_top2_E;} + const std::vector<unsigned int>& klfitter_model_lj2_from_top2_jetIndex() const {return m_klfitter_model_lj2_from_top2_jetIndex;} + + // calculated KLFitter variables for best perm + const float& klfitter_bestPerm_topLep_pt() const {return m_klfitter_bestPerm_topLep_pt;} + const float& klfitter_bestPerm_topLep_eta() const {return m_klfitter_bestPerm_topLep_eta;} + const float& klfitter_bestPerm_topLep_phi() const {return m_klfitter_bestPerm_topLep_phi;} + const float& klfitter_bestPerm_topLep_E() const {return m_klfitter_bestPerm_topLep_E;} + const float& klfitter_bestPerm_topLep_m() const {return m_klfitter_bestPerm_topLep_m;} + const float& klfitter_bestPerm_topHad_pt() const {return m_klfitter_bestPerm_topHad_pt;} + const float& klfitter_bestPerm_topHad_eta() const {return m_klfitter_bestPerm_topHad_eta;} + const float& klfitter_bestPerm_topHad_phi() const {return m_klfitter_bestPerm_topHad_phi;} + const float& klfitter_bestPerm_topHad_E() const {return m_klfitter_bestPerm_topHad_E;} + const float& klfitter_bestPerm_topHad_m() const {return m_klfitter_bestPerm_topHad_m;} + const float& klfitter_bestPerm_ttbar_pt() const {return m_klfitter_bestPerm_ttbar_pt;} + const float& klfitter_bestPerm_ttbar_eta() const {return m_klfitter_bestPerm_ttbar_eta;} + const float& klfitter_bestPerm_ttbar_phi() const {return m_klfitter_bestPerm_ttbar_phi;} + const float& klfitter_bestPerm_ttbar_E() const {return m_klfitter_bestPerm_ttbar_E;} + const float& klfitter_bestPerm_ttbar_m() const {return m_klfitter_bestPerm_ttbar_m;} + // PseudoTop variables + const float& PseudoTop_Reco_ttbar_pt() const {return m_PseudoTop_Reco_ttbar_pt;} + const float& PseudoTop_Reco_ttbar_eta() const {return m_PseudoTop_Reco_ttbar_eta;} + const float& PseudoTop_Reco_ttbar_phi() const {return m_PseudoTop_Reco_ttbar_phi;} + const float& PseudoTop_Reco_ttbar_m() const {return m_PseudoTop_Reco_ttbar_m;} + const float& PseudoTop_Reco_top_had_pt() const {return m_PseudoTop_Reco_top_had_pt;} + const float& PseudoTop_Reco_top_had_eta() const {return m_PseudoTop_Reco_top_had_eta;} + const float& PseudoTop_Reco_top_had_phi() const {return m_PseudoTop_Reco_top_had_phi;} + const float& PseudoTop_Reco_top_had_m() const {return m_PseudoTop_Reco_top_had_m;} + const float& PseudoTop_Reco_top_lep_pt() const {return m_PseudoTop_Reco_top_lep_pt;} + const float& PseudoTop_Reco_top_lep_eta() const {return m_PseudoTop_Reco_top_lep_eta;} + const float& PseudoTop_Reco_top_lep_phi() const {return m_PseudoTop_Reco_top_lep_phi;} + const float& PseudoTop_Reco_top_lep_m() const {return m_PseudoTop_Reco_top_lep_m;} + const float& PseudoTop_Particle_ttbar_pt() const {return m_PseudoTop_Particle_ttbar_pt;} + const float& PseudoTop_Particle_ttbar_eta() const {return m_PseudoTop_Particle_ttbar_eta;} + const float& PseudoTop_Particle_ttbar_phi() const {return m_PseudoTop_Particle_ttbar_phi;} + const float& PseudoTop_Particle_ttbar_m() const {return m_PseudoTop_Particle_ttbar_m;} + const float& PseudoTop_Particle_top_had_pt() const {return m_PseudoTop_Particle_top_had_pt;} + const float& PseudoTop_Particle_top_had_eta() const {return m_PseudoTop_Particle_top_had_eta;} + const float& PseudoTop_Particle_top_had_phi() const {return m_PseudoTop_Particle_top_had_phi;} + const float& PseudoTop_Particle_top_had_m() const {return m_PseudoTop_Particle_top_had_m;} + const float& PseudoTop_Particle_top_lep_pt() const {return m_PseudoTop_Particle_top_lep_pt;} + const float& PseudoTop_Particle_top_lep_eta() const {return m_PseudoTop_Particle_top_lep_eta;} + const float& PseudoTop_Particle_top_lep_phi() const {return m_PseudoTop_Particle_top_lep_phi;} + const float& PseudoTop_Particle_top_lep_m() const {return m_PseudoTop_Particle_top_lep_m;} + + //MC + const std::vector<float>& mc_pt() const {return m_mc_pt;} + const std::vector<float>& mc_eta() const {return m_mc_eta;} + const std::vector<float>& mc_phi() const {return m_mc_phi;} + const std::vector<float>& mc_e() const {return m_mc_e;} + const std::vector<double>& mc_charge() const {return m_mc_charge;} + const std::vector<int>& mc_pdgId() const {return m_mc_pdgId;} + const std::vector<int>& mc_status() const {return m_mc_status;} + const std::vector<int>& mc_barcode() const {return m_mc_barcode;} + + //PDFInfo + const std::vector<float>& PDFinfo_X1() const {return m_PDFinfo_X1;} + const std::vector<float>& PDFinfo_X2() const {return m_PDFinfo_X2;} + const std::vector<int>& PDFinfo_PDGID1() const {return m_PDFinfo_PDGID1;} + const std::vector<int>& PDFinfo_PDGID2() const {return m_PDFinfo_PDGID2;} + const std::vector<float>& PDFinfo_Q() const {return m_PDFinfo_Q;} + const std::vector<float>& PDFinfo_XF1() const {return m_PDFinfo_XF1;} + const std::vector<float>& PDFinfo_XF2() const {return m_PDFinfo_XF2;} + + //the on-the-fly computed generator weights stored in EventInfo + const std::vector<float>& mc_generator_weights() const {return m_mc_generator_weights;} + + //Extra variables for Particle Level (bare lepton kinematics and b-Hadron + //tagging information). + const std::vector<float>& el_pt_bare() const {return m_el_pt_bare;} + const std::vector<float>& el_eta_bare() const {return m_el_eta_bare;} + const std::vector<float>& el_phi_bare() const {return m_el_phi_bare;} + const std::vector<float>& el_e_bare() const {return m_el_e_bare;} + const std::vector<float>& mu_pt_bare() const {return m_mu_pt_bare;} + const std::vector<float>& mu_eta_bare() const {return m_mu_eta_bare;} + const std::vector<float>& mu_phi_bare() const {return m_mu_phi_bare;} + const std::vector<float>& mu_e_bare() const {return m_mu_e_bare;} + const std::vector<int>& jet_Ghosts_BHadron_Final_Count() const {return m_jet_Ghosts_BHadron_Final_Count;} + const std::vector<int>& jet_Ghosts_CHadron_Final_Count() const {return m_jet_Ghosts_CHadron_Final_Count;} + const std::vector<int>& ljet_Ghosts_BHadron_Final_Count() const {return m_ljet_Ghosts_BHadron_Final_Count;} + const std::vector<int>& ljet_Ghosts_CHadron_Final_Count() const {return m_ljet_Ghosts_CHadron_Final_Count;} + const std::vector<std::vector<int> >& rcjetsub_Ghosts_BHadron_Final_Count() const {return m_rcjetsub_Ghosts_BHadron_Final_Count;} + const std::vector<std::vector<int> >& rcjetsub_Ghosts_CHadron_Final_Count() const {return m_rcjetsub_Ghosts_CHadron_Final_Count;} // Truth tree inserted variables // This can be expanded as required // This is just a first pass at doing this sort of thing - std::unordered_map<std::string,int*> m_extraTruthVars_int; - std::unordered_map<std::string,float*> m_extraTruthVars_float; + const std::unordered_map<std::string, int*>& extraTruthVars_int() const {return m_extraTruthVars_int;} + + // Prompt lepton definition for event saver + std::pair<bool, bool> isPromptElectron(int type, int origin, int egMotherType, int egMotherOrigin, int egMotherPdgId, int RecoCharge); + bool isPromptMuon(int type, int origin); - ClassDef(top::EventSaverFlatNtuple, 0); -}; + int filterBranches(const top::TreeManager*, const std::string& variable); + ClassDefOverride(top::EventSaverFlatNtuple, 0); + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAOD.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAOD.h index 9bd31692393895451dd9668567399f7edbbc0985..cd17afeead8390c7284f4330a2127ddf36148a5e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAOD.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAOD.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSAVERXAOD_H_ #define EVENTSAVERXAOD_H_ @@ -13,14 +13,12 @@ class TFile; namespace top { - /** * @brief Write out the selected events in xAOD format. At some point this will * be the future. But probably not right now. Still too many missing features. */ -class EventSaverxAOD : public top::EventSaverBase , public asg::AsgTool { - -public: + class EventSaverxAOD: public top::EventSaverBase, public asg::AsgTool { + public: /** * @brief Kept simple, set the output container prefix (so they have a * different name to the input containers). @@ -46,11 +44,12 @@ public: * EventInfo. e.g. the branch that tells you if an event passed a certain * selection. If you add it here, it'll be written to the output file. */ - virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches); - + virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches); + //Keep the asg::AsgTool happy - virtual StatusCode initialize(){return StatusCode::SUCCESS;} - + virtual StatusCode initialize() {return StatusCode::SUCCESS;} + /** * @brief Save an event. * @@ -73,8 +72,7 @@ public: ///xAOD needs to write some more stuff to the file at the end of a job virtual void finalize(); - -private: + private: ///Name to prepend to the output containers const std::string m_prefix; @@ -85,8 +83,7 @@ private: TFile* m_outputFile; ClassDef(top::EventSaverxAOD, 0); -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAODNext.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAODNext.h index ff2257b9f749ec0f4ddbd2a51fd4b570ccf6096e..9aa702bf8dd352719a9f6d75237e25ad100ae107 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAODNext.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSaverxAODNext.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSAVERXAODNEXT_H_ #define EVENTSAVERXAODNEXT_H_ @@ -13,76 +13,72 @@ class TFile; namespace top { - /** - * @brief Write out the selected events in xAOD format. - * Next generation xAOD output - still in development - */ - class EventSaverxAODNext : public top::EventSaverBase , public asg::AsgMetadataTool { - - public: - - EventSaverxAODNext(); - - virtual ~EventSaverxAODNext(); - - /** - * @brief This does some configuration of the output file. It also keeps track - * of which branches should be saved. - * - * You surely don't need all the branches, but if you do remove the - * corresponding line. - * - * We can't do much in the constructor, like I would like, because we're - * letting root make this. So instead we have a function here. - * - * @param config The top::TopConfig object that contains lots of settings and - * stuff. - * @param file The output TFile that you want to save things to. - * @param extraBranches List of extra branches that (currently) are attached to - * EventInfo. e.g. the branch that tells you if an event passed a certain - * selection. If you add it here, it'll be written to the output file. + * @brief Write out the selected events in xAOD format. + * Next generation xAOD output - still in development + */ + class EventSaverxAODNext: public top::EventSaverBase, public asg::AsgMetadataTool { + public: + EventSaverxAODNext(); + + virtual ~EventSaverxAODNext(); + + /** + * @brief This does some configuration of the output file. It also keeps track + * of which branches should be saved. + * + * You surely don't need all the branches, but if you do remove the + * corresponding line. + * + * We can't do much in the constructor, like I would like, because we're + * letting root make this. So instead we have a function here. + * + * @param config The top::TopConfig object that contains lots of settings and + * stuff. + * @param file The output TFile that you want to save things to. + * @param extraBranches List of extra branches that (currently) are attached to + * EventInfo. e.g. the branch that tells you if an event passed a certain + * selection. If you add it here, it'll be written to the output file. */ - virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, const std::vector<std::string>& extraBranches); - - //Keep the asg::AsgTool happy - virtual StatusCode initialize(){return StatusCode::SUCCESS;} - - - virtual void saveEventToxAOD(); - - ///xAOD needs to write some more stuff to the file at the end of a job - virtual void finalize(); - - private: - ///We need access to the configuration file to get the container names. - std::shared_ptr<top::TopConfig> m_config; - - ///We need to hold on to the output file - TFile* m_outputFile; - - bool m_saveAllObjects; - - // helper typedef - typedef std::map<std::size_t,std::map<unsigned int,unsigned int>> ThinningMap_t; - typedef ThinningMap_t::const_iterator ThinningMap_Itr; - - std::shared_ptr<ThinningMap_t> savePhotons(const bool saveEventObjects); - std::shared_ptr<ThinningMap_t> saveElectrons(const bool saveEventObjects); - std::shared_ptr<ThinningMap_t> saveMuons(const bool saveEventObjects); - std::shared_ptr<ThinningMap_t> saveTaus(const bool saveEventObjects); - std::shared_ptr<ThinningMap_t> saveJets(const bool saveEventObjects); - std::shared_ptr<ThinningMap_t> saveLargeRJets(const bool saveEventObjects); - std::shared_ptr<ThinningMap_t> saveTrackJets(const bool saveEventObjects); - - std::vector<unsigned int> thinObjectSelection(const std::size_t hashValue , - const std::vector<unsigned int>& objectList , - const std::shared_ptr<ThinningMap_t> thinningMap) const; - - - ClassDef(top::EventSaverxAODNext, 0); - }; + virtual void initialize(std::shared_ptr<top::TopConfig> config, TFile* file, + const std::vector<std::string>& extraBranches); + + //Keep the asg::AsgTool happy + virtual StatusCode initialize() {return StatusCode::SUCCESS;} + + + virtual void saveEventToxAOD(); + + ///xAOD needs to write some more stuff to the file at the end of a job + virtual void finalize(); + private: + ///We need access to the configuration file to get the container names. + std::shared_ptr<top::TopConfig> m_config; + + ///We need to hold on to the output file + TFile* m_outputFile; + bool m_saveAllObjects; + + // helper typedef + typedef std::map<std::size_t, std::map<unsigned int, unsigned int> > ThinningMap_t; + typedef ThinningMap_t::const_iterator ThinningMap_Itr; + + std::shared_ptr<ThinningMap_t> savePhotons(const bool saveEventObjects); + std::shared_ptr<ThinningMap_t> saveElectrons(const bool saveEventObjects); + std::shared_ptr<ThinningMap_t> saveMuons(const bool saveEventObjects); + std::shared_ptr<ThinningMap_t> saveTaus(const bool saveEventObjects); + std::shared_ptr<ThinningMap_t> saveJets(const bool saveEventObjects); + std::shared_ptr<ThinningMap_t> saveLargeRJets(const bool saveEventObjects); + std::shared_ptr<ThinningMap_t> saveTrackJets(const bool saveEventObjects); + + std::vector<unsigned int> thinObjectSelection(const std::size_t hashValue, + const std::vector<unsigned int>& objectList, + const std::shared_ptr<ThinningMap_t> thinningMap) const; + + + ClassDef(top::EventSaverxAODNext, 0); + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelection.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelection.h index 116fa78daa2cd7364074fe3916dabb62194f4575..a5d54b3f4dcc69e30199796f550d31673d7c8f9a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelection.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelection.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSELECTION_H_ #define EVENTSELECTION_H_ @@ -34,8 +34,8 @@ namespace top { * of events passing each cut. It is also responsible for writing out the * 4-vectors in the output file if the user so wished. */ -class EventSelection final { -public: + class EventSelection final { + public: /** * @brief Construct using a vector of cuts. * @@ -46,7 +46,9 @@ public: * It also sets up a histogram which contains all the cuts on the x-axis * and each bin is the number of events passing a cut (in order). */ - EventSelection(const std::string& name, const std::vector<std::string>& cutNames, TFile* outputFile, const std::vector<std::unique_ptr<top::ToolLoaderBase>>& toolLoaders,std::shared_ptr<top::TopConfig> config, EL::Worker* wk); + EventSelection(const std::string& name, const std::vector<std::string>& cutNames, TFile* outputFile, + const std::vector<std::unique_ptr<top::ToolLoaderBase> >& toolLoaders, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk); /** * @brief Does not do anything @@ -71,25 +73,25 @@ public: /** * @brief Assignment is not allowed. */ - EventSelection& operator=(const EventSelection&) = delete; - - /** + EventSelection& operator = (const EventSelection&) = delete; + + /** * @brief Count the number of initial events */ - virtual void countInitial(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const; - /** + virtual void countInitial(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) const; + /** * @brief Count the number of events passing GRL */ - virtual void countGRL(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const; - /** + virtual void countGRL(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) const; + /** * @brief Count the number of events passing Good Calo */ - virtual void countGoodCalo(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const; + virtual void countGoodCalo(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) const; /** * @brief Count the number of events passing Primary Vertex */ - virtual void countPrimaryVertex(const float mcEventWeight,const float pileupWeight,const float zvtxWeight) const; - + virtual void countPrimaryVertex(const float mcEventWeight, const float pileupWeight, const float zvtxWeight) const; + /** * @brief Apply the selection for each event. * @@ -162,7 +164,7 @@ public: * @return The list of configurations */ std::vector<std::string> GetFakesMMConfigs() const; - + /** * @brief Tells if the event should be saved if it passes this selection * @@ -170,15 +172,14 @@ public: * */ bool ToBeSaved() const {return m_toBeSaved;}; - -private: + private: /** * @brief Print a cutflow showing the number of events passing each cut. */ virtual void printCuts(); ///Vector of all the tools that will be used in the analysis. - std::vector<std::unique_ptr<EventSelectorBase>> m_allCuts; + std::vector<std::unique_ptr<EventSelectorBase> > m_allCuts; ///The cutflow histogram filled by the tool. mutable TH1D* m_cutflow; @@ -214,6 +215,7 @@ private: ///The particle level cutflow histogram filled by the tool. mutable TH1D* m_cutflowParticleLevel; + mutable TH1D* m_cutflowParticleLevelMCWeights; ///The upgrade level cutflow histogram filled by the tool. mutable TH1D* m_cutflowUpgradeLevel; @@ -231,12 +233,14 @@ private: /// std::shared_ptr<TopConfig> m_config; - ///Scale factors - std::unique_ptr<ScaleFactorRetriever> m_sfRetriever; + ///Scale factors + ScaleFactorRetriever* m_sfRetriever; + /// Function to setup the tool in one place + void initialiseTopScaleFactorRetriever(std::shared_ptr<TopConfig> config); // Nominal hash value - std::size_t m_nominalHashValue; - + std::size_t m_nominalHashValue; + // Does this selection contain initial and GRL? // If so, what are their positions in the cut flow? bool m_containsInitial; @@ -247,13 +251,12 @@ private: unsigned int m_positionGRL; unsigned int m_positionGoodCalo; unsigned int m_positionPrimaryVertex; - + // If true, event will be saved if it passes this selection // If false, event will only be saved if it passes another selection // If an event is saved, the flags of all selections (those passed and those not passed) are saved bool m_toBeSaved; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelectionManager.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelectionManager.h index 53f793c3f333783bb62a5e9d65726e92a55cdb45..3da71c551e44ede896dfc9a6acdbd37c5f834e37 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelectionManager.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/EventSelectionManager.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSELECTIONMANAGER_H_ #define EVENTSELECTIONMANAGER_H_ @@ -17,7 +17,7 @@ namespace EL { class Worker; } -namespace xAOD{ +namespace xAOD { class SystematicEvent; } @@ -27,7 +27,7 @@ namespace top { class ParticleLevelEvent; } -namespace top{ +namespace top { /** * @brief Maybe you want to run multiple selections (e+jets, mu+jets) on the * same input files at the same time. This class helps. @@ -37,8 +37,8 @@ namespace top{ * selections at the same time on the same input files. You could imagine * running ee, mumu, emu, e+jets and mu+jets. */ -class EventSelectionManager { -public: + class EventSelectionManager { + public: /** * @brief Loads the file and initialises all the relevant tools. * @@ -47,7 +47,9 @@ public: * string format * @param outputFile Output file for attaching plots to, etc. */ - explicit EventSelectionManager(const std::vector<SelectionConfigurationData>& selectionConfigData, TFile* outputFile, const std::string& toolLoaderNames, std::shared_ptr<top::TopConfig> config,EL::Worker* wk = nullptr); + explicit EventSelectionManager(const std::vector<SelectionConfigurationData>& selectionConfigData, + TFile* outputFile, const std::string& toolLoaderNames, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk = nullptr); /** * @brief Does not need to do anything @@ -61,24 +63,24 @@ public: EventSelectionManager() = delete; EventSelectionManager(const EventSelectionManager& rhs) = delete; - EventSelectionManager& operator=(const EventSelectionManager& rhs) = delete; - + EventSelectionManager& operator = (const EventSelectionManager& rhs) = delete; + /** * @brief Count the number of initial events */ - virtual void countInitial(const float mcEventWeight,const float pileupWeight,const float zvtxWeight); + virtual void countInitial(const float mcEventWeight, const float pileupWeight, const float zvtxWeight); /** * @brief Count the number of events passing GRL */ - virtual void countGRL(const float mcEventWeight,const float pileupWeight,const float zvtxWeight); + virtual void countGRL(const float mcEventWeight, const float pileupWeight, const float zvtxWeight); /** * @brief Count the number of events passing Good Calo */ - virtual void countGoodCalo(const float mcEventWeight,const float pileupWeight,const float zvtxWeight); + virtual void countGoodCalo(const float mcEventWeight, const float pileupWeight, const float zvtxWeight); /** * @brief Count the number of events passing Primary Vertex */ - virtual void countPrimaryVertex(const float mcEventWeight,const float pileupWeight,const float zvtxWeight); + virtual void countPrimaryVertex(const float mcEventWeight, const float pileupWeight, const float zvtxWeight); /** * @brief Run through the event selections for each event. @@ -95,7 +97,7 @@ public: * @return Returns true if the event passes at least one selection for which * SAVE is requested (for saving events to trees). */ - virtual bool apply(top::Event& event,const xAOD::SystematicEvent& currentSystematic); + virtual bool apply(top::Event& event, const xAOD::SystematicEvent& currentSystematic); /*! * @brief Execute the event selection using the Particle Level data. @@ -144,7 +146,7 @@ public: * for each selection is added (this is stored in event info). */ virtual void addExtraBranches(std::vector<std::string>& extraBranchList); - + /** * @brief Gives you the lists of the Fakes MM configurations associated to a selection. * @@ -153,12 +155,10 @@ public: * @param selection The requested selection. */ std::vector<std::string> GetFakesMMConfigs(std::string selection) const; - -private: + private: ///A vector of EventSelection objects, for doing fancy things std::vector<top::EventSelection> m_selections; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/MsgCategory.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/MsgCategory.h new file mode 100644 index 0000000000000000000000000000000000000000..4a75fbb02458029ad65cbc40d57a918f717b05d7 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/MsgCategory.h @@ -0,0 +1,12 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#ifndef TOPANALYSIS_MSG_CATEGORY_H_ +#define TOPANALYSIS_MSG_CATEGORY_H_ +#include <AsgMessaging/MessageCheck.h> + +// define custom message source for top-xaod and related tools +// this ensures we get "top-xaod" in the messages to know where they're coming from +ANA_MSG_HEADER(TopAnalysis) + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderBase.h index 08984fddff5a209284e433fcf9e8f561dabf2c72..792d0af3dfa01987c8c45b20079da014bc3c667e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef OBJECTLOADERBASE_H_ #define OBJECTLOADERBASE_H_ @@ -9,8 +9,8 @@ #include <memory> namespace top { -class TopConfig; -class TopObjectSelection; + class TopConfig; + class TopObjectSelection; /** * @brief People seem to want to be able to configure the objects used in their @@ -19,8 +19,8 @@ class TopObjectSelection; * selection object then this can be deleted. * */ -class ObjectLoaderBase { -public: + class ObjectLoaderBase { + public: /** * @brief This will inherit from this, but it doesn't do anything really. */ @@ -37,8 +37,7 @@ public: virtual top::TopObjectSelection* init(std::shared_ptr<top::TopConfig> topConfig) = 0; ClassDef(top::ObjectLoaderBase, 0) -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderStandardCuts.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderStandardCuts.h index cbcf30c59cfefe95bdf91a16ff98da5eea4ee680..7f5ba3453f32454171fd9ddb07c9357267c752bd 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderStandardCuts.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/ObjectLoaderStandardCuts.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef OBJECTLOADERSTANDARDCUTS_H_ #define OBJECTLOADERSTANDARDCUTS_H_ @@ -8,7 +8,6 @@ #include "TopAnalysis/ObjectLoaderBase.h" namespace top { - /** * @brief This loads our "standard" object selection used in the top group. * @@ -17,9 +16,8 @@ namespace top { * write your own in a separate library then when you change release it wont * be a big deal). */ -class ObjectLoaderStandardCuts : public ObjectLoaderBase { -public: - + class ObjectLoaderStandardCuts: public ObjectLoaderBase { + public: /** * @brief Setup the cuts. Probably easiest if you look at the code, no? * @@ -30,8 +28,7 @@ public: top::TopObjectSelection* init(std::shared_ptr<top::TopConfig> topConfig); ClassDef(top::ObjectLoaderStandardCuts, 0) -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/Tools.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/Tools.h index 9833c9d8f03bb4a59e5520f7f4e400c227a0d950..613d72b399c6d216c1c36a0ed3cac953e7f1c7e9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/Tools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/TopAnalysis/Tools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPTOOLS_H__ #define TOPTOOLS_H__ @@ -10,10 +10,13 @@ #include "xAODRootAccess/TEvent.h" +#include "xAODCutFlow/CutBookkeeper.h" +#include "xAODCutFlow/CutBookkeeperContainer.h" + #include "TopConfiguration/TopConfig.h" /** - * @file TopAnalysis/Tools.h + * @file Tools.h * * Some tools to make life in the xAOD world a bit easier. Including ways * to initialise, guess the best "mode" to open an xAOD with, load cuts, list @@ -21,8 +24,8 @@ */ namespace top { -class TopObjectSelection; -class EventSaverBase; + class TopObjectSelection; + class EventSaverBase; /** * @brief A little wrapper for the xAOD tools. Also turns enabled the failure @@ -31,7 +34,7 @@ class EventSaverBase; * @param failOnUnchecked Terminate the job on unchecked status codes by * default. */ -void xAODInit(bool failOnUnchecked = true); + void xAODInit(bool failOnUnchecked = true); /** * @brief Sometimes we need to know if we're running on a primary xAOD or a @@ -45,7 +48,7 @@ void xAODInit(bool failOnUnchecked = true); * @param inputFile A pointer to the input file * @return True if this is a primary xAOD */ -bool isFilePrimaryxAOD(TFile* inputFile); + bool isFilePrimaryxAOD(TFile* inputFile); /** * @brief Some of our things need to know if the events are MC or data before @@ -56,21 +59,33 @@ bool isFilePrimaryxAOD(TFile* inputFile); * @param eventInfoName Name of the EventInfo container in the xAOD * @return True if MC simulation, false for data */ -bool isFileSimulation(TFile* inputFile, const std::string& eventInfoName); + bool isFileSimulation(TFile* inputFile, const std::string& eventInfoName); + +/** + * @brief For fallback cases when metadata is broken in dxAOD, we need to know + * how many MC generator weights are stored in the MC sample. This is needed + * to determine, whether there is an unambiguous choice of nominal weight (e.g. + * only one weight in sample), or if we can't conclusively tell which one it is. + * + * @param inputFile A pointer to the input file + * @param eventInfoName Name of the EventInfo container in the xAOD + * @return Size of vector of MC generator weights + */ + size_t MCweightsSize(TFile* inputFile, const std::string& eventInfoName); -bool isTruthDxAOD(TFile* inputFile); + bool isTruthDxAOD(TFile* inputFile); -unsigned int getDSID(TFile* inputFile, const std::string& eventInfoName); + unsigned int getDSID(TFile* inputFile, const std::string& eventInfoName); -/** +/** * @brief Some of our things need to know if the events are AFII or FullSim - * for certain systematics. - * - * @param inputFile A pointer to the input file - * @param eventInfoName Name of the EventInfo container in the xAOD - * @return True if fast simulation, false for FullSim + * for certain systematics. + * + * @param inputFile A pointer to the input file + * @param eventInfoName Name of the EventInfo container in the xAOD + * @return True if fast simulation, false for FullSim */ -bool isFileFastSim(TFile* inputFile); + bool isFileFastSim(TFile* inputFile); /** * @brief Function to determine the derivation type using string manipulation @@ -80,8 +95,39 @@ bool isFileFastSim(TFile* inputFile); * @return string with the derivation stream name */ -std::string getDerivationStream(TFile* inputFile); + std::string getDerivationStream(TFile* inputFile); + +/** + * @brief Search bookkeepers for ones matching AllExecutedEvents, and which + * originate from AOD before skimming. + * + * @param cutBookKeepers Container with bookkeepers + * @param names Vector of names of the selected bookkeepers + * @param sumW Vector of sum of weights of the selected bookkeepers + * @param isHLLHC Whether this is a HLLHC ugprade sample, it uses different stream for bookkeepers + */ + void parseCutBookkeepers(const xAOD::CutBookkeeperContainer *cutBookKeepers, + std::vector<std::string> &names, std::vector<float>& sumW, const bool isHLLHC=false); + +/** + * @brief Get raw number of events before skimming from "AllExecutedEvents" bookkeeper + * + * @param cutBookKeepers Container with CutBookkeepers + * @param isHLLHC Whether this is a HLLHC ugprade sample, it uses different stream for bookkeepers + * + * @return number of raw events before skimming + */ + ULong64_t getRawEventsBookkeeper(const xAOD::CutBookkeeperContainer *cutBookKeepers, + const bool isHLLHC=false); +/** + * @brief Rename CutBookkeeper names according to MC generator weight names reported by PMGTruthWeightTool + * + * @param bookkeeper_names Vector of original AllExecutedEvents* bookkeeper names + * @param pmg_weight_names Vector with MC generator weight names from PMGTruthWeightTool + */ + void renameCutBookkeepers(std::vector<std::string>& bookkepeer_names, + const std::vector<std::string>& pmg_weight_names); /** * @brief xAODs can be accessed in class or branch access mode. Guess 'the best' @@ -105,7 +151,7 @@ std::string getDerivationStream(TFile* inputFile); * * @return BranchAccess (preferred) or ClassAccess if the test fails. */ -xAOD::TEvent::EAuxMode guessAccessMode(const std::string& filename, const std::string& electronCollectionName); + xAOD::TEvent::EAuxMode guessAccessMode(const std::string& filename, const std::string& electronCollectionName); /** * @brief Load the file and make a vector of the cuts to pass on to the @@ -116,7 +162,7 @@ xAOD::TEvent::EAuxMode guessAccessMode(const std::string& filename, const std::s * * @return a vector with one cut-tool and configuration per line. */ -std::vector<std::string> loadCuts(const std::string& filename); + std::vector<std::string> loadCuts(const std::string& filename); /** * @brief Given a filename for a text file, parse it and extract a list of root @@ -128,7 +174,7 @@ std::vector<std::string> loadCuts(const std::string& filename); * @param filename The text file that we want to parse. * @return A vector of filenames. */ -std::vector<std::string> fileList(const std::string& filename); + std::vector<std::string> fileList(const std::string& filename); /** * @brief Open each file in the vector and get the number of events in it. @@ -141,7 +187,7 @@ std::vector<std::string> fileList(const std::string& filename); * @param filenames A vector of filenames to check. * @return The total yield for all files. */ -unsigned int checkFiles(const std::vector<std::string>& filenames); + size_t checkFiles(const std::vector<std::string>& filenames); /** * @brief So that we can load external libraries with (1) extra event selection @@ -153,7 +199,7 @@ unsigned int checkFiles(const std::vector<std::string>& filenames); * @param libraryNames The name of the library, for exmample * libTopEventSelectionTools */ -void loadLibraries(const std::string& libraryNames); + void loadLibraries(const std::string& libraryNames); /** * @brief Users may want to define (and load!) their own object selection. Once @@ -168,7 +214,7 @@ void loadLibraries(const std::string& libraryNames); * * @return The object selection pointer. */ -top::TopObjectSelection* loadObjectSelection(std::shared_ptr<top::TopConfig> config); + top::TopObjectSelection* loadObjectSelection(std::shared_ptr<top::TopConfig> config); /** * @brief Users may also want to write out custom ntuples / xAODs. This too @@ -181,8 +227,19 @@ top::TopObjectSelection* loadObjectSelection(std::shared_ptr<top::TopConfig> con * @return If everything works, then a pointer to the event saver object. * Otherwise the program should end and tell people why. */ -top::EventSaverBase* loadEventSaver(std::shared_ptr<top::TopConfig> config); + top::EventSaverBase* loadEventSaver(std::shared_ptr<top::TopConfig> config); + +/** + * @brief This function will be used to load the metadata object and pull information + * from it. We will then need to look at storing the info in TopConfig + * + * @param inputFile Include a single TFile which we load and read + * @param config Pass in the config, before it is fixed, so that we can add info + * + * @return If successful, return true, else return false + */ + bool readMetaData(TFile* inputFile, std::shared_ptr<top::TopConfig> config); } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMPFlowDatatest.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMPFlowDatatest.py new file mode 100755 index 0000000000000000000000000000000000000000..5b3f7d155342ebfc1c135ce06254e9ca605bc63d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMPFlowDatatest.py @@ -0,0 +1,28 @@ +#! /usr/bin/env python +# This script is designed to be used as a quick runtime ctest in the CI framework +# We use python to better handle getting our validation cutfile which should be stable +# We will augment the NEvents line in our cutfile to limit the job +# This is primarily to catch any runtime changes introduced before they are merged + +from PathResolver import PathResolver +from CI_test import CITest +import sys,ROOT + +cutfilename = "validation-cuts-pflow.txt" +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +returnCode = CITest("TOPQ1 DATA", + cutfilename, + cutfilepath, + "/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/ContinuousIntegration/Data/p4173/"+ + "data16_13TeV.AllYear.physics_Main.PhysCont.DAOD_TOPQ1.grp16_v01_p4173/DAOD_TOPQ1.21542408._000018.pool.root.1", + [("#NEvents.*","NEvents 3000")]) + +if returnCode != 0: + print "Error in EMPFlow TOPQ1 Data" + sys.exit(returnCode) + +# -- Return 0 as all tests were successful -- # +sys.exit(0) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMPFlowMCtest.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMPFlowMCtest.py new file mode 100755 index 0000000000000000000000000000000000000000..ed62c91a15dfc96bd6c3984eeac6bb68bf3cf384 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMPFlowMCtest.py @@ -0,0 +1,29 @@ +#! /usr/bin/env python +# This script is designed to be used as a quick runtime ctest in the CI framework +# We use python to better handle getting our validation cutfile which should be stable +# We will augment the NEvents line in our cutfile to limit the job +# This is primarily to catch any runtime changes introduced before they are merged + +from PathResolver import PathResolver +from CI_test import CITest +import sys,ROOT + +cutfilename = "validation-cuts-pflow.txt" +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +returnCode = CITest("TOPQ1 MC", + cutfilename, + cutfilepath, + "/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/ContinuousIntegration/MC/p4174/"+ + "mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_s3126_r9364_p4174/"+ + "test.pool.root", + [("#NEvents.*","NEvents 100")]) + +if returnCode != 0: + print "Error in EMPFlow TOPQ1 MC" + sys.exit(returnCode) + +# -- Return 0 as all tests were successful -- # +sys.exit(0) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMTopoDatatest.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMTopoDatatest.py new file mode 100755 index 0000000000000000000000000000000000000000..cab12b1c4043ebae4efe145480a9406e6e6eec73 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMTopoDatatest.py @@ -0,0 +1,28 @@ +#! /usr/bin/env python +# This script is designed to be used as a quick runtime ctest in the CI framework +# We use python to better handle getting our validation cutfile which should be stable +# We will augment the NEvents line in our cutfile to limit the job +# This is primarily to catch any runtime changes introduced before they are merged + +from PathResolver import PathResolver +from CI_test import CITest +import sys,ROOT + +cutfilename = "validation-cuts.txt" +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +returnCode = CITest("TOPQ1 DATA", + cutfilename, + cutfilepath, + "/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/ContinuousIntegration/Data/p4173/"+ + "data16_13TeV.AllYear.physics_Main.PhysCont.DAOD_TOPQ1.grp16_v01_p4173/DAOD_TOPQ1.21542408._000018.pool.root.1", + [("#NEvents.*","NEvents 3000")]) + +if returnCode != 0: + print "Error in EMTopo TOPQ1 Data" + sys.exit(returnCode) + +# -- Return 0 as all tests were successful -- # +sys.exit(0) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMTopoMCtest.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMTopoMCtest.py new file mode 100755 index 0000000000000000000000000000000000000000..0c0f9acccb6ed5f0b4d59a69826daf5bdee19b14 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_EMTopoMCtest.py @@ -0,0 +1,29 @@ +#! /usr/bin/env python +# This script is designed to be used as a quick runtime ctest in the CI framework +# We use python to better handle getting our validation cutfile which should be stable +# We will augment the NEvents line in our cutfile to limit the job +# This is primarily to catch any runtime changes introduced before they are merged + +from PathResolver import PathResolver +from CI_test import CITest +import sys,ROOT + +cutfilename = "validation-cuts.txt" +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +returnCode = CITest("TOPQ1 MC", + cutfilename, + cutfilepath, + "/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/ContinuousIntegration/MC/p4174/"+ + "mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_s3126_r9364_p4174/"+ + "test.pool.root", + [("#NEvents.*","NEvents 100")]) + +if returnCode != 0: + print "Error in EMTopo TOPQ1 MC" + sys.exit(returnCode) + +# -- Return 0 as all tests were successful -- # +sys.exit(0) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_test.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_test.py new file mode 100755 index 0000000000000000000000000000000000000000..92e3bb059d2ff53533894303044992d3c7971c2e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/CI_test.py @@ -0,0 +1,52 @@ +#! /usr/bin/env python +# This script is designed to be used as a quick runtime ctest in the CI framework +# We use python to better handle getting our validation cutfile which should be stable +# We will augment the NEvents line in our cutfile to limit the job +# This is primarily to catch any runtime changes introduced before they are merged + +import sys, subprocess, random, os, shlex, ROOT, shutil + +def CITest(testname, cutfile, cutfilepath, inputfile, sedreplace): + """ Templated test to allow extension """ + print "CI Integration Test :",testname + + # -- Settings -- + cutfilename = cutfile + inputfilename = inputfile + + # -- Move to a unique directory -- + cwd = os.getcwd() + rundir = str(random.randrange(10**8)) + os.mkdir(rundir) + os.chdir(rundir) + + # -- Get the validation file path from the most recent location -- + + # -- Print the file location for debugging -- + print "CI Integration Test : Using cutfile %s"%(cutfilepath) + print "CI Integration Test : Using inputfile %s"%(inputfilename) + + # -- Copy the cutfile locally to be updated -- + shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- + inputfilepath = open("input.txt","w") + inputfilepath.write(inputfilename+"\n") + inputfilepath.close() + + # -- Edit the cutfile to set any provided options -- + for (old, new) in sedreplace: + cmd = "sed -i -e 's/"+old+"/"+new+"/g' %s"%(cutfilename) + proc = subprocess.Popen(shlex.split(cmd)) + proc.wait() + + # -- Run top-xaod -- + cmd = "top-xaod %s input.txt"%(cutfilename) + proc = subprocess.Popen(shlex.split(cmd)) + proc.wait() + + # Return to starting directory + os.chdir(cwd) + + # -- Check the return code and exit this script with that -- + return proc.returncode diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/ConfigExampleMakeQuarkGluonFractionPlots.xml b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/ConfigExampleMakeQuarkGluonFractionPlots.xml new file mode 100644 index 0000000000000000000000000000000000000000..e875a0e13dbe169495c20a93a08d2152fc66d7eb --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/ConfigExampleMakeQuarkGluonFractionPlots.xml @@ -0,0 +1,32 @@ +<configuration> +<!-- Configuration file to compute the gluon fraction --> + <!-- Paths configuration. If folder attribute is empty, assume folder="JetFlavorPlots" if scalefactor attribute is empty, assume scalefactor="1.0" --> + <!-- Path to nominal input file or txt list (this is valid for any path) --> + <nominal path="./nominal_list.txt" folder="JetFlavorPlots" /> + <!-- If you want the Loose selection, just specify in the folder field, like: --> + <!-- + <nominal path="/afs/cern.ch/user/m/mscornaj/QGFPlots/prova.root" folder="JetFlavorPlots_Loose" /> + --> + <!-- Systematic uncertainties (you can add as much as you want) --> + <!-- one point systematic example: delta=scalefactor*abs(central-variation)/central --> + <systematic1point name="GeneratorSyst1P" central="./nominal.root" variation="./alternative_generator.root" scalefactor="1.0" folder_variation="JetFlavorPlots" folder_central="JetFlavorPlots" /> + <systematic1point name="PartonShowerSyst1P" central="./nominal.root" variation="./alternative_shower_list.txt" scalefactor="1.0" folder_variation="JetFlavorPlots" folder_central="JetFlavorPlots" /> + <!-- two point systematic example: delta_up=scalefactor*abs(central-variation_up)/central delta_down=scalefactor*abs(central-variation_down)/central --> + <systematic2point name="IFSRSyst2P" central="./nominal_list.txt" folder_central="JetFlavorPlots" variation_up="./IFSR_UP.root" folder_up="JetFlavorPlots_RadHigh" variation_down="./IFSR_DOWN.root" folder_down="JetFlavorPlots_RadLow" scalefactor="1.0" /> + <!-- Path to output file --> + <output path="FlavourComposition.root" /> + <!-- End paths configuration --> + <!-- Channel list (add as much as you want) --> + <channel name="mumu_2016" /> + <channel name="mumu_2015" /> + <channel name="ee_2015" /> + <channel name="ee_2016" /> + <!-- Merge different channels in single QGF histogram --> + <mergechannels value="false" /> + <!-- Run the extended configuration? --> + <detailed value="false" /> + <!-- Compute the gluon fraction taking into account only light quarks or also heavy quarks ( light, lightC(default) or lightCB ) --> + <gluon_vs_flavour value="lightC" /> + <!-- Save histograms as PS files --> + <do_ps value="true" /> +</configuration> diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/MakeQuarkGluonFractionPlots.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/MakeQuarkGluonFractionPlots.cxx new file mode 100644 index 0000000000000000000000000000000000000000..782be55c195cec47a4c021ee6fb3e971dda5e39f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/MakeQuarkGluonFractionPlots.cxx @@ -0,0 +1,771 @@ +// Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration +// =============================================================================== +// Macro to compute the gluon initiated jets fraction in your sample/selection +// To run the macro: .x MakeQuarkGluonFractionPlots.cxx+("config.txt") +// =============================================================================== +#include "MakeQuarkGluonFractionPlots.h" + +MakeQuarkGluonFractionPlots::MakeQuarkGluonFractionPlots(std::string filename): + m_doGluVsFlavour("lightC"), + m_channel({}), + m_detailedConfig(false), + m_OutputFile("FlavourComposition"), + m_doPS(false){ + + //Suppressing info/error/... ROOT messages + gErrorIgnoreLevel = 5000; + TH1::AddDirectory(kFALSE); + gStyle->SetPaintTextFormat(".3f"); + gROOT->SetBatch(kTRUE); + printf("\n %s\n MakeQuarkGluonFractionPlots::MakeQuarkGluonFractionPlots\n %s\n",std::string(75,'=').c_str(),std::string(75,'=').c_str()); + //---------------------------- + // reading configuration file + //---------------------------- + readXMLConfigFile(filename); + printXMLConfigFile(); + //----------------------------------------------------------------------------------------------- + // plotting the 2D input histograms in a ps file and storing them in a vector and + // compute the gluon fraction for nominal and systematic samples + //----------------------------------------------------------------------------------------------- + std::string psfilename; + TCanvas c1; + //Maps to store histograms + std::map<std::string, TH2D*> h_input; + std::vector< std::map<std::string, TH2D*> > h_input_1P; + std::vector< std::map<std::string, TH2D*> > h_input_1PVar; + std::vector< std::map<std::string, TH2D*> > h_input_2P; + std::vector< std::map<std::string, TH2D*> > h_input_2PUp; + std::vector< std::map<std::string, TH2D*> > h_input_2PDown; + printf("\n %s\n Retrieving histograms\n %s\n",std::string(75,'%').c_str(),std::string(75,'%').c_str()); + if(m_mergechannels){ + psfilename = "PlotsGluonFraction_AllChannels.ps"; + if(m_doPS) c1.Print((psfilename+"[").c_str()); + bool createMap = true; + for(unsigned int c=0; c<m_channel.size(); ++c){ + std::string append = "nominal_"; + DumpToMap(h_input, m_configNominal.path, m_channel.at(c), m_configNominal.folder, append, createMap); + createMap = false; + } + if(m_doPS) drawhistos(h_input, psfilename); + for(unsigned int v=0; v<m_config1PointVec.size(); ++v){ + createMap = true; + std::map<std::string, TH2D*> map_temp; + for(unsigned int c=0; c<m_channel.size(); ++c){ + std::string append = "central1P_"+std::to_string(v)+"_"; + DumpToMap(map_temp, m_config1PointVec.at(v).central, m_channel.at(c), m_config1PointVec.at(v).folder_c, append, createMap); + createMap = false; + } + h_input_1P.push_back(map_temp); + if(m_doPS) drawhistos(h_input_1P.at(v), psfilename); + } + for(unsigned int v=0; v<m_config1PointVec.size(); ++v){ + createMap = true; + std::map<std::string, TH2D*> map_temp; + for(unsigned int c=0; c<m_channel.size(); ++c){ + std::string append = "variation1P_"+std::to_string(v)+"_"; + DumpToMap(map_temp, m_config1PointVec.at(v).variation, m_channel.at(c), m_config1PointVec.at(v).folder_v, append, createMap); + createMap = false; + } + h_input_1PVar.push_back(map_temp); + if(m_doPS) drawhistos(h_input_1PVar.at(v), psfilename); + } + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + createMap = true; + std::map<std::string, TH2D*> map_temp; + for(unsigned int c=0; c<m_channel.size(); ++c){ + std::string append = "central2P_"+std::to_string(v)+"_"; + DumpToMap(map_temp, m_config2PointVec.at(v).central, m_channel.at(c), m_config2PointVec.at(v).folder_c, append, createMap); + createMap = false; + } + h_input_2P.push_back(map_temp); + if(m_doPS) drawhistos(h_input_2P.at(v), psfilename); + } + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + createMap = true; + std::map<std::string, TH2D*> map_temp; + for(unsigned int c=0; c<m_channel.size(); ++c){ + std::string append = "variation2PUp_"+std::to_string(v)+"_"; + DumpToMap(map_temp, m_config2PointVec.at(v).variation_up, m_channel.at(c), m_config2PointVec.at(v).folder_up, append, createMap); + createMap = false; + } + h_input_2PUp.push_back(map_temp); + if(m_doPS) drawhistos(h_input_2PUp.at(v), psfilename); + } + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + createMap = true; + std::map<std::string, TH2D*> map_temp; + for(unsigned int c=0; c<m_channel.size(); ++c){ + std::string append = "variation2PDown_"+std::to_string(v)+"_"; + DumpToMap(map_temp, m_config2PointVec.at(v).variation_down, m_channel.at(c), m_config2PointVec.at(v).folder_down, append, createMap); + createMap = false; + } + h_input_2PDown.push_back(map_temp); + if(m_doPS) drawhistos(h_input_2PDown.at(v), psfilename); + } + CreateQGFFile("AllChannels",h_input,h_input_1P,h_input_1PVar,h_input_2P,h_input_2PUp,h_input_2PDown); + } + else{ + for(unsigned int c=0; c<m_channel.size(); ++c){ + psfilename = "PlotsGluonFraction_" + m_channel.at(c) +".ps"; + if(m_doPS) c1.Print((psfilename+"[").c_str()); + bool createMap = true; + std::string append = "nominal_"; + + //Clear the input map + h_input.clear(); + h_input_1P.clear(); + h_input_1PVar.clear(); + h_input_2P.clear(); + h_input_2PUp.clear(); + h_input_2PDown.clear(); + + DumpToMap(h_input, m_configNominal.path, m_channel.at(c), m_configNominal.folder, append, createMap); + if(m_doPS) drawhistos(h_input, psfilename); + + for(unsigned int v=0; v<m_config1PointVec.size(); ++v){ + std::map<std::string, TH2D*> map_temp; + std::string append = "central1P_"+std::to_string(v)+"_"+m_channel.at(c)+"_"; + DumpToMap(map_temp, m_config1PointVec.at(v).central, m_channel.at(c), m_config1PointVec.at(v).folder_c, append, createMap); + h_input_1P.push_back(map_temp); + if(m_doPS) drawhistos(h_input_1P.at(v), psfilename); + } + for(unsigned int v=0; v<m_config1PointVec.size(); ++v){ + std::map<std::string, TH2D*> map_temp; + std::string append = "variation1P_"+std::to_string(v)+"_"+m_channel.at(c)+"_"; + DumpToMap(map_temp, m_config1PointVec.at(v).variation, m_channel.at(c), m_config1PointVec.at(v).folder_v, append, createMap); + h_input_1PVar.push_back(map_temp); + if(m_doPS) drawhistos(h_input_1PVar.at(v), psfilename); + } + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + std::map<std::string, TH2D*> map_temp; + std::string append = "central2P_"+std::to_string(v)+"_"+m_channel.at(c)+"_"; + DumpToMap(map_temp, m_config2PointVec.at(v).central, m_channel.at(c), m_config2PointVec.at(v).folder_c, append, createMap); + h_input_2P.push_back(map_temp); + if(m_doPS) drawhistos(h_input_2P.at(v), psfilename); + } + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + std::map<std::string, TH2D*> map_temp; + std::string append = "variation2PUp_"+std::to_string(v)+"_"+m_channel.at(c)+"_"; + DumpToMap(map_temp, m_config2PointVec.at(v).variation_up, m_channel.at(c), m_config2PointVec.at(v).folder_up, append, createMap); + h_input_2PUp.push_back(map_temp); + if(m_doPS) drawhistos(h_input_2PUp.at(v), psfilename); + } + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + std::map<std::string, TH2D*> map_temp; + std::string append = "variation2PDown_"+std::to_string(v)+"_"+m_channel.at(c)+"_"; + DumpToMap(map_temp, m_config2PointVec.at(v).variation_down, m_channel.at(c), m_config2PointVec.at(v).folder_down, append, createMap); + h_input_2PDown.push_back(map_temp); + if(m_doPS) drawhistos(h_input_2PDown.at(v), psfilename); + } + CreateQGFFile(m_channel.at(c),h_input,h_input_1P,h_input_1PVar,h_input_2P,h_input_2PUp,h_input_2PDown); + } + } +} +/********************************************* + * Drawing methods + * *******************************************/ +// Draw histograms from a map +void MakeQuarkGluonFractionPlots::drawhistos(std::map<std::string, TH2D*> histos, std::string psfilename){ + TCanvas c1; + c1.SetLogx(); + for (std::map<std::string, TH2D*>::iterator it = histos.begin() ; it != histos.end(); ++it){ + TH2D *h = it->second; + if(h->Integral()==0.) continue; + h->Draw("COLZtext"); + c1.Print(psfilename.c_str()); + + } +} +// Draw histograms from a vector +void MakeQuarkGluonFractionPlots::drawhistos(std::vector<TH2D*> histos, std::string psfilename){ + TCanvas c1; + c1.SetLogx(); + for (std::vector<TH2D*>::iterator it = histos.begin() ; it != histos.end(); ++it){ + TH2D *h = *it; + if(h->Integral()==0.) continue; + h->Draw("COLZtext"); + c1.Print(psfilename.c_str()); + + } +} +//Write histograms to file (nominal and uncertainties, if presents) +void MakeQuarkGluonFractionPlots::createOutputFile(std::string filename, std::vector<TH2D*> histos, std::vector<TH2D*> histosUnc){ + TFile *fout = new TFile(filename.c_str(),"recreate"); + fout->cd(); + for (std::vector<TH2D*>::iterator it = histos.begin() ; it != histos.end(); ++it) (*it)->Write(); + for (std::vector<TH2D*>::iterator it = histosUnc.begin() ; it != histosUnc.end(); ++it) { if((*it)!= NULL) (*it)->Write();} + fout->Close(); + std::cout<<" Histograms are saved in "<<filename<<std::endl; +} +/************************************************************** + * QGF Evaluation - related methods + * ************************************************************/ +void MakeQuarkGluonFractionPlots::DumpToMap(std::map<std::string, TH2D*> &h_map, std::string filename, std::string channel, std::string folder, std::string keyname, bool createMap){ + bool newMap = createMap; + bool istxt = ( (filename.find(".txt") + 4 ) == filename.length()); + if(istxt){ + std::string f_name; + ifstream reader; + reader.open (filename); + while(!reader.eof()){ + getline(reader,f_name); + if(f_name.compare("")==0) continue; + DumpFileToMap(h_map, f_name, channel, folder, keyname, newMap); + newMap = false; + } + reader.close(); + } + else + DumpFileToMap(h_map, filename, channel, folder, keyname, newMap); +} +void MakeQuarkGluonFractionPlots::DumpFileToMap(std::map<std::string, TH2D*> &h_map, std::string filename, std::string channel, std::string folder, std::string keyname, bool createMap){ + TFile *f_in=TFile::Open(filename.c_str()); + std::string dirname = channel + "/"+folder; + TDirectory* dir = f_in->GetDirectory(dirname.c_str()); + if(!dir) { + std::cout<<" ERROR: directory "<<dirname<<" not found in file "<<filename<<"! Exiting.\n"; + abort(); + } + TIter next(dir->GetListOfKeys()); + TKey *key; + int counter = 0; + while ((key = (TKey*)next())) { + TClass *cl = gROOT->GetClass(key->GetClassName()); + if (!cl->InheritsFrom("TH2D")) continue; + TH2D *h = (TH2D*)key->ReadObj(); + if(createMap){ + std::string histoname = keyname + std::to_string(counter); + ++counter; + std::string orig_name = h->GetName(); + h->SetName(histoname.c_str()); + std::string titlename = keyname + "_" + orig_name; + h->SetTitle(titlename.c_str()); + h->SetStats(kTRUE); // Activate or desactivate the statistics box + gStyle->SetStatY(0.95); // Set y-position (fraction of pad size) + gStyle->SetStatX(0.89); // Set x-position (fraction of pad size) + h_map.insert( std::pair<std::string, TH2D* >( orig_name, h ) ); + } + else{ + h_map.at(h->GetName())->Add(h); + } + } +} +//QGF File creation +void MakeQuarkGluonFractionPlots::CreateQGFFile(std::string prename, std::map<std::string, TH2D*> h_input,std::vector< std::map<std::string, TH2D*> > h_input_1P,std::vector< std::map<std::string, TH2D*> > h_input_1PVar,std::vector< std::map<std::string, TH2D*> > h_input_2P,std::vector< std::map<std::string, TH2D*> > h_input_2PUp,std::vector< std::map<std::string, TH2D*> > h_input_2PDown){ + //Since I am here, all histograms have already been retrieved! + printf("\n %s\n Computing the gluon fraction in %s channel\n %s\n",std::string(75,'%').c_str(),prename.c_str(),std::string(75,'%').c_str()); + std::string outputName = prename + "_" + m_OutputFile; + //Creating ps file to plot all flavour plots/channel + std::string psfilename = "PlotsGluonFraction_" + prename +".ps"; + TCanvas c1; + if(m_doPS) c1.Print((psfilename+"[").c_str()); + //Nominal + printf("\n %s\n Computing QGF (nominal): \n %s\n",std::string(75,'=').c_str(),std::string(75,'=').c_str()); + std::vector<TH2D*> fractionhistos=computeQuarkGluonFraction(h_input, m_doGluVsFlavour, prename); + if(m_doPS) drawhistos(fractionhistos, psfilename); + //Systematics: + std::vector<std::vector<TH2D*>> h_fractionUnc1PSyst; + std::vector<std::vector<TH2D*>> h_fractionUnc2PSyst_up; + std::vector<std::vector<TH2D*>> h_fractionUnc2PSyst_down; + printf("\n %s\n Computing QGF (%s): \n %s\n",std::string(75,'%').c_str(),"1 point systematics",std::string(75,'%').c_str()); + for(unsigned int v=0; v<m_config1PointVec.size(); ++v){ + std::string prehistname="central_1PSystematic" + std::to_string(v) ; + std::string prehistnameVar="variation_1PSystematic" + std::to_string(v) ;//std::to_string(v) + "variation_1PSystematic"; + printf("\n %s\n Computing QGF (%s): \n %s\n",std::string(75,'=').c_str(),m_config1PointVec.at(v).name.c_str(),std::string(75,'=').c_str()); + std::vector<TH2D*> qgf_nominal = computeQuarkGluonFraction(h_input_1P.at(v), m_doGluVsFlavour, prehistname); + if(m_doPS) drawhistos(qgf_nominal, psfilename); + std::vector<TH2D*> qgf_variation = computeQuarkGluonFraction(h_input_1PVar.at(v), m_doGluVsFlavour, prehistnameVar); + if(m_doPS) drawhistos(qgf_variation, psfilename); + prehistname=std::to_string(v) + "_1PSystematic_delta"; + h_fractionUnc1PSyst.push_back(getDelta(qgf_nominal, qgf_variation, m_config1PointVec.at(v).scalefactor, prehistname)); //nominal-var + if(m_doPS) drawhistos(h_fractionUnc1PSyst.at(v), psfilename); + } + printf("\n %s\n Computing QGF (%s): \n %s\n",std::string(75,'%').c_str(),"2 point systematics",std::string(75,'%').c_str()); + for(unsigned int v=0; v<m_config2PointVec.size(); ++v){ + std::string prehistname=std::to_string(v) + "_2PSystematic"; + printf("\n %s\n Computing QGF (%s): \n %s\n",std::string(75,'=').c_str(),m_config2PointVec.at(v).name.c_str(),std::string(75,'=').c_str()); + std::vector<TH2D*> qgf_nominal = computeQuarkGluonFraction(h_input_2P.at(v), m_doGluVsFlavour, prehistname); + if(m_doPS) drawhistos(qgf_nominal, psfilename); + std::vector<TH2D*> qgf_variationUp = computeQuarkGluonFraction(h_input_2PUp.at(v), m_doGluVsFlavour, prehistname); + if(m_doPS) drawhistos(qgf_variationUp, psfilename); + prehistname=std::to_string(v) + "_2PSystematic_deltaUp"; + h_fractionUnc2PSyst_up.push_back(getDelta(qgf_variationUp, qgf_nominal, m_config2PointVec.at(v).scalefactor, prehistname)); //up-nominal + if(m_doPS) drawhistos(h_fractionUnc2PSyst_up.at(v), psfilename); + + std::vector<TH2D*> qgf_variationDown = computeQuarkGluonFraction(h_input_2PDown.at(v), m_doGluVsFlavour, prehistname); + if(m_doPS) drawhistos(qgf_variationDown, psfilename); + prehistname=std::to_string(v) + "_2PSystematic_deltaDown"; + h_fractionUnc2PSyst_down.push_back(getDelta(qgf_nominal, qgf_variationDown, m_config2PointVec.at(v).scalefactor, prehistname)); //up-nominal + if(m_doPS) drawhistos(h_fractionUnc2PSyst_down.at(v), psfilename); + + } + //----------------------------------------------------------- + // compute the uncertainty histograms + //----------------------------------------------------------- + printf("\n %s\n Computing the total systematic uncertainty: \n %s\n",std::string(75,'=').c_str(),std::string(75,'=').c_str()); + std::vector<TH2D*> fractionTotalUnc = evaluateQGFUncertaity(h_fractionUnc1PSyst,h_fractionUnc2PSyst_up,h_fractionUnc2PSyst_down,prename); + if(m_doPS) drawhistos( fractionTotalUnc, psfilename); + //------------------------------------------------------------------ + // create output file to store fraction histograms in a root file + //------------------------------------------------------------------ + printf("\n %s\n Writing output file: \n %s\n",std::string(75,'%').c_str(),std::string(75,'%').c_str()); + if(m_config1PointVec.size()+m_config2PointVec.size()) + createOutputFile(outputName, fractionhistos, fractionTotalUnc); + else + createOutputFile(outputName, fractionhistos, {}); + //close ps file + c1.Print((psfilename+"]").c_str()); +} +// Evaluate Delta +std::vector<TH2D*> MakeQuarkGluonFractionPlots::getDelta (std::vector<TH2D*> h_nom, std::vector<TH2D*> h_var, double scale, std::string prehistname){ + std::vector<TH2D*> QuarkGluonDiffFractionhistos; + if(h_nom.size() != h_var.size()) std::cout<<"ERROR: Systematic variation don't have the same number of histograms!\n"; + std::string JetCollection = extractJetCollectionName((h_nom.at(0))->GetName()); + for(size_t i = 0; i<h_nom.size(); i++){ + //return diff*(nominal-varied) + std::string njets = extractJetNumber(h_nom.at(i)->GetName()); + std::string histname = prehistname + "_gluonFractionError_" + njets + "_" + JetCollection; + TH2D *hist_diff; + hist_diff = (TH2D*)((h_nom.at(i))->Clone(histname.c_str())); + hist_diff->Add((TH2D*)(h_var.at(i)), -1); + hist_diff->Scale(scale); + hist_diff->SetTitle(hist_diff->GetName()); + hist_diff->SetStats(kFALSE); + QuarkGluonDiffFractionhistos.push_back(hist_diff); + } + return QuarkGluonDiffFractionhistos; +} + +//Evaluate uncertainty +std::vector<TH2D*> MakeQuarkGluonFractionPlots::evaluateQGFUncertaity(std::vector<std::vector<TH2D*> > f_1P, std::vector<std::vector<TH2D*> > f_2PUp, std::vector<std::vector<TH2D*> > f_2PDown, std::string channel){ + std::vector<TH2D*> histUnc; + TH2D *h_tmp; + std::string h_tmp_name; + if(f_1P.size()!=0){ + h_tmp = (TH2D*)((f_1P.at(0)).at(0))->Clone("TH2_tmp_TotalUnc"); + h_tmp_name = ((f_1P.at(0)).at(0))->GetName(); + } + else{ + h_tmp = (TH2D*)((f_2PUp.at(0)).at(0))->Clone("TH2_tmp_TotalUnc"); + h_tmp_name = ((f_2PUp.at(0)).at(0))->GetName(); + } + std::string JetCollection = extractJetCollectionName(h_tmp_name); + // create a new uncertainty histogram (take the bin and axis from the histograms) + int binX = h_tmp->GetXaxis()->GetNbins(); + int binY = h_tmp->GetYaxis()->GetNbins(); + h_tmp->Reset(); + h_tmp->Sumw2(); + //Get squared 1P systematics histograms + std::vector<TH2D*> squared_histos1P; + if(f_1P.size()!=0){ + for(unsigned int h=0; h<f_1P.at(0).size(); ++h){ + + std::string h_tmp_name = ((f_1P.at(0)).at(h))->GetName(); + std::string h_new_name("TH2_tmp_1P_TotalUnc_"+std::to_string(h)); + TH2D *h_tmp = (TH2D*)((f_1P.at(0)).at(h))->Clone(h_new_name.c_str()); + h_tmp->Reset(); + h_tmp->Sumw2(); + for(int x = 0; x <= binX; ++x){ + for(int y = 0; y <= binY; ++y){ + int bin = h_tmp->GetBin(x,y); + float sq_err = 0.; + for(unsigned int hs=0; hs<f_1P.size(); ++hs){ + sq_err+=pow(((f_1P.at(hs)).at(h))->GetBinContent(bin),2); + } + + h_tmp->SetBinContent(bin,sq_err); + } + } + squared_histos1P.push_back(h_tmp); + } + } + //Get squared 2P systematics (symmetrized) histograms + std::vector<TH2D*> squared_histos2P; + if(f_2PUp.size()!=0){ + for(unsigned int h=0; h<f_2PUp.at(0).size(); ++h){ + std::string h_tmp_name = ((f_2PUp.at(0)).at(h))->GetName(); + std::string h_new_name("TH2_tmp_2P_TotalUnc_"+std::to_string(h)); + TH2D *h_tmp = (TH2D*)((f_2PUp.at(0)).at(h))->Clone(h_new_name.c_str()); + h_tmp->Reset(); + h_tmp->Sumw2(); + for(int x = 0; x <= binX; ++x){ + for(int y = 0; y <= binY; ++y){ + int bin = h_tmp->GetBin(x,y); + float sq_err = 0.; + float sq_err_up = 0.; + float sq_err_down = 0.; + for(unsigned int hs=0; hs<f_2PUp.size(); ++hs){ + float err_up = ((f_2PUp.at(hs)).at(h))->GetBinContent(bin); + float err_down = ((f_2PDown.at(hs)).at(h))->GetBinContent(bin); + /* 4 different cases: + * (+,-): no action + * (-,+): swap + * (+,+): (max(+,+),0) + * (-,-): (0,min(-,-)) + */ + bool isneg_up = std::signbit(err_up); + bool isneg_down = std::signbit(err_down); + if((isneg_up)&&(!isneg_down)){ + float tmp_swap = err_up; + err_up = err_down; + err_down = tmp_swap; + } + else if((!isneg_up)&&(!isneg_down)){ + err_up = std::max(err_up,err_down); + err_down = 0.; + } + else if((isneg_up)&&(isneg_down)){ + err_down = std::min(err_up,err_down); + err_up = 0.; + } + sq_err_up+=pow(err_up,2); + sq_err_down+=pow(err_down,2); + } + //symmetrize error + sq_err=pow((sqrt(sq_err_down)+sqrt(sq_err_up))/2.,2); + h_tmp->SetBinContent(bin,sq_err); + } + } + squared_histos2P.push_back(h_tmp); + } + } + //Filling empty final histograms (just to retrieve correct binning + std::vector<TH2D*> final_histos; + + if(f_1P.size()!=0){ + for(unsigned int h=0; h<f_1P.at(0).size(); ++h){ + std::string h_tmp_name = ((f_1P.at(0)).at(h))->GetName(); + std::string JetCollection = extractJetCollectionName(h_tmp_name); + std::string njets = extractJetNumber(h_tmp_name); + std::string histoname = channel + "_gluonFractionError_"+ njets + JetCollection; + TH2D *h_tmp = (TH2D*)((f_1P.at(0)).at(h))->Clone(histoname.c_str()); + h_tmp->Reset(); + h_tmp->SetTitle(histoname.c_str()); + h_tmp->Sumw2(); + final_histos.push_back(h_tmp); + } + } + else{ + for(unsigned int h=0; h<f_2PUp.at(0).size(); ++h){ + std::string h_tmp_name = ((f_2PUp.at(0)).at(h))->GetName(); + std::string JetCollection = extractJetCollectionName(h_tmp_name); + std::string njets = extractJetNumber(h_tmp_name); + std::string histoname = channel + "_gluonFractionError_"+ njets + "_" + JetCollection; + TH2D *h_tmp = (TH2D*)((f_2PUp.at(0)).at(h))->Clone(histoname.c_str()); + h_tmp->Reset(); + h_tmp->SetTitle(histoname.c_str()); + h_tmp->Sumw2(); + final_histos.push_back(h_tmp); + } + } + //Filling final histograms + for(unsigned int h=0; h<final_histos.size(); ++h){ + for(int x = 0; x <= binX; ++x){ + for(int y = 0; y <= binY; ++y){ + int bin = h_tmp->GetBin(x,y); + float content = 0.; + + if((squared_histos1P.size())!=0){ + content+=(squared_histos1P.at(h))->GetBinContent(bin); + } + if((squared_histos2P.size())!=0){ + content+=(squared_histos2P.at(h))->GetBinContent(bin); + } + content = sqrt(content); + final_histos.at(h)->SetBinContent(bin,content); + } + } + } + return final_histos; +} +// Compute quark-gluon composition +std::vector<TH2D*> MakeQuarkGluonFractionPlots::computeQuarkGluonFraction (std::map< std::string, TH2D* > inputhistos, std::string quarkflavour, std::string prename){ + std::vector<TH2D*> QuarkGluonFractionhistos; + std::string jetCollection = extractJetCollectionName(inputhistos.begin()->first); + int njets = (inputhistos.size()-6)/5; //FIXME this can be potentially wrong + if(!m_detailedConfig){ + std::string name_gluons = "gluon_jets_"; name_gluons += jetCollection.c_str(); + std::string name_quarks = "quark_jets_"; name_quarks += jetCollection.c_str(); + TH2D *hist_g = inputhistos[name_gluons]; + TH2D *hist_q = inputhistos[name_quarks]; + //Ratio is f=g/(g+q) + std::string name_fraction = prename + "_gluonFraction_" + jetCollection; + TH2D *hist_ratio = (TH2D*)hist_g->Clone(name_fraction.c_str()); + hist_ratio->SetTitle(hist_ratio->GetName()); + hist_ratio->SetStats(kFALSE); + TH2D *hist_summ = (TH2D*)hist_g->Clone("hist_summ"); //denominator + hist_summ->Add(hist_q); + hist_ratio->Divide(hist_summ); + QuarkGluonFractionhistos.push_back(hist_ratio); + } + else{ + for (int nj = -1; nj < njets ; nj++) { //nj = -1 mean inclusive case + std::string name_gluons = "gluon_jets_"; + std::string name_lquarks = "lightquark_jets_"; + std::string name_cquarks = "cquark_jets_"; + std::string name_bquarks = "bquark_jets_"; + std::string name_other = "other_jets_"; + std::string name_fraction = prename + "_gluonFraction_"; + if (nj==-1){ + name_gluons += jetCollection; + name_lquarks += jetCollection; + name_cquarks += jetCollection; + name_bquarks += jetCollection; + name_other += jetCollection; + name_fraction += jetCollection; + } + else{ + std::string name_append="njet" + std::to_string(nj) + "_" + jetCollection; + name_gluons += name_append; + name_lquarks += name_append; + name_cquarks += name_append; + name_bquarks += name_append; + name_other += name_append; + name_fraction += name_append; + } + TH2D *hist_g = inputhistos[name_gluons]; + TH2D *hist_lj = inputhistos[name_lquarks]; + TH2D *hist_cj = inputhistos[name_cquarks]; + TH2D *hist_bj = inputhistos[name_bquarks]; + TH2D *hist_oth = inputhistos[name_other]; + //Ratio is f=g/(g+lj[light]+cj[lightC]+bj[lightCB]) + TH2D *hist_ratio = (TH2D*)hist_g->Clone(name_fraction.c_str()); + hist_ratio->SetTitle(hist_ratio->GetName()); + hist_ratio->SetStats(kFALSE); + std::string name_summ = "hist_summ_" + std::to_string(nj); //denominator + TH2D *hist_summ = (TH2D*)hist_g->Clone(name_summ.c_str()); + hist_summ->Add(hist_lj); + if(quarkflavour.compare("light") == 0){ + hist_ratio->Divide(hist_summ);} + else if (quarkflavour.compare("lightC") == 0){ + hist_summ->Add(hist_cj); + hist_ratio->Divide(hist_summ);} + else if(quarkflavour.compare("lightCB") == 0){ + hist_summ->Add(hist_cj); + hist_summ->Add(hist_bj); + hist_ratio->Divide(hist_summ);} + else + std::cout<< " WARNING: no flavor known to calculate the gluon fraction" << std::endl; + QuarkGluonFractionhistos.push_back(hist_ratio); + } + } + return QuarkGluonFractionhistos; +} +// Extract jet collection name +std::string MakeQuarkGluonFractionPlots::extractJetCollectionName(std::string histoname){ + if(histoname.find("EMPFlow")!=std::string::npos) return "AntiKt4EMPFlow"; + else if(histoname.find("EMTopo")!=std::string::npos) return "AntiKt4EMTopo"; + else if(histoname.find("LCTopo")!=std::string::npos) return "AntiKt4LCTopo"; + else std::cout<<"ERROR: jet collection not found"<<std::endl; + return NULL; +} +// Extract number of jets +std::string MakeQuarkGluonFractionPlots::extractJetNumber(std::string histoname){ + std::string njets; + std::size_t found = histoname.find("njet"); + if (found!=std::string::npos){ + std::size_t first= histoname.find("njet"); + std::size_t last = histoname.find("_AntiKt"); + njets = histoname.substr(first,(last-first)); + } + return njets; +} +/************************************************************** + * Configuration - related methods + * ************************************************************/ +void MakeQuarkGluonFractionPlots::printXMLConfigFile(){ + printf("\n %s\n Extracting configuration: \n %s\n",std::string(75,'=').c_str(),std::string(75,'=').c_str()); + std::cout<<" Nominal input file: "<<m_configNominal.path<<std::endl; + checkFile(m_configNominal.path); + std::cout<<" Nominal folder: "<<m_configNominal.folder<<std::endl; + std::cout<<" The gluon fraction will be calculated for the following channels: \n"; + for(unsigned int i=0; i<m_channel.size(); ++i) + std::cout<<"\t"<<i<<") "<<m_channel.at(i)<<std::endl; + if(m_detailedConfig) std::cout<<" It will be calculated for different jet multiplicities.\n"; + if(m_mergechannels) std::cout<<" The different channels will be merged.\n"; + std::cout<<" The gluon fraction will be calculated taking into account: "<< m_doGluVsFlavour<< " jets\n"; + std::cout<<"\n\n Systematic samples:\n"; + std::cout<<"\t 1 PointSystematic samples:\n"; + for(unsigned int i=0; i<m_config1PointVec.size();++i){ + std::cout<<"\t("<<i<<") "<<m_config1PointVec.at(i).name<<"\n"; + std::cout<<"\t\tCentral file: "<<m_config1PointVec.at(i).central<<std::endl; + checkFile(m_config1PointVec.at(i).central); + std::cout<<"\t\tCentral folder: "<<m_config1PointVec.at(i).folder_c<<std::endl; + std::cout<<"\t\tVariated file: "<<m_config1PointVec.at(i).variation<<std::endl; + checkFile(m_config1PointVec.at(i).variation); + std::cout<<"\t\tVariated folder: "<<m_config1PointVec.at(i).folder_v<<std::endl; + std::cout<<"\t\tScalefactor to apply: "<<m_config1PointVec.at(i).scalefactor<<std::endl; + } + std::cout<<"\t 2 PointSystematic samples:\n"; + for(unsigned int i=0; i<m_config2PointVec.size();++i){ + std::cout<<"\t("<<i<<") "<<m_config2PointVec.at(i).name<<"\n"; + std::cout<<"\t\tCentral file: "<<m_config2PointVec.at(i).central<<std::endl; + checkFile(m_config2PointVec.at(i).central); + std::cout<<"\t\tCentral folder : "<<m_config2PointVec.at(i).folder_c<<std::endl; + std::cout<<"\t\tUp-variated file: "<<m_config2PointVec.at(i).variation_up<<std::endl; + checkFile(m_config2PointVec.at(i).variation_up); + std::cout<<"\t\tUp-variated folder: "<<m_config2PointVec.at(i).folder_up<<std::endl; + std::cout<<"\t\tDown-variated file: "<<m_config2PointVec.at(i).variation_down<<std::endl; + checkFile(m_config2PointVec.at(i).variation_down); + std::cout<<"\t\tDown-variated folder: "<<m_config2PointVec.at(i).folder_down<<std::endl; + std::cout<<"\t\tScalefactor to apply: "<<m_config2PointVec.at(i).scalefactor<<std::endl; + } + std::cout<<"\n\n The histograms will be stored inside [channel]_"<<m_OutputFile<<std::endl; + if (m_doPS) std::cout<<" All plots will be stored in PS files "<<std::endl; + printf("\n %s\n Configuration Extracted\n %s\n",std::string(75,'=').c_str(),std::string(75,'=').c_str()); +} + +void MakeQuarkGluonFractionPlots::AbortXMLDecode(std::string value){ + std::cout<<"ERROR! Unknown attribute: "<<value<<". Aborting!\n"; + abort(); +} + +bool MakeQuarkGluonFractionPlots::decodeFloat(TXMLEngine xml, XMLAttrPointer_t attr, std::string match, float &value){ + if(strncmp(xml.GetAttrName(attr),match.c_str(),100)!=0) return false; + value=std::stof(xml.GetAttrValue(attr)); + return true; +} + +bool MakeQuarkGluonFractionPlots::decodeString(TXMLEngine xml, XMLAttrPointer_t attr, std::string match, std::string &value){ + if(strncmp(xml.GetAttrName(attr),match.c_str(),100)!=0) return false; + value=xml.GetAttrValue(attr); + return true; +} + +bool MakeQuarkGluonFractionPlots::decodeBool(TXMLEngine xml, XMLAttrPointer_t attr, std::string match, bool &value){ + if(strncmp(xml.GetAttrName(attr),match.c_str(),100)!=0) return false; + if(strncmp(xml.GetAttrValue(attr),"true",100)==0) + value=true; + else if(strncmp(xml.GetAttrValue(attr),"false",100)==0) + value=false; + else{ + std::cout<<"ERROR! Unknown attribute value: "<<xml.GetAttrValue(attr)<<". Choose between true or false! Exiting!\n"; + abort(); + } + return true; +} + +void MakeQuarkGluonFractionPlots::readXMLConfigFile(std::string configfile){ + TXMLEngine xml; + // Now try to parse xml file + XMLDocPointer_t xmldoc = xml.ParseFile(configfile.c_str()); + if (xmldoc==0) { + std::cout<<"ERROR! No valid xml configuration file provided! Aborting!\n"; + abort(); + } + // Access to main node + XMLNodePointer_t mainnode = xml.DocGetRootElement(xmldoc); + // Loop through all nodes and subnodes + readXMLNode(xml, mainnode); + // Release memory before exit + xml.FreeDoc(xmldoc); +} +void MakeQuarkGluonFractionPlots::readXMLNode(TXMLEngine xml, XMLNodePointer_t node){ + if(strncmp(xml.GetNodeName(node),"nominal",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + while (attr!=0) { + bool pass=0; + pass+=decodeString(xml, attr, "path", m_configNominal.path); + pass+=decodeString(xml, attr, "folder", m_configNominal.folder); + if(!pass) AbortXMLDecode(xml.GetAttrName(attr)); + attr = xml.GetNextAttr(attr); + } + } + else if(strncmp(xml.GetNodeName(node),"systematic1point",100)==0){ + config_1PointSyst temp_config1Point; + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + while (attr!=0) { + bool pass=0; + pass+=decodeString(xml, attr, "name", temp_config1Point.name); + pass+=decodeString(xml, attr, "central", temp_config1Point.central); + pass+=decodeString(xml, attr, "variation", temp_config1Point.variation); + pass+=decodeFloat(xml, attr, "scalefactor", temp_config1Point.scalefactor); + pass+=decodeString(xml, attr, "folder_central", temp_config1Point.folder_c); + pass+=decodeString(xml, attr, "folder_variation", temp_config1Point.folder_v); + if(!pass) AbortXMLDecode(xml.GetAttrName(attr)); + attr = xml.GetNextAttr(attr); + } + m_config1PointVec.push_back(temp_config1Point); + } + else if(strncmp(xml.GetNodeName(node),"systematic2point",100)==0){ + config_2PointSyst temp_config2Point; + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + while (attr!=0) { + bool pass=0; + pass+=decodeString(xml, attr, "name", temp_config2Point.name); + pass+=decodeString(xml, attr, "central", temp_config2Point.central); + pass+=decodeString(xml, attr, "variation_up", temp_config2Point.variation_up); + pass+=decodeString(xml, attr, "variation_down", temp_config2Point.variation_down); + pass+=decodeFloat(xml, attr, "scalefactor", temp_config2Point.scalefactor); + pass+=decodeString(xml, attr, "folder_central", temp_config2Point.folder_c); + pass+=decodeString(xml, attr, "folder_up", temp_config2Point.folder_up); + pass+=decodeString(xml, attr, "folder_down", temp_config2Point.folder_down); + if(!pass) AbortXMLDecode(xml.GetAttrName(attr)); + attr = xml.GetNextAttr(attr); + } + m_config2PointVec.push_back(temp_config2Point); + std::cout<<"systematic2point\n"; + } + else if(strncmp(xml.GetNodeName(node),"output",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + if(!decodeString(xml, attr, "path", m_OutputFile)) AbortXMLDecode(xml.GetAttrName(attr)); + } + else if(strncmp(xml.GetNodeName(node),"channel",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + std::string tmp_channel=""; + if(!decodeString(xml, attr, "name", tmp_channel)) AbortXMLDecode(xml.GetAttrName(attr)); + m_channel.push_back(tmp_channel); + } + else if(strncmp(xml.GetNodeName(node),"mergechannels",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + if(!decodeBool(xml, attr, "value", m_mergechannels)) AbortXMLDecode(xml.GetAttrName(attr)); + } + else if(strncmp(xml.GetNodeName(node),"detailed",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + if(!decodeBool(xml, attr, "value", m_detailedConfig)) AbortXMLDecode(xml.GetAttrName(attr)); + } + else if(strncmp(xml.GetNodeName(node),"gluon_vs_flavour",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + if(!decodeString(xml, attr, "value", m_doGluVsFlavour)) AbortXMLDecode(xml.GetAttrName(attr)); + if(strncmp(xml.GetAttrValue(attr),"light" ,100) + *strncmp(xml.GetAttrValue(attr),"lightC" ,100) + *strncmp(xml.GetAttrValue(attr),"lightCB",100)) + AbortXMLDecode(xml.GetAttrName(attr)); + } + else if(strncmp(xml.GetNodeName(node),"do_ps",100)==0){ + XMLAttrPointer_t attr = xml.GetFirstAttr(node); + if(!decodeBool(xml, attr, "value", m_doPS)) AbortXMLDecode(xml.GetAttrName(attr)); + } + //Loop over child nodes + XMLNodePointer_t child = xml.GetChild(node); + while (child!=0) { + readXMLNode(xml, child); + child = xml.GetNext(child); + } +} +void MakeQuarkGluonFractionPlots::checkFile(std::string inputfilename){ + bool istxt = ( (inputfilename.find(".txt") + 4 ) == inputfilename.length()); + if(istxt){ + std::string f_name; + ifstream reader; + reader.open (inputfilename); + while(!reader.eof()){ + getline(reader,f_name); + if(f_name.compare("")==0) continue; + TFile *f = TFile::Open(f_name.c_str()); + if (f->IsZombie()){ + std::cout<<"File "<<f_name<<" from list "<<inputfilename<<" not found! Please check against your configuration file! Aborting|\n"; + abort(); + } + } + reader.close(); + } + else{ + TFile f(inputfilename.c_str()); + if (f.IsZombie()){ + std::cout<<"File "<<inputfilename<<" not found! Please check against your configuration file! Aborting|\n"; + abort(); + } + } +} + diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/MakeQuarkGluonFractionPlots.h b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/MakeQuarkGluonFractionPlots.h new file mode 100644 index 0000000000000000000000000000000000000000..d4282739f4af55d499f30c621e0c83f269687a2d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/MakeQuarkGluonFractionPlots.h @@ -0,0 +1,136 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration +*/ +//Author: Regina Moles Valls - <regina.moles.valls@cern.ch> +//R21 migration: Matteo Scornajenghi - <matteo.scornajenghi@cern.ch> + +#ifndef MAKEQUARKGLUONFRACTIONPLOTS_H +#define MAKEQUARKGLUONFRACTIONPLOTS_H + +#include <iostream> +#include <string> +#include <fstream> +#include <sstream> +#include <stdlib.h> +#include <vector> +#include "TStyle.h" +#include "TCanvas.h" +#include "TFile.h" +#include "TKey.h" +#include "TH2D.h" +#include "TPostScript.h" +#include <TError.h> +#include "TROOT.h" +#include "TClass.h" +#include "TXMLEngine.h" +#include <map> +#include <fstream> + +// =============================================================================== +// Macro to compute the gluon initiated jets fraction in your sample/selection +// =============================================================================== +struct config_NominalInput{ + config_NominalInput(): path(""),folder("JetFlavorPlots"){} + std::string path; + std::string folder; +}; +struct config_1PointSyst{ + config_1PointSyst(): name(""),central(""),variation(""),scalefactor(1),folder_c("JetFlavorPlots"),folder_v("JetFlavorPlots"){} + std::string name; + std::string central; + std::string variation; + float scalefactor; + std::string folder_c; + std::string folder_v; +}; +struct config_2PointSyst{ + config_2PointSyst(): name(""),central(""),variation_up(""),variation_down(""),scalefactor(1),folder_c("JetFlavorPlots"),folder_up("JetFlavorPlots"),folder_down("JetFlavorPlots"){} + std::string name; + std::string central; + std::string variation_up; + std::string variation_down; + float scalefactor; + std::string folder_c; + std::string folder_up; + std::string folder_down; +}; + +class MakeQuarkGluonFractionPlots { + + public: +//new functions + void printXMLConfigFile(); + void readXMLConfigFile(std::string configfile); + void readXMLNode(TXMLEngine xml, XMLNodePointer_t node); + bool decodeBool(TXMLEngine xml, XMLAttrPointer_t attr, std::string match, bool &value); + bool decodeString(TXMLEngine xml, XMLAttrPointer_t attr, std::string match, std::string &value); + bool decodeFloat(TXMLEngine xml, XMLAttrPointer_t attr, std::string match, float &value); + void AbortXMLDecode(std::string value); +//end new + + //function that reads the configuration file and makes the gluon fraction plots + MakeQuarkGluonFractionPlots(std::string configfile); + + //function to check if the file exists + void checkFile(std::string filename); + + //function to draw histograms from a map + void drawhistos(std::map<std::string, TH2D*> histos, std::string psfilename); + //function to draw histograms from a vector + void drawhistos(std::vector<TH2D*> histos, std::string psfilename); + + //function to extract the JetCollectionName + std::string extractJetCollectionName(std::string histoname); + + //function to extract the JetNumber + std::string extractJetNumber(std::string histoname); + + //function to compute the gluon fraction + std::vector<TH2D*> computeQuarkGluonFraction (std::map< std::string,TH2D* > inputhistos, std::string quarkflavour, std::string prename); + + //function to create the output file + void createOutputFile(std::string filename,std::vector<TH2D*> histos, std::vector<TH2D*> histosUnc ); + + //Subtract + std::vector<TH2D*> getDelta (std::vector<TH2D*> h_nom, std::vector<TH2D*> h_var, double scale, std::string prehistname); + + //function to compute the total systematic uncertainty + std::vector<TH2D*> evaluateQGFUncertaity(std::vector<std::vector<TH2D*> > f_1P, std::vector<std::vector<TH2D*> > f_2PUp, std::vector<std::vector<TH2D*> > f_2PDown, std::string channel); + + + + + private: + // QuarkGluon fraction can be calculated respect to different quark flavours + // light: computed only talking into account light quarks (gluons/light-quarks) + // lightC default): computed only talking into account light quarks (gluons/light-quarks+c-quarks) + // lightCB: computed only talking into account light quarks (gluons/light-quarks+c-quarks+b-quarks) + std::string m_doGluVsFlavour; + + // channel:name of the folder where the histograms has been stored: ee, mumu, emu, mujets, ejets... + std::vector<std::string> m_channel; + + //compute the gluon fraction versus jet multiplicity + bool m_detailedConfig; + + // name of the output file + std::string m_OutputFile; + + // store plots in PS files + bool m_doPS; + + config_NominalInput m_configNominal; + std::vector<config_1PointSyst> m_config1PointVec; + std::vector<config_2PointSyst> m_config2PointVec; + + bool m_mergechannels; + + void DumpToMap(std::map<std::string, TH2D*> &h_map, std::string filename, std::string channel, std::string folder, std::string keyname, bool createMap); + void DumpFileToMap(std::map<std::string, TH2D*> &h_map, std::string filename, std::string channel, std::string folder, std::string keyname, bool createMap); + void CreateQGFFile(std::string prename, std::map<std::string, TH2D*> h_input,std::vector< std::map<std::string, TH2D*> > h_input_1P,std::vector< std::map<std::string, TH2D*> > h_input_1PVar,std::vector< std::map<std::string, TH2D*> > h_input_2P,std::vector< std::map<std::string, TH2D*> > h_input_2PUp,std::vector< std::map<std::string, TH2D*> > h_input_2PDown); + +}; + + +#endif + diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/at-pkg b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/at-pkg index 5f1b64bcde01780cada00311b2a52a3ed0729d99..3042fa0686c6a36aa718957516ddad4f89bc46dd 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/at-pkg +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/at-pkg @@ -23,7 +23,6 @@ atlas_depends_on_subdirs( PUBLIC TopPartons TopObjectSelectionTools TopSystematicObjectMaker - TopFakes TopDataPreparation TopHLUpgrade ) @@ -53,7 +52,6 @@ atlas_add_library( $pkgname Root/*.cxx Root/*.h Root/*.icc TopPartons TopObjectSelectionTools TopSystematicObjectMaker - TopFakes TopDataPreparation TopHLUpgrade \${ROOT_LIBRARIES} @@ -77,7 +75,6 @@ atlas_install_scripts( scripts/*.py ) # TopPartons # TopObjectSelectionTools # TopSystematicObjectMaker -# TopFakes # TopDataPreparation # TopHLUpgrade # ${ROOT_LIBRARIES} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/generate_art_configs.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/generate_art_configs.py new file mode 100755 index 0000000000000000000000000000000000000000..73a4050e30c61e02c46b8b9b0e03c06c812d29dd --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/generate_art_configs.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python +# +# Generate cut files for ARTs from validation-cuts.txt. +# To be run from directory PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share. + +import sys +import re + + +def rewriteConfig(artConfigName, inputConfigPath, campaign, overrides=None, klfitter=False, actualmurw=False): + overrides2 = {} + if overrides is not None: + overrides2.update(overrides) + overrides = overrides2 + if not actualmurw: + overrides.setdefault('PRWActualMu_FS', None) + overrides.setdefault('PRWActualMu_AF', None) + rexEol = re.compile(r'[\n\r]*$') + rexLine = re.compile(r'(\s*)(\S+)(\s+)') + rexSelection = re.compile(r'\s*(?:SELECTION|SUB)\b') + rexCampaignSpecificStart = re.compile(r'(?i)\s*#\s*(mc\w+) configuration\s*$') + rexCampaignSpecificEnd = re.compile(r'#?PRWLumiCalcFiles\b') + section = 1 # 1 = config options, 2 = selections + campaignSpecificState = None # True (False) = forcefully enable (disable) current campaign-specific set of config options + emitted = set() # which config keys have already been written + def writeln(line): + out.write(line) + out.write('\n') + with open(inputConfigPath, 'rb') as f: + with open('ART/artcut_test_' + artConfigName + '.txt', 'wb') as out: + for line in f: + line = rexEol.sub('', line) + if section == 1: + if not rexSelection.match(line): + + # hacks for per-campaign PRW configuration + m = rexCampaignSpecificStart.match(line) + if m: + campaignSpecificState = m.group(1).lower() == campaign.lower() + if campaignSpecificState and campaign.lower() == 'mc16a': + campaignSpecificState = None # mc16a enabled by default + if campaignSpecificState is False: + if rexCampaignSpecificEnd.match(line): + campaignSpecificState = None + continue + if campaignSpecificState is True and line.startswith('#PRW'): + line = line[1:] + + m = rexLine.match(line) + if m: + k = m.group(2) + if k in overrides: + if k not in emitted: + v = overrides[k] + emitted.add(k) + if v is not None: + writeln(' '.join((k, v))) + else: + writeln(line) + else: + writeln(line) + continue + # emit remaining options that did not appear in the original config file + for k, v in overrides.iteritems(): + if v is not None and k not in emitted: + writeln(' '.join((k, v))) + # done with config options + section = 2 + + if section == 2: + m = re.match('^#?((?:RECO::)?KLFITTER.*)', line) + if m: + line = m.group(1) + if not klfitter: + line = '#' + line + writeln(line) + + +rewriteConfig('410470afmc16a', 'validation-cuts.txt', 'mc16a') +rewriteConfig('410470afmc16d', 'validation-cuts.txt', 'mc16d') +rewriteConfig('410470fsmc16a', 'validation-cuts.txt', 'mc16a') +rewriteConfig('410470fsmc16d', 'validation-cuts.txt', 'mc16d') +rewriteConfig('410470fsmc16dactualmurw', 'validation-cuts.txt', 'mc16d', actualmurw=True) +rewriteConfig('410470fsmc16apflow', 'validation-cuts.txt', 'mc16a', overrides={ + 'JetCollectionName': 'AntiKt4EMPFlowJets_BTagging201810', + }) +rewriteConfig('410470fsmc16dpflow', 'validation-cuts.txt', 'mc16d', overrides={ + 'JetCollectionName': 'AntiKt4EMPFlowJets_BTagging201810', + }) +rewriteConfig('410470fsmc16asysts', 'validation-cuts.txt', 'mc16a', overrides={ + 'Systematics': 'All', + }) +rewriteConfig('410470fsmc16dsysts', 'validation-cuts.txt', 'mc16d', overrides={ + 'Systematics': 'All', + }) +rewriteConfig('410470fsmc16dklfitter', 'validation-cuts.txt', 'mc16d', klfitter=True) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation-data.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation-data.py new file mode 100755 index 0000000000000000000000000000000000000000..9f81a2bbacf69930c82dd843fc557cd65a664091 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation-data.py @@ -0,0 +1,398 @@ +#!/usr/bin/env python + +# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + +import ROOT +import random,string + +import TopExamples.AtlasStyle + +import sys +import os +import re + +def thumbnail(plot, width, height): + img = ROOT.TASImage(plot) + img.Scale(width, height) + name = plot.replace('.png', '_tn.png') + img.WriteImage(name) + +def br(): + out.write('<br>\n') + +def h1(txt): + out.write('<h1>%s</h1>\n' % txt) + +def h3(txt): + out.write('<h3>%s</h3>\n' % txt) + + +# rebin histogram to add underflow and overflow bins +def addUnderOverflowBin(h): + # see https://root.cern.ch/phpBB3/viewtopic.php?t=6764 + # function to paint the histogram h with extra bins for underflows/overflows + nx = h.GetNbinsX()+1 + xbins = [] + for r in range(nx+1): + xbins.append(h.GetBinLowEdge(r)) + + xbins.append(xbins[nx-1]+h.GetBinWidth(nx)) + # book a temporary histogram having extra bins, change name to avoid memory leak warnings + xName="".join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(5)) + htmp = ROOT.TH1D(h.GetName()+xName, h.GetTitle(), nx+1, h.GetBinLowEdge(1)-h.GetBinWidth(1), xbins[nx]) + # Set up plot for markers and errors + htmp.Sumw2() + # fill the new histogram including the underflows/overflows + for r in range(nx+1): + htmp.SetBinContent(htmp.FindBin(htmp.GetBinCenter(r+1)),h.GetBinContent(r)) + htmp.SetBinError(htmp.FindBin(htmp.GetBinCenter(r+1)),h.GetBinError(r)) + + htmp.SetEntries(h.GetEffectiveEntries()) + htmp.SetXTitle(h.GetXaxis().GetTitle()) + htmp.SetYTitle(h.GetYaxis().GetTitle()) + return htmp + + +# create ratio plot +def createRatio(h1, h2): + hRatio = h1.Clone("hRatio") + hRatio.SetLineColor(ROOT.kBlack) + hRatio.SetMarkerStyle(20) + hRatio.SetTitle("") + hRatio.SetMinimum(0.8) + hRatio.SetMaximum(1.20) + #hRatio.Sumw2() # this should have already been done in addUnderOverflowBin (warnings if uncommented) + hRatio.SetStats(0) + hRatio.Divide(h2) + + # Adjust y-axis settings + y = hRatio.GetYaxis() + y.SetTitle("Ratio") + y.SetNdivisions(505) + y.SetTitleSize(20) + y.SetTitleFont(43) + y.SetTitleOffset(1.2) + y.SetLabelFont(43) + y.SetLabelSize(15) + + # Adjust x-axis settings + x = hRatio.GetXaxis() + x.SetTitleSize(20) + x.SetTitleFont(43) + x.SetTitleOffset(3.5) + x.SetLabelFont(43) + x.SetLabelSize(10) + return hRatio + + +def createCanvasPads(): + c1.cd() + # Upper histogram plot is pad1 + pad1.SetBottomMargin(0) + pad1.Draw() + # Lower ratio plot is pad2 + pad2.SetTopMargin(0) + pad2.SetBottomMargin(0.2) + pad2.SetGridx() + pad2.SetGridy() + pad2.Draw() + + +def plot(name): + legend = ROOT.TLegend(0.70, 0.80, 0.90, 0.90) + legend.SetFillColor(0) + legend.SetFillStyle(0) + legend.SetBorderSize(0) + legend.SetTextFont(72) + legend.SetTextSize(0.04) + + stack = ROOT.THStack() + h = [] # list of rebinned histograms for the stack + + for i, f in enumerate(files): + h_orig = f.Get(name) + if h_orig == None: + print "Cannot find :",name,"in",f.GetName() + return None + h.append(addUnderOverflowBin(h_orig)) + + h[i].SetLineColor(histogramStyles[i].m_linecolour) + h[i].SetLineStyle(histogramStyles[i].m_linestyle) + h[i].SetLineWidth(histogramStyles[i].m_linewidth) + h[i].SetFillColor(histogramStyles[i].m_fillcolour) + + version = re.findall("\d+[\.]?", names[i]) + if (version): + versionName = 'AT-%s'% ''.join(str(e) for e in version) + else: + versionName = names[i].replace('.root','') + legend.AddEntry(h[i], versionName, 'f') + + stack.Add(h[i]) + + #for the cutflow histograms print the number of entries on the bin + txt = 'hist nostack' + if name.find('cutflow') > -1: + txt += ' text' + + # Create different pads + createCanvasPads() + pad1.cd() + + stack.Draw(txt) + stack.GetHistogram().GetXaxis().SetTitle(h[0].GetXaxis().GetTitle()) + stack.GetHistogram().GetYaxis().SetTitle(h[0].GetYaxis().GetTitle()) + # Change the size of the numbers in the Y axis and the range + stack.GetHistogram().GetYaxis().SetLabelSize(0.04) + Ymax = stack.GetHistogram().GetMaximum() + stack.SetMaximum(Ymax+0.1*Ymax) + + legend.Draw('same') + + if len(files) == 2: + # Create ratio plot + hRatio = createRatio(h[0],h[1]) + pad2.cd() + hRatio.Draw() + + thesame = True + for i in range(1, h[0].GetNbinsX()): #h.Chi2Test better? + if h[0].GetBinContent(i) != h[1].GetBinContent(i): + thesame = False + + if not thesame: + x1 = stack.GetHistogram().GetXaxis().GetXmin() + x2 = stack.GetHistogram().GetXaxis().GetXmax() + + y1 = stack.GetHistogram().GetMinimum() + y2 = stack.GetHistogram().GetMaximum() + + pad1.cd() + box = ROOT.TBox(x1, y1, x2, y2) + box.SetFillStyle(0) + box.SetLineColor(ROOT.kRed) + box.SetLineWidth(3) + box.Draw('same') + + + #write the channel in the top right + caption = name.split('/')[0] + lmode = ROOT.TLatex() + lmode.SetTextAlign(31); #right, obviously + lmode.SetNDC() + lmode.SetTextColor(1) + lmode.SetTextFont(72) + lmode.SetTextSize(0.04) + lmode.DrawLatex(0.95, 0.96, caption) + + filename = name.replace('/','_') + '.png' + c1.Print(outputdir + '/' + filename) + thumbnail(outputdir + '/' + filename, 250, 250) + out.write('<a href="%s"><img src="%s"></a>\n' % (filename, filename.replace('.png', '_tn.png'))) + + +# electron plots +def plotElectrons(channel): + h3('Electrons') + plot(channel + '/el_true_type') + plot(channel + '/el_n') + br() + plot(channel + '/el_pt') + plot(channel + '/el_eta') + plot(channel + '/el_phi') + plot(channel + '/el_charge') + plot(channel + '/el_trkpart_charge') + br() + + plot(channel + '/el_topoetcone20') + plot(channel + '/el_topoetcone30') + plot(channel + '/el_topoetcone40') + br() + + plot(channel + '/el_ptcone20') + plot(channel + '/el_ptcone30') + plot(channel + '/el_ptcone40') + br() + + plot(channel + '/el_ptvarcone20') + plot(channel + '/el_ptvarcone30') + plot(channel + '/el_ptvarcone40') + br() + + +# muon plots +def plotMuons(channel): + h3('Muons') + plot(channel + '/mu_true_type') + plot(channel + '/mu_n') + br() + plot(channel + '/mu_pt') + plot(channel + '/mu_eta') + plot(channel + '/mu_phi') + plot(channel + '/mu_charge') + br() + + plot(channel + '/mu_topoetcone20') + plot(channel + '/mu_topoetcone30') + plot(channel + '/mu_topoetcone40') + br() + + plot(channel + '/mu_ptcone20') + plot(channel + '/mu_ptcone30') + plot(channel + '/mu_ptcone40') + br() + + plot(channel + '/mu_ptvarcone20') + plot(channel + '/mu_ptvarcone30') + plot(channel + '/mu_ptvarcone40') + br() + + +# photon plots +def plotPhotons(channel): + h3('Photons') + plot(channel + '/ph_n') + plot(channel + '/ph_pt') + plot(channel + '/ph_eta') + plot(channel + '/ph_phi') + plot(channel + '/ph_e') + plot(channel + '/ph_ptvarcone20') + br() + + +# jet and large-R jet plots +def plotJets(channel): + h3('All Jets') + plot(channel + '/jet_n') + br() + plot(channel + '/jet_pt') + plot(channel + '/jet_eta') + plot(channel + '/jet_phi') + plot(channel + '/jet_e') + br() + plot(channel + '/jet_mv2c10') + plot(channel + '/jet_truthflav') + plot(channel + '/jet_isbtagged_MV2c10_77') + plot(channel + '/jet_btagSF_MV2c10_77') + + for i in range(4): + h3('Jet%d' % i) + plot(channel + '/jet%d_pt' % i) + plot(channel + '/jet%d_eta' % i) + plot(channel + '/jet%d_phi' % i) + plot(channel + '/jet%d_e' % i) + br() + plot(channel + '/jet%d_mv2c10' % i) + plot(channel + '/jet%d_truthflav' % i) + plot(channel + '/jet%d_isbtagged_MV2c10_77' % i) + plot(channel + '/jet%d_btagSF_MV2c10_77' % i) + + h3('Large-R jet') + plot(channel + '/ljet_n') + plot(channel + '/ljet_pt') + plot(channel + '/ljet_eta') + plot(channel + '/ljet_phi') + plot(channel + '/ljet_m') + plot(channel + '/ljet_sd12') + + + +# tau plots +def plotTau(channel): + h3('Tau') + plot(channel + '/taujet_n') + plot(channel + '/taujet_pt') + plot(channel + '/taujet_eta') + plot(channel + '/taujet_phi') + plot(channel + '/taujet_charge') + + + +ROOT.gROOT.SetBatch(True) + +channels = ['ejets_2015', 'ejets_2016', 'mujets_2015', 'mujets_2016', 'ee_2015', 'ee_2016', 'mumu_2015', 'mumu_2016', 'emu_2015', 'emu_2016'] +particles = ['Electrons', 'Muons', 'Photons', 'Jets', 'Tau', 'MET'] + + +if len(sys.argv) < 2: + print 'Try:' + print 'python %s outputdir/ primary.root rel_1.root' % sys.argv[0] + sys.exit() + +outputdir = sys.argv[1] + +names = sys.argv[2:] +print 'Expecting these files', names + +#try to make it, but don't worry too much if it already exists +try: + os.mkdir(outputdir) +except: + pass + +class HistStyle: + def __init__(self, linecolour, linestyle, linewidth, fillcolour): + self.m_linecolour = linecolour + self.m_linestyle = linestyle + self.m_linewidth = linewidth + self.m_fillcolour = fillcolour + +histogramStyles = [ + HistStyle(ROOT.kYellow, 1, 3, ROOT.kYellow), + HistStyle(ROOT.kBlack, 2, 3, 0), + HistStyle(ROOT.kRed, 3, 3, 0), + HistStyle(ROOT.kGreen, 4, 3, 0), + HistStyle(ROOT.kBlue, 5, 3, 0), + HistStyle(ROOT.kGray, 6, 3, ROOT.kGray), +] + +files = [] +for name in names: + files.append(ROOT.TFile.Open(name)) + +if len(files) > len(histogramStyles): + print 'You are trying to open more files than we have styles' + print 'edit the histogramStyles list and add some more' + sys.exit(1) + +out = open(outputdir + '/index.html', 'w') +c1 = ROOT.TCanvas('c1', '', 600, 600) +pad1 = ROOT.TPad("pad1", "pad1", 0, 0.3, 1, 1.0) +pad2 = ROOT.TPad("pad2", "pad2", 0, 0.05, 1, 0.3) + +h3('Cutflows') +for channel in channels: + plot(channel + '/cutflow') + +for channel in channels: + h1(channel) + + h3('Event stuff') + plot(channel + '/mc_weight') + plot(channel + '/pileup_weight') + plot(channel + '/event_mu') + plot(channel + '/jvt_SF') + + print channel + + if 'Electrons' in particles: + plotElectrons(channel) + + if 'Muons' in particles: + plotMuons(channel) + + if 'Photons' in particles: + plotPhotons(channel) + + if 'Jets' in particles: + plotJets(channel) + + if 'Taus' in particles: + plotTaus(channel) + + + h3('MET') + plot(channel + '/event_met_et') + plot(channel + '/event_met_phi') + +out.close() diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation.py index 0b4cc37b6445bb872af23ee0501d96e17b5130d2..9c0b17d53b91e569e65afbb34a8545060e0f5f77 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/scripts/validation.py @@ -269,8 +269,8 @@ def plotJets(channel): br() plot(channel + '/jet_mv2c10') plot(channel + '/jet_truthflav') - plot(channel + '/jet_isbtagged_77') - plot(channel + '/jet_btagSF_77') + plot(channel + '/jet_isbtagged_MV2c10_77') + plot(channel + '/jet_btagSF_MV2c10_77') for i in range(4): h3('Jet%d' % i) @@ -281,8 +281,8 @@ def plotJets(channel): br() plot(channel + '/jet%d_mv2c10' % i) plot(channel + '/jet%d_truthflav' % i) - plot(channel + '/jet%d_isbtagged_77' % i) - plot(channel + '/jet%d_btagSF_77' % i) + plot(channel + '/jet%d_isbtagged_MV2c10_77' % i) + plot(channel + '/jet%d_btagSF_MV2c10_77' % i) h3('Large-R jet') plot(channel + '/ljet_n') diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470afmc16a.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470afmc16a.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d88e74845dab0b7d72f395eb65eaf8fbebbae7f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470afmc16a.txt @@ -0,0 +1,666 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use +# MC16a configuration + +### This setup is for the CI tests +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/CI.prw.merged.root + +### Use following lines (uncomment) for your config file +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root + +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470afmc16d.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470afmc16d.txt new file mode 100644 index 0000000000000000000000000000000000000000..8593ff03c6c588ae50db94aeaa8279b63a6a1fa1 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470afmc16d.txt @@ -0,0 +1,659 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use + +# MC16d configuration +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16a.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16a.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d88e74845dab0b7d72f395eb65eaf8fbebbae7f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16a.txt @@ -0,0 +1,666 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use +# MC16a configuration + +### This setup is for the CI tests +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/CI.prw.merged.root + +### Use following lines (uncomment) for your config file +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root + +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16apflow.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16apflow.txt new file mode 100644 index 0000000000000000000000000000000000000000..8efe455701e0e167a2fbf2814481d4d18956bb52 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16apflow.txt @@ -0,0 +1,666 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use +# MC16a configuration + +### This setup is for the CI tests +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/CI.prw.merged.root + +### Use following lines (uncomment) for your config file +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root + +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMPFlowJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16asysts.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16asysts.txt new file mode 100644 index 0000000000000000000000000000000000000000..44ef3f743ce1ae4d9b089ff627e8970bc350dd9e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16asysts.txt @@ -0,0 +1,666 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use +# MC16a configuration + +### This setup is for the CI tests +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/CI.prw.merged.root + +### Use following lines (uncomment) for your config file +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root + +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics All +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16d.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16d.txt new file mode 100644 index 0000000000000000000000000000000000000000..8593ff03c6c588ae50db94aeaa8279b63a6a1fa1 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16d.txt @@ -0,0 +1,659 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use + +# MC16d configuration +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dactualmurw.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dactualmurw.txt new file mode 100644 index 0000000000000000000000000000000000000000..0294a1b39b25e531b7d6427085d2ee56d358445a --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dactualmurw.txt @@ -0,0 +1,661 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use + +# MC16d configuration +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +PRWActualMu_FS GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +PRWActualMu_AF GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dklfitter.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dklfitter.txt new file mode 100644 index 0000000000000000000000000000000000000000..27778c324d5fe681fc6e73d34aebf47f8b6465ca --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dklfitter.txt @@ -0,0 +1,659 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use + +# MC16d configuration +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dpflow.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dpflow.txt new file mode 100644 index 0000000000000000000000000000000000000000..379fac330b98807084cb3d1819e684848c5c4a8f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dpflow.txt @@ -0,0 +1,659 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use + +# MC16d configuration +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMPFlowJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dsysts.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dsysts.txt new file mode 100644 index 0000000000000000000000000000000000000000..3fffa54bfc6f30dbe4a3ce49dc97dbc486a45396 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/ART/artcut_test_410470fsmc16dsysts.txt @@ -0,0 +1,659 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use + +# MC16d configuration +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + + +BTagCDIPath xAODBTaggingEfficiency/13TeV/2019-21-13TeV-MC16-CDI-2019-10-07_v1.root + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics All +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None + +### Tau configuration +TauPt 25000 +TauJetIDWP Medium +TauJetIDWPLoose Medium +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingWP MV2c10:FixedCutBEff_77 MV2c10:Continuous DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/example-config.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/example-config.txt new file mode 100644 index 0000000000000000000000000000000000000000..89ad1df916dcadf355fb1ea900079141ac148f4f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/example-config.txt @@ -0,0 +1,286 @@ +#this is an example configuration file for AnalysisTop; refer to https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21 for a guide on most common options +#IMPORTANT: THIS IS ONLY AN EXAMPLE AND NOT A RECOMMENDATION OF THE BEST CONFIGURATION TO BE USED (because there is no single configuration optimal for all cases) +#the values used for all the possible config options are printed at the beginning of the execution of top-xaod +#all options not explicitely configured in the file use the default values +#all available options and their default values can be seen here https://gitlab.cern.ch/atlas/athena/-/blob/21.2/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/ConfigurationSettings.cxx +#(this is the default link for the HEAD version, if you're using a specific release, search e.g. "21.2.XXX" from the drop-down release menu to see the one relative to your version) + +############General setup########### +#these are the libraries included for the execution. Update if you add a package (e.g. if you add MyCustomSaver, you have to add libMyCustomSaver to the list below) +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +#use this to run on a limited number of events; comment to run on all events in the input files provided via the filelist +#NEvents 500 + +#if you want to use a custom object selection, in case existing configurable options are not enough, change this (see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#5_Extend_AnalysisTop_for_your_ow ) +ObjectSelectionName top::ObjectLoaderStandardCuts +#if you want to use a custom event saver, change this (see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#5_Extend_AnalysisTop_for_your_ow ) +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents # AllEvents-> store all events, SelectedEvents -> store events passing at least one of the event-level selections (defined below) +OutputFilename output.root + +# DoTight/DoLoose to activate the loose and tight trees, can be: Data, MC, Both, False. Loose trees are tipically used for multijetestimation in data, see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#Systematics +DoTight Both +DoLoose Data + +### Systematics you want to run +Systematics Nominal #Nominal->only nominal. All -> all systematics (will be much slower). You can also use AllMuons, AllJets... see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#Systematics + +#If you use MedaData (as you usually should) IsAFII (needed for fast simulation) is automatically set, see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#FullSim_vs_AFII +UseAodMetaData True +#IsAFII False + +############GRL and PRW############# +#here Good Run List and Pileup Reweighting settings are provided, see https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/TopGroupDataDerivationList#Lumicalc_GRL_and_PRW_files for the most update settings + +##these are the settings for MC16a +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + +###########Reco-level object definitions (i.e. object-level selection)########## + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMPFlowJets_BTagging201903 +LargeJetCollectionName None # can be e.g. AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName None #can be e.g. TauJets +PhotonCollectionName None #can be e.g. Photons +TrackJetCollectionName None #can be e.g. AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903 +JetGhostTrackDecoName None # can be e.g. GhostTrack + +### Electron configuration +ElectronPt 25000 +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation FCTight +ElectronIsolationLoose None + +### Muon configuration +MuonPt 25000 +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation FCTight_FixedRad +MuonIsolationLoose None +doExtraSmearing False +do2StationsHighPt False + +### Jet configuration +JetPt 25000 +JVTWP Default + +### B-tagging configuration +BTaggingCaloJetWP DL1r:FixedCutBEff_77 +# for track jet, use BTaggingTrackJetWP option + +###########Reco-level systematics models########## +ElectronEfficiencySystematicModel TOTAL +EgammaSystematicModel 1NP_v1 #egamma calibration uncertainties model +JetUncertainties_NPModel CategoryReduction #JES +JetJERSmearingModel Simple #JER + +###########Truth-level settings########## +#see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#Truth_options for more info +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthDressedWZJets +TruthLargeRJetCollectionName None # can be AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory False # can be e.g. ttbar +TopPartonLevel False #this option only exists for recent releases; it switches on/off writing the "truth" partol-level tree +TopParticleLevel False #this switches on/off writing the "particleLevel" tree +TruthBlockInfo False +PDFInfo True + +############################################## +#############Event-level selections########### +############################################## +###more info here https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#Which_event_level_cuts_can_I_use +###see https://gitlab.cern.ch/atlas/athena/-/blob/21.2/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts-pflow.txt for some more complicated examples +### here we have just very simple selections for ttbar e+jets/mu+jets channels +### these should be considered as a simple example AND NOT as suggestions for real analyses, that should carefully evaluate the selections applied + +#####General definition of periods##### + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + +#####Reco-level definitions###### + +### basic sub-selections with mandatory cuts for reco level + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +### lepton trigger and offline cuts sub-selections + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +### e+jets selections + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +#RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:DL1r:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +### mu+jets selections + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +#RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:DL1r:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +##### particle-level selection ##### + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-data-rel21.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-data-rel21.txt index 158d152f748cfb9248c8e68c10f7b23d26014942..02a97f994beee99455db169a2be98083d9e74cb2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-data-rel21.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-data-rel21.txt @@ -1,10 +1 @@ -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000027.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000153.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000393.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000073.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000228.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000422.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000132.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000279.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000146.pool.root.1 -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/data/data16_13TeV.00311321.physics_Main.deriv.DAOD_TOPQ1.r9264_p3083_p3142/DAOD_TOPQ1.11286123._000368.pool.root.1 +/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/ContinuousIntegration/Data/p4173/data16_13TeV.AllYear.physics_Main.PhysCont.DAOD_TOPQ1.grp16_v01_p4173/DAOD_TOPQ1.21542408._000018.pool.root.1 diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-mc-rel21.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-mc-rel21.txt index c37f9f0daa93a81691c0f774682b457136761586..d1b25bc90b75d93f36f7be344ad61b2aa94bdce8 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-mc-rel21.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/input-mc-rel21.txt @@ -1 +1 @@ -root://eosatlas.cern.ch//eos/atlas/atlascerngroupdisk/phys-top/topreco/rel21/mc/group.phys-top.11303793.EXT0._000011.DAOD_TOPQ1.DAOD.root +/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/dev/AnalysisTop/ContinuousIntegration/MC/p4174/mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_s3126_r9364_p4174/test.pool.root diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/nocuts.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/nocuts.txt index c958a57ad82fcbb0d16fe94d4478a5efa5ceca3b..c259eb231b94d89328c1c80658b72033ef8d0ddb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/nocuts.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/nocuts.txt @@ -43,12 +43,13 @@ ElectronIsolationLoose None MuonQuality Medium MuonQualityLoose Medium -MuonIsolation Gradient +MuonIsolation PflowTight_FixedRad MuonIsolationLoose None -FakesControlRegionDoLooseMC False -OverlapRemovalLeptonDef Tight -ApplyElectronInJetSubtraction False +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data NEvents 2000 diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/upgrade-cuts.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/upgrade-cuts.txt new file mode 100644 index 0000000000000000000000000000000000000000..00de68ae65e725970161cf120da32a12afa7caa5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/upgrade-cuts.txt @@ -0,0 +1,364 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +#These aren't used in upgrade studies, just filled so top-xaod doesn't complain +GRLDir GoodRunsLists +GRLFile data15_13TeV/20160720/physics_25ns_20.7.xml data16_13TeV/20161101/physics_25ns_20.7.xml +PRWConfigFiles +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20160720/physics_25ns_20.7.lumicalc.OflLumi-13TeV-005.root GoodRunsLists/data16_13TeV/20161101/physics_25ns_20.7.lumicalc.OflLumi-13TeV-005.root + +TDPPath TopUpgradeGrid/XSection-MC15-14TeV.data +MCGeneratorWeights True + + +ElectronCollectionName None +MuonCollectionName None +JetCollectionName None +LargeJetCollectionName None +LargeJetSubstructure None +TauCollectionName None +PhotonCollectionName None + +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthDressedWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +TruthPhotonCollectionName TruthPhotons +PDFInfo True + +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + +Systematics All +JetUncertainties_NPModel GlobalReduction + +ElectronID MediumLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation Gradient +ElectronIsolationLoose None +ElectronPt 7000. + +MuonQuality Medium +MuonQualityLoose Medium +MuonIsolation Gradient +MuonIsolationLoose None +MuonPt 4000. #j/psi +TruthMuonPt 4000. #j/psi + +JetPt 25000. +JetEta 2.5 + +TruthPhotonEta 2.37 #default is 2.5 +TruthPhotonPt 15000. #default is 25000. +#PhotonID None #default is Tight +#PhotonIDLoose None #default is Loose +#PhotonIsolation None #default is FixedCutTight +#PhotonIsolationLoose None #default is FixedCutLoose + + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +UseAodMetaData False +IsAFII False + +BTaggingCaloJetWP FixedCutBEff_77 + +HLLHC True +HLLHCFakes True + + +######################## +### Muon+jets selection +######################## +SELECTION mujets_upgrade +INITIAL +MU_N 25000 >= 1 +EL_N 25000 == 0 +MU_N 25000 == 1 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +SAVE + +######################## +### Electron+jets selection +######################## +SELECTION ejets_upgrade +INITIAL +EL_N 25000 >= 1 +MU_N 25000 == 0 +EL_N 25000 == 1 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +SAVE + + +######################## +### Muon+1jet selection +######################## +SELECTION mu1jet_upgrade +INITIAL +MU_N 25000 >= 1 +EL_N 25000 == 0 +MU_N 25000 == 1 +JET_N 25000 >= 1 +SAVE + +######################## +### Electron+1jet selection +######################## +SELECTION e1jet_upgrade +INITIAL +EL_N 25000 >= 1 +MU_N 25000 == 0 +EL_N 25000 == 1 +JET_N 25000 >= 1 +SAVE + + +### ttV +#TRILEPTON + +### +### dead cone: +### +SELECTION deadcone +INITIAL +EL_N 25000 == 1 +MU_N 25000 == 0 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MET > 25000 +#JET_N_BTAG FixedCutBEff_85 >= 1 +LJET_N 200000 >= 2 +LJET_N 300000 >= 1 +#LJET_TOPTAGGED tagged_80 == 1 +#LJET_CONTAINS_LEPTON 200000 == 1 +#LJET_CONTAINS_B_AND_LEPTON FixedCutBEff_85 >= 1 +#LEPTONIC_B_LJET_DECOMPOSED ungroomed == 1 +SAVE + +SELECTION mujets_trimming_basic +INITIAL +MU_N 25000 == 1 +EL_N 25000 == 0 +TRIGMATCH +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MET > 25000 +#JET_N_BTAG FixedCutBEff_85 >= 1 +LJET_N 200000 >= 2 +LJET_N 300000 >= 1 +#LJET_TOPTAGGED tagged_80 == 1 +#LJET_CONTAINS_LEPTON 200000 == 1 +#LJET_CONTAINS_B_AND_LEPTON FixedCutBEff_85 >= 1 +#LEPTONIC_B_LJET_DECOMPOSED trimming == 1 +SAVE + +### ======== ttgamma: + +SELECTION ejets_gamma_basic +INITIAL +EL_N 25000 == 1 +MU_N 25000 == 0 +TRIGMATCH +JETCLEAN LooseBad +NOBADMUON +PH_N 10000 >= 1 +SAVE + +SELECTION mujets_gamma_basic +INITIAL +MU_N 25000 == 1 +EL_N 25000 == 0 +TRIGMATCH +JETCLEAN LooseBad +NOBADMUON +PH_N 10000 >= 1 +SAVE + +SELECTION emu_gamma_basic +INITIAL +EL_N 25000 >= 1 +MU_N 25000 >= 1 +TRIGMATCH +JETCLEAN LooseBad +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +#MLL > 15000 +NOBADMUON +PH_N 10000 >= 1 +SAVE + +SELECTION ee_gamma_basic +INITIAL +EL_N 25000 >= 2 +TRIGMATCH +JETCLEAN LooseBad +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +#MLL > 15000 +NOBADMUON +PH_N 10000 >= 1 +SAVE + +SELECTION mumu_gamma_basic +INITIAL +MU_N 25000 >= 2 +TRIGMATCH +JETCLEAN LooseBad +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +#MLL > 15000 +NOBADMUON +PH_N 10000 >= 1 +SAVE + + +###======== tZ: + +SELECTION mumumu +INITIAL +MU_N 15000 >= 3 +MU_N 15000 == 3 +EL_N 15000 == 0 +JET_N 30000 >= 1 +JET_N 30000 >= 2 +SAVE + +SELECTION eee +INITIAL +EL_N 15000 >= 3 +EL_N 15000 == 3 +MU_N 15000 == 0 +JET_N 30000 >= 1 +JET_N 30000 >= 2 +SAVE + +SELECTION eemu +INITIAL +MU_N 15000 >= 1 +EL_N 15000 >= 1 +EL_N 15000 >= 2 +MU_N 15000 == 1 +EL_N 15000 == 2 +JET_N 30000 >= 1 +JET_N 30000 >= 2 +SAVE + +SELECTION emumu +INITIAL +EL_N 15000 >= 1 +MU_N 15000 >= 1 +MU_N 15000 >= 2 +EL_N 15000 == 1 +MU_N 15000 == 2 +JET_N 30000 >= 1 +JET_N 30000 >= 2 +SAVE + +###======== Jpsi top mass: +### l+>=4 jets && all other muons (i need to go as low as 4 GeV tight muons). + +SELECTION ejets_jpsi_basic +INITIAL +EL_N 25000 == 1 +MU_N 25000 == 0 +TRIGMATCH +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +SAVE + +SELECTION mujets_jpsi_basic +INITIAL +MU_N 25000 >= 1 +EL_N 25000 == 0 +TRIGMATCH +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +SAVE + + +###======== t->Zq FCNC: +SELECTION sel1_tZq +INITIAL +EL_N 15000 == 1 +MU_N 15000 == 2 +JET_N 25000 >= 1 +SAVE + +SELECTION sel2_tZq +INITIAL +MU_N 15000 == 1 +EL_N 15000 == 2 +JET_N 25000 >= 1 +SAVE + +SELECTION sel3_tZq +INITIAL +EL_N 15000 == 3 +MU_N 15000 == 0 +JET_N 25000 >= 1 +SAVE + +SELECTION sel4_tZq +INITIAL +MU_N 15000 == 3 +EL_N 15000 == 0 +JET_N 25000 >= 1 +SAVE + +######################## +### Di-muon selection +######################## +SELECTION mumu +INITIAL +MU_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +#MLL > 15000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +SAVE + +######################## +### Di-electron selection +######################## +SELECTION ee +INITIAL +EL_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +#MLL > 15000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +SAVE + +######################## +### e-mu selection +######################## +SELECTION emu +INITIAL +MU_N 25000 >= 1 +EL_N 25000 >= 1 +MU_N 25000 == 1 +EL_N 25000 == 1 +#MLL > 15000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts-pflow.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts-pflow.txt new file mode 100644 index 0000000000000000000000000000000000000000..b02b1726c68fae86e7dad12a902637284f9680a4 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts-pflow.txt @@ -0,0 +1,637 @@ +LibraryNames libTopEventSelectionTools libTopEventReconstructionTools + +### Good Run List +GRLDir GoodRunsLists +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml + +### Pile-up reweighting tool - Metadata determines which to use +# MC16a configuration + +### This setup is for the CI tests +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/CI.prw.merged.root + +### Use following lines (uncomment) for your config file +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root + +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + +# MC16d configuration +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +#PRWActualMu_FS GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWActualMu_AF GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + +# MC16e configuration +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16e.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16e.AF.v2/prw.merged.root +#PRWActualMu_FS GoodRunsLists/data18_13TeV/20190318/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWActualMu_AF GoodRunsLists/data18_13TeV/20190318/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWLumiCalcFiles GoodRunsLists/data18_13TeV/20190318/ilumicalc_histograms_None_348885-364292_OflLumi-13TeV-010.root + +#setup of TDP file, comment the following line to use the default one instead +TDPPath dev/AnalysisTop/TopDataPreparation/CI-XSection-MC16-13TeV.data + +### Object container names +ElectronCollectionName Electrons +MuonCollectionName Muons +JetCollectionName AntiKt4EMPFlowJets_BTagging201903 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903 +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass +LargeRJetPt 200000 +LargeRJetEta 2 +LargeJetSubstructure None + +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration +TruthCollectionName TruthParticles +TruthJetCollectionName AntiKt4TruthDressedWZJets +TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets +TopPartonHistory ttbar +TopParticleLevel True +TruthBlockInfo False +PDFInfo True + +### Object loader/ output configuration +ObjectSelectionName top::ObjectLoaderStandardCuts +OutputFormat top::EventSaverFlatNtuple +OutputEvents SelectedEvents +OutputFilename output.root +PerfStats No + + +### Systematics configuration +Systematics Nominal +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction + +### Electron configuration +ElectronID TightLH +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation FCTight +ElectronIsolationLoose None + +### Photon configuration +PhotonPt 25000 +PhotonEta 2.5 +PhotonID Tight +PhotonIDLoose Loose +PhotonIsolation FixedCutTight +PhotonIsolationLoose FixedCutLoose +PhotonUseRadiativeZ False + +### Muon configuration +MuonQuality Medium +MuonUseMVALowPt False +MuonUse2stationHighPt True +MuonIsolation PflowTight_FixedRad +MuonQualityLoose Medium +MuonUseMVALowPtLoose False +MuonUse2stationHighPtLoose True +MuonIsolationLoose None +MuonDoExtraSmearingHighPt False +MuonDoSmearing2stationHighPt True + +### Tau configuration +TauPt 25000 +TauJetIDWP RNNMedium +TauJetIDWPLoose RNNLoose +TauEleBDTWP Loose +TauEleBDTWPLoose Loose +TauEleOLR False +TauEleOLRLoose False + +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False + +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 + +### B-tagging configuration +BTaggingCaloJetWP DL1:Continuous DL1r:FixedCutBEff_77 +BTaggingTrackJetWP DL1:Continuous DL1r:FixedCutBEff_77 +# Example of how to remove systematics from b-tag EV + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 + +#NEvents 500 + +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + +######################## +### basic selection with mandatory cuts for reco level +######################## + +SUB BASIC +INITIAL +GRL +GOODCALO +PRIVTX +RECO_LEVEL + +######################## +### definition of the data periods +######################## + +SUB period_2015 +RUN_NUMBER >= 276262 +RUN_NUMBER <= 284484 + +SUB period_2016 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + + +######################## +### lepton trigger and offline cuts for reco-level selections +######################## + +SUB EL_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N 25000 >= 1 + +SUB EL_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N 27000 >= 1 + +SUB MU_2015 +. BASIC +. period_2015 +GTRIGDEC +MU_N 25000 >= 1 + +SUB MU_2016 +. BASIC +. period_2016 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC +MU_N 27000 >= 1 + +SUB EM_2015 +. BASIC +. period_2015 +GTRIGDEC +EL_N_OR_MU_N 25000 >= 1 + +SUB EM_2016 +. BASIC +. period_2016 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +######################## +### e+jets selections +######################## + +SUB ejets_basic +EL_N 25000 == 1 +MU_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET > 30000 +MWT > 30000 +RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:DL1r:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION ejets_2015 +. EL_2015 +. ejets_basic +SAVE + +SELECTION ejets_2016 +. EL_2016 +. ejets_basic +SAVE + +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_DL1r_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_DL1r_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_DL1r_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_DL1r_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_DL1r_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_DL1r_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION ejets_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ejets_basic +SAVE + +######################## +### mu+jets selections +######################## + +SUB mujets_basic +MU_N 25000 == 1 +EL_N 25000 == 0 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +JET_N 25000 >= 1 +JET_N 25000 >= 2 +JET_N 25000 >= 3 +JET_N 25000 >= 4 +MET+MWT > 60000 +RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:DL1r:FixedCutBEff_77 +#KLFITTER > -50.0 +EXAMPLEPLOTS +#PRINT +NOBADMUON + +SELECTION mujets_2015 +. MU_2015 +. mujets_basic +SAVE + +SELECTION mujets_2016 +. MU_2016 +. mujets_basic +SAVE + +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_DL1r_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_DL1r_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_DL1r_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_DL1r_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_DL1r_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_DL1r_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG DL1r:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + +SELECTION mujets_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mujets_basic +SAVE + +######################## +### emu selections +######################## + +SUB emu_basic +EL_N 25000 >= 1 +MU_N 25000 >= 1 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +HT > 120000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 1 +MU_N 25000 == 1 +OS +MLL > 15000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +NOBADMUON + +SELECTION emu_2015 +. EM_2015 +. emu_basic +SAVE + +SELECTION emu_2016 +. EM_2016 +. emu_basic +SAVE + +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + +SELECTION emu_particle +PRIVTX +PARTICLE_LEVEL +EL_N_OR_MU_N 27000 >= 1 +. emu_basic +SAVE + +######################## +### ee selections +######################## + +SUB ee_basic +EL_N 25000 >= 2 +GTRIGMATCH +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +EL_N 25000 == 2 +MU_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION ee_2015 +. EL_2015 +. ee_basic +SAVE + +SELECTION ee_2016 +. EL_2016 +. ee_basic +SAVE + +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + +SELECTION ee_particle +PRIVTX +PARTICLE_LEVEL +EL_N 27000 >= 1 +. ee_basic +SAVE + +######################## +### mumu selections +######################## + +SUB mumu_basic +MU_N 25000 >= 2 +GTRIGMATCH +#EMU_OVERLAP +JETCLEAN LooseBad +MET > 60000 +JET_N 25000 >= 1 +JET_N 25000 >= 2 +MU_N 25000 == 2 +EL_N 25000 == 0 +OS +MLL > 15000 +MLLWIN 80000 100000 +#TRUTH_MATCH +#JET_N_BTAG FixedCutBEff_77 >= 1 +EXAMPLEPLOTS +#JET_N_BTAG FixedCutBEff_77 > 1 +NOBADMUON + +SELECTION mumu_2015 +. MU_2015 +. mumu_basic +SAVE + +SELECTION mumu_2016 +. MU_2016 +. mumu_basic +SAVE + +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + +SELECTION mumu_particle +PRIVTX +PARTICLE_LEVEL +MU_N 27000 >= 1 +. mumu_basic +SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts.txt b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts.txt index 1502a9b738a0bcacbadd82cd0605af042431e939..a2c0ac8a2a276538e4a2c9d2d4bcac10fafa2594 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/share/validation-cuts.txt @@ -2,28 +2,63 @@ LibraryNames libTopEventSelectionTools libTopEventReconstructionTools ### Good Run List GRLDir GoodRunsLists -GRLFile data15_13TeV/20160720/physics_25ns_20.7.xml data16_13TeV/20170215/physics_25ns_20.7.xml - -### Pile-up reweighting tool - this is now mandatory -### Now requires only PRWLumiCalcFiles -### No PRWDefaultChannel anymore -### The nominal mc15c PU distribution is now appended to PRWConfigFiles automatically -### Will hence be using mc15c_v2_defaults.NotRecommended.prw.root if nothing is provided for PRWConfigFiles -# PRWConfigFiles TopCorrections/PRW.410000.mc15c.r7725_r7676.root -PRWConfigFiles -PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20160720/physics_25ns_20.7.lumicalc.OflLumi-13TeV-005.root GoodRunsLists/data16_13TeV/20170215/physics_25ns_20.7.lumicalc.OflLumi-13TeV-008.root -# no PRWDefaultChannel anymore +GRLFile data15_13TeV/20170619/physics_25ns_21.0.19.xml data16_13TeV/20180129/physics_25ns_21.0.19.xml data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.xml +### Pile-up reweighting tool - Metadata determines which to use +# MC16a configuration + +### This setup is for the CI tests +PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/CI.prw.merged.root +PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/CI.prw.merged.root + +### Use following lines (uncomment) for your config file +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16a.AF.v2/prw.merged.root + +PRWLumiCalcFiles GoodRunsLists/data15_13TeV/20170619/PHYS_StandardGRL_All_Good_25ns_276262-284484_OflLumi-13TeV-008.root GoodRunsLists/data16_13TeV/20180129/PHYS_StandardGRL_All_Good_25ns_297730-311481_OflLumi-13TeV-009.root + +# MC16d configuration +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.FS.v2/CI.prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16d.AF.v2/CI.prw.merged.root +#PRWActualMu_FS GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWActualMu_AF GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWLumiCalcFiles GoodRunsLists/data17_13TeV/20180619/physics_25ns_Triggerno17e33prim.lumicalc.OflLumi-13TeV-010.root + +# MC16e configuration +#PRWConfigFiles_FS dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16e.FS.v2/prw.merged.root +#PRWConfigFiles_AF dev/AnalysisTop/PileupReweighting/user.iconnell.Top.PRW.MC16e.AF.v2/prw.merged.root +#PRWActualMu_FS GoodRunsLists/data18_13TeV/20190318/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWActualMu_AF GoodRunsLists/data18_13TeV/20190318/physics_25ns_Triggerno17e33prim.actualMu.OflLumi-13TeV-010.root +#PRWLumiCalcFiles GoodRunsLists/data18_13TeV/20190318/ilumicalc_histograms_None_348885-364292_OflLumi-13TeV-010.root + +#setup of TDP file, comment the following line to use the default one instead +TDPPath dev/AnalysisTop/TopDataPreparation/CI-XSection-MC16-13TeV.data + +### Object container names ElectronCollectionName Electrons MuonCollectionName Muons -JetCollectionName AntiKt4EMTopoJets -LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +JetCollectionName AntiKt4EMTopoJets_BTagging201810 +LargeJetCollectionName AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets +TauCollectionName TauJets +PhotonCollectionName Photons +TrackJetCollectionName AntiKtVR30Rmax4Rmin02TrackJets_BTagging201810 +JetGhostTrackDecoName GhostTrack + +### Large-R configuration +LargeRJESJMSConfig CombMass LargeRJetPt 200000 LargeRJetEta 2 LargeJetSubstructure None -TauCollectionName TauJets -PhotonCollectionName Photons +### Reclustered jet configuration +UseRCJets True +#UseRCJetSubstructure True +RCJetEta 2.0 +UseVarRCJets True +VarRCJetMassScale m_w,m_t +VarRCJetRho 2 + +### Truth configuration TruthCollectionName TruthParticles TruthJetCollectionName AntiKt4TruthWZJets TruthLargeRJetCollectionName AntiKt10TruthTrimmedPtFrac5SmallR20Jets @@ -32,22 +67,26 @@ TopParticleLevel True TruthBlockInfo False PDFInfo True +### Object loader/ output configuration ObjectSelectionName top::ObjectLoaderStandardCuts OutputFormat top::EventSaverFlatNtuple OutputEvents SelectedEvents OutputFilename output.root PerfStats No + +### Systematics configuration Systematics Nominal -JetUncertainties_NPModel 21NP -JetUncertainties_BunchSpacing 25ns -LargeRJESUncertaintyConfig Split23,Tau32WTA +JetUncertainties_NPModel CategoryReduction +LargeRJetUncertainties_NPModel CategoryReduction +### Electron configuration ElectronID TightLH -ElectronIDLoose MediumLH -ElectronIsolation Gradient +ElectronIDLoose LooseAndBLayerLH +ElectronIsolation FCTight ElectronIsolationLoose None +### Photon configuration PhotonPt 25000 PhotonEta 2.5 PhotonID Tight @@ -56,30 +95,56 @@ PhotonIsolation FixedCutTight PhotonIsolationLoose FixedCutLoose PhotonUseRadiativeZ False +### Muon configuration MuonQuality Medium +MuonUseMVALowPt False +MuonUse2stationHighPt True +MuonIsolation PflowTight_FixedRad MuonQualityLoose Medium -MuonIsolation Gradient +MuonUseMVALowPtLoose False +MuonUse2stationHighPtLoose True MuonIsolationLoose None +MuonDoExtraSmearingHighPt False +MuonDoSmearing2stationHighPt True +### Tau configuration TauPt 25000 -TauJetIDWP Medium -TauJetIDWPLoose Medium +TauJetIDWP RNNMedium +TauJetIDWPLoose RNNLoose TauEleBDTWP Loose TauEleBDTWPLoose Loose TauEleOLR False TauEleOLRLoose False -FakesControlRegionDoLooseMC False -OverlapRemovalLeptonDef Tight -ApplyElectronInJetSubtraction False +# DoTight/DoLoose to activate the loose and tight trees +# each should be one in: Data, MC, Both, False +DoTight Both +DoLoose Data + +# Turn on MetaData to pull IsAFII from metadata +UseAodMetaData True +#IsAFII False -UseAodMetaData False -IsAFII False +### Boosted jet taggers configuration +BoostedJetTagging JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50 JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50 JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80 -BTaggingWP FixedCutBEff_77 +### B-tagging configuration +BTaggingCaloJetWP MV2c10:FixedCutBEff_77 MV2c10:Continuous +BTaggingTrackJetWP MV2c10:FixedCutBEff_77 MV2c10:Continuous +# Example of how to remove systematics from b-tag EV +#BTaggingSystExcludedFromEV FT_EFF_JET_BJES_Response;FT_EFF_JET_EffectiveNP_1;FT_EFF_EG_RESOLUTION_ALL + +# Saving bootstrapping weights +SaveBootstrapWeights False +NumberOfBootstrapReplicas 100 #NEvents 500 +### Global lepton trigger scale factor example +UseGlobalLeptonTriggerSF True +GlobalTriggers 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 +GlobalTriggersLoose 2015@e24_lhmedium_L1EM20VH_OR_e60_lhmedium_OR_e120_lhloose,mu20_iloose_L1MU15_OR_mu50 2016@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2017@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 2018@e26_lhtight_nod0_ivarloose_OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0,mu26_ivarmedium_OR_mu50 + ######################## ### basic selection with mandatory cuts for reco level ######################## @@ -100,7 +165,16 @@ RUN_NUMBER >= 276262 RUN_NUMBER <= 284484 SUB period_2016 -RUN_NUMBER >= 297730 +RUN_NUMBER >= 296939 +RUN_NUMBER <= 311481 + +SUB period_2017 +RUN_NUMBER >= 324320 +RUN_NUMBER <= 341649 + +SUB period_2018 +RUN_NUMBER >= 348197 + ######################## ### lepton trigger and offline cuts for reco-level selections @@ -109,37 +183,73 @@ RUN_NUMBER >= 297730 SUB EL_2015 . BASIC . period_2015 -TRIGDEC HLT_e24_lhmedium_L1EM20VH HLT_e60_lhmedium HLT_e120_lhloose +GTRIGDEC EL_N 25000 >= 1 SUB EL_2016 . BASIC . period_2016 -TRIGDEC HLT_e26_lhtight_nod0_ivarloose HLT_e60_lhmedium_nod0 HLT_e140_lhloose_nod0 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N 27000 >= 1 + +SUB EL_2018 +. BASIC +. period_2018 +GTRIGDEC EL_N 27000 >= 1 SUB MU_2015 . BASIC . period_2015 -TRIGDEC HLT_mu20_iloose_L1MU15 HLT_mu50 +GTRIGDEC MU_N 25000 >= 1 SUB MU_2016 . BASIC . period_2016 -TRIGDEC HLT_mu26_ivarmedium HLT_mu50 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2017 +. BASIC +. period_2017 +GTRIGDEC +MU_N 27000 >= 1 + +SUB MU_2018 +. BASIC +. period_2018 +GTRIGDEC MU_N 27000 >= 1 SUB EM_2015 . BASIC . period_2015 -TRIGDEC HLT_e24_lhmedium_L1EM20VH HLT_e60_lhmedium HLT_e120_lhloose HLT_mu20_iloose_L1MU15 HLT_mu50 +GTRIGDEC EL_N_OR_MU_N 25000 >= 1 SUB EM_2016 . BASIC . period_2016 -TRIGDEC HLT_e26_lhtight_nod0_ivarloose HLT_e60_lhmedium_nod0 HLT_e140_lhloose_nod0 HLT_mu26_ivarmedium HLT_mu50 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2017 +. BASIC +. period_2017 +GTRIGDEC +EL_N_OR_MU_N 27000 >= 1 + +SUB EM_2018 +. BASIC +. period_2018 +GTRIGDEC EL_N_OR_MU_N 27000 >= 1 ######################## @@ -149,7 +259,7 @@ EL_N_OR_MU_N 27000 >= 1 SUB ejets_basic EL_N 25000 == 1 MU_N 25000 == 0 -TRIGMATCH +GTRIGMATCH #EMU_OVERLAP JETCLEAN LooseBad JET_N 25000 >= 1 @@ -158,8 +268,7 @@ JET_N 25000 >= 3 JET_N 25000 >= 4 MET > 30000 MWT > 30000 -#JET_N_BTAG FixedCutBEff_77 >= 1 -#RECO::KLFITTERRUN kElectron +RECO::KLFITTERRUN kElectron KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 #KLFITTER > -50.0 EXAMPLEPLOTS #PRINT @@ -175,6 +284,70 @@ SELECTION ejets_2016 . ejets_basic SAVE +SELECTION ejets_2017 +. EL_2017 +. ejets_basic +SAVE + +SELECTION ejets_2018 +. EL_2018 +. ejets_basic +SAVE + +SELECTION ejets_MV2c10_2015 +. EL_2015 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2016 +. EL_2016 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2017 +. EL_2017 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_MV2c10_2018 +. EL_2018 +. ejets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION ejets_tjet_MV2c10_2015 +. EL_2015 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2016 +. EL_2016 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2017 +. EL_2017 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION ejets_tjet_MV2c10_2018 +. EL_2018 +. ejets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + SELECTION ejets_particle PRIVTX PARTICLE_LEVEL @@ -189,7 +362,7 @@ SAVE SUB mujets_basic MU_N 25000 == 1 EL_N 25000 == 0 -TRIGMATCH +GTRIGMATCH #EMU_OVERLAP JETCLEAN LooseBad JET_N 25000 >= 1 @@ -197,8 +370,7 @@ JET_N 25000 >= 2 JET_N 25000 >= 3 JET_N 25000 >= 4 MET+MWT > 60000 -#JET_N_BTAG FixedCutBEff_77 >= 1 -#RECO::KLFITTERRUN kMuon +RECO::KLFITTERRUN kMuon KLFitterBTaggingWP:MV2c10:FixedCutBEff_77 #KLFITTER > -50.0 EXAMPLEPLOTS #PRINT @@ -214,6 +386,70 @@ SELECTION mujets_2016 . mujets_basic SAVE +SELECTION mujets_2017 +. MU_2017 +. mujets_basic +SAVE + +SELECTION mujets_2018 +. MU_2018 +. mujets_basic +SAVE + +SELECTION mujets_MV2c10_2015 +. MU_2015 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2016 +. MU_2016 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2017 +. MU_2017 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_MV2c10_2018 +. MU_2018 +. mujets_basic +JET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +######################################################################## +# For testing whether track jet b-tag selection works +# ONLY FOR TESTING, DOES NOT MAKE SENSE TO USE THIS FOR PHYSICS ANALYSIS +# THESE COMBINE TRACK-JET B-TAGGING WITH KLFITTER ON CALO JETS!!! + +SELECTION mujets_tjet_MV2c10_2015 +. MU_2015 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2016 +. MU_2016 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2017 +. MU_2017 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE + +SELECTION mujets_tjet_MV2c10_2018 +. MU_2018 +. mujets_basic +TJET_N_BTAG MV2c10:FixedCutBEff_77 >= 1 +SAVE +######################################################################## + SELECTION mujets_particle PRIVTX PARTICLE_LEVEL @@ -228,7 +464,7 @@ SAVE SUB emu_basic EL_N 25000 >= 1 MU_N 25000 >= 1 -TRIGMATCH +GTRIGMATCH #EMU_OVERLAP JETCLEAN LooseBad HT > 120000 @@ -253,6 +489,16 @@ SELECTION emu_2016 . emu_basic SAVE +SELECTION emu_2017 +. EM_2017 +. emu_basic +SAVE + +SELECTION emu_2018 +. EM_2018 +. emu_basic +SAVE + SELECTION emu_particle PRIVTX PARTICLE_LEVEL @@ -266,7 +512,7 @@ SAVE SUB ee_basic EL_N 25000 >= 2 -TRIGMATCH +GTRIGMATCH JETCLEAN LooseBad MET > 60000 JET_N 25000 >= 1 @@ -292,6 +538,16 @@ SELECTION ee_2016 . ee_basic SAVE +SELECTION ee_2017 +. EL_2017 +. ee_basic +SAVE + +SELECTION ee_2018 +. EL_2018 +. ee_basic +SAVE + SELECTION ee_particle PRIVTX PARTICLE_LEVEL @@ -305,7 +561,7 @@ SAVE SUB mumu_basic MU_N 25000 >= 2 -TRIGMATCH +GTRIGMATCH #EMU_OVERLAP JETCLEAN LooseBad MET > 60000 @@ -332,9 +588,51 @@ SELECTION mumu_2016 . mumu_basic SAVE +SELECTION mumu_2017 +. MU_2017 +. mumu_basic +SAVE + +SELECTION mumu_2018 +. MU_2018 +. mumu_basic +SAVE + SELECTION mumu_particle PRIVTX PARTICLE_LEVEL MU_N 27000 >= 1 . mumu_basic SAVE + +######################## +### large-r jet selections +######################## + +SELECTION large_r_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +LJET_N 350000 >=1 +SAVE + +SELECTION rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +RCJET_N 350000 >=1 +SAVE + +SELECTION var_rc_jets +INITIAL +GRL +GOODCALO +PRIVTX +JETCLEAN LooseBad +VRCJET_N 2m_w 300000 >= 1 +VRCJET_N 2m_t 350000 >= 1 +SAVE diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470afmc16a.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470afmc16a.py new file mode 100755 index 0000000000000000000000000000000000000000..709caa4aeb6228aac7cf2df7bfea200f10a32807 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470afmc16a.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16a TOPQ1 AtlFast2 410470 +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_a875_r9364_r9315_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470afmc16d.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470afmc16d.py new file mode 100755 index 0000000000000000000000000000000000000000..67f53542af1040d53f17c05919872e2bf952f14a --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470afmc16d.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16d TOPQ1 AtlFast2 410470 +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_a875_r10201_r10210_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16a.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16a.py new file mode 100755 index 0000000000000000000000000000000000000000..2bdfeb96e11f14e3ad362de9e60200166496b7c3 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16a.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# art-description: DxAOD MC16a TOPQ1 FullSim 410470 +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r9364_r9315_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16apflow.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16apflow.py new file mode 100755 index 0000000000000000000000000000000000000000..8a694f1fd9b193429cdd7ab7a0960b96e97ae032 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16apflow.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16a TOPQ1 FullSim 410470 PFlow Jets +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r9364_r9315_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16asysts.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16asysts.py new file mode 100755 index 0000000000000000000000000000000000000000..6141d6f5d671abdfab75427886dc84e9d3c7c6b9 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16asysts.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# art-description: DxAOD MC16a TOPQ1 FullSim 410470 with systematics +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r9364_r9315_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16d.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16d.py new file mode 100755 index 0000000000000000000000000000000000000000..b849e8634246f156bd1c77166ebfb508a2731e27 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16d.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16d TOPQ1 FullSim 410470 +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r10201_r10210_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dactualmurw.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dactualmurw.py new file mode 100755 index 0000000000000000000000000000000000000000..00323c5d4280b1ea81582c0851f2ad1b4afe20f9 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dactualmurw.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16d TOPQ1 FullSim 410470 Actual Mu Pileup Reweighting +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r10201_r10210_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dklfitter.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dklfitter.py new file mode 100755 index 0000000000000000000000000000000000000000..b849e8634246f156bd1c77166ebfb508a2731e27 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dklfitter.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16d TOPQ1 FullSim 410470 +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r10201_r10210_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dpflow.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dpflow.py new file mode 100755 index 0000000000000000000000000000000000000000..00a0dd4f1b68a706e41e60a5d73155d1db997600 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dpflow.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16d TOPQ1 FullSim 410470 PFlow Jets +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r10201_r10210_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dsysts.py b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dsysts.py new file mode 100755 index 0000000000000000000000000000000000000000..7d8c6fcca08b4d71efcf32da385791686cfbb79e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/test/test_410470fsmc16dsysts.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python + +# art-description: DxAOD MC16d TOPQ1 FullSim 410470 with systematics +# art-type: grid +# art-output: output.root +# art-input: user.mvanadia.ART.mc16_13TeV.410470.PhPy8EG_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e6337_e5984_s3126_r10201_r10210_p3980 +# art-input-nfiles: 2 +# art-include: 21.2/AnalysisTop + +import ROOT +from PathResolver import PathResolver +import subprocess, sys, shlex, random, shutil, os + +# Create empty PoolFileCatalog +os.system('art.py createpoolfile') + +# -- Settings -- +cutfilename = "artcut_"+os.path.basename( sys.argv[0] ).replace(".py",".txt") + +try: + inputfilenames=os.environ["ArtInFile"] +except KeyError: + print "Please set the environment variable ArtInFile" + sys.exit(1) + +# -- Get the validation file path from the most recent location -- +cutfilepath = ROOT.PathResolver.find_file(cutfilename, + "DATAPATH", + ROOT.PathResolver.RecursiveSearch) + +# -- Print the file location for debugging -- +print "ART Test : Using cutfile (%s) from %s"%(cutfilename, cutfilepath) +print "ART Test : Using inputfiles :",inputfilenames +print "Running on full statistics" + +# -- Copy the cutfile locally to be updated -- +shutil.copyfile(cutfilepath, cutfilename) + + # -- Write the input file path to a temporary file -- +lines = inputfilenames.split(",") +with open('input.txt', 'w') as inputfilepath: + for line in lines: + print "line : ", line + inputfilepath.write(line+'\n') + +f = open('input.txt', 'r') +print "Printing input.txt" +print f.read() +f.close() + +# -- Run top-xaod -- +cmd = "top-xaod %s input.txt"%(cutfilename) +proc = subprocess.Popen(shlex.split(cmd)) +proc.wait() + +# -- Print the art-result return code +print "art-result: " + str(proc.returncode) + +# -- Check the return code and exit this script with that -- +sys.exit( proc.returncode ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-tool-ftag.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-tool-ftag.cxx new file mode 100644 index 0000000000000000000000000000000000000000..10657f9b08d7f3ea2349d47d6c23a8995d05a8fb --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-tool-ftag.cxx @@ -0,0 +1,132 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include <iostream> + +#include "TFile.h" +#include "TTree.h" +#include "TTreeFormula.h" +#include "TSystem.h" + +#include "xAODRootAccess/TEvent.h" +#include "xAODRootAccess/TStore.h" +#include "xAODRootAccess/TActiveStore.h" + +#include "TopConfiguration/AodMetaDataAccess.h" +#include "TopConfiguration/ConfigurationSettings.h" +#include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/SelectionConfigurationData.h" + +#include "TopAnalysis/Tools.h" +#include "TopCPTools/TopToolStore.h" + +#include "TopAnalysis/ObjectLoaderBase.h" +#include "TopAnalysis/EventSaverBase.h" +#include "TopEvent/EventTools.h" +#include "TopEvent/TopEventMaker.h" +#include "TopEvent/SystematicEvent.h" +#include "TopObjectSelectionTools/TopObjectSelection.h" +#include "TopObjectSelectionTools/EventCleaningSelection.h" + +#include "TopCorrections/BTagScaleFactorCalculator.h" + +// to disable the sending of file access statistics +#include "xAODRootAccess/tools/TFileAccessTracer.h" + +#include "TopAnalysis/MsgCategory.h" +// use ATH_MSG macros defined in the namespace TopAnalysis +using namespace TopAnalysis; + +/** + * @file The main executable. + * + * @brief Entry point code to perform object and event selection and write-out a + * few histograms and / or a tree in xAOD format. + * + * @return 0 If everything is okay. + */ + +// Prototype functions +std::shared_ptr<top::TopConfig> InitialiseTopSoftware(int, char**); +int TestFTag(std::shared_ptr<top::TopConfig>); + +std::shared_ptr<top::TopConfig> InitialiseTopSoftware(int argc, char** argv) { + if (argc != 3) { + ATH_MSG_INFO("Code to read an input file and return information on the" + << "anticipated systematics list in the b-tagging calibration" + << "Use like:\n" + << " " << argv[0] << " cuts.txt input.txt\n" + << " cuts.txt - file containing TopConfig\n" + << " input.txt - file containing list of input files\n" + << "\n" + << "For example\n" + << " " << argv[0] << + " $ROOTCOREBIN/data/TopAnalysis/nocuts.txt $ROOTCOREBIN/data/TopAnalysis/input-13TeV-fondueworld.txt\n"); + return 0; + } + + // to disable the sending of file access statistics + xAOD::TFileAccessTracer::enableDataSubmission(false); + + //magic xAOD stuff + //true = fail at even the slightest xaod issue + top::xAODInit(true); + StatusCode::enableFailure(); + + xAOD::TStore store; + + std::string settingsFilename = std::string(argv[1]); + ATH_MSG_INFO("Configuration Files:\n" + << settingsFilename << "\n" + << std::string(argv[2]) << "\n"); + + //load the settings from the input file + auto* const settings = top::ConfigurationSettings::get(); + settings->loadFromFile(settingsFilename); + ATH_MSG_INFO("Configuration:\n" << *settings << "\n"); + + const std::string libraryNames = settings->value("LibraryNames"); + top::loadLibraries(libraryNames); + + //load the event selection from the input file + std::string cutsFilename = std::string(settingsFilename); + + //open the files (to check they exist) and count how many events we have + std::vector<std::string> filenames = top::fileList(std::string(argv[2])); + + // A configuration that John can easily understand + // This is not the same as a good configuration + std::shared_ptr<top::TopConfig> topConfig(new top::TopConfig()); + + topConfig->setMapIndex(410501); + topConfig->setConfigSettings(settings); + xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); + // Setup all asg::AsgTools + top::TopToolStore topTools("top::TopToolStore"); + top::check(topTools.setProperty("config", topConfig), + "Failed to setProperty of topTools"); + top::check(topTools.initialize(), "Failed to initialize topTools"); + topConfig->fixConfiguration(); + ATH_MSG_INFO(*topConfig); + + return topConfig; +} + +int TestFTag(std::shared_ptr<top::TopConfig> topConfig) { + // Here we need to access the flavour tagging CP tool + // and get it to tell us what systematics are available + // given the configuration we setup up + + // Get TopCPTool handle + top::BTagScaleFactorCalculator* m_btagSF = new top::BTagScaleFactorCalculator("top::BTagScaleFactorCalculator"); + top::check(m_btagSF->setProperty("config", topConfig), "Failed to pass in the config"); + top::check(m_btagSF->initialize(), "Failed to init"); + top::check(m_btagSF->debug(), "Failed to debug"); + return 0; +} + +int main(int argc, char** argv) { + std::shared_ptr<top::TopConfig> topConfig = InitialiseTopSoftware(argc, argv); + TestFTag(topConfig); +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-xaod.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-xaod.cxx index d8a21ef32679cf2f98c188ef966feb7ab6493795..95aad4ecb79c4607eba1bbebba5b12bb0a91db18 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-xaod.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopAnalysis/util/top-xaod.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include <iostream> #include <memory> @@ -26,7 +26,7 @@ #include "TopCorrections/ScaleFactorCalculator.h" #include "TopCorrections/PDFScaleFactorCalculator.h" -#include "TopFakes/TopFakesMMWeightCalculator.h" +//#include "FakeBkgTools/AsymptMatrixTool.h" #include "TopSystematicObjectMaker/ObjectCollectionMaker.h" @@ -34,7 +34,9 @@ #include "TopConfiguration/ConfigurationSettings.h" #include "TopConfiguration/TopConfig.h" #include "TopConfiguration/SelectionConfigurationData.h" +#include "TopConfiguration/Tokenize.h" +#include "TopAnalysis/AnalysisTrackingHelper.h" #include "TopAnalysis/EventSelectionManager.h" #include "TopAnalysis/Tools.h" #include "TopCPTools/TopToolStore.h" @@ -49,18 +51,31 @@ #include "TopObjectSelectionTools/EventCleaningSelection.h" #include "TopPartons/CalcTtbarPartonHistory.h" +#include "TopPartons/CalcTtbarLightPartonHistory.h" #include "TopPartons/CalcTbbarPartonHistory.h" +#include "TopPartons/CalcWtbPartonHistory.h" +#include "TopPartons/CalcTTZPartonHistory.h" #include "TopPartons/CalcTopPartonHistory.h" +#include "TopPartons/CalcTtbarGammaPartonHistory.h" +#include "TopPartons/CalcThqPartonHistory.h" +#include "TopPartons/CalcTzqPartonHistory.h" #include "TopParticleLevel/ParticleLevelLoader.h" #include "TopDataPreparation/SampleXsection.h" -#include "TopHLUpgrade/UpgradeObjectLoader.h" +//#include "TopHLUpgrade/UpgradeObjectLoader.h" // to disable the sending of file access statistics #include "xAODRootAccess/tools/TFileAccessTracer.h" +// Path resolver +#include "PathResolver/PathResolver.h" + +#include "TopAnalysis/MsgCategory.h" +// use ATH_MSG macros defined in the namespace TopAnalysis +using namespace TopAnalysis; + /** * @file The main executable. * @@ -70,787 +85,1054 @@ * @return 0 If everything is okay. */ int main(int argc, char** argv) { - if (argc != 3) { - std::cout << "Code to perform object and event selection and write-out\n"; - std::cout << "a few histograms and / or a tree in xAOD format.\n"; - std::cout << "Use like:\n"; - std::cout << " " << argv[0] << " cuts.txt input.txt\n"; - std::cout << " cuts.txt - file containing cuts\n"; - std::cout << " input.txt - file containing list of input files\n"; - std::cout << "\n"; - std::cout << "For example\n"; - std::cout << " " << argv[0] << " $ROOTCOREBIN/data/TopAnalysis/nocuts.txt $ROOTCOREBIN/data/TopAnalysis/input-13TeV-fondueworld.txt\n"; - return 1; + if (argc != 3) { + ATH_MSG_INFO("Code to perform object and event selection and write-out\n" + << "a few histograms and / or a tree in xAOD format.\n" + << "Use like:\n" + << " " << argv[0] << " cuts.txt input.txt\n" + << " cuts.txt - file containing cuts\n" + << " input.txt - file containing list of input files\n" + << "\n" + << "For example\n" + << " " << argv[0] + << " $ROOTCOREBIN/data/TopAnalysis/nocuts.txt $ROOTCOREBIN/data/TopAnalysis/input-13TeV-fondueworld.txt\n"); + return 1; + } + + // to disable the sending of file access statistics + xAOD::TFileAccessTracer::enableDataSubmission(false); + + //magic xAOD stuff + //true = fail at even the slightest xaod issue + top::xAODInit(true); + StatusCode::enableFailure(); + + xAOD::TStore store; + + ATH_MSG_INFO("INPUT: Configuration file (argv[1]) = " + << argv[1] << "\n"); + std::string settingsFilename = PathResolver::find_file(argv[1],"DATAPATH",PathResolver::LocalSearch); + + ATH_MSG_INFO("LOCATED (using PathResolverFindFile ): Configuration file = " + << settingsFilename << "\n"); + + ATH_MSG_INFO("Configuration Files:\n" + << settingsFilename << "\n" + << argv[2] << "\n"); + + //load the settings from the input file + auto* const settings = top::ConfigurationSettings::get(); + settings->loadFromFile(settingsFilename); + ATH_MSG_INFO("Configuration:\n" << *settings << "\n"); + + const std::string libraryNames = settings->value("LibraryNames"); + top::loadLibraries(libraryNames); + + // Analysis tracking + std::unique_ptr<top::AnalysisTrackingHelper> tracker; + { + bool useTracking = true; + settings->retrieve("WriteTrackingData", useTracking); + if (useTracking) { + tracker.reset(new top::AnalysisTrackingHelper()); } - - // to disable the sending of file access statistics - xAOD::TFileAccessTracer::enableDataSubmission( false ); - - //magic xAOD stuff - //true = fail at even the slightest xaod issue - top::xAODInit(true); - StatusCode::enableFailure(); - - xAOD::TStore store; - - std::cout << "Configuration Files:\n"; - std::string settingsFilename = std::string(argv[1]); - std::cout << " " << settingsFilename << "\n"; - std::cout << " " << std::string(argv[2]) << "\n\n"; - - //load the settings from the input file - auto* const settings = top::ConfigurationSettings::get(); - settings->loadFromFile(settingsFilename); - std::cout << "Configuration:\n"; - std::cout << *settings << "\n"; - - const std::string libraryNames = settings->value("LibraryNames"); - top::loadLibraries(libraryNames); - - // I/O Performance stats? - // Summary gives a summary - // Full gives detailed info on each collection in the file - unsigned int doPerfStats(0); - if (settings->value("PerfStats") == "Summary") - doPerfStats = 1; - - if (settings->value("PerfStats") == "Full") - doPerfStats = 2; - - //load the event selection from the input file - std::string cutsFilename = std::string(settingsFilename); - - //open the files (to check they exist) and count how many events we have - std::vector<std::string> filenames = top::fileList(std::string(argv[2])); - unsigned int totalYield = top::checkFiles(filenames); - - //open output file - std::unique_ptr<TFile> outputFile(TFile::Open((settings->value("OutputFilename") + ".tmp").c_str(), "RECREATE")); - - // A configuration that John can easily understand - // This is not the same as a good configuration - std::shared_ptr<top::TopConfig> topConfig(new top::TopConfig()); - - // load AOD meta-data from all files - bool useAodMetaData = false; - settings->retrieve("UseAodMetaData", useAodMetaData); - if (useAodMetaData) { - std::cout << "Loading meta-data from input files ... " << std::flush; - topConfig->aodMetaData().loadWithFilesFrom(argv[2]); - std::cout << "OK." << std::endl; + } + + // I/O Performance stats? + // Summary gives a summary + // Full gives detailed info on each collection in the file + unsigned int doPerfStats(0); + if (settings->value("PerfStats") == "Summary") doPerfStats = 1; + + if (settings->value("PerfStats") == "Full") doPerfStats = 2; + + //load the event selection from the input file + std::string cutsFilename = std::string(settingsFilename); + + //open the files (to check they exist) and count how many events we have + std::vector<std::string> filenames = top::fileList(std::string(argv[2])); + size_t totalYield = top::checkFiles(filenames); + + //open output file + std::unique_ptr<TFile> outputFile(TFile::Open((settings->value("OutputFilename") + ".tmp").c_str(), "RECREATE")); + + // A configuration that John can easily understand + // This is not the same as a good configuration + std::shared_ptr<top::TopConfig> topConfig(new top::TopConfig()); + + // load AOD meta-data from all files + bool useAodMetaData = false; + settings->retrieve("UseAodMetaData", useAodMetaData); + if (useAodMetaData) { + ATH_MSG_INFO("Loading meta-data from input files ... "); + topConfig->aodMetaData().loadWithFilesFrom(argv[2]); + ATH_MSG_INFO("OK."); + } + + + //picking the first file was a bad idea because in the derivations it often + //has no events (no CollectionTree). Be sure to pick a file with events in + //it... + // The isMC flag needs to be taken from the xAOD metadata + // We also need something for AFII + { + std::string usethisfile = filenames[0]; + bool atLeastOneFileIsValid(false); + for (const auto& filename : filenames) { + std::unique_ptr<TFile> checkingYieldFile(TFile::Open(filename.c_str())); + + //collection tree means > 0 events + const TTree* const collectionTree = dynamic_cast<TTree* > (checkingYieldFile->Get("CollectionTree")); + if (collectionTree) { + usethisfile = filename; + atLeastOneFileIsValid = true; + break; + } } - //picking the first file was a bad idea because in the derivations it often - //has no events (no CollectionTree). Be sure to pick a file with events in - //it... - // The isMC flag needs to be taken from the xAOD metadata - // We also need something for AFII - { - std::string usethisfile = filenames[0]; - bool atLeastOneFileIsValid(false); - for (const auto& filename : filenames) { - std::unique_ptr<TFile> checkingYieldFile(TFile::Open(filename.c_str())); - - //collection tree means > 0 events - const TTree* const collectionTree = dynamic_cast<TTree* > (checkingYieldFile->Get("CollectionTree")); - if (collectionTree) { - usethisfile = filename; - atLeastOneFileIsValid = true; - break; - } - } + // If there are no valid files, let's exit cleanly + if (!(atLeastOneFileIsValid || useAodMetaData)) { + ATH_MSG_ERROR("No input file contains a CollectionTree and no metadata used. Cannot Continue."); + ATH_MSG_ERROR("If you had turned on 'UseAodMetaData' in your configuration, " + "we could overcome this limitation."); + return 1; + } - // If there are no valid files, let's exit cleanly - if (!(atLeastOneFileIsValid || useAodMetaData)) { - std::cout << "No input file contains a CollectionTree -- exiting.\n" - << "Unfortunately, we don't have enough information to prepare an output file for\n" - << "you. If you had turned on 'UseAodMetaData' in your configuration, we could\n" - << "overcome this limitation.\n" << std::endl; - return 1; - } + std::unique_ptr<TFile> testFile(TFile::Open(usethisfile.c_str())); + if (!top::readMetaData(testFile.get(), topConfig)) { + ATH_MSG_ERROR("Unable to access FileMetaData and/or TruthMetaData in this file : " << usethisfile + << "\nPlease report this message."); + } - std::unique_ptr<TFile> testFile(TFile::Open(usethisfile.c_str())); - bool const isMC = (useAodMetaData ? + const bool isOverlay = useAodMetaData ? topConfig->aodMetaData().IsEventOverlayInputSim() : false; + bool isMC(true); + if (!isOverlay) { + isMC = (useAodMetaData ? topConfig->aodMetaData().isSimulation() : top::isFileSimulation(testFile.get(), topConfig->sgKeyEventInfo()) - ); - topConfig->setIsMC(isMC); - - const bool isPrimaryxAOD = top::isFilePrimaryxAOD(testFile.get()); - topConfig->setIsPrimaryxAOD(isPrimaryxAOD); - - const std::string derivationStream = top::getDerivationStream(testFile.get()); - std::cout << "Derivation stream is -> " << derivationStream << std::endl; - topConfig->setDerivationStream(derivationStream); - - if(isMC){ - ///-- Are we using a truth derivation (no reco information)? --/// - ///-- Let's find out in the first event, this could be done better --/// - bool isTruthDxAOD = top::isTruthDxAOD(testFile.get()); - topConfig->setIsTruthDxAOD(isTruthDxAOD); - - if (!isTruthDxAOD && atLeastOneFileIsValid) { - unsigned int DSID = top::getDSID(testFile.get(), topConfig->sgKeyEventInfo()); - topConfig -> setDSID(DSID); - - // now need to get and set the parton shower generator from TopDataPrep - SampleXsection tdp; - const char* const rc = getenv("ROOTCOREBIN"); - std::string filename = std::string(rc) + "/data/TopDataPreparation/XSection-MC15-13TeV.data"; - - if (!tdp.readFromFile(filename.c_str())) { - std::cout << "ERROR::TopDataPreparation - could not read file \n"; - std::cout << filename << "\n"; - exit(1); - } - - int ShowerIndex = tdp.getShoweringIndex(DSID); - std::cout << "DSID: " << DSID << "\t" << "ShowerIndex: " << ShowerIndex << std::endl; - topConfig->setMapIndex(ShowerIndex); - } - } - } //close and delete the ptr to testFile - - // Pass the settings file to the TopConfig - topConfig->setConfigSettings(settings); - - //In rel 19 we had a function to guess Class or Branch Access. - //In rel20 just use branch (quicker) - // In rel 20.7, need to go back to class access - xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); - - // Setup all asg::AsgTools - top::TopToolStore topTools("top::TopToolStore"); - top::check(topTools.setProperty("config", topConfig), - "Failed to setProperty of topTools"); - top::check(topTools.initialize() , "Failed to initialize topTools"); - // EventCleaningSelection - // Decorates EventInfo with GRL decision (always true for MC) - // Evaluates all triggers requested from all selections - // Trigger matching - // Check for good Tile and LAr calorimeters - // Let's check this passes before running expensive calibrations - // If ANY selection does not request a trigger, we won't veto any events - - std::unique_ptr<top::EventCleaningSelection> eventCleaning( new top::EventCleaningSelection("top::EventCleaningSelection") ); - top::check(eventCleaning->setProperty("config", topConfig), - "Failed to setProperty of triggerGRLSelection" ); - top::check(eventCleaning->initialize(), - "Failed to initialize triggerGRLSelection"); - eventCleaning->setEventSelections(settings->selections()); - - - // Systematic object collection making - std::unique_ptr<top::ObjectCollectionMaker> systObjMaker( new top::ObjectCollectionMaker( "top::ObjectCollectionMaker" ) ); - top::check( systObjMaker->setProperty( "config" , topConfig ) , "Failed to setProperty of systObjMaker" ); - if (!topConfig->isTruthDxAOD()) - top::check( systObjMaker->initialize() , "Failed to initialize systObjMaker" ); - - //setup object definitions - std::unique_ptr<top::TopObjectSelection> objectSelection(top::loadObjectSelection(topConfig)); - objectSelection->print(std::cout); + ); + } - //setup event-level cuts - top::EventSelectionManager eventSelectionManager(settings->selections(), outputFile.get(), libraryNames, topConfig); + topConfig->setIsMC(isMC); + + const bool isPrimaryxAOD = top::isFilePrimaryxAOD(testFile.get()); + topConfig->setIsPrimaryxAOD(isPrimaryxAOD); + + const std::string derivationStream = top::getDerivationStream(testFile.get()); + ATH_MSG_INFO("Derivation stream is -> " << derivationStream); + topConfig->setDerivationStream(derivationStream); + + // first we need to read some metadata before we read the config + if (isMC) { + // check number of MC generator weights -- we need this before start initializing PMGTruthWeightTool later + if (atLeastOneFileIsValid) topConfig->setMCweightsVectorSize(top::MCweightsSize(testFile.get(), topConfig->sgKeyEventInfo())); + ///-- Are we using a truth derivation (no reco information)? --/// + ///-- Let's find out in the first event, this could be done better --/// + bool isTruthDxAOD = top::isTruthDxAOD(testFile.get()); + topConfig->setIsTruthDxAOD(isTruthDxAOD); + + unsigned int DSID {0}; + if (!useAodMetaData) { + if (atLeastOneFileIsValid) { + DSID = top::getDSID(testFile.get(), topConfig->sgKeyEventInfo()); + topConfig->setDSID(DSID); + } else { + ATH_MSG_ERROR("We could not determine DSID for this sample from either CollectionTree, or FileMetaData, or TruthMetaData. There is something seriously wrong with this sample."); + return 1; + } + } else { + DSID = topConfig->getDSID(); + } + } - //The loader tool for top::ParticleLevelEvent objects - top::ParticleLevelLoader particleLevelLoader( topConfig ); - // The loader tool for Upgrade objects - top::UpgradeObjectLoader upgradeLoader( topConfig ); - // Fix the configuration - it now knows about: - // * all objects collections to work with - // * all systematic variations - topConfig->fixConfiguration(); + // Pass the settings file to the TopConfig + topConfig->setConfigSettings(settings); + if (isMC && !topConfig->isTruthDxAOD()) { + // now need to get and set the parton shower generator from TopDataPrep + SampleXsection tdp; + // Package/filename - XS file we want to use (can now be configured via cutfile) + const std::string tdp_filename = settings->value("TDPPath"); + // Use the path resolver to find the first file in the list of possible paths ($CALIBPATH) + const std::string fullpath = PathResolverFindCalibFile(tdp_filename); + if (!tdp.readFromFile(fullpath.c_str())) { + ATH_MSG_ERROR("TopDataPreparation - could not read file\n" << tdp_filename); + return 1; + } + ATH_MSG_INFO("SampleXsection::Found " << fullpath); - // OK let's printout the TopConfig - std::cout << *topConfig << "\n"; + tdp.setTranslator(topConfig->GetMCMCTranslator()); - //Top parton history for MC events - // This is quite ugly and simple, it will be harmonized with in the future - // along with all other factory methods (it's not a factory method right now) - std::unique_ptr<top::CalcTopPartonHistory> topPartonHistory(nullptr); - if(settings->value("TopPartonHistory") == "ttbar"){ - topPartonHistory = std::unique_ptr<top::CalcTopPartonHistory> ( new top::CalcTtbarPartonHistory( "top::CalcTtbarPartonHistory" ) ); - top::check(topPartonHistory->setProperty( "config" , topConfig ) , "Failed to setProperty of top::CalcTtbarPartonHistory"); + int ShowerIndex = tdp.getShoweringIndex(topConfig->getDSID()); + ATH_MSG_INFO("DSID: " << topConfig->getDSID() << "\t" << "ShowerIndex: " << ShowerIndex << " PS generator: "<< tdp.getShoweringString(topConfig->getDSID())); + topConfig->setMapIndex(ShowerIndex); + topConfig->setShoweringAlgorithm(tdp.getShowering(topConfig->getDSID())); } - else if(settings->value("TopPartonHistory") == "tb"){ - topPartonHistory = std::unique_ptr<top::CalcTopPartonHistory> ( new top::CalcTbbarPartonHistory( "top::CalcTbbarPartonHistory" ) ); - top::check(topPartonHistory->setProperty( "config" , topConfig ) , "Failed to setProperty of top::CalcTbbarPartonHistory"); + // check year + { + xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); + top::check(xaodEvent.readFrom(testFile.get()), "Failed to read file in"); + const unsigned int entries = xaodEvent.getEntries(); + if (entries > 0) { + xaodEvent.getEntry(0); + const xAOD::EventInfo* eventInfo(nullptr); + top::check(xaodEvent.retrieve(eventInfo, topConfig->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + const unsigned int runnumber = eventInfo->runNumber(); + const std::string thisYear = topConfig->getYear(runnumber, isMC); + topConfig->SetYear(thisYear); + } else { + topConfig->SetYear("UNKNOWN"); + } + topConfig->SetTriggersToYear(isMC); } - //LHAPDF SF calculation - std::unique_ptr<top::PDFScaleFactorCalculator> PDF_SF(nullptr); - PDF_SF = std::unique_ptr<top::PDFScaleFactorCalculator> (new top::PDFScaleFactorCalculator( "top::PDFScaleFactorCalculator" ) ); - if ( topConfig->doLHAPDF() ){ - top::check( PDF_SF->setProperty( "config", topConfig ), "Failed to set config for PDF SF Calculator" ); - top::check( PDF_SF->initialize(), "Failed to initialize PDF SF calculator" ); + } //close and delete the ptr to testFile + + + //In rel 19 we had a function to guess Class or Branch Access. + //In rel20 just use branch (quicker) + // In rel 20.7, need to go back to class access + xAOD::TEvent xaodEvent(xAOD::TEvent::kClassAccess); + + // Read metadata + std::unique_ptr<TFile> metadataInitFile(TFile::Open(filenames[0].c_str())); + top::check(xaodEvent.readFrom(metadataInitFile.get()), "xAOD::TEvent readFrom failed"); + + + // Setup all asg::AsgTools + top::TopToolStore topTools("top::TopToolStore"); + top::check(topTools.setProperty("config", topConfig), + "Failed to setProperty of topTools"); + top::check(topTools.initialize(), "Failed to initialize topTools"); + // EventCleaningSelection + // Decorates EventInfo with GRL decision (always true for MC) + // Evaluates all triggers requested from all selections + // Trigger matching + // Check for good Tile and LAr calorimeters + // Let's check this passes before running expensive calibrations + // If ANY selection does not request a trigger, we won't veto any events + + std::unique_ptr<top::EventCleaningSelection> eventCleaning(new top::EventCleaningSelection( + "top::EventCleaningSelection")); + top::check(eventCleaning->setProperty("config", topConfig), + "Failed to setProperty of triggerGRLSelection"); + top::check(eventCleaning->initialize(), + "Failed to initialize triggerGRLSelection"); + eventCleaning->setEventSelections(settings->selections()); + + + // Systematic object collection making + std::unique_ptr<top::ObjectCollectionMaker> systObjMaker(new top::ObjectCollectionMaker("top::ObjectCollectionMaker")); + top::check(systObjMaker->setProperty("config", topConfig), "Failed to setProperty of systObjMaker"); + if (!topConfig->isTruthDxAOD()) top::check(systObjMaker->initialize(), "Failed to initialize systObjMaker"); + + //setup object definitions - not used in HLUpgrade tools + std::unique_ptr<top::TopObjectSelection> objectSelection; + if (!topConfig->HLLHC()) { + objectSelection.reset(top::loadObjectSelection(topConfig)); + objectSelection->print(msg(MSG::Level::INFO)); // forward to msg stream using INFO level + } + + //setup event-level cuts + top::EventSelectionManager eventSelectionManager(settings->selections(), outputFile.get(), libraryNames, topConfig); + + //The loader tool for top::ParticleLevelEvent objects + top::ParticleLevelLoader particleLevelLoader(topConfig); + + // The loader tool for Upgrade objects +// top::UpgradeObjectLoader upgradeLoader(topConfig); + + // Fix the configuration - it now knows about: + // * all objects collections to work with + // * all systematic variations + topConfig->fixConfiguration(); + + + // OK let's printout the TopConfig + ATH_MSG_INFO(*topConfig << "\n"); + if (tracker) tracker->setTopConfig(topConfig); + + //Top parton history for MC events + // This is quite ugly and simple, it will be harmonized with in the future + // along with all other factory methods (it's not a factory method right now) + std::unique_ptr<top::CalcTopPartonHistory> topPartonHistory(nullptr); + if (settings->value("TopPartonHistory") == "ttbar") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory> (new top::CalcTtbarPartonHistory("top::CalcTtbarPartonHistory")); + top::check(topPartonHistory->setProperty("config", + topConfig), "Failed to setProperty of top::CalcTtbarPartonHistory"); + } else if (settings->value("TopPartonHistory") == "ttbarlight") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory> (new top::CalcTtbarLightPartonHistory( + "top::CalcTtbarLightPartonHistory")); + top::check(topPartonHistory->setProperty("config", + topConfig), "Failed to setProperty of top::CalcTtbarLightPartonHistory"); + } else if (settings->value("TopPartonHistory") == "tb") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory> (new top::CalcTbbarPartonHistory("top::CalcTbbarPartonHistory")); + top::check(topPartonHistory->setProperty("config", + topConfig), "Failed to setProperty of top::CalcTbbarPartonHistory"); + } else if (settings->value("TopPartonHistory") == "Wtb") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory> (new top::CalcWtbPartonHistory("top::CalcWtbPartonHistory")); + top::check(topPartonHistory->setProperty("config", topConfig), + "Failed to setProperty of top::CalcWtbPartonHistory"); + } else if (settings->value("TopPartonHistory") == "ttz") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory> (new top::CalcTTZPartonHistory("top::CalcTTZPartonHistory")); + top::check(topPartonHistory->setProperty("config", topConfig), + "Failed to setProperty of top::CalcTTZPartonHistory"); + } else if (settings->value("TopPartonHistory") == "ttgamma") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory> (new top::CalcTtbarGammaPartonHistory( + "top::CalcTtbarGammaPartonHistory")); + top::check(topPartonHistory->setProperty("config", + topConfig), "Failed to setProperty of top::CalcTtbarGammaPartonHistory"); + } else if (settings->value("TopPartonHistory") == "tHq") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory>(new top::CalcThqPartonHistory("top::CalcThqPartonHistory")); + top::check(topPartonHistory->setProperty("config", topConfig), + "Failed to setProperty of top::CalcThqPartonHistory"); + } else if (settings->value("TopPartonHistory") == "tZq") { + topPartonHistory = + std::unique_ptr<top::CalcTopPartonHistory>(new top::CalcTzqPartonHistory("top::CalcTzqPartonHistory")); + top::check(topPartonHistory->setProperty("config", topConfig), + "Failed to setProperty of top::CalcTzqPartonHistory"); + } + + + //LHAPDF SF calculation + std::unique_ptr<top::PDFScaleFactorCalculator> PDF_SF(nullptr); + PDF_SF = + std::unique_ptr<top::PDFScaleFactorCalculator> (new top::PDFScaleFactorCalculator("top::PDFScaleFactorCalculator")); + if (topConfig->doLHAPDF()) { + top::check(PDF_SF->setProperty("config", topConfig), "Failed to set config for PDF SF Calculator"); + top::check(PDF_SF->initialize(), "Failed to initialize PDF SF calculator"); + } + + + // make top::Event objects + std::unique_ptr<top::TopEventMaker> topEventMaker(new top::TopEventMaker("top::TopEventMaker")); + top::check(topEventMaker->setProperty("config", topConfig), "Failed to setProperty of top::TopEventMaker"); + top::check(topEventMaker->initialize(), "Failed to initialize top::TopEventMaker"); + // Debug messages? + // topEventMaker.msg().setLevel(MSG::DEBUG); + + std::unique_ptr<top::ScaleFactorCalculator> topScaleFactors(new top::ScaleFactorCalculator( + "top::ScaleFactorCalculator")); + top::check(topScaleFactors->setProperty("config", topConfig), "Failed to setProperty of top::ScaleFactorCalculator"); + top::check(topScaleFactors->initialize(), "Failed to initialize top::ScaleFactorCalculator"); + + //std::vector<std::unique_ptr<CP::AsymptMatrixTool> > topfakesMMWeightsIFF; + //std::vector<std::vector<std::string> > FakesMMConfigIFF; + //if (!topConfig->isMC() && topConfig->doLooseEvents() && topConfig->doFakesMMWeightsIFF()) { + // if (topConfig->FakesMMConfigIFF() != "") { + // std::vector<std::string> tokens; + // top::tokenize(topConfig->FakesMMConfigIFF(), tokens, ";"); + // std::reverse(tokens.begin(), tokens.end()); + // while (tokens.size()) { + // const auto& token = tokens.back(); + // std::vector<std::string> tokens2; + // top::tokenize(token, tokens2, ":"); + // top::check(tokens2.size() == 3, + // "Failed to read FakesMMConfigIFF: " + topConfig->FakesMMConfigIFF() + " has size " + + // std::to_string(tokens2.size()) + " (should be 3)"); + // FakesMMConfigIFF.push_back(tokens2); + // FakesMMConfigIFF.back()[0] = PathResolverFindCalibFile(tokens2[0]); + // tokens.pop_back(); + // } + // } + // for (unsigned int mmi = 0; mmi < FakesMMConfigIFF.size(); ++mmi) { + // topfakesMMWeightsIFF.emplace_back(std::make_unique<CP::AsymptMatrixTool>("AsymptMatrixTool_" + std::to_string (mmi))); + // top::check(topfakesMMWeightsIFF.back()->setProperty("InputFiles", + // std::vector<std::string>{FakesMMConfigIFF[mmi][0]}), + // "Failed To setProperty InputFiles of AsymptMatrixTool"); + // top::check(topfakesMMWeightsIFF.back()->setProperty("Selection", + // FakesMMConfigIFF[mmi][1]), + // "Failed to set the selection FakesMMIFFConfigs for selection " + FakesMMConfigIFF[mmi][1]); + // top::check(topfakesMMWeightsIFF.back()->setProperty("Process", + // FakesMMConfigIFF[mmi][2]), + // "Failed to set the selection FakesMMIFFConfigs for process " + FakesMMConfigIFF[mmi][2]); + // top::check(topfakesMMWeightsIFF.back()->setProperty("EnergyUnit", + // "GeV"), + // "Failed to setProperty EnergyUnit of AsymptMatrixTool"); + // top::check(topfakesMMWeightsIFF.back()->setProperty("ConvertWhenMissing", + // true), + // "Failed to setProperty ConvertWhenMissing of AsymptMatrixTool"); + // top::check(topfakesMMWeightsIFF.back()->setProperty("TightDecoration", + // "passPreORSelection,as_char"), + // "Failed to setProperty TightDecoration of AsymptMatrixTool"); + // if (topConfig->FakesMMIFFDebug()) top::check(topfakesMMWeightsIFF.back()->setProperty("OutputLevel", + // MSG::INFO), + // "Failed to setProperty of AsymptMatrixTool"); + // top::check(topfakesMMWeightsIFF.back()->initialize(), "Failed to initialize AsymptMatrixTool"); + // } + //} + + //A list of extra branches that we create in this code and want to save + std::vector<std::string> extraBranches; + eventSelectionManager.addExtraBranches(extraBranches); + + //output file format (and any user-modified code) + std::unique_ptr<top::EventSaverBase> eventSaver(top::loadEventSaver(topConfig)); + eventSaver->initialize(topConfig, outputFile.get(), extraBranches); + + // save sum of weights before derivations + outputFile->cd(); + TTree* sumWeights = new TTree("sumWeights", ""); + float totalEventsWeighted = 0; + double totalEventsWeighted_temp = 0; + std::vector<float> totalEventsWeighted_LHE3; + std::vector<double> totalEventsWeighted_LHE3_temp;// having doubles is necessary in case of re-calculation of the sum + // of weights on the fly + std::vector<std::string> names_LHE3; + bool recalc_LHE3 = false; + bool recalculateNominalWeightSum = false; + int dsid = topConfig->getDSID(); + int isAFII = topConfig->isAFII(); + std::string generators = topConfig->getGenerators(); + std::string AMITag = topConfig->getAMITag(); + ULong64_t totalEvents = 0; + ULong64_t totalEventsInFiles = 0; + sumWeights->Branch("dsid", &dsid); + sumWeights->Branch("isAFII", &isAFII); + sumWeights->Branch("generators", &generators); + sumWeights->Branch("AMITag", &AMITag); + sumWeights->Branch("totalEventsWeighted", &totalEventsWeighted); + if (topConfig->doMCGeneratorWeights()) {// the main problem is that we don't have the list of names a priori + sumWeights->Branch("totalEventsWeighted_mc_generator_weights", &totalEventsWeighted_LHE3); + sumWeights->Branch("names_mc_generator_weights", &names_LHE3); + } + sumWeights->Branch("totalEvents", &totalEvents, "totalEvents/l"); + + TTree* sumPdfWeights = 0; + std::unordered_map<std::string, std::vector<float>*> totalEventsPdfWeighted; + int dsidPdf = topConfig->getDSID(); + bool pdfMetadataExists = false; + if (topConfig->doLHAPDF()) { + sumPdfWeights = new TTree("PDFsumWeights", ""); + sumPdfWeights->Branch("dsid", &dsidPdf); + for (const auto& pdf_set : topConfig->LHAPDFSets()) { + totalEventsPdfWeighted[pdf_set] = new std::vector<float>(); + sumPdfWeights->Branch(pdf_set.c_str(), totalEventsPdfWeighted[pdf_set]); } - - - // make top::Event objects - std::unique_ptr<top::TopEventMaker> topEventMaker( new top::TopEventMaker( "top::TopEventMaker" ) ); - top::check(topEventMaker->setProperty( "config" , topConfig ) , "Failed to setProperty of top::TopEventMaker"); - // Debug messages? - // topEventMaker.msg().setLevel(MSG::DEBUG); - - std::unique_ptr<top::ScaleFactorCalculator> topScaleFactors( new top::ScaleFactorCalculator("top::ScaleFactorCalculator") ); - top::check(topScaleFactors->setProperty( "config" , topConfig ) , "Failed to setProperty of top::ScaleFactorCalculator"); - top::check(topScaleFactors->initialize(),"Failed to initialize top::ScaleFactorCalculator"); - - ///-- weights for matrix-method fakes estimate --/// - std::unique_ptr<top::TopFakesMMWeightCalculator> topfakesMMWeights(nullptr); - if (!topConfig->isMC() && topConfig->doLooseEvents() && topConfig->doFakesMMWeights()) { - topfakesMMWeights = std::unique_ptr<top::TopFakesMMWeightCalculator>( new top::TopFakesMMWeightCalculator() ); - top::check(topfakesMMWeights->setProperty( "config" , topConfig ) , "Failed to setProperty of top::TopFakesMMWeightCalculator"); - top::check(topfakesMMWeights->initialize(),"Failed to initialize top::TopFakesMMWeightCalculator"); - for (auto sel : settings->selections()) { - top::check(topfakesMMWeights->setSelectionConfigs(sel.m_name, eventSelectionManager.GetFakesMMConfigs(sel.m_name)),"Failed to set the selection FakesMMConfigs for selection"+sel.m_name); + } + + //the analysis loop + ATH_MSG_INFO("Starting event loop\n"); + + // Performance stats + if (doPerfStats > 0) xAOD::PerfStats::instance().start(); // start Perfstats timer + + unsigned int totalYieldSoFar = 0; + unsigned int skippedEventsSoFar = 0; + unsigned int eventSavedReco(0), eventSavedRecoLoose(0), eventSavedTruth(0), eventSavedParticle(0); +// unsigned int eventSavedUpgrade(0); + + // Close the file that we opened only for metadata + metadataInitFile->Close(); + + for (const auto& filename : filenames) { + if (topConfig->numberOfEventsToRun() != 0 && totalYieldSoFar >= topConfig->numberOfEventsToRun()) break; + ATH_MSG_INFO("Opening " << filename); + std::unique_ptr<TFile> inputFile(TFile::Open(filename.c_str())); + + // the derivation framework is making files with an empty collection tree + // which TEvent can now handle + // However, at least for data, this is causing problems with the trigger menu + // skip the file, after the meta data access above + const TTree* const collectionTree = dynamic_cast<TTree* > (inputFile->Get("CollectionTree")); + if (!collectionTree && !topConfig->isMC()) { + if (top::ConfigurationSettings::get()->feature("SkipInputFilesWithoutCollectionTree")) { + ATH_MSG_INFO("No CollectionTree found, skipping file"); + continue; } } - //A list of extra branches that we create in this code and want to save - std::vector<std::string> extraBranches; - eventSelectionManager.addExtraBranches(extraBranches); - - //output file format (and any user-modified code) - std::unique_ptr<top::EventSaverBase> eventSaver(top::loadEventSaver(topConfig)); - eventSaver->initialize(topConfig, outputFile.get(), extraBranches); - - // save sum of weights before derivations - outputFile->cd(); - TTree* sumWeights = new TTree("sumWeights", ""); - float totalEventsWeighted = 0; - std::vector<float> totalEventsWeighted_LHE3; - std::vector<double> totalEventsWeighted_LHE3_temp;// having doubles is necessary in case of re-calculation of the sum of weights on the fly - std::vector<std::string> names_LHE3; - bool recalc_LHE3 = false; - int dsid = 0; - ULong64_t totalEvents = 0; - ULong64_t totalEventsInFiles = 0; - sumWeights->Branch("dsid", &dsid); - sumWeights->Branch("totalEventsWeighted", &totalEventsWeighted); - if (topConfig->doMCGeneratorWeights()) {// the main problem is that we don't have the list of names a priori - sumWeights->Branch("totalEventsWeighted_mc_generator_weights", &totalEventsWeighted_LHE3); - sumWeights->Branch("names_mc_generator_weights", &names_LHE3); + top::check(xaodEvent.readFrom(inputFile.get()), "xAOD::TEvent readFrom failed"); + + // Sum of weights and raw number of entries before skimming in current file + double sumW_file = 0; + ULong64_t initialEvents = 0; + + // vector of MC generator weights and their names in current file + std::vector<float> LHE3_sumW_file; + std::vector<std::string> LHE3_names_file; + + // See https://twiki.cern.ch/twiki/bin/view/AtlasProtected/AnalysisMetadata#Event_Bookkeepers + const xAOD::CutBookkeeperContainer* cutBookKeepers = 0; + // Try to get the cut bookkeepers. + // <tom.neep@cern.ch> (4/4/16): Not there in DAOD_TRUTH1? + // If we can't get them and we are running on TRUTH then carry on, + // but anything else is bad! + if(topConfig->isTruthDxAOD()) + { + ATH_MSG_INFO("Bookkeepers are not read for TRUTH derivations"); } - sumWeights->Branch("totalEvents", &totalEvents, "totalEvents/l"); + else if (!xaodEvent.retrieveMetaInput(cutBookKeepers, "CutBookkeepers")) { + ATH_MSG_ERROR("Failed to retrieve cut book keepers"); + return 1; + } else { + if (topConfig->isMC()) { + // try to retrieve CutBookKeepers for LHE3Weights first + top::parseCutBookkeepers(cutBookKeepers, LHE3_names_file, LHE3_sumW_file, topConfig->HLLHC()); + + // here we attempt to name the CutBookkeepers based on the MC weight names + // but we might end up in a situation where we don't have PMGTruthWeightTool + // e.g. if TruthMetaData container is broken in derivation + // we continue without names of the MC weights, only indices will be available + ToolHandle<PMGTools::IPMGTruthWeightTool> m_pmg_weightTool("PMGTruthWeightTool"); + if (m_pmg_weightTool.retrieve()) { + const std::vector<std::string> &weight_names = m_pmg_weightTool->getWeightNames(); + // if we have MC generator weights, we rename the bookkeepers in sumWeights TTree to match the weight names from MetaData + top::renameCutBookkeepers(LHE3_names_file, weight_names); + } else { + for (std::string &name : LHE3_names_file) { + name = "?"; + } + } - TTree* sumPdfWeights = 0; - std::unordered_map<std::string, std::vector<float> *> totalEventsPdfWeighted; - int dsidPdf = 0; - bool pdfMetadataExists = false; - if (topConfig->doLHAPDF()) { - sumPdfWeights = new TTree("PDFsumWeights", ""); - sumPdfWeights->Branch("dsid", &dsidPdf); - for (const auto &pdf_set : topConfig->LHAPDFSets()) { - totalEventsPdfWeighted[pdf_set] = new std::vector<float>(); - sumPdfWeights->Branch(pdf_set.c_str(), totalEventsPdfWeighted[pdf_set]); + // raw number of events taken from "AllExecutedEvents" bookkeeper, which corresponds to 0th MC weight + // but these are raw entries, so doesn't matter if 0th MC weight is nominal or not + initialEvents = top::getRawEventsBookkeeper(cutBookKeepers, topConfig->HLLHC()); + + // determine the nominal sum of weight -- we already found the nominal weight in ScaleFactorCalculator + const size_t nominalWeightIndex = topConfig->nominalWeightIndex(); + sumW_file = LHE3_sumW_file.at(nominalWeightIndex); + } else { + initialEvents = top::getRawEventsBookkeeper(cutBookKeepers, topConfig->HLLHC()); + sumW_file = initialEvents; // this is data, it's the same number... } } - //the analysis loop - std::cout << "Starting event loop\n"; + totalEventsWeighted += sumW_file; + totalEvents += initialEvents; - // Performance stats - if (doPerfStats > 0) - xAOD::PerfStats::instance().start(); // start Perfstats timer - - unsigned int totalYieldSoFar = 0; - unsigned int skippedEventsSoFar = 0; - unsigned int eventSavedReco(0),eventSavedRecoLoose(0),eventSavedTruth(0),eventSavedParticle(0); - for (const auto& filename : filenames) { - if (topConfig->numberOfEventsToRun() != 0 && totalYieldSoFar >= topConfig->numberOfEventsToRun() ) break; - std::cout << "Opening " << filename << std::endl; - std::unique_ptr<TFile> inputFile(TFile::Open(filename.c_str())); - - // the derivation framework is making files with an empty collection tree - // which TEvent can now handle - // However, at least for data, this is causing problems with the trigger menu - // skip the file, after the meta data access above - const TTree* const collectionTree = dynamic_cast<TTree* > (inputFile->Get("CollectionTree")); - if (!collectionTree && !topConfig->isMC()) { - std::cout << "No CollectionTree found, skipping file\n"; - continue; + // now we must fill two vectors in sync for MCGeneratorWeights sum of weights + if (topConfig->doMCGeneratorWeights() && topConfig->isMC()) { + if (totalEventsWeighted_LHE3.size() != 0) { + if (totalEventsWeighted_LHE3.size() != LHE3_sumW_file.size() + || names_LHE3.size() != LHE3_names_file.size() + || names_LHE3.size() != totalEventsWeighted_LHE3.size()) { + ATH_MSG_ERROR("Strange inconsistency of vector sizes in sum of LHE3 weights calculation."); + return 1; } - - top::check(xaodEvent.readFrom(inputFile.get()), "xAOD::TEvent readFrom failed"); - - //Get some of event weights before derivation - double initialSumOfWeightsInThisFile = 0; - ULong64_t initialEvents = 0; - - // vector of LH3 weights and teir names - std::vector<float> initialSumOfWeights_mc_generator_weightsInThisFile; - std::vector<std::string> initialSumOfWeights_mc_generator_namesInThisFile; - - // vector of PDF weights and their names - std::vector<float> initialSumOfWeights_pdf_weightsInThisFile; - std::vector<std::string> initialSumOfWeights_pdf_namesInThisFile; - - // See https://twiki.cern.ch/twiki/bin/view/AtlasProtected/AnalysisMetadata#Event_Bookkeepers - const xAOD::CutBookkeeperContainer* cutBookKeepers = 0; - // Try to get the cut bookkeepers. - // <tom.neep@cern.ch> (4/4/16): Not there in DAOD_TRUTH1? - // If we can't get them and we are running on TRUTH then carry on, - // but anything else is bad! - if (!xaodEvent.retrieveMetaInput(cutBookKeepers, "CutBookkeepers")) { - top::check(topConfig->isTruthDxAOD(), - "Failed to retrieve cut book keepers"); - } else { - int maxCycle = -1; - std::vector<int> maxCycle_LH3;// for LHE3 weights - // for the sum of number of events and of mc event weights - for ( auto cbk : *cutBookKeepers ) { - // skip RDO and ESD numbers, which are nonsense; and - // skip the derivation number, which is the one after skimming - // we want the primary xAOD numbers - if (cbk->inputStream() == "StreamAOD" && cbk->name() == "AllExecutedEvents") { - double sumOfEventWeights = cbk->sumOfEventWeights(); - ULong64_t nEvents = cbk->nAcceptedEvents(); - if (cbk->cycle() > maxCycle) { - initialSumOfWeightsInThisFile = sumOfEventWeights; - initialEvents = nEvents; - maxCycle = cbk->cycle(); - } - } - else if (cbk->inputStream() == "StreamAOD" && cbk->name().find("LHE3Weight_") != std::string::npos - && topConfig->doMCGeneratorWeights()) { - double sumOfEventWeights = cbk->sumOfEventWeights(); - std::string name=cbk->name(); - name.erase(0,11); // remove the "LHE3Weight_" - // is it a new name? If yes append it to the vector of names - // if not no need, but we must check the corresponding entry for the sum of weights exist - auto pos_name = std::find(initialSumOfWeights_mc_generator_namesInThisFile.begin(), - initialSumOfWeights_mc_generator_namesInThisFile.end(),name); - if (pos_name == initialSumOfWeights_mc_generator_namesInThisFile.end()) { - initialSumOfWeights_mc_generator_namesInThisFile.push_back(name); - initialSumOfWeights_mc_generator_weightsInThisFile.push_back(sumOfEventWeights); - maxCycle_LH3.push_back(cbk->cycle()); - } - else if (cbk->cycle() > maxCycle_LH3.at(pos_name-initialSumOfWeights_mc_generator_namesInThisFile.begin())) { - initialSumOfWeights_mc_generator_weightsInThisFile.at(pos_name-initialSumOfWeights_mc_generator_namesInThisFile.begin()) = sumOfEventWeights; - maxCycle_LH3.at(pos_name-initialSumOfWeights_mc_generator_namesInThisFile.begin()) = cbk->cycle(); - } - } - else continue; + for (unsigned int i_genweights = 0; i_genweights < LHE3_names_file.size(); + i_genweights++) { + if (names_LHE3.at(i_genweights) != LHE3_names_file.at(i_genweights)) { + ATH_MSG_ERROR("Strange inconsistency in the vector of weight names in sum of LHE3 weights calculation."); + return 1; + } else { + totalEventsWeighted_LHE3.at(i_genweights) + = totalEventsWeighted_LHE3.at(i_genweights) + + LHE3_sumW_file.at(i_genweights); } } - totalEventsWeighted += initialSumOfWeightsInThisFile; - totalEvents += initialEvents; - - // now we must fill two vectors in sync - if (topConfig->doMCGeneratorWeights()) { - if (totalEventsWeighted_LHE3.size() != 0 ) { - if (totalEventsWeighted_LHE3.size() != initialSumOfWeights_mc_generator_weightsInThisFile.size() - || names_LHE3.size() != initialSumOfWeights_mc_generator_namesInThisFile.size() - || names_LHE3.size() != totalEventsWeighted_LHE3.size() ) { - std::cout << "Ouch: strange inconsistency of vector sizes in sum of LHE3 weights calculation. There is an issue somewhere." << std::endl; - std::cout << "Exiting...." << std::endl; - std::exit(1); - } - for (unsigned int i_genweights = 0; i_genweights < initialSumOfWeights_mc_generator_namesInThisFile.size(); i_genweights++) { - if (names_LHE3.at(i_genweights) != initialSumOfWeights_mc_generator_namesInThisFile.at(i_genweights)) { - std::cout << "Ouch: strange inconsistency in the vector of weight names in sum of LHE3 weights calculation. There is an issue somewhere." << std::endl; - std::cout << "Exiting...." << std::endl; - std::exit(1); - } - else { - totalEventsWeighted_LHE3.at(i_genweights) - = totalEventsWeighted_LHE3.at(i_genweights) - + initialSumOfWeights_mc_generator_weightsInThisFile.at(i_genweights); - } - } - } - else { - for (unsigned int i_genweights = 0; i_genweights < initialSumOfWeights_mc_generator_namesInThisFile.size(); i_genweights++) { - names_LHE3.push_back(initialSumOfWeights_mc_generator_namesInThisFile.at(i_genweights)); - totalEventsWeighted_LHE3.push_back(initialSumOfWeights_mc_generator_weightsInThisFile.at(i_genweights)); - } - } - if (!names_LHE3.empty()) { - std::cout << "The sum of weights for the following LHE3 weights were retrieved from the input file:"<<std::endl; - for (std::string s : names_LHE3) std::cout<<s<<" "; - std::cout<< std::endl; - } - else { - std::cout << "No sum of LHE3 weights could be found in meta-data. Will try to recompute these sums."<<std::endl; - std::cout << "It will only work on un-skimmed derivations, and it will be impossible to know the name of these weights."<<std::endl; - recalc_LHE3 = true; - } + } else { + for (unsigned int i_genweights = 0; i_genweights < LHE3_names_file.size(); + i_genweights++) { + names_LHE3.push_back(LHE3_names_file.at(i_genweights)); + totalEventsWeighted_LHE3.push_back(LHE3_sumW_file.at(i_genweights)); } + } + if (!names_LHE3.empty()) { + ATH_MSG_INFO("The sum of weights for the following LHE3 weights were retrieved from the input file:"); + for (std::string s : names_LHE3) + msg(MSG::Level::INFO) << s << " "; + msg(MSG::Level::INFO) << std::endl; + } else { + ATH_MSG_INFO("No sum of LHE3 weights could be found in meta-data. Will try to recompute these sums.\n" + "This only works on un-skimmed derivations, and the names of these weights may be unknown (but we'll try to read them from the PMG tool"); + recalc_LHE3 = true; + } + } + + if (topConfig->isTruthDxAOD()) recalculateNominalWeightSum=true; + + if (topConfig->printCDIpathWarning()) { + ATH_MSG_WARNING( + "\n*************************************************************************\n" + << "YOU ARE USING A CUSTOM PATH TO THE CDI FILE WHICH IS NOT THE DEFAULT PATH\n" + << " YOU MANY NOT BE USING THE LATEST BTAGGING RECOMMENDATIONS \n" + << "*************************************************************************\n\n"); + } - const unsigned int entries = xaodEvent.getEntries(); - totalEventsInFiles += entries; - unsigned int firstEvent = 0; - if(topConfig->numberOfEventsToSkip() > skippedEventsSoFar){ - firstEvent = topConfig->numberOfEventsToSkip()-skippedEventsSoFar; - skippedEventsSoFar += entries < firstEvent ? entries : firstEvent; - } - for (unsigned int entry = firstEvent; entry < entries; ++entry, ++totalYieldSoFar) { - - if (topConfig->numberOfEventsToRun() != 0 && totalYieldSoFar >= topConfig->numberOfEventsToRun() ) break; - - if (entry % 100 == 0) - std::cout << " Processing event " << totalYieldSoFar << " / " << totalYield << " (current file: " << entry << " / " << entries << ")" << std::endl; - - // clear the TStore - get rid of the last events objects - xAOD::TActiveStore::store()->clear(); - // increment the event - xaodEvent.getEntry(entry); - - // Pile up and MC event weight - used to normalize the cut flows - float mcEventWeight(1.),pileupWeight(1.),zvtxWeight(1.); - if (topConfig->isMC()) - mcEventWeight = topScaleFactors->mcEventWeight(); - - if (topConfig->doPileupReweighting() && !topConfig->isTruthDxAOD()) { - top::check(topScaleFactors->executePileup(), "Failed to execute pileup reweighting"); - pileupWeight = topScaleFactors->pileupWeight(); - } - - - // get mc channel number - // to save the sum of weights - if (totalYieldSoFar == 0 && topConfig->isMC()) { - const xAOD::EventInfo *ei(nullptr); - top::check(xaodEvent.retrieve(ei, topConfig->sgKeyEventInfo()), - "xAOD::TEvent retrieve failed to get EventInfo"); - - //mcChannelNumber only available in MC simulation - if (ei->eventType(xAOD::EventInfo::IS_SIMULATION)) { - dsid = ei->mcChannelNumber(); - dsidPdf = ei->mcChannelNumber(); - } - } - - ///-- Truth events --/// - if (topConfig->isMC()) { + const unsigned int entries = xaodEvent.getEntries(); + totalEventsInFiles += entries; + unsigned int firstEvent = 0; + if (topConfig->numberOfEventsToSkip() > skippedEventsSoFar) { + firstEvent = topConfig->numberOfEventsToSkip() - skippedEventsSoFar; + skippedEventsSoFar += entries < firstEvent ? entries : firstEvent; + } + unsigned int entry; + bool isFirst(true); + for (entry = firstEvent; entry < entries; ++entry, ++totalYieldSoFar) { + if (topConfig->numberOfEventsToRun() != 0 && totalYieldSoFar >= topConfig->numberOfEventsToRun()) break; + + if (entry % 100 == 0) + ATH_MSG_INFO("Processing event " << totalYieldSoFar << " / " << totalYield + << " (current file: " << entry << " / " << entries << ")"); + + // clear the TStore - get rid of the last events objects + xAOD::TActiveStore::store()->clear(); + // increment the event + xaodEvent.getEntry(entry); + + // Pile up and MC event weight - used to normalize the cut flows + float mcEventWeight(1.), pileupWeight(1.), zvtxWeight(1.); + if (topConfig->isMC()) mcEventWeight = topScaleFactors->mcEventWeight(); + + if (topConfig->doPileupReweighting() && !topConfig->isTruthDxAOD()) { + top::check(topScaleFactors->executePileup(), "Failed to execute pileup reweighting"); + pileupWeight = topScaleFactors->pileupWeight(); + } - // Save, if requested, MC truth block, PDFInfo, TopPartons - // This will be saved for every event + // perform any operation common to both reco and truth level + // currently we load the MC generator weights inside, if requested + eventSaver->execute(); - // Run topPartonHistory - if (topConfig->doTopPartonHistory()) - top::check( topPartonHistory->execute() , "Failed to execute topPartonHistory" ); + ///-- Truth events --/// + if (topConfig->isMC()) { + // Save, if requested, MC truth block, PDFInfo, TopPartons + // This will be saved for every event - // calculate PDF weights - if( topConfig->doLHAPDF() ) - top::check( PDF_SF->execute(), - "Failed to execute PDF SF"); + // Run topPartonHistory + if (topConfig->doTopPartonHistory()) top::check(topPartonHistory->execute(), "Failed to execute topPartonHistory"); - eventSaver->saveTruthEvent(); - ++eventSavedTruth; + // calculate PDF weights + if (topConfig->doLHAPDF()) top::check(PDF_SF->execute(), + "Failed to execute PDF SF"); - // Upgrade analysis - only for truth DAODs when asking to do upgrade studies - if (topConfig->isTruthDxAOD() && topConfig->HLLHC()) { - top::ParticleLevelEvent upgradeEvent = upgradeLoader.load(); + eventSaver->saveTruthEvent(); + if(topConfig->doTopPartonLevel()) ++eventSavedTruth; - //event selection - const bool saveEventInOutputFile = eventSelectionManager.applyUpgradeLevel( upgradeEvent ); + // Upgrade analysis - only for truth DAODs when asking to do upgrade studies + if (topConfig->isTruthDxAOD() && topConfig->HLLHC()) { + //top::ParticleLevelEvent upgradeEvent = upgradeLoader.load(); - if ( saveEventInOutputFile ) { - eventSaver->saveUpgradeEvent( upgradeEvent ); - } - } + ////event selection + //const bool saveEventInOutputFile = eventSelectionManager.applyUpgradeLevel(upgradeEvent); - // Particle level analysis, saved only for truth events passing fiducial selection + //if (saveEventInOutputFile) { + // eventSaver->saveUpgradeEvent(upgradeEvent); + // ++eventSavedUpgrade; + //} + } - // -------------------------------------------------- - // If the truth loader is active, perform truth loading. - if ( particleLevelLoader.active() && !topConfig->HLLHC() ){ - // -------------------------------------------------- - // Get the top::TruthEvent for the current event - top::ParticleLevelEvent particleLevelEvent = particleLevelLoader.load(); + // Particle level analysis, saved only for truth events passing fiducial selection - //event selection - const bool saveEventInOutputFile = eventSelectionManager.applyParticleLevel( particleLevelEvent ); + // -------------------------------------------------- + // If the truth loader is active, perform truth loading. + if (particleLevelLoader.active()) { + // -------------------------------------------------- + // Get the top::TruthEvent for the current event + top::ParticleLevelEvent particleLevelEvent = particleLevelLoader.load(); - if ( saveEventInOutputFile ) { - eventSaver->saveParticleLevelEvent( particleLevelEvent ); - ++eventSavedParticle; - } - } + //event selection + const bool saveEventInOutputFile = eventSelectionManager.applyParticleLevel(particleLevelEvent); + if (saveEventInOutputFile) { + eventSaver->saveParticleLevelEvent(particleLevelEvent); + ++eventSavedParticle; + } + } + } + if (totalYieldSoFar == 0 && topConfig->isMC() && topConfig->doLHAPDF()) { + const xAOD::TruthEventContainer* truthEvent(nullptr); + top::check(xaodEvent.retrieve(truthEvent, topConfig->sgKeyTruthEvent()), "Failed to retrieve TruthEvent container for LHAPDF"); + top::check(truthEvent->size() == 1, "TruthEvent container size != 1, not sure what to do with PDF reweighting"); + for (auto tePtr : *truthEvent) { + for (auto& pdf : totalEventsPdfWeighted) { + if (tePtr->isAvailable< std::vector<float> >("AnalysisTop_" + pdf.first + "_Weights")) { + pdf.second->resize(tePtr->auxdata< std::vector<float> >("AnalysisTop_" + pdf.first + "_Weights").size()); } - if (totalYieldSoFar == 0 && topConfig->isMC() && topConfig->doLHAPDF()) { - const xAOD::TruthEventContainer* truthEvent(nullptr); - top::check( xaodEvent.retrieve(truthEvent, topConfig->sgKeyTruthEvent()) , "Failed to retrieve truth PDF info" ); - for( auto tePtr : *truthEvent ) { - for (auto &pdf : totalEventsPdfWeighted) { - if( tePtr->isAvailable< std::vector<float> >("AnalysisTop_"+pdf.first+"_Weights") ) { - pdf.second->resize(tePtr->auxdata< std::vector<float> >("AnalysisTop_"+pdf.first+"_Weights").size()); - } - } - } - } - // on the first event, set the size of the vector of sum of LHE3 weights in case it needs to be calculated on the fly - if (topConfig->isMC() && topConfig->doMCGeneratorWeights()) { - const xAOD::TruthEventContainer* truthEvent(nullptr); - top::check( xaodEvent.retrieve(truthEvent, topConfig->sgKeyTruthEvent()) , "Failed to retrieve LHE3 weights from truth event" ); - unsigned int weightsSize = truthEvent->at(0)->weights().size(); - if (recalc_LHE3) { - if (totalYieldSoFar == 0) { - totalEventsWeighted_LHE3_temp.resize(weightsSize); - for (unsigned int i_LHE3 = 0; i_LHE3<weightsSize; i_LHE3++) { - totalEventsWeighted_LHE3_temp.at(i_LHE3) = truthEvent->at(0)->weights().at(i_LHE3); - } - names_LHE3.resize(weightsSize); - std::fill(names_LHE3.begin(),names_LHE3.end(),"?"); - } - else { - for (unsigned int i_LHE3 = 0; i_LHE3<weightsSize; i_LHE3++) { - totalEventsWeighted_LHE3_temp.at(i_LHE3) = totalEventsWeighted_LHE3_temp.at(i_LHE3) + truthEvent->at(0)->weights().at(i_LHE3); - } - } + } + } + } + // on the first event, set the size of the vector of sum of LHE3 weights in case it needs to be calculated on the + // fly + + if (topConfig->isMC()) { + const xAOD::EventInfo* ei(nullptr); + top::check(xaodEvent.retrieve(ei, topConfig->sgKeyEventInfo()), + "Failed to retrieve LHE3 weights from EventInfo"); + + if(recalculateNominalWeightSum) + { + if (totalYieldSoFar == 0) ATH_MSG_INFO("Trying to recalculate nominal weights sum for TRUTH derivation"); + const size_t nominalWeightIndex = topConfig->nominalWeightIndex(); + totalEventsWeighted_temp += ei->mcEventWeights().at(nominalWeightIndex); + totalEvents++; + } + + if(topConfig->doMCGeneratorWeights()) + { + unsigned int weightsSize = ei->mcEventWeights().size(); + if (recalc_LHE3) { + if (totalYieldSoFar == 0) { + totalEventsWeighted_LHE3_temp.resize(weightsSize); + for (unsigned int i_LHE3 = 0; i_LHE3 < weightsSize; i_LHE3++) { + totalEventsWeighted_LHE3_temp.at(i_LHE3) = ei->mcEventWeights().at(i_LHE3); + } + names_LHE3.resize(weightsSize); + + ToolHandle<PMGTools::IPMGTruthWeightTool> m_pmg_weightTool("PMGTruthWeightTool"); + if (m_pmg_weightTool.retrieve()) { + const std::vector<std::string> &weight_names = m_pmg_weightTool->getWeightNames(); + if(weight_names.size() != weightsSize) + { + ATH_MSG_INFO("In top-xaod, while calculating mc weights sums on the fly, names from PMG tools have different size wrt weight vector, we'll not retrieve weight names"); + std::fill(names_LHE3.begin(), names_LHE3.end(), "?"); } - else if (weightsSize != names_LHE3.size()) {// don't recalc sum of weights, but cross-check the size of the vectors - std::cout << "Ouch: strange inconsistency in the sum of LHE3 weights vectors from the meta-data and the vector of LHE3 weights in the TruthEventContainer." << std::endl; - std::cout << "It should be the same; since it's not, it's pointless to continue."; - std::cout << "Exiting...." << std::endl; - std::exit(1); + else{ + for(unsigned int i_wgt=0; i_wgt<weight_names.size(); i_wgt++) names_LHE3[i_wgt]=weight_names[i_wgt]; } - } - ///-- End of Truth events -- start of reconstruction level events --/// - if (topConfig->isTruthDxAOD()) - continue; - - - ///-- We veto events that do not pass the GRL, trigger or have bad calorimeters --/// - ///-- No point calibrating and cutting on events that fail these cuts --/// - ///-- We only apply a veto if ALL selectors request a cut --/// - ///-- And if the user selects "OutputEvents SelectedEvents" --/// - - ///-- Count initial events --/// - eventSelectionManager.countInitial(mcEventWeight,pileupWeight,zvtxWeight); - - ///-- Does event pass the GRL? (always true for MC) --/// - ///-- Only veto events when ALL user selectors request GRL --/// - bool passGRLVeto = eventCleaning->applyGRL(); - if (!passGRLVeto) - continue; - eventSelectionManager.countGRL(mcEventWeight,pileupWeight,zvtxWeight); - - ///-- Are the Tile and LAr calorimeters in a good state? (always true for MC) --/// - ///-- Only veto events when ALL user selectors request GOODCALO --/// - bool passGoodCalo = eventCleaning->applyGoodCalo(); - if (!passGoodCalo) - continue; - eventSelectionManager.countGoodCalo(mcEventWeight,pileupWeight,zvtxWeight); - - ///-- Do we have a Primary Vertex? --/// - ///-- Only veto events when ALL user selectors request PRIVTX -- /// - bool passPriVtx = eventCleaning->applyPrimaryVertex(); - if (!passPriVtx) - continue; - eventSelectionManager.countPrimaryVertex(mcEventWeight,pileupWeight,zvtxWeight); - - ///-- Wondering which triggers are available ??? --/// - ///-- Uncomment this line and get ready for a LOT of output --/// - // eventCleaning->printTriggers(); - - ///-- Does event pass any trigger ? --/// - ///-- Only veto events when ALL user selectors request TRIGDEC --/// - ///-- And all trigger fail --/// - bool passAnyTriggerVeto = eventCleaning->applyTrigger(); - if (!passAnyTriggerVeto) - continue; - - ///-- Calibrate objects and make all required systematic copies --/// - top::check( systObjMaker->execute() , "Failed to execute systObjMaker" ); - - ///-- Object selection (e.g. good electrons, muons, jets etc.). Event selection cuts comes later --/// - top::check( objectSelection->execute() , "Failed to execute objectSelection" ); - - ///-- Recalculate MissingET based on object selection --/// - top::check( systObjMaker->recalculateMET() , "Failed to recalculateMET with systObjMaker" ); - - ///-- Scale Factor calculation --/// - if (topConfig->isMC()) - top::check( topScaleFactors->execute() , "Failed to calculate scale factors" ); - - if (!topConfig->doLooseTreeOnly()) { - ///-- Loop over all systematics and make a "top::Event" for each --/// - const xAOD::SystematicEventContainer* allSystematics = topEventMaker->systematicEvents( topConfig->sgKeyTopSystematicEvents() ); - for (auto currentSystematic : *allSystematics) { - ///-- Make a top::Event --/// - top::Event topEvent = topEventMaker->makeTopEvent( *currentSystematic ); - ///-- Apply event selection --/// - const bool passAnyEventSelection = eventSelectionManager.apply(topEvent,*currentSystematic ); - currentSystematic->auxdecor<char>(topConfig->passEventSelectionDecoration()) = passAnyEventSelection ? 1 : 0; - topEvent.m_saveEvent = passAnyEventSelection; - ///-- Save event - we defer to eventSaver the decision to write or not --/// - eventSaver->saveEvent(topEvent); - - ///-- For printout at the end of job, only count nominal events --/// - if (passAnyEventSelection && currentSystematic->hashValue() == topConfig->nominalHashValue()) - ++eventSavedReco; } - ///-- End loop over all calibration systematics --/// + else{ + std::fill(names_LHE3.begin(), names_LHE3.end(), "?"); + } + } else { + for (unsigned int i_LHE3 = 0; i_LHE3 < weightsSize; i_LHE3++) { + totalEventsWeighted_LHE3_temp.at(i_LHE3) = totalEventsWeighted_LHE3_temp.at(i_LHE3) + + ei->mcEventWeights().at(i_LHE3); + } } - ///-- End of tight events --/// - - if (topConfig->doLooseEvents()) { - ///-- Loop over all Loose systematics and make a "top::Event" for each --/// - const xAOD::SystematicEventContainer* allSystematicsLoose = topEventMaker->systematicEvents( topConfig->sgKeyTopSystematicEventsLoose() ); - for (auto currentSystematic : *allSystematicsLoose) { - ///-- Make a top::Event --/// - top::Event topEvent = topEventMaker->makeTopEvent( *currentSystematic ); - ///-- Apply event selection --/// - const bool passAnyEventSelection = eventSelectionManager.apply(topEvent,*currentSystematic ); - currentSystematic->auxdecor<char>(topConfig->passEventSelectionDecoration()) = passAnyEventSelection ? 1 : 0; - topEvent.m_saveEvent = passAnyEventSelection; - ///-- weights for matrix-method fakes estimate, only for nominal --/// - if (!topConfig->isMC() && topConfig->doFakesMMWeights() && currentSystematic->hashValue() == topConfig->nominalHashValue()) { - top::check( topfakesMMWeights->execute(&topEvent) , "Failed to execute fakes mmweight calculation"); - } - ///-- Save event - we defer to eventSaver the decision to write or not --/// - eventSaver->saveEvent(topEvent); - - ///-- For printout at the end of job, only count nominal events --/// - if (passAnyEventSelection && currentSystematic->hashValue() == topConfig->nominalHashValue()) - ++eventSavedRecoLoose; + } else if (weightsSize != names_LHE3.size()) {// don't recalc sum of weights, but cross-check the size of the + // vectors + ATH_MSG_ERROR("Strange size inconsistency in the AllExecutedEvents* " + "sum of weights bookkeepers from the meta-data and the vector of " + "LHE3 weights in the EventInfo container."); + return 1; + } + } + } + ///-- End of Truth events -- start of reconstruction level events --/// + if (topConfig->isTruthDxAOD()) continue; + + + ///-- We veto events that do not pass the GRL, trigger or have bad calorimeters --/// + ///-- No point calibrating and cutting on events that fail these cuts --/// + ///-- We only apply a veto if ALL selectors request a cut --/// + ///-- And if the user selects "OutputEvents SelectedEvents" --/// + + ///-- Count initial events --/// + eventSelectionManager.countInitial(mcEventWeight, pileupWeight, zvtxWeight); + + ///-- Does event pass the GRL? (always true for MC) --/// + ///-- Only veto events when ALL user selectors request GRL --/// + bool passGRLVeto = eventCleaning->applyGRL(); + if (!passGRLVeto) continue; + eventSelectionManager.countGRL(mcEventWeight, pileupWeight, zvtxWeight); + + ///-- Are the Tile and LAr calorimeters in a good state? (always true for MC) --/// + ///-- Only veto events when ALL user selectors request GOODCALO --/// + bool passGoodCalo = eventCleaning->applyGoodCalo(); + if (!passGoodCalo) continue; + eventSelectionManager.countGoodCalo(mcEventWeight, pileupWeight, zvtxWeight); + + ///-- Do we have a Primary Vertex? --/// + ///-- Only veto events when ALL user selectors request PRIVTX -- /// + bool passPriVtx = eventCleaning->applyPrimaryVertex(); + if (!passPriVtx) continue; + eventSelectionManager.countPrimaryVertex(mcEventWeight, pileupWeight, zvtxWeight); + + ///-- Wondering which triggers are available ??? --/// + ///-- Uncomment this line and get ready for a LOT of output --/// + // eventCleaning->printTriggers(); + + ///-- Does event pass any trigger ? --/// + ///-- Only veto events when ALL user selectors request TRIGDEC --/// + ///-- And all trigger fail --/// + bool passAnyTriggerVeto = eventCleaning->applyTrigger(); + if (!passAnyTriggerVeto) continue; + + ///-- Nominal objects -- /// + ///-- Calibrate objects and make all required systematic copies --/// + top::check(systObjMaker->execute(true), "Failed to execute systObjMaker"); + + ///-- Object selection (e.g. good electrons, muons, jets etc.). Event selection cuts comes later --/// + top::check(objectSelection->execute(true), "Failed to execute objectSelection"); + + ///-- Recalculate MissingET based on object selection --/// + top::check(systObjMaker->recalculateMET(true), "Failed to recalculateMET with systObjMaker"); + + ///-- Systematic objects -- /// + ///-- Calibrate objects and make all required systematic copies --/// + top::check(systObjMaker->execute(false), "Failed to execute systObjMaker"); + + ///-- Object selection (e.g. good electrons, muons, jets etc.). Event selection cuts comes later --/// + top::check(objectSelection->execute(false), "Failed to execute objectSelection"); + + ///-- Recalculate MissingET based on object selection --/// + top::check(systObjMaker->recalculateMET(false), "Failed to recalculateMET with systObjMaker"); + + + ///-- Scale Factor calculation --/// + if (topConfig->isMC()) top::check(topScaleFactors->execute(), "Failed to calculate scale factors"); + + if (topConfig->doTightEvents()) { + ///-- Loop over all systematics and make a "top::Event" for each --/// + const xAOD::SystematicEventContainer* allSystematics = topEventMaker->systematicEvents( + topConfig->sgKeyTopSystematicEvents()); + for (auto currentSystematic : *allSystematics) { + if (!(currentSystematic->hashValue() == topConfig->nominalHashValue() || topConfig->doTightSysts())) continue; + + ///-- Make a top::Event --/// + top::Event topEvent = topEventMaker->makeTopEvent(currentSystematic); + ///-- Apply event selection --/// + const bool passAnyEventSelection = eventSelectionManager.apply(topEvent, *currentSystematic); + // check if we are using actual mu for mc16d or mc16e + if (isFirst && topConfig->isMC()) { + const int runNumber = topEvent.m_info->runNumber(); + if (runNumber >= 300000) { + if ((!topConfig->isAFII() && topConfig->PileupActualMu_FS().size() == 0) || + (topConfig->isAFII() && topConfig->PileupActualMu_AF().size() == 0)) { + ATH_MSG_WARNING("\n***************************************************************************************\nYou are running over mc16d or mc16e sample but you are not using actual mu reweighting!\nYou are strongly adviced to use it.\nCheck https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#PRW_and_Lumicalc_files\n***************************************************************************************\n"); } - ///-- End loop over all loose calibration systematics --/// } - ///-- End of loose events --/// - - ///-- Needed for xAOD output, all systematics go into the same TTree --/// - eventSaver->saveEventToxAOD(); - - } //loop over events in current file - - // do it at the end, so we can get the DS id from the first event - // notice this is different from the normal sum of weights: all entries matter, not only the highest per file - if (topConfig->doLHAPDF()) { - bool pdfInCBK = false; - if (xaodEvent.retrieveMetaInput( cutBookKeepers, "CutBookkeepers" )) { - // try to get the first entry - std::string pdf_set = totalEventsPdfWeighted.begin()->first; - std::string p = pdf_set+"_0"; - for ( auto cbk : *cutBookKeepers ) { - std::string pdfName = cbk->name(); - if (p != pdfName) continue; - pdfMetadataExists = true; - pdfInCBK = true; - // reload to set iterator back to original state - if (!xaodEvent.retrieveMetaInput(cutBookKeepers, "CutBookkeepers")) {} - break; + } + currentSystematic->auxdecor<char>(topConfig->passEventSelectionDecoration()) = passAnyEventSelection ? 1 : 0; + topEvent.m_saveEvent = passAnyEventSelection; + ///-- Save event - we defer to eventSaver the decision to write or not --/// + eventSaver->saveEvent(topEvent); + + ///-- For printout at the end of job, only count nominal events --/// + if (passAnyEventSelection && + currentSystematic->hashValue() == topConfig->nominalHashValue()) ++eventSavedReco; + } + ///-- End loop over all calibration systematics --/// + } + ///-- End of tight events --/// + + if (topConfig->doLooseEvents()) { + ///-- Loop over all Loose systematics and make a "top::Event" for each --/// + const xAOD::SystematicEventContainer* allSystematicsLoose = topEventMaker->systematicEvents( + topConfig->sgKeyTopSystematicEventsLoose()); + for (auto currentSystematic : *allSystematicsLoose) { + if (!(currentSystematic->hashValue() == topConfig->nominalHashValue() || topConfig->doLooseSysts())) continue; + + ///-- Make a top::Event --/// + top::Event topEvent = topEventMaker->makeTopEvent(currentSystematic); + ///-- Apply event selection --/// + const bool passAnyEventSelection = eventSelectionManager.apply(topEvent, *currentSystematic); + + // check if we are using actual mu for mc16d or mc16e + if (isFirst && topConfig->isMC()) { + const int runNumber = topEvent.m_info->runNumber(); + ATH_MSG_INFO("RunNumber: " << runNumber); + if (runNumber >= 300000) { + if ((!topConfig->isAFII() && topConfig->PileupActualMu_FS().size() == 0) || + (topConfig->isAFII() && topConfig->PileupActualMu_AF().size() == 0)) { + ATH_MSG_WARNING("\n***************************************************************************************\nYou are running over mc16d or mc16e sample but you are not using actual mu reweighting!\nYou are strongly adviced to use it.\nCheck https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21#PRW_and_Lumicalc_files\n***************************************************************************************\n"); + } } } - // if the pdf info was in the CBK the PDFSumOfWeights retrieve never happens, - // and cutBookKeepers, will keep its reference to the main CBK - if (!pdfInCBK) { // only try this if the info is not in the CBK -- this is legacy stuff - if (!xaodEvent.retrieveMetaInput( cutBookKeepers, "PDFSumOfWeights" )) { - pdfMetadataExists = false; - } - } - if (pdfMetadataExists && topConfig->saveLHAPDFEvent() && topConfig->baseLHAPDF().empty()) { - // just make a copy of it, but not all derivations have it, so just ignore it if it is not there - for (auto &pdfentry : totalEventsPdfWeighted) { - std::string pdf_set = pdfentry.first; - for (size_t n = 0; n < totalEventsPdfWeighted[pdf_set]->size(); ++n) { - std::string p = pdf_set+"_"+std::to_string(n); - bool foundPdf = false; - for ( auto cbk : *cutBookKeepers ) { - std::string pdfName = cbk->name(); - if (p != pdfName) - continue; - totalEventsPdfWeighted[pdf_set]->at(n) = cbk->sumOfEventWeights(); - foundPdf = true; - break; - } - if (!foundPdf) { // asked for PDF weighting, the PDF metadata exists, but this particular PDF is missing - // crash hard - std::cout << "The force is not strong with us, young Padawan ..." << std::endl; - std::cout << "You want to save weights to do PDF reweighting using '" << pdf_set << "', which I figure has " << totalEventsPdfWeighted[pdf_set]->size() << " sets on it." << std::endl; - std::cout << "There is metadata information for the sum of MC*PDF weights in PDFSumOfWeights, but none seem to refer to '" << p << "' therefore I do not know how to estimate the sum of weights before acceptance for this configuration." << std::endl; - std::cout << "May the force be with you in your next attempt." << std::endl; - std::exit(1); + currentSystematic->auxdecor<char>(topConfig->passEventSelectionDecoration()) = passAnyEventSelection ? 1 : 0; + topEvent.m_saveEvent = passAnyEventSelection; + ///-- weights for matrix-method fakes estimate from IFF tools, only for nominal --/// + if (!topConfig->isMC() && topConfig->doFakesMMWeightsIFF() && + currentSystematic->hashValue() == topConfig->nominalHashValue()) { + xAOD::IParticleContainer lepton(SG::VIEW_ELEMENTS); + for (auto const& t : topEvent.m_electrons) + lepton.push_back(static_cast<xAOD::Electron*>(t)); + for (auto const& t : topEvent.m_muons) + lepton.push_back(static_cast<xAOD::Muon*>(t)); + + topEvent.m_info->auxdecor<int>("njets") = topEvent.m_jets.size(); + for (const auto& tagWP : topConfig->bTagWP_available()) { + if (tagWP.find("Continuous") != std::string::npos) continue; + int nbjets = 0; + for (const auto& jetPtr : topEvent.m_jets) { + if (jetPtr->isAvailable<char>("isbtagged_" + tagWP)) { + nbjets += jetPtr->auxdataConst<char>("isbtagged_" + tagWP); } } + topEvent.m_info->auxdecor<int>("nbjets_" + tagWP) = nbjets; } - sumPdfWeights->Fill(); - } - } //doLHAPDF - } //loop over files - - //finish - std::cout << "\n"; - - if (doPerfStats > 0) - xAOD::PerfStats::instance().stop(); // Stop the PerfStats timer + std::vector<float> mmweight; + std::vector<std::vector<float> > mmweight_var; + std::vector<std::vector<std::string> > mmweight_varname; + //for (unsigned int mmi = 0; mmi < topfakesMMWeightsIFF.size(); ++mmi) { + // top::check(topfakesMMWeightsIFF[mmi]->addEvent(lepton), + // "Failed to execute fakes mmweight IFF addEvent()"); + // float asmWgt = 0.; + // top::check(topfakesMMWeightsIFF[mmi]->applySystematicVariation( + // {}), "Failed to execute fakes mmweight IFF applySystematicVariation()"); + // top::check(topfakesMMWeightsIFF[mmi]->getEventWeight(asmWgt, FakesMMConfigIFF[mmi][1], + // FakesMMConfigIFF[mmi][2]), "Failed to execute fakes mmweight IFF getEventWeight()"); + + // std::vector<float> asmWgt_var(topfakesMMWeightsIFF[mmi]->affectingSystematics().size()); + // std::vector<std::string> asmWgt_varname(topfakesMMWeightsIFF[mmi]->affectingSystematics().size()); + // for (const auto& sysvar : topfakesMMWeightsIFF[mmi]->affectingSystematics()) { + // float mmweight_syst; + // top::check(topfakesMMWeightsIFF[mmi]->applySystematicVariation( + // {sysvar}), "Failed to execute fakes mmweight IFF applySystematicVariation()"); + // top::check(topfakesMMWeightsIFF[mmi]->getEventWeight(mmweight_syst, FakesMMConfigIFF[mmi][1], + // FakesMMConfigIFF[mmi][2]), "Failed to execute fakes mmweight IFF getEventWeight()"); + // asmWgt_var.push_back(mmweight_syst); + // asmWgt_varname.push_back(sysvar.name()); + // } + // mmweight.push_back(asmWgt); + // mmweight_var.push_back(asmWgt_var); + // mmweight_varname.push_back(asmWgt_varname); + //} + topEvent.m_info->auxdecor<std::vector<float> >("ASMWeight") = mmweight; + topEvent.m_info->auxdecor<std::vector<std::vector<float> > >("ASMWeight_Syst") = mmweight_var; + topEvent.m_info->auxdecor<std::vector<std::vector<std::string> > >("ASMWeight_Systname") = mmweight_varname; + } + ///-- Save event - we defer to eventSaver the decision to write or not --/// + eventSaver->saveEvent(topEvent); - if( topConfig->doLHAPDF() ) top::check( PDF_SF->finalize() , "Failed to finalize PDF SF" ); + ///-- For printout at the end of job, only count nominal events --/// + if (passAnyEventSelection && + currentSystematic->hashValue() == topConfig->nominalHashValue()) ++eventSavedRecoLoose; + } + ///-- End loop over all loose calibration systematics --/// + } + ///-- End of loose events --/// - // this fills the sum of weights - // if the list of input files has more than - // one type of dataset (ie: the first file is ttbar and the second one - // is W+jets), then the Fill statement below needs to come in the end of - // each file's processing instead ... but why would you do that?! - if (recalc_LHE3) {// in case the sum of LHE3 weight has been re-calculated with double (but we need floats in the end) - for (double d:totalEventsWeighted_LHE3_temp) totalEventsWeighted_LHE3.push_back(d); - } - sumWeights->Fill(); - outputFile->cd(); + ///-- Needed for xAOD output, all systematics go into the same TTree --/// + eventSaver->saveEventToxAOD(); + isFirst = false; + } //loop over events in current file + if (tracker) tracker->addInputFile(inputFile->GetName(), entry - firstEvent); + // do it at the end, so we can get the DS id from the first event + // notice this is different from the normal sum of weights: all entries matter, not only the highest per file if (topConfig->doLHAPDF()) { + bool pdfInCBK = false; + if (xaodEvent.retrieveMetaInput(cutBookKeepers, "CutBookkeepers")) { + // try to get the first entry + std::string pdf_set = totalEventsPdfWeighted.begin()->first; + std::string p = pdf_set + "_0"; + for (auto cbk : *cutBookKeepers) { + std::string pdfName = cbk->name(); + if (p != pdfName) continue; + pdfMetadataExists = true; + pdfInCBK = true; + // reload to set iterator back to original state + if (!xaodEvent.retrieveMetaInput(cutBookKeepers, "CutBookkeepers")) { + } + break; + } + } + // if the pdf info was in the CBK the PDFSumOfWeights retrieve never happens, + // and cutBookKeepers, will keep its reference to the main CBK + if (!pdfInCBK) { // only try this if the info is not in the CBK -- this is legacy stuff + if (!xaodEvent.retrieveMetaInput(cutBookKeepers, "PDFSumOfWeights")) { + pdfMetadataExists = false; + } + } + if (pdfMetadataExists && topConfig->saveLHAPDFEvent() && topConfig->baseLHAPDF().empty()) { + // just make a copy of it, but not all derivations have it, so just ignore it if it is not there + for (auto& pdfentry : totalEventsPdfWeighted) { + std::string pdf_set = pdfentry.first; + for (size_t n = 0; n < totalEventsPdfWeighted[pdf_set]->size(); ++n) { + std::string p = pdf_set + "_" + std::to_string(n); + bool foundPdf = false; + for (auto cbk : *cutBookKeepers) { + std::string pdfName = cbk->name(); + if (p != pdfName) continue; + totalEventsPdfWeighted[pdf_set]->at(n) = cbk->sumOfEventWeights(); + foundPdf = true; + break; + } + if (!foundPdf) { // asked for PDF weighting, the PDF metadata exists, but this particular PDF is missing + // crash hard + ATH_MSG_ERROR( + "The force is not strong with us, young Padawan ...\n" + "You want to save weights to do PDF reweighting using '" << pdf_set << + "', which I figure has " << totalEventsPdfWeighted[pdf_set]->size() << " sets on it.\n" + "There is metadata information for the sum of MC*PDF weights in PDFSumOfWeights, " + "but none seem to refer to '" << p << "' therefore I do not know how to estimate " + "the sum of weights before acceptance for this configuration.\n" + "May the force be with you in your next attempt."); + return 1; + } + } + } + sumPdfWeights->Fill(); + } + } //doLHAPDF + } //loop over files + + if (doPerfStats > 0) xAOD::PerfStats::instance().stop(); // Stop the PerfStats timer + + if (topConfig->doLHAPDF()) top::check(PDF_SF->finalize(), "Failed to finalize PDF SF"); + + // this fills the sum of weights + // if the list of input files has more than + // one type of dataset (ie: the first file is ttbar and the second one + // is W+jets), then the Fill statement below needs to come in the end of + // each file's processing instead ... but why would you do that?! + if (recalc_LHE3) {// in case the sum of LHE3 weight has been re-calculated with double (but we need floats in the end) + for (double d:totalEventsWeighted_LHE3_temp) totalEventsWeighted_LHE3.push_back(d); + } + if(recalculateNominalWeightSum) + { + totalEventsWeighted=totalEventsWeighted_temp; + } + sumWeights->Fill(); + outputFile->cd(); + + if (topConfig->doLHAPDF()) { // Save sum of weights of PDF variations // Only do this if the metadata is not available if (totalEventsInFiles != totalEvents && !pdfMetadataExists) { - std::cout << "These are not the droids you are looking for." << std::endl; - std::cout << "There are " << totalEventsInFiles << " events in the input files, but the metadata tells me there were " << totalEvents << "before skimming." << std::endl; - std::cout << "This means you are running on skimmed derivations. You also want me to do PDF reweighting, but no PDF metadata exists!" << std::endl; - std::cout << "I don't know how to tell you the sum of MC*PDF weights before skimming. I will explode now in 3, 2, 1 ..." << std::endl; - std::exit(1); + ATH_MSG_ERROR("These are not the droids you are looking for.\n" + "You are running over skimmed derivations. We cannot determine " + "the sum of MC*PDF weights before skimming " + "because no PDF metadata is available in the file!"); + return 1; } // save recomputed sum weights - if( (!topConfig->baseLHAPDF().empty() || !pdfMetadataExists) ) { - for( auto& pdf_result : topConfig->getLHAPDFResults() ) - *(totalEventsPdfWeighted[pdf_result.first]) = pdf_result.second; + if ((!topConfig->baseLHAPDF().empty() || !pdfMetadataExists)) { + for (auto& pdf_result : topConfig->getLHAPDFResults()) + *(totalEventsPdfWeighted[pdf_result.first]) = pdf_result.second; sumPdfWeights->Fill(); } - } //doLHAPDF - - outputFile->cd(); - eventSelectionManager.finalise(); - eventSaver->finalize(); - outputFile->Close(); - bool outputFileGood = !outputFile->TestBit(TFile::kWriteError); - if (outputFileGood) { - if (gSystem->Rename(outputFile->GetName(), settings->value("OutputFilename").c_str()) != 0) - outputFileGood = false; - } - - if (!topConfig->isTruthDxAOD()) { - std::cout << "\nEvents saved to output file nominal reconstruction tree: " << eventSavedReco << "\n"; - if (topConfig->doLooseEvents()) - std::cout << "Events saved to output file nominal Loose reconstruction tree: " << eventSavedRecoLoose << "\n"; - } - if (topConfig->isMC()) { - std::cout << "Events saved to output file truth tree : "<<eventSavedTruth << "\n"; - if (particleLevelLoader.active()) { - std::cout << "Events saved to output file particle level tree : "<<eventSavedParticle << "\n"; - } - } - std::cout << "Total sum-of-weights (for normalization) : " - << totalEventsWeighted - << std::endl; - - //print some xAOD performance info - if (doPerfStats == 1) - xAOD::IOStats::instance().stats().Print("Summary"); - if (doPerfStats == 2) - xAOD::IOStats::instance().stats().Print(); - - if (!outputFileGood) { - std::cout << "ERROR: an I/O error occured while attempting to save the output file." << std::endl; - return 1; + } //doLHAPDF + + outputFile->cd(); + eventSelectionManager.finalise(); + eventSaver->finalize(); + outputFile->cd(); + if (tracker) tracker->writeTree("AnalysisTracking"); + outputFile->Close(); + bool outputFileGood = !outputFile->TestBit(TFile::kWriteError); + if (outputFileGood) { + if (gSystem->Rename(outputFile->GetName(), settings->value("OutputFilename").c_str()) != 0) outputFileGood = false; + } + + if (!topConfig->isTruthDxAOD()) { + if (topConfig->doTightEvents()) + ATH_MSG_INFO("Events saved to output file nominal reconstruction tree: " << eventSavedReco); + if (topConfig->doLooseEvents()) + ATH_MSG_INFO("Events saved to output file nominal loose reconstruction tree: " << eventSavedRecoLoose); + } + if (topConfig->isMC()) { + ATH_MSG_INFO("Events saved to output file truth tree : " << eventSavedTruth); + if (particleLevelLoader.active()) { + ATH_MSG_INFO("Events saved to output file particle level tree : " << eventSavedParticle); } - - return 0; + //if (upgradeLoader.active()) { + // ATH_MSG_INFO("Events saved to output file upgrade tree : " << eventSavedUpgrade); + //} + } + ATH_MSG_INFO("Total sum-of-weights (for normalization) : " << totalEventsWeighted); + + //print some xAOD performance info + if (doPerfStats == 1) xAOD::IOStats::instance().stats().Print("Summary"); + if (doPerfStats == 2) xAOD::IOStats::instance().stats().Print(); + + if (!outputFileGood) { + ATH_MSG_ERROR("ERROR: an I/O error occured while attempting to save the output file."); + return 1; + } + + return 0; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/CMakeLists.txt index 1b86e1641a66983eff7be6a0169afd217a508911..83394cfc539c73fd6f11952b4bbafdfff68dbf39 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/CMakeLists.txt @@ -1,7 +1,5 @@ -# Auto-generated on: 2017-03-08 14:47:34.346308 - # Declare the name of this package: -atlas_subdir( TopCPTools None ) +atlas_subdir( TopCPTools ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC @@ -10,6 +8,7 @@ atlas_depends_on_subdirs( PUBLIC AthContainers PATCore PATInterfaces + TrigBunchCrossingTool TrigConfInterfaces TrigConfxAOD TrigDecisionTool @@ -34,7 +33,6 @@ atlas_depends_on_subdirs( PUBLIC JetInterface JetMomentTools JetSelectorTools - JetResolution METInterface METUtilities IsolationSelection @@ -46,14 +44,19 @@ atlas_depends_on_subdirs( PUBLIC AssociationUtils JetJvtEfficiency PMGTools - InDetTrackSystematicsTools ) + InDetTrackSelectionTool + InDetTrackSystematicsTools + #BoostedJetTaggers + FTagAnalysisInterfaces + MuonAnalysisInterfaces + #TriggerAnalysisInterfaces + #TrigGlobalEfficiencyCorrection + PMGAnalysisInterfaces + JetAnalysisInterfaces) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) -# Custom definitions needed for this package: -add_definitions( -g -std=c++14 ) - # Build a library that other components can link against: atlas_add_library( TopCPTools Root/*.cxx Root/*.h Root/*.icc TopCPTools/*.h TopCPTools/*.icc TopCPTools/*/*.h @@ -64,6 +67,7 @@ atlas_add_library( TopCPTools Root/*.cxx Root/*.h Root/*.icc AthContainers PATCoreLib PATInterfaces + TrigBunchCrossingTool TrigConfInterfaces TrigConfxAODLib TrigDecisionToolLib @@ -88,7 +92,6 @@ atlas_add_library( TopCPTools Root/*.cxx Root/*.h Root/*.icc JetInterface JetMomentToolsLib JetSelectorToolsLib - JetResolutionLib METInterface METUtilitiesLib IsolationSelectionLib @@ -100,10 +103,15 @@ atlas_add_library( TopCPTools Root/*.cxx Root/*.h Root/*.icc AssociationUtilsLib JetJvtEfficiencyLib PMGToolsLib + InDetTrackSelectionToolLib InDetTrackSystematicsToolsLib + #BoostedJetTaggersLib + FTagAnalysisInterfacesLib + MuonAnalysisInterfacesLib + #TriggerAnalysisInterfacesLib + #TrigGlobalEfficiencyCorrectionLib + PMGAnalysisInterfacesLib + JetAnalysisInterfacesLib ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) -# Install data files from the package: -atlas_install_data( share/* ) - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopBoostedTaggingCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopBoostedTaggingCPTools.cxx new file mode 100644 index 0000000000000000000000000000000000000000..66dea52ac4013a849d013b62cbec022b93960398 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopBoostedTaggingCPTools.cxx @@ -0,0 +1,169 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopCPTools/TopBoostedTaggingCPTools.h" + +#include <map> +#include <string> +#include <algorithm> +#include <iterator> + +// Top includes +#include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/Tokenize.h" +#include "TopEvent/EventTools.h" + +// JetUncertaintiesTool for the tagger SFs +#include "JetUncertainties/JetUncertaintiesTool.h" + +// Boosted tagging includes +//#include "BoostedJetTaggers/SmoothedTopTagger.h" +//#include "BoostedJetTaggers/SmoothedWZTagger.h" +//#include "BoostedJetTaggers/JSSWTopTaggerDNN.h" + +namespace top { + BoostedTaggingCPTools::BoostedTaggingCPTools(const std::string& name) : + asg::AsgTool(name) { + declareProperty("config", m_config); + } + + StatusCode BoostedTaggingCPTools::initialize() { + ATH_MSG_INFO("top::BoostedTaggingCPTools initialize..."); + + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::BoostedTaggingCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; + } + + if (!m_config->useLargeRJets()) { + ATH_MSG_INFO("top::BoostedTaggingCPTools: no need to initialise anything since not using large-R jets"); + return StatusCode::SUCCESS; + } + + + std::vector<std::pair<std::string, std::string> > boostedJetTaggers = m_config->boostedJetTaggers(); + if (boostedJetTaggers.size() == 0) { + ATH_MSG_INFO("top::BoostedTaggingCPTools: boostedJetTagging not set. No need to initialise anything."); + return StatusCode::SUCCESS; + } + + + top::check( + m_config->sgKeyLargeRJets() == "AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets" || m_config->sgKeyLargeRJets() == "AntiKt10TrackCaloClusterTrimmedPtFrac5SmallR20Jets", + "Error in BoostedTaggingCPTools: boosted jet taggers are not available for this large-R jet collection."); + + std::unordered_map<std::string, std::string > taggersConfigs; + std::unordered_map<std::string, std::string > taggerSFconfigs; + std::unordered_map<std::string, std::string > taggerSFnames; + std::unordered_map<std::string, std::string > taggersCalibAreas; + + std::vector<std::string > taggersTypes = { + "JSSWTopTaggerDNN", "SmoothedWZTagger" + }; + + taggersCalibAreas["JSSWTopTaggerDNN"] = "JSSWTopTaggerDNN/Rel21/"; + taggersCalibAreas["SmoothedWZTagger"] = "SmoothedWZTaggers/Rel21/"; + + if (m_config->sgKeyLargeRJets() == "AntiKt10LCTopoTrimmedPtFrac5SmallR20Jets") { + taggersConfigs["JSSWTopTaggerDNN:DNNTaggerTopQuarkContained50"] = + "JSSDNNTagger_AntiKt10LCTopoTrimmed_TopQuarkContained_MC16d_20190405_50Eff.dat"; + taggersConfigs["JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80"] = + "JSSDNNTagger_AntiKt10LCTopoTrimmed_TopQuarkContained_MC16d_20190827_80Eff.dat"; + taggersConfigs["JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive50"] = + "JSSDNNTagger_AntiKt10LCTopoTrimmed_TopQuarkInclusive_MC16d_20190405_50Eff.dat"; + taggersConfigs["JSSWTopTaggerDNN:DNNTaggerTopQuarkInclusive80"] = + "JSSDNNTagger_AntiKt10LCTopoTrimmed_TopQuarkInclusive_MC16d_20190405_80Eff.dat"; + + taggersConfigs["SmoothedWZTagger:SmoothWContained50"] = + "SmoothedContainedWTagger_AntiKt10LCTopoTrimmed_FixedSignalEfficiency50_MC16d_20190410.dat"; + taggersConfigs["SmoothedWZTagger:SmoothWContained80"] = + "SmoothedContainedWTagger_AntiKt10LCTopoTrimmed_FixedSignalEfficiency80_MC16d_20190410.dat"; + + taggersConfigs["SmoothedWZTagger:SmoothZContained50"] = + "SmoothedContainedZTagger_AntiKt10LCTopoTrimmed_FixedSignalEfficiency50_MC16d_20190410.dat"; + taggersConfigs["SmoothedWZTagger:SmoothZContained80"] = + "SmoothedContainedZTagger_AntiKt10LCTopoTrimmed_FixedSignalEfficiency80_MC16d_20190410.dat"; + + // tagger SF uncertainties + taggerSFconfigs["JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80"] = + "rel21/Summer2019/R10_SF_LC_DNNContained80_TopTag.config"; + taggerSFnames["JSSWTopTaggerDNN:DNNTaggerTopQuarkContained80"] = "DNNTaggerTopQuarkContained80_SF"; + } else if (m_config->sgKeyLargeRJets() == "AntiKt10TrackCaloClusterTrimmedPtFrac5SmallR20Jets") { + taggersConfigs["SmoothedWZTagger:SmoothWContained2VarMaxSig"] = + "SmoothedWTagger_AntiKt10TrackCaloClusterTrimmed_MaxSignificance_2Var_MC16d_20190809.dat"; + taggersConfigs["SmoothedWZTagger:SmoothZContained2VarMaxSig"] = + "SmoothedZTagger_AntiKt10TrackCaloClusterTrimmed_MaxSignificance_2Var_MC16d_20190809.dat"; + + taggersConfigs["SmoothedWZTagger:SmoothW3VarMaxSig"] = + "SmoothedContainedWTagger_AntiKt10TrackCaloClusterTrimmed_MaxSignificance_3Var_MC16d_20190410.dat"; + taggersConfigs["SmoothedWZTagger:SmoothZ3VarMaxSig"] = + "SmoothedContainedZTagger_AntiKt10TrackCaloClusterTrimmed_MaxSignificance_3Var_MC16d_20190410.dat"; + + // tagger SF uncertainties + taggerSFconfigs["SmoothedWZTagger:SmoothWContained2VarMaxSig"] = + "rel21/Summer2019/R10_SF_TCC_2VarSmooth_WTag.config"; + taggerSFnames["SmoothedWZTagger:SmoothWContained2VarMaxSig"] = "SmoothWContained2VarMaxSig_SF"; + taggerSFconfigs["SmoothedWZTagger:SmoothZContained2VarMaxSig"] = + "rel21/Summer2019/R10_SF_TCC_2VarSmooth_ZTag.config"; + taggerSFnames["SmoothedWZTagger:SmoothZContained2VarMaxSig"] = "SmoothZContained2VarMaxSig_SF"; + } + + for (const std::pair<std::string, std::string>& name : boostedJetTaggers) { + const std::string& taggerType = name.first; + const std::string& shortName = name.second; + const std::string fullName = taggerType + "_" + shortName; // Name to idendify tagger + const std::string origName = taggerType + ":" + shortName; // Original name set in the top config + + top::check(taggersConfigs.find(origName) != taggersConfigs.end(), + ("Error in BoostedTaggingCPTools: Unknown tagger in the config file: " + origName).c_str()); + + top::check(std::find(taggersTypes.begin(), taggersTypes.end(), + taggerType) != taggersTypes.end(), "Error in BoostedTaggingCPTools: Unknown TAGGER_TYPE."); +// if (taggerType == "JSSWTopTaggerDNN") top::check(ASG_MAKE_ANA_TOOL(m_taggers[fullName], +// JSSWTopTaggerDNN), +// "Failed to make " + origName); +// else if (taggerType == "SmoothedWZTagger") top::check(ASG_MAKE_ANA_TOOL(m_taggers[fullName], +// SmoothedWZTagger), +// "Failed to make " + origName); + + m_taggers[fullName].setName(fullName); + top::check(m_taggers[fullName].setProperty("ConfigFile", + taggersConfigs[origName]), "Failed to set ConfigFile for " + origName); + top::check(m_taggers[fullName].setProperty("CalibArea", + taggersCalibAreas[taggerType]), + "Failed to set CalibArea for " + origName); + // not all BJT taggers implement IsMC property -- only those that have calibration SFs + // so we have to check here that we try to set this property only where applicable + if (taggerType == "JSSWTopTaggerDNN" || taggerType == "SmoothedWZTagger") { + top::check(m_taggers[fullName].setProperty("IsMC", m_config->isMC()), "Failed to set IsMC for " + origName); + } + top::check(m_taggers[fullName].initialize(), "Failed to initialize " + origName); + + // initialize SF uncertainty tools for supported WPs + if (m_config->isMC()) { + std::string jet_def = m_config->sgKeyLargeRJets(); + jet_def.erase(jet_def.length() - 4); // jet collection name sans 'Jets' suffix + + const std::string name = "JetSFuncert_" + fullName; + try { + const std::string& cfg = taggerSFconfigs.at(origName); + JetUncertaintiesTool* jet_SF_tmp = new JetUncertaintiesTool(name); + + top::check(jet_SF_tmp->setProperty("JetDefinition", jet_def), "Failed to set JetDefinition for " + name); + top::check(jet_SF_tmp->setProperty("MCType", "MC16"), "Failed to set MCType for " + name); + top::check(jet_SF_tmp->setProperty("ConfigFile", cfg), "Failed to set MCType for " + name); + top::check(jet_SF_tmp->setProperty("IsData", false), "Failed to set IsData for " + name); + top::check(jet_SF_tmp->initialize(), "Failed to initialize " + name); + m_tagSFuncertTool[fullName] = jet_SF_tmp; + m_config->setCalibBoostedJetTagger(fullName, taggerSFnames[origName]); + } catch (std::out_of_range& e) { + // skip taggers which do not yet have SFs available + ATH_MSG_WARNING("Boosted jet tagger " + fullName + " is not yet calibrated! No SFs are available."); + } + } + } + + return StatusCode::SUCCESS; + } +} // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopEgammaCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopEgammaCPTools.cxx index 47cdda921fead0679b3e952d8b932b4f80147825..77f0c5fc712231d0ac8ab86e94f5766cd58f9bf2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopEgammaCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopEgammaCPTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopEgammaCPTools.h" @@ -19,14 +19,13 @@ #include "ElectronPhotonSelectorTools/AsgElectronLikelihoodTool.h" #include "ElectronEfficiencyCorrection/AsgElectronEfficiencyCorrectionTool.h" #include "ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h" -#include "ElectronPhotonSelectorTools/AsgElectronChargeIDSelectorTool.h" #include "ElectronPhotonSelectorTools/AsgPhotonIsEMSelector.h" #include "ElectronPhotonShowerShapeFudgeTool/ElectronPhotonShowerShapeFudgeTool.h" #include "PhotonEfficiencyCorrection/AsgPhotonEfficiencyCorrectionTool.h" +#include "Root/EGSelectorConfigurationMapping.h" namespace top { - -EgammaCPTools::EgammaCPTools(const std::string& name) : + EgammaCPTools::EgammaCPTools(const std::string& name) : asg::AsgTool(name), m_electronEffTriggerFile("SetMe"), m_electronEffTriggerLooseFile("SetMe"), @@ -37,405 +36,719 @@ EgammaCPTools::EgammaCPTools(const std::string& name) : m_electronEffSFIDLooseFile("SetMe"), m_electronEffSFIsoFile("SetMe"), m_electronEffSFIsoLooseFile("SetMe"), - m_electronEffSFChargeIDFile("SetMe") { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); - - declareProperty( "EgammaCalibrationAndSmearingTool" , m_egammaCalibrationAndSmearingTool ); - declareProperty( "ElectronEffTrigger" , m_electronEffTrigger ); - declareProperty( "ElectronEffTriggerLoose" , m_electronEffTriggerLoose ); - declareProperty( "ElectronEffSFTrigger" , m_electronEffSFTrigger ); - declareProperty( "ElectronEffSFTriggerLoose" , m_electronEffSFTriggerLoose ); - declareProperty( "ElectronEffReco" , m_electronEffSFReco ); - declareProperty( "ElectronEffID" , m_electronEffSFID ); - declareProperty( "ElectronEffIDLoose" , m_electronEffSFIDLoose ); - declareProperty( "ElectronEffIso" , m_electronEffSFIso ); - declareProperty( "ElectronEffIsoLoose" , m_electronEffSFIsoLoose ); - declareProperty( "ElectronEffChargeID" , m_electronEffSFChargeID ); - - declareProperty( "PhotonIsEMSelectorLoose" , m_photonLooseIsEMSelector); - declareProperty( "PhotonIsEMSelectorMedium" , m_photonMediumIsEMSelector); - declareProperty( "PhotonIsEMSelectorTight" , m_photonTightIsEMSelector); -} - -StatusCode EgammaCPTools::initialize() { - ATH_MSG_INFO("top::EgammaCPTools initialize..."); - - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::EgammaCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; + m_electronEffSFChargeIDFile("SetMe"), + m_electronEffSFChargeIDLooseFile("SetMe"), + m_electronEffSFChargeMisIDFile("SetMe"), + m_electronEffSFChargeMisIDLooseFile("SetMe") { +// m_fwdElectronEffSFIDFile("SetMe"), +// m_fwdElectronEffSFIDLooseFile("SetMe") { + declareProperty("config", m_config); + + declareProperty("EgammaCalibrationAndSmearingTool", m_egammaCalibrationAndSmearingTool); + declareProperty("ElectronEffTrigger", m_electronEffTrigger); + declareProperty("ElectronEffTriggerLoose", m_electronEffTriggerLoose); + declareProperty("ElectronEffSFTrigger", m_electronEffSFTrigger); + declareProperty("ElectronEffSFTriggerLoose", m_electronEffSFTriggerLoose); + declareProperty("ElectronEffReco", m_electronEffSFReco); + declareProperty("ElectronEffID", m_electronEffSFID); + declareProperty("ElectronEffIDLoose", m_electronEffSFIDLoose); + declareProperty("ElectronEffIso", m_electronEffSFIso); + declareProperty("ElectronEffIsoLoose", m_electronEffSFIsoLoose); + declareProperty("ElectronEffChargeID", m_electronEffSFChargeID); + declareProperty("ElectronEffChargeIDLoose", m_electronEffSFChargeIDLoose); + + declareProperty("ElectronEffTriggerCorrModel", m_electronEffTriggerCorrModel); + declareProperty("ElectronEffTriggerLooseCorrModel", m_electronEffTriggerLooseCorrModel); + declareProperty("ElectronEffSFTriggerCorrModel", m_electronEffSFTriggerCorrModel); + declareProperty("ElectronEffSFTriggerLooseCorrModel", m_electronEffSFTriggerLooseCorrModel); + declareProperty("ElectronEffRecoCorrModel", m_electronEffSFRecoCorrModel); + declareProperty("ElectronEffIDCorrModel", m_electronEffSFIDCorrModel); + declareProperty("ElectronEffIDLooseCorrModel", m_electronEffSFIDLooseCorrModel); + declareProperty("ElectronEffIsoCorrModel", m_electronEffSFIsoCorrModel); + declareProperty("ElectronEffIsoLooseCorrModel", m_electronEffSFIsoLooseCorrModel); + + declareProperty("PhotonIsEMSelectorLoose", m_photonLooseIsEMSelector); + declareProperty("PhotonIsEMSelectorMedium", m_photonMediumIsEMSelector); + declareProperty("PhotonIsEMSelectorTight", m_photonTightIsEMSelector); + +// declareProperty("FwdElectronSelector", m_fwdElectronSelector); +// declareProperty("FwdElectronSelectorLoose", m_fwdElectronSelectorLoose); +// declareProperty("FwdElectronEffIDLoose", m_fwdElectronEffSFIDLoose); +// declareProperty("WebBunchCrossingTool", m_webBunchCrossingTool); } - if (m_config->usePhotons() || m_config->useElectrons()) { - if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs - top::check(setupCalibration(), "Failed to setup Egamma calibration tools"); + StatusCode EgammaCPTools::initialize() { + ATH_MSG_INFO("top::EgammaCPTools initialize..."); + + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::EgammaCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; } - if (m_config->isMC()) {// scale-factors are only for MC - top::check(setupScaleFactors(), "Failed to setup Egamma scale-factor tools"); + + if (m_config->usePhotons() || m_config->useElectrons() || m_config->useFwdElectrons()) { + if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs + top::check(setupCalibration(), "Failed to setup Egamma calibration tools"); + } + if (m_config->useFwdElectrons() && m_config->makeAllCPTools()) { + top::check(setupSelectors(), "Failed to setup Fwd electrons selectors tools"); + } + if (m_config->isMC()) {// scale-factors are only for MC + top::check(setupScaleFactors(), "Failed to setup Egamma scale-factor tools"); + } + } else { + ATH_MSG_INFO( + "top::EgammaCPTools: no need to initialise anything since using neither electrons nor fwd electrons nor photons"); } - } - else { - ATH_MSG_INFO("top::EgammaCPTools: no need to initialise anything since using neither electrons nor photons"); - } - return StatusCode::SUCCESS; -} - - -StatusCode EgammaCPTools::setupCalibration() { - // Setup electron and photon calibration tools - // List of tools include: - // - EgammaCalibrationAndSmearingTool - // - Electron Charge ID Selector tool - // - Photon shower shape fudge tool - // - Photon efficiency correction tool - using IEgammaCalibTool = CP::IEgammaCalibrationAndSmearingTool; - const std::string egamma_calib_name = "CP::EgammaCalibrationAndSmearingTool"; - if (asg::ToolStore::contains<IEgammaCalibTool>(egamma_calib_name)) { - m_egammaCalibrationAndSmearingTool = asg::ToolStore::get<IEgammaCalibTool>(egamma_calib_name); - } else { - IEgammaCalibTool* egammaCalibrationAndSmearingTool = new CP::EgammaCalibrationAndSmearingTool(egamma_calib_name); - top::check(asg::setProperty(egammaCalibrationAndSmearingTool, - "ESModel", "es2016data_mc15c"), - "Failed to set ESModel for " + egamma_calib_name); - top::check(asg::setProperty(egammaCalibrationAndSmearingTool, - "decorrelationModel", - m_config->egammaSystematicModel()), - "Failed to set decorrelationModel for " + egamma_calib_name); - - if(m_config->isAFII()) - top::check(asg::setProperty(egammaCalibrationAndSmearingTool, - "useAFII", 1), - "Failed to useAFII to true for" + egamma_calib_name); - top::check(egammaCalibrationAndSmearingTool->initialize(), - "Failed to initialize " + egamma_calib_name); - m_egammaCalibrationAndSmearingTool = egammaCalibrationAndSmearingTool; + return StatusCode::SUCCESS; } - // - Electron Charge ID Selector Tool - // The only supported working point is Medium with 97% integrated efficiency - // Note: this working point is to be applied on top of MediumLLH + d0z0 cuts + isolFixedCutTight - // https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/ElectronChargeFlipTaggerTool - std::string toolName="ECIDS_medium"; - AsgElectronChargeIDSelectorTool* electronChargeIDSelectorTool = new AsgElectronChargeIDSelectorTool(toolName); - std::string trainingfile="ElectronPhotonSelectorTools/ChargeID/ECIDS_20161125for2017Moriond.root"; - float BDT_OP=-0.28087; //Set your operating point with the table above. - top::check( electronChargeIDSelectorTool->setProperty("TrainingFile",trainingfile) , "Failed to setProperty" ); - top::check( electronChargeIDSelectorTool->setProperty("CutOnBDT",BDT_OP) , "Failed to setProperty" ); - top::check( electronChargeIDSelectorTool->initialize() , "Failed to initialize" ); - - // The terribly named ElectronPhotonShowerShapeFudgeTool... - // We apply this only to photons to correct the shower shape - // This should only be applied on MC - using IFudgeTool = IElectronPhotonShowerShapeFudgeTool; - const std::string fudgeName = "PhotonFudgeTool"; - if (asg::ToolStore::contains<IFudgeTool>(fudgeName)) { - m_photonFudgeTool = asg::ToolStore::get<IFudgeTool>(fudgeName); - } else { - IFudgeTool* fudge_tool = new ElectronPhotonShowerShapeFudgeTool(fudgeName); - // Set Preselection to 21 (was 16) according to http://cern.ch/go/trk9 - // for MC15 samples, which are based on a geometry derived from GEO-21 from 2015+2016 data - top::check(asg::setProperty(fudge_tool, "Preselection", 21), - "Failed to set " + fudgeName + " property: Preselection"); - top::check(fudge_tool->initialize(), - "Failed to initialize PhotonFudgeTool"); - m_photonFudgeTool = fudge_tool; + StatusCode EgammaCPTools::setupSelectors() { + ATH_MSG_INFO("top::EgammaCPTools setupSelectors.."); + if (m_config->useFwdElectrons()) { +// m_fwdElectronSelector = new AsgForwardElectronLikelihoodTool("CP::FwdElectronSelector"); +// top::check(m_fwdElectronSelector->setProperty("ConfigFile", +// EgammaSelectors::ForwardLHPointToConfFile.at( +// m_config->fwdElectronID() + "LHForwardElectron")), +// "Failed to set config for AsgElectronFwdLikelihoodTool"); +// top::check(m_fwdElectronSelector->initialize(), "Couldn't initialise Forward Electron LH ID Tool"); +// +// m_fwdElectronSelectorLoose = new AsgForwardElectronLikelihoodTool("CP::FwdElectronSelectorLoose"); +// top::check(m_fwdElectronSelectorLoose->setProperty("ConfigFile", +// EgammaSelectors::ForwardLHPointToConfFile.at( +// m_config->fwdElectronIDLoose() + "LHForwardElectron")), +// "Failed to set config for AsgElectronFwdLikelihoodTool"); +// top::check(m_fwdElectronSelectorLoose->initialize(), "Couldn't initialise Forward Electron LH ID Loose Tool"); + + if (!m_config->isMC()) { + ATH_MSG_INFO("top::EgammaCPTools setting up web bunch crossing tool"); +// m_webBunchCrossingTool = new Trig::WebBunchCrossingTool("CP::WebBunchCrossingTool"); +// top::check(m_webBunchCrossingTool->setProperty("OutputLevel", +// MSG::INFO), "failed to set propert for WebBunchCrossingTool"); +// top::check(m_webBunchCrossingTool->setProperty("ServerAddress", +// "atlas-trigconf.cern.ch"), +// "failed to set propert for WebBunchCrossingTool"); + } + } + return StatusCode::SUCCESS; } - // The photon efficiency SF tool - bool af2 = m_config->isAFII(); - int data_type = 0; // Data - if (m_config->isMC()) { - data_type = 1; // Full sim - if (af2) { - data_type = 3; // AF2 + StatusCode EgammaCPTools::setupCalibration() { + // Setup electron and photon calibration tools + // List of tools include: + // - EgammaCalibrationAndSmearingTool + // - Electron Charge ID Selector tool + // - Photon shower shape fudge tool + // - Photon efficiency correction tool + using IEgammaCalibTool = CP::IEgammaCalibrationAndSmearingTool; + const std::string egamma_calib_name = "CP::EgammaCalibrationAndSmearingTool"; + if (asg::ToolStore::contains<IEgammaCalibTool>(egamma_calib_name)) { + m_egammaCalibrationAndSmearingTool = asg::ToolStore::get<IEgammaCalibTool>(egamma_calib_name); + } else { + IEgammaCalibTool* egammaCalibrationAndSmearingTool = new CP::EgammaCalibrationAndSmearingTool(egamma_calib_name); + top::check(asg::setProperty(egammaCalibrationAndSmearingTool, + "ESModel", "es2018_R21_v0"), + "Failed to set ESModel for " + egamma_calib_name); + top::check(asg::setProperty(egammaCalibrationAndSmearingTool, + "decorrelationModel", + m_config->egammaSystematicModel()), + "Failed to set decorrelationModel for " + egamma_calib_name); + + if (m_config->isAFII()) { + top::check(asg::setProperty(egammaCalibrationAndSmearingTool, + "useAFII", 1), + "Failed to useAFII to true for" + egamma_calib_name); + } + top::check(egammaCalibrationAndSmearingTool->initialize(), + "Failed to initialize " + egamma_calib_name); + m_egammaCalibrationAndSmearingTool = egammaCalibrationAndSmearingTool; } - } - // The file to make the tool with. - std::string file_base = "PhotonEfficiencyCorrection/"; - std::string file_map = file_base + "2015_2016/rel20.7/Moriond2017_v1/map0.txt"; - file_map = PathResolverFindCalibFile(file_map); - std::string file_con = ""; - std::string file_unc = ""; - if (af2) { - // for AFII we keep using the previous recommendations - file_base += "v1/efficiencySF.offline.Tight.2015.13TeV.rel20.AFII."; - file_con = file_base; // Conv file - file_unc = file_base; // Unconv file - file_con += "con.v01.root"; - file_con = PathResolverFindCalibFile(file_con); - file_unc += "unc.v01.root"; - file_unc = PathResolverFindCalibFile(file_unc); - } + // The terribly named ElectronPhotonShowerShapeFudgeTool... + // We apply this only to photons to correct the shower shape + // This should only be applied on MC + using IFudgeTool = IElectronPhotonShowerShapeFudgeTool; + const std::string fudgeName = "PhotonFudgeTool"; + if (asg::ToolStore::contains<IFudgeTool>(fudgeName)) { + m_photonFudgeTool = asg::ToolStore::get<IFudgeTool>(fudgeName); + } else { + IFudgeTool* fudge_tool = new ElectronPhotonShowerShapeFudgeTool(fudgeName); + // Set Preselection to 22 + // for MC15 samples, which are based on a geometry derived from GEO-21 from 2015+2016 data + top::check(asg::setProperty(fudge_tool, "Preselection", 22), + "Failed to set " + fudgeName + " property: Preselection"); + top::check(asg::setProperty(fudge_tool, "FFCalibFile", + "ElectronPhotonShowerShapeFudgeTool/v2/PhotonFudgeFactors.root"), + "Failed to set ElectronPhotonShowerShapeFudgeTool"); + top::check(fudge_tool->initialize(), + "Failed to initialize PhotonFudgeTool"); + m_photonFudgeTool = fudge_tool; + } - using IPhotonEffTool = IAsgPhotonEfficiencyCorrectionTool; - const std::string photonSFName = "AsgPhotonEfficiencyCorrectionTool"; // to retrieve ID Eff scale factors - if (asg::ToolStore::contains<IPhotonEffTool>(photonSFName)) { - m_photonEffSF = asg::ToolStore::get<IPhotonEffTool>(photonSFName); - } else { - if (m_config->isMC()) { // Seem to only be able to setup the tool for MC - IPhotonEffTool* photonEffSF = new AsgPhotonEfficiencyCorrectionTool(photonSFName); - if (!af2) { - top::check(asg::setProperty(photonEffSF, - "MapFilePath", - file_map), - "Failed to set MapFilePath for " + photonSFName); + // The photon efficiency SF tool + bool af2 = m_config->isAFII(); + int data_type = 0; // Data + if (m_config->isMC()) { + if (af2) { + ATH_MSG_WARNING("PhotonEfficiencies - Currently there are no recommendations for FastSimulation photons"); + ATH_MSG_WARNING("PhotonEfficiencies - Therefore we are advised to treat FastSim as FullSim for configuration"); + //data_type = 3; // AF2 + data_type = 1; // AF2 masquerading as full sim } else { - top::check(asg::setProperty(photonEffSF, - "CorrectionFileNameConv", - file_con), - "Failed to set CorrectionFileNameConv for " + photonSFName); - top::check(asg::setProperty(photonEffSF, - "CorrectionFileNameUnconv", - file_unc), - "Failed to set CorrectionFileNameUnconv for " + photonSFName); + data_type = 1; // Full sim } - top::check(asg::setProperty(photonEffSF, "ForceDataType", data_type), - "Failed to set ForceDataType for " + photonSFName); - top::check(photonEffSF->initialize(), - "Failed to initialize " + photonSFName); - m_photonEffSF = photonEffSF; } - } - // https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/IsolationSF2016Moriond#Radiative_Z_low_ET - // To retrieve Isolation Eff scale factors - // N.B. Naming for isolation working points for AsgPhotonEfficiencyCorrectionTool isolation scale factors - // are different than those for the IsolationCorrectionTool (preceded by FixedCut) - std::set<std::string> photon_isolations = {"TightCaloOnly", - "Tight", - "Loose"}; - for (const std::string& isoWP : photon_isolations) { - std::string photonIsoSFName = "AsgPhotonEfficiencyCorrectionTool_IsoSF" + isoWP; - if (!asg::ToolStore::contains<IPhotonEffTool>(photonIsoSFName)) { - if (m_config->isMC() && !af2) { // only available for full simulation - IPhotonEffTool* photonIsoSFTool = new AsgPhotonEfficiencyCorrectionTool(photonIsoSFName); - top::check(asg::setProperty(photonIsoSFTool, - "MapFilePath", - file_map), - "Failed to set MapFilePath for " + photonIsoSFName); - top::check(asg::setProperty(photonIsoSFTool, "ForceDataType", data_type), - "Failed to set ForceDataType for " + photonIsoSFName); - top::check(asg::setProperty(photonIsoSFTool, "UseRadiativeZSF_mediumPT", m_config->photonUseRadiativeZ()), - "Failed to set useRadiativeZSF_mediumPT for " + photonIsoSFName); - top::check(asg::setProperty(photonIsoSFTool, "IsoWP", isoWP), - "Failed to set IsoWP for " + photonIsoSFName); - top::check(photonIsoSFTool->initialize(), - "Failed to initialize " + photonIsoSFName); - m_photonIsoSFTools.push_back(photonIsoSFTool); + using IPhotonEffTool = IAsgPhotonEfficiencyCorrectionTool; + const std::string photonSFName = "AsgPhotonEfficiencyCorrectionTool"; // to retrieve ID Eff scale factors + if (asg::ToolStore::contains<IPhotonEffTool>(photonSFName)) { + m_photonEffSF = asg::ToolStore::get<IPhotonEffTool>(photonSFName); + } else { + if (m_config->isMC()) { // Seem to only be able to setup the tool for MC + IPhotonEffTool* photonEffSF = new AsgPhotonEfficiencyCorrectionTool(photonSFName); + top::check(asg::setProperty(photonEffSF, "ForceDataType", data_type), + "Failed to set ForceDataType for " + photonSFName); + top::check(photonEffSF->initialize(), + "Failed to initialize " + photonSFName); + m_photonEffSF = photonEffSF; } } - } - return StatusCode::SUCCESS; -} - -StatusCode EgammaCPTools::setupScaleFactors() { - // Don't need for data, return SUCCESS straight away - if (!m_config->isMC()) return StatusCode::SUCCESS; - ///-- Scale factors --/// - - std::string electron_data_dir = "ElectronEfficiencyCorrection/"; - ///-- Reco SFs doesn't depend on WP --/// - std::string electronID = m_config->electronID(); - electronID.replace(electronID.find("LH"), 2, "LLH"); // that way people do not have to change their cuts file - std::string electronIDLoose = m_config->electronIDLoose(); - electronIDLoose.replace(electronIDLoose.find("LH"), 2, "LLH"); // that way people do not have to change their cuts file - - m_electronEffSFRecoFile = electronSFFilePath("reco"); - m_electronEffSFIDFile = electronSFFilePath("ID", electronID); - m_electronEffSFTriggerFile = electronSFFilePath("triggerSF", electronID, - m_config->electronIsolation()); - if (m_electronEffSFTriggerFile.empty()) { - m_electronEffSFTriggerFile = electronSFFilePath("triggerSF", electronID, - "None"); - } - m_electronEffTriggerFile = electronSFFilePath("triggerEff", electronID, - m_config->electronIsolation()); - if (m_electronEffTriggerFile.empty()) { - m_electronEffTriggerFile = electronSFFilePath("triggerEff", electronID, - "None"); - } - if (m_config->electronIsolation() != "None") { - m_electronEffSFIsoFile = electronSFFilePath("isolation", electronID, - m_config->electronIsolation()); - } - // Loose SFs - m_electronEffSFIDLooseFile = electronSFFilePath("ID", electronIDLoose); - m_electronEffSFTriggerLooseFile = electronSFFilePath("triggerSF", electronIDLoose, - m_config->electronIsolationLoose()); - if (m_electronEffSFTriggerLooseFile.empty()) { - m_electronEffSFTriggerLooseFile = electronSFFilePath("triggerSF", electronIDLoose, - "None"); - } - m_electronEffTriggerLooseFile = electronSFFilePath("triggerEff", electronIDLoose, - m_config->electronIsolationLoose()); - if (m_electronEffTriggerLooseFile.empty()) { - m_electronEffTriggerLooseFile = electronSFFilePath("triggerEff", electronIDLoose, - "None"); - } - if (m_config->electronIsolationLoose() != "None") { - m_electronEffSFIsoLooseFile = electronSFFilePath("isolation", electronIDLoose, - m_config->electronIsolationLoose()); - } - // for the moment only for MediumLH and FixedCutTight isolation - // either at Tight or Loose level - if ( ( electronIDLoose == "MediumLLH" && m_config->electronIsolationLoose() == "FixedCutTight" ) - || ( electronID == "MediumLLH" && m_config->electronIsolation() == "FixedCutTight" ) ) { - m_electronEffSFChargeIDFile = electronSFFilePath("ChargeID", "MediumLLH", - "FixedCutTight"); - } - // The tools want the files in vectors: remove this with function - std::vector<std::string> inRecoSF {m_electronEffSFRecoFile}; - std::vector<std::string> inIDSF {m_electronEffSFIDFile}; - std::vector<std::string> inTriggerSF {m_electronEffSFTriggerFile}; - std::vector<std::string> inTrigger {m_electronEffTriggerFile}; - - std::vector<std::string> inIDSFLoose {m_electronEffSFIDLooseFile}; - std::vector<std::string> inTriggerSFLoose {m_electronEffSFTriggerLooseFile}; - std::vector<std::string> inTriggerLoose {m_electronEffTriggerLooseFile}; - std::vector<std::string> inChargeID {m_electronEffSFChargeIDFile}; - - /********************************************************************** - * Electron Isolation - * Some WPs aren't supported at the moment... - * As people want to use e.g. LooseLH electrons, we will allow - * everything to procede without the isolation SFs, although they - * should be careful and have to set ElectronIsoSFs False in their config - **********************************************************************/ - std::vector< std::string > inIso; - std::vector< std::string > inIsoLoose; - - if (m_config->electronIsolation() != "None") { - if (m_electronEffSFIsoFile.empty()) { - ATH_MSG_WARNING("Electron isolation configuration not found"); - if (m_config->electronIsoSFs()) { - ATH_MSG_WARNING("If you really want to run with this electron " - "ID/Isolation setup then you can add:" - "\tElectronIsoSFs False\tto your config file"); - return StatusCode::FAILURE; + // https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/IsolationSF2016Moriond#Radiative_Z_low_ET + // To retrieve Isolation Eff scale factors + // N.B. Naming for isolation working points for AsgPhotonEfficiencyCorrectionTool isolation scale factors + // are different than those for the IsolationCorrectionTool (preceded by FixedCut) + std::set<std::string> photon_isolations = { + "Tight", + "Loose", + "TightCaloOnly" + }; + for (const std::string& isoWP : photon_isolations) { + std::string photonIsoSFName = "AsgPhotonEfficiencyCorrectionTool_IsoSF" + isoWP; + if (!asg::ToolStore::contains<IPhotonEffTool>(photonIsoSFName)) { + if (m_config->isMC()) { + IPhotonEffTool* photonIsoSFTool = new AsgPhotonEfficiencyCorrectionTool(photonIsoSFName); + top::check(asg::setProperty(photonIsoSFTool, "ForceDataType", data_type), + "Failed to set ForceDataType for " + photonIsoSFName); + top::check(asg::setProperty(photonIsoSFTool, "IsoKey", isoWP), + "Failed to set IsoKey for " + photonIsoSFName); + top::check(photonIsoSFTool->initialize(), + "Failed to initialize " + photonIsoSFName); + m_photonIsoSFTools.push_back(photonIsoSFTool); + } } - ATH_MSG_INFO("Isolation SFs will be set to 1.0"); - } else { - inIso.push_back( m_electronEffSFIsoFile ); } + return StatusCode::SUCCESS; } - if (m_config->electronIsolationLoose() != "None") { - if (m_electronEffSFIsoLooseFile.empty()) { - ATH_MSG_WARNING("Loose Electron isolation configuration not found"); - if (m_config->electronIsoSFs()) { - ATH_MSG_WARNING("If you really want to run with this (loose) " - "electron ID/Isolation setup then you can add:" - "\tElectronIsoSFs False\tto your config file"); - return StatusCode::FAILURE; + + StatusCode EgammaCPTools::setupScaleFactors() { + // Don't need for data, return SUCCESS straight away + if (!m_config->isMC()) return StatusCode::SUCCESS; + + ///-- Scale factors --/// + std::string electron_data_dir = "ElectronEfficiencyCorrection/"; + + // Define the data type variable - 0 : Data, 1 : MC FullSim, 3 : MC AFII + int dataType(0); + if (m_config->isMC()) { + dataType = (m_config->isAFII()) ? 3 : 1; + } + + ///-- Reco SFs doesn't depend on WP --/// + std::string electronID = m_config->electronID(); + if (electronID.find("LH") != std::string::npos) electronID.replace(electronID.find("LH"), 2, "LLH"); // that way + // people do + // not have to + // change their + // cuts file + std::string electronIDLoose = m_config->electronIDLoose(); + if (electronIDLoose.find("LH") != std::string::npos) electronIDLoose.replace(electronIDLoose.find("LH"), 2, "LLH"); // that + // way + // people + // do + // not + // have + // to + // change + // their + // cuts + // file + std::string electronIsolation = mapWorkingPoints(m_config->electronIsolationSF()); // temporary fix: we can + // hopefully remove the map soon! + std::string electronIsolationLoose = mapWorkingPoints(m_config->electronIsolationSFLoose()); + + // Retrieve full path to maps for different types of tool + m_electronEffSFRecoFile = electronSFMapFilePath("reco"); + // - Tight + m_electronEffSFIDFile = electronSFMapFilePath("ID"); + m_electronEffSFTriggerFile = electronSFMapFilePath("trigger"); + m_electronEffTriggerFile = electronSFMapFilePath("trigger"); + std::vector<std::string> inPLViso; + if (electronIsolation == "PLVTight" || + electronIsolation == "PLVLoose") { + m_electronEffSFIsoFile = electronSFFilePath("PLV", electronID, electronIsolation); + inPLViso.push_back(m_electronEffSFIsoFile); + } + else { + m_electronEffSFIsoFile = electronSFMapFilePath("isolation"); + } + // - Loose + m_electronEffSFIDLooseFile = electronSFMapFilePath("ID"); + m_electronEffSFTriggerLooseFile = electronSFMapFilePath("trigger"); + m_electronEffTriggerLooseFile = electronSFMapFilePath("trigger"); + std::vector<std::string> inPLVisoLoose; + if (electronIsolationLoose == "PLVTight" || + electronIsolationLoose == "PLVLoose") { + m_electronEffSFIsoLooseFile = electronSFFilePath("PLV", electronID, electronIsolationLoose); + inPLVisoLoose.push_back(m_electronEffSFIsoLooseFile); + } + else { + m_electronEffSFIsoLooseFile = electronSFMapFilePath("isolation"); + } + + // Define the trigger string for scale factors + const std::string trigger_string = "SINGLE_E_2015_e24_lhmedium_L1EM20VH_" + "OR_e60_lhmedium_" + "OR_e120_lhloose_" + "2016_2018_e26_lhtight_nod0_ivarloose_" + "OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0"; + + + + // Define the tool prefix name + const std::string elSFPrefix = "AsgElectronEfficiencyCorrectionTool_"; + + ATH_MSG_INFO("Setting up Electrons SF tool for TOTAL correlation model"); + // Configure the tools with the maps - Name, map, reco_key, ID_key, iso_key, trigger_key, data_type, for the TOTAL + // correlation model + // Reco SFs + m_electronEffSFReco = setupElectronSFToolWithMap(elSFPrefix + "Reco", m_electronEffSFRecoFile, "Reconstruction", "", + "", "", dataType, "TOTAL", "", ""); + // ID SFs + m_electronEffSFID = setupElectronSFToolWithMap(elSFPrefix + "ID", m_electronEffSFIDFile, "", electronID, "", "", + dataType, "TOTAL", "", ""); + m_electronEffSFIDLoose = setupElectronSFToolWithMap(elSFPrefix + "IDLoose", m_electronEffSFIDLooseFile, "", + electronIDLoose, "", "", dataType, "TOTAL", "", ""); + // Trigger SFs + m_electronEffSFTrigger = setupElectronSFToolWithMap(elSFPrefix + "TriggerSF", m_electronEffSFTriggerFile, "", + electronID, electronIsolation, trigger_string, dataType, + "TOTAL", "", ""); + m_electronEffSFTriggerLoose = setupElectronSFToolWithMap(elSFPrefix + "TriggerSFLoose", + m_electronEffSFTriggerLooseFile, "", electronIDLoose, + electronIsolationLoose, trigger_string, dataType, "TOTAL", + "", ""); + // Trigger Efficiencies + m_electronEffTrigger = setupElectronSFToolWithMap(elSFPrefix + "Trigger", m_electronEffTriggerFile, "", electronID, + electronIsolation, "Eff_" + trigger_string, dataType, "TOTAL", "", + ""); + m_electronEffTriggerLoose = setupElectronSFToolWithMap(elSFPrefix + "TriggerLoose", m_electronEffTriggerLooseFile, + "", electronIDLoose, electronIsolationLoose, + "Eff_" + trigger_string, dataType, "TOTAL", "", ""); + // Isolation SFs + if (electronIsolation == "PLVTight" || + electronIsolation == "PLVLoose") { + m_electronEffSFIso = setupElectronSFTool(elSFPrefix + "Iso", inPLViso, dataType); + } + else { + m_electronEffSFIso = setupElectronSFToolWithMap(elSFPrefix + "Iso", m_electronEffSFIsoFile, "", electronID, + electronIsolation, "", dataType, "TOTAL", "", ""); + } + if (electronIsolationLoose == "PLVTight" || + electronIsolationLoose == "PLVLoose") { + m_electronEffSFIsoLoose = setupElectronSFTool(elSFPrefix + "IsoLoose", inPLVisoLoose, dataType); + } + else { + m_electronEffSFIsoLoose = setupElectronSFToolWithMap(elSFPrefix + "IsoLoose", m_electronEffSFIsoLooseFile, "", + electronIDLoose, electronIsolationLoose, "", dataType, "TOTAL", "", + ""); + } + + ATH_MSG_INFO( + "Requested Electrons SF tool for " << m_config->electronEfficiencySystematicModel() << " correlation model"); + + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + ATH_MSG_INFO( + "Setting up Electrons SF tool for " << m_config->electronEfficiencySystematicModel() << " correlation model"); + const std::string elSFPrefixCorrModel = elSFPrefix + "CorrModel_"; + // Reco SFs + m_electronEffSFRecoCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "Reco", m_electronEffSFRecoFile, + "Reconstruction", "", "", "", dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + // ID SFs + m_electronEffSFIDCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "ID", m_electronEffSFIDFile, "", + electronID, "", "", dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + m_electronEffSFIDLooseCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "IDLoose", + m_electronEffSFIDLooseFile, "", electronIDLoose, "", + "", dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + // Trigger SFs + m_electronEffSFTriggerCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "TriggerSF", + m_electronEffSFTriggerFile, "", electronID, + electronIsolation, trigger_string, dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + m_electronEffSFTriggerLooseCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "TriggerSFLoose", + m_electronEffSFTriggerLooseFile, "", + electronIDLoose, electronIsolationLoose, + trigger_string, dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + // Trigger Efficiencies + m_electronEffTriggerCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "Trigger", + m_electronEffTriggerFile, "", electronID, + electronIsolation, "Eff_" + trigger_string, dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + m_electronEffTriggerLooseCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "TriggerLoose", + m_electronEffTriggerLooseFile, "", + electronIDLoose, electronIsolationLoose, + "Eff_" + trigger_string, dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + // Isolation SFs + if (electronIsolation == "PLVTight" || + electronIsolation == "PLVLoose") { + m_electronEffSFIsoCorrModel = setupElectronSFTool(elSFPrefixCorrModel + "Iso", inPLViso, dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + } + else { + m_electronEffSFIsoCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "Iso", m_electronEffSFIsoFile, "", + electronID, electronIsolation, "", dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + } + if (electronIsolationLoose == "PLVTight" || + electronIsolationLoose == "PLVLoose") { + m_electronEffSFIsoLooseCorrModel = setupElectronSFTool(elSFPrefixCorrModel + "IsoLoose", inPLVisoLoose, dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); + + } + else { + m_electronEffSFIsoLooseCorrModel = setupElectronSFToolWithMap(elSFPrefixCorrModel + "IsoLoose", + m_electronEffSFIsoLooseFile, "", electronIDLoose, + electronIsolationLoose, "", dataType, + m_config->electronEfficiencySystematicModel(), + m_config->electronEfficiencySystematicModelEtaBinning(), + m_config->electronEfficiencySystematicModelEtBinning()); } - ATH_MSG_INFO("Loose Isolation SFs will be set to 1.0"); - } else { - inIsoLoose.push_back( m_electronEffSFIsoLooseFile ); } - } - // data type - // 0 : Data - // 1 : MC FullSim - // 3 : MC AFII - int dataType(0); - if (m_config->isMC()) { - dataType = (m_config->isAFII()) ? 3 : 1; - } - - const std::string elSFPrefix = "AsgElectronEfficiencyCorrectionTool_"; - - // Reco SFs - m_electronEffSFReco = setupElectronSFTool(elSFPrefix + "Reco", inRecoSF, dataType); - // Trigger SFs - m_electronEffSFTrigger = setupElectronSFTool(elSFPrefix + "TriggerSF", inTriggerSF, dataType); - m_electronEffSFTriggerLoose = setupElectronSFTool(elSFPrefix + "TriggerSFLoose", inTriggerSFLoose, dataType); - // Trigger Efficiencies (wow- this is bad naming!) - m_electronEffTrigger = setupElectronSFTool(elSFPrefix + "Trigger", inTrigger, dataType); - m_electronEffTriggerLoose = setupElectronSFTool(elSFPrefix + "TriggerLoose", inTriggerLoose, dataType); - // ID SFs - m_electronEffSFID = setupElectronSFTool(elSFPrefix + "ID", inIDSF, dataType); - m_electronEffSFIDLoose = setupElectronSFTool(elSFPrefix + "IDLoose", inIDSFLoose, dataType); - // Isolation SFs - m_electronEffSFIso = setupElectronSFTool(elSFPrefix + "Iso", inIso, dataType); - m_electronEffSFIsoLoose = setupElectronSFTool(elSFPrefix + "IsoLoose", inIsoLoose, dataType); - - // ChargeID SFs (if using Electron Charge ID Selector Tool) - // for the moment only for MediumLH and FixedCutTight isolation - // either at Tight or Loose level - if ( ( electronIDLoose == "MediumLLH" && m_config->electronIsolationLoose() == "FixedCutTight" ) - || ( electronID == "MediumLLH" && m_config->electronIsolation() == "FixedCutTight" ) ) { - // Charge Id efficiency scale factor - m_electronEffSFChargeID = setupElectronSFTool(elSFPrefix + "ChargeID", inChargeID, dataType); + if (m_config->useFwdElectrons()) { + ATH_MSG_INFO("Setting up forward Electrons SF tool"); + +// m_fwdElectronEffSFIDFile = electronSFMapFilePath("FWDID"); +// m_fwdElectronEffSFIDLooseFile = electronSFMapFilePath("FWDID"); +// m_fwdElectronEffSFID = setupElectronSFToolWithMap("AsgFwdElectronEfficiencyCorrectionTool_ID", +// m_fwdElectronEffSFIDFile, "", +// "Fwd" + m_config->fwdElectronID(), "", "", dataType, "TOTAL", "", +// ""); +// m_fwdElectronEffSFIDLoose = setupElectronSFToolWithMap("AsgFwdElectronEfficiencyCorrectionTool_IDLoose", +// m_fwdElectronEffSFIDLooseFile, "", +// "Fwd" + m_config->fwdElectronIDLoose(), "", "", dataType, "TOTAL", "", +// ""); + + ATH_MSG_INFO("Finished setting up forward Electrons SF tool"); + } + + // Charge ID cannot use maps at the moment so we default to the old method + if (m_config->useElectronChargeIDSelection() + && electronIsolation != "PLVTight" + && electronIsolation != "PLVLoose" + && electronIsolationLoose != "PLVTight" + && electronIsolationLoose != "PLVLoose" ) { // We need to update the implementation according to new + // recommendations + ATH_MSG_INFO("Setting up Electrons ChargeID SF tool"); + // Charge ID file (no maps) + m_electronEffSFChargeIDFile = electronSFFilePath("ChargeID", electronID, electronIsolation); + if (m_config->applyTightSFsInLooseTree()) // prevent crash on-supported loose electron WPs with ECIDS + m_electronEffSFChargeIDLooseFile = electronSFFilePath("ChargeID", electronID, electronIsolation); + else m_electronEffSFChargeIDLooseFile = electronSFFilePath("ChargeID", electronIDLoose, electronIsolationLoose); + // The tools want the files in vectors: remove this with function + std::vector<std::string> inChargeID { + m_electronEffSFChargeIDFile + }; + std::vector<std::string> inChargeIDLoose { + m_electronEffSFChargeIDLooseFile + }; + // Charge Id efficiency scale factor + m_electronEffSFChargeID = setupElectronSFTool(elSFPrefix + "ChargeID", inChargeID, dataType); + m_electronEffSFChargeIDLoose = setupElectronSFTool(elSFPrefix + "ChargeIDLoose", inChargeIDLoose, dataType); + } // Charge flip correction: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/EgammaChargeMisIdentificationTool - CP::ElectronChargeEfficiencyCorrectionTool* ChargeMisIDCorrections = new CP::ElectronChargeEfficiencyCorrectionTool("ElectronChargeEfficiencyCorrection"); - //top::check( ChargeMisIDCorrections->setProperty("OutputLevel", MSG::VERBOSE ) , "Failed to setProperty" ); - top::check( ChargeMisIDCorrections->setProperty("CorrectionFileName", "ElectronEfficiencyCorrection/2015_2016/rel20.7/Moriond_February2017_v1/charge_misID/ChargeCorrectionSF.Medium_FixedCutTightIso_CFTMedium.root") , "Failed to setProperty" ); - top::check( ChargeMisIDCorrections->initialize() , "Failed to setProperty" ); + CP::ElectronChargeEfficiencyCorrectionTool* ChargeMisIDCorrections = new CP::ElectronChargeEfficiencyCorrectionTool( + "ElectronChargeEfficiencyCorrection"); + CP::ElectronChargeEfficiencyCorrectionTool* ChargeMisIDCorrectionsLoose = + new CP::ElectronChargeEfficiencyCorrectionTool("ElectronChargeEfficiencyCorrectionLoose"); + m_electronEffSFChargeMisIDFile = electronSFFilePath("ChargeMisID", electronID, electronIsolation); + m_electronEffSFChargeMisIDLooseFile = electronSFFilePath("ChargeMisID", electronIDLoose, electronIsolationLoose); + top::check(ChargeMisIDCorrections->setProperty("CorrectionFileName", + m_electronEffSFChargeMisIDFile), "Failed to setProperty"); + top::check(ChargeMisIDCorrections->initialize(), "Failed to setProperty"); + top::check(ChargeMisIDCorrectionsLoose->setProperty("CorrectionFileName", + m_electronEffSFChargeMisIDLooseFile), "Failed to setProperty"); + top::check(ChargeMisIDCorrectionsLoose->initialize(), "Failed to setProperty"); + + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} + IAsgElectronEfficiencyCorrectionTool* + EgammaCPTools::setupElectronSFTool(const std::string& name, const std::vector<std::string>& file_list, + const int& data_type, + const std::string& correlation_model, + const std::string& correlationModelEtaBinning, + const std::string& correlationModelEtBinning) { + IAsgElectronEfficiencyCorrectionTool* tool = nullptr; + + if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool>(name)) { + tool = asg::ToolStore::get<IAsgElectronEfficiencyCorrectionTool>(name); + } else { + if (!file_list.empty()) { // If the file list is empty do nothing + tool = new AsgElectronEfficiencyCorrectionTool(name); + top::check(asg::setProperty(tool, "CorrectionFileNameList", file_list), + "Failed to set CorrectionFileNameList to " + name); + top::check(asg::setProperty(tool, "ForceDataType", data_type), + "Failed to set ForceDataType to " + name); + top::check(asg::setProperty(tool, "CorrelationModel", correlation_model), + "Failed to set CorrelationModel to " + name); + if (correlationModelEtaBinning != "" && correlationModelEtaBinning != "default") this->setCorrelationModelBinning(tool, "UncorrEtaBinsUser", correlationModelEtaBinning); + if (correlationModelEtBinning != "" && correlationModelEtBinning != "default") this->setCorrelationModelBinning(tool, "UncorrEtBinsUser", correlationModelEtBinning); + top::check(tool->initialize(), "Failed to initialize " + name); + } + } + return tool; + } + + void EgammaCPTools::setCorrelationModelBinning(IAsgElectronEfficiencyCorrectionTool* tool, + const std::string& binningName, const std::string& binning) { + std::vector<std::string> tokens; + top::tokenize(binning, tokens, ":"); + if (tokens.size() < 1) { + ATH_MSG_ERROR( + "EgammaCPTools::setupElectronSFToolWithMap, correlation model " << binningName << + " binning must be in the form XXX:YYY:WWW:ZZZ..."); + } + std::vector<float> bins; + for (unsigned int i = 0; i < tokens.size(); i++) { + std::string token = tokens[i]; + float value = 0.; + try{ + value = std::stof(token); + } + catch (...) { + throw std::invalid_argument { + "EgammaCPTools::setupElectronSFToolWithMap, correlation model " + binningName + + " binning must be in the for XXX:YYY:WWW:ZZZ, couldn't convert correctly to float" + }; + } + bins.push_back(value); + } + ATH_MSG_INFO(" ---> electron SF tools will use " << binningName << " bins:"); + for (unsigned int i = 0; i < bins.size(); i++) ATH_MSG_INFO(" " << bins[i]); + top::check(asg::setProperty(tool, binningName, + bins), "Failed to set correlation model " + binningName + " binning to " + binning); + } -IAsgElectronEfficiencyCorrectionTool* -EgammaCPTools::setupElectronSFTool(const std::string& name, const std::vector<std::string>& file_list, int data_type) { - IAsgElectronEfficiencyCorrectionTool* tool = nullptr; - if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool>(name)) { - tool = asg::ToolStore::get<IAsgElectronEfficiencyCorrectionTool>(name); - } else { - if (!file_list.empty()) { // If the file list is empty do nothing + IAsgElectronEfficiencyCorrectionTool* + EgammaCPTools::setupElectronSFToolWithMap(const std::string& name, const std::string& map_path, + const std::string& reco_key, const std::string& ID_key, + const std::string& ISO_key, const std::string& trigger_key, + const int& data_type, const std::string& correlation_model, + const std::string& correlationModelEtaBinning, + const std::string& correlationModelEtBinning) { + std::string iso_key = ISO_key; + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/LatestRecommendationsElectronIDRun2#PLV_scale_factors_for_central_el + // If isolation WP is PLVTight or PLVLoose, switch to no isolation to trick this function. + if (iso_key == "PLVTight" || iso_key == "PLVLoose") iso_key = ""; + + std::string infoStr = "Configuring : name=" + name + " map=" + map_path + " reco_key=" + reco_key + " ID_key=" + + ID_key + " iso_key=" + iso_key + " trigger_key=" + trigger_key + "data_type=" + + std::to_string(data_type) + + " correlation_model=" + correlation_model + " etaBinning=" + correlationModelEtaBinning + + " etBinning=" + + correlationModelEtBinning; + ATH_MSG_INFO(infoStr); + IAsgElectronEfficiencyCorrectionTool* tool = nullptr; + if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool>(name)) { + tool = asg::ToolStore::get<IAsgElectronEfficiencyCorrectionTool>(name); + } else { tool = new AsgElectronEfficiencyCorrectionTool(name); - top::check(asg::setProperty(tool, "CorrectionFileNameList", file_list), - "Failed to set CorrectionFileNameList to " + name); - top::check(asg::setProperty(tool, "ForceDataType", data_type), - "Failed to set ForceDataType to " + name); - top::check(asg::setProperty(tool, "CorrelationModel", "TOTAL"), - "Failed to set CorrelationModel to " + name); + // Give the full map path + top::check(asg::setProperty(tool, "MapFilePath", map_path), "Failed to set MapFilePath to " + name); + // Set the data type for all tools + top::check(asg::setProperty(tool, "ForceDataType", data_type), "Failed to set ForceDataType to " + name); + // Set the correlation model for all tools + top::check(asg::setProperty(tool, "CorrelationModel", + correlation_model), "Failed to set CorrelationModel to " + name); + + if (correlationModelEtaBinning != "" && correlationModelEtaBinning != "default") this->setCorrelationModelBinning( + tool, "UncorrEtaBinsUser", correlationModelEtaBinning); + if (correlationModelEtBinning != "" && correlationModelEtBinning != "default") this->setCorrelationModelBinning( + tool, "UncorrEtBinsUser", correlationModelEtBinning); + + // Set the keys which configure the tool options (empty string means we do not include this key) + if (reco_key != "" && reco_key != "None") { + ATH_MSG_INFO(" Adding RecoKey : " + reco_key); + top::check(asg::setProperty(tool, "RecoKey", reco_key), "Failed to set RecoKey to " + name); + } + if (ID_key != "" && ID_key != "None") { + std::string id_key = mapWorkingPoints(ID_key); + ATH_MSG_INFO(" Adding IDKey : " + id_key); + top::check(asg::setProperty(tool, "IdKey", id_key), "Failed to set IdKey to " + name); + } + if (iso_key != "" && iso_key != "None") { + ATH_MSG_INFO(" Adding IsoKey : " + iso_key); + top::check(asg::setProperty(tool, "IsoKey", iso_key), "Failed to set IsoKey to " + name); + } + if (trigger_key != "" && trigger_key != "None") { + ATH_MSG_INFO(" Adding TriggerKey : " + trigger_key); + top::check(asg::setProperty(tool, "TriggerKey", trigger_key), "Failed to set TriggerKey to " + name); + } + // Initialise this tool top::check(tool->initialize(), "Failed to initialize " + name); } + return tool; } - return tool; -} - -std::string EgammaCPTools::electronSFFilePath(const std::string& type, const std::string& ID, const std::string& isolation) { - const std::string el_calib_path - = "ElectronEfficiencyCorrection/" - "2015_2016/rel20.7/Moriond_February2017_v1/"; - - const std::string ridiculous_trigger_string - = "SINGLE_E_2015_e24_lhmedium_L1EM20VH_" - "OR_e60_lhmedium_" - "OR_e120_lhloose_" - "2016_e26_lhtight_nod0_ivarloose_" - "OR_e60_lhmedium_nod0_OR_e140_lhloose_nod0"; - - std::string new_iso = (isolation == "None") ? "" : "_isol" + isolation; - - std::string file_path; - - if (type == "reco") { - file_path = "offline/efficiencySF.offline.RecoTrk.root"; - } else if (type == "ID") { - file_path = "offline/efficiencySF.offline." + ID + "_d0z0_v11.root"; - } else if (type == "isolation") { - file_path = "isolation/efficiencySF.Isolation." - + ID + "_d0z0_v11" + new_iso + ".root"; - } else if (type == "triggerSF") { - file_path = "trigger/efficiencySF." + ridiculous_trigger_string - + "." + ID + "_d0z0_v11" + new_iso + ".root"; - } else if (type == "triggerEff") { - file_path = "trigger/efficiency." + ridiculous_trigger_string - + "." + ID + "_d0z0_v11" + new_iso + ".root"; - } else if (type == "ChargeID") { - if (ID != "MediumLLH") ATH_MSG_WARNING("Only Medium WP available at the moment " + ID); - file_path = "charge_misID/efficiencySF.ChargeID.MediumLLH_d0z0_v11_isolFixedCutTight_MediumCFT.root"; - } else { - ATH_MSG_ERROR("Unknown electron SF type"); + + std::string EgammaCPTools::electronSFFilePath(const std::string& type, const std::string& ID, + const std::string& ISO) { + const std::string el_calib_path = "ElectronEfficiencyCorrection/2015_2017/rel21.2/Consolidation_September2018_v1/"; + + std::string file_path; + + if (type == "reco") { + ATH_MSG_ERROR("Moved to using egamma maps for configuring scale factor tools - electronSFMapFilePath"); + } else if (type == "ID") { + ATH_MSG_ERROR("Moved to using egamma maps for configuring scale factor tools - electronSFMapFilePath"); + } else if (type == "triggerSF") { + ATH_MSG_ERROR("Moved to using egamma maps for configuring scale factor tools - electronSFMapFilePath"); + } else if (type == "triggerEff") { + ATH_MSG_ERROR("Moved to using egamma maps for configuring scale factor tools - electronSFMapFilePath"); + } else if (type == "ChargeID") { + if (ID != "MediumLLH" && ID != "TightLLH") ATH_MSG_ERROR( + "The requested ID WP (" + ID + + ") is not supported for electron ChargeID SFs! Try TightLH or MediumLH instead."); + if (ISO != "FCTight" && ISO != "Gradient") ATH_MSG_ERROR("The requested ISO WP (" + ISO + ") is not supported for electron ChargeID SFs! Try FCTight or Gradient instead."); + file_path += "additional/efficiencySF.ChargeID."; + file_path += ID; + file_path += "_d0z0_v13_"; + file_path += ISO; + file_path += "_ECIDSloose.root"; + file_path = el_calib_path + file_path; + } else if (type == "PLV") { + if (ID != "MediumLLH" && ID != "TightLLH") + ATH_MSG_ERROR( + "The requested ID WP (" + ID + + ") is not supported for PLV SFs! try TightLH or MediumLH instead." + ); + file_path = "/ElectronEfficiencyCorrection/2015_2018/rel21.2/Precision_Summer2020_v1/isolation/"; + file_path += "efficiencySF.Isolation.MediumLHorTightLH_d0z0_v13_isol"; + file_path += ISO; + if (ISO == "PLVTight" && m_config->useElectronChargeIDSelection()) { + ATH_MSG_INFO( + "ECIDS tool and PLVTight isolation detected, switching to combined isolation SFs." + ); + file_path += "ECIDS"; + } + file_path += ".root"; + } else if (type == "ChargeMisID") { + // Protect against "None" Iso key + std::string iso = ISO; + if (iso == "None") iso = ""; + // Protect against Loose ID + any Iso + if (ID == "LooseAndBLayerLLH") iso = ""; + file_path = "charge_misID/"; + file_path += "chargeEfficiencySF."; + file_path += ID; + file_path += "_d0z0_v13"; + if (iso != "" && iso != "PLVTight" && iso != "PLVLoose") file_path += "_" + iso; + if (m_config->useElectronChargeIDSelection()) { + if (ID != "MediumLLH" && ID != "TightLLH") ATH_MSG_WARNING("The requested ID WP (" + ID + ") is not supported for electron ECIDS+ChargeMisID SFs! Try TightLH or MediumLH instead. Will now switch to regular ChargeMisID SFs."); + else if (iso != "FCTight" && iso != "Gradient") ATH_MSG_WARNING("The requested ISO WP (" + iso + ") is not supported for electron ECIDS+ChargeMisID SFs! Try FCTight or Gradient instead. Will now switch to regular ChargeMisID SFs."); + else file_path += "_ECIDSloose"; + } + file_path += ".root"; + file_path = el_calib_path + file_path; + } else { + ATH_MSG_ERROR("Unknown electron SF type"); + } + return PathResolverFindCalibFile(file_path); + } + + std::string EgammaCPTools::electronSFMapFilePath(const std::string& type) { + // Store here the paths to maps which may be updated with new recommendations + // Currently can use maps for reco, id, iso, trigger but not ChargeID + const std::string el_calib_path = "ElectronEfficiencyCorrection/2015_2017/rel21.2/Consolidation_September2018_v1/"; + + std::string file_path; + if (type == "reco") { + file_path = "map3.txt"; + } else if (type == "ID") { + file_path = "map3.txt"; + } else if (type == "FWDID") { + file_path = "map3.txt"; + } else if (type == "isolation") { + file_path = "map3.txt"; + } else if (type == "trigger") { + file_path = "map3.txt"; + } else if (type == "ChargeID") { + ATH_MSG_ERROR("Use electronSFFilePath method until ChargeID is supported by maps"); + } else if (type == "ChargeMisID") { + ATH_MSG_ERROR("Use electronSFFilePath method until ChargeMisID is supported by maps"); + } else { + ATH_MSG_ERROR("Unknown electron SF type"); + } + return PathResolverFindCalibFile(el_calib_path + file_path); } - return PathResolverFindCalibFile(el_calib_path + file_path); -} + std::string EgammaCPTools::mapWorkingPoints(const std::string& type) { + // Ian Connelly - 27 Sept 2017 + // When moving to the maps, the working points are converted to a nicer format + // We will provide a mapping from the names used by analysers and the map WP names to prevent cutfiles breaking + // See : + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/XAODElectronEfficiencyCorrectionTool#Configuration_of_the_tool_using + std::string working_point = ""; + // ID + if (type == "LooseAndBLayerLLH" || type == "LooseBLayer") { + working_point = "LooseBLayer"; + } + if (type == "MediumLLH" || type == "Medium") { + working_point = "Medium"; + } + if (type == "TightLLH" || type == "Tight") { + working_point = "Tight"; + } + if (type == "FwdLoose" || type == "FwdMedium" || type == "FwdTight") working_point = type; + + // Temporary ISO map to handle the mess that is EGamma+IFF right now... + if (type.find("Pflow") != std::string::npos) { + ATH_MSG_WARNING("You selected a Pflow isolation WP for at least one of your electron collections - BE WARNED THAT THESE ARE NOT YET READY TO BE RELEASED FOR USE IN PHYSICS ANALYSES AND OF COURSE DON'T HAVE ASSOCIATED SCALE FACTORS YET!!!"); + if (type == "PflowLoose") working_point = "FCLoose"; + if (type == "PflowTight") working_point = "FCTight"; + } + if (type == "Tight") working_point = "FCTight"; + if (type == "Loose") working_point = "FCLoose"; + if (type == "HighPtCaloOnly") working_point = "FCHighPtCaloOnly"; + if (type == "TightTrackOnly") working_point = "Gradient"; + if (type == "TightTrackOnly_FixedRad") working_point = "Gradient"; + if (type == "FCTight" || type == "FCLoose" || type == "FCHighPtCaloOnly" || type == "Gradient" || type == "PLVTight" || type == "PLVLoose") working_point = type; + + return working_point; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopFlavorTaggingCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopFlavorTaggingCPTools.cxx index b15c3df0a5f68c3adba1985d97be0036c5322e2e..407ba89f7bf16575b800f4d2baaab9b4de789182 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopFlavorTaggingCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopFlavorTaggingCPTools.cxx @@ -1,14 +1,17 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopFlavorTaggingCPTools.h" #include <map> #include <string> +#include <algorithm> +#include <iterator> // Top includes #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/Tokenize.h" #include "TopEvent/EventTools.h" // PathResolver include(s): @@ -18,254 +21,411 @@ #include "xAODBTaggingEfficiency/BTaggingSelectionTool.h" namespace top { - -FlavorTaggingCPTools::FlavorTaggingCPTools(const std::string& name) : + FlavorTaggingCPTools::FlavorTaggingCPTools(const std::string& name) : asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); -} - -StatusCode FlavorTaggingCPTools::initialize() { - ATH_MSG_INFO("top::FlavorTaggingCPTools initialize..."); - - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::FlavorTaggingCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; + declareProperty("config", m_config); } - if (!m_config->useJets()) { - ATH_MSG_INFO("top::FlavorTaggingCPTools: no need to initialise anything since not using jets"); - return StatusCode::SUCCESS; - } + StatusCode FlavorTaggingCPTools::initialize() { + ATH_MSG_INFO("top::FlavorTaggingCPTools initialize..."); - m_tagger = "MV2c10"; - m_cdi_file = "xAODBTaggingEfficiency/13TeV/2016-20_7-13TeV-MC15-CDI-2017-04-24_v1.root"; - m_efficiency_maps = "410000;410004;410500;410187;410021"; - - // working points for calo jets - m_calo_WPs_calib = {"FixedCutBEff_60", - "FixedCutBEff_70", - "FixedCutBEff_77", - "FixedCutBEff_85", - "Continuous" }; - m_calo_WPs = m_calo_WPs_calib; - m_calo_WPs.push_back("FlatBEff_30");// some other WPs are defined in addition to the calibrated ones - m_calo_WPs.push_back("FlatBEff_40"); - m_calo_WPs.push_back("FlatBEff_50"); - m_calo_WPs.push_back("FlatBEff_60"); - m_calo_WPs.push_back("FlatBEff_70"); - m_calo_WPs.push_back("FlatBEff_77"); - m_calo_WPs.push_back("FlatBEff_85"); - m_calo_WPs.push_back("FixedCutBEff_30"); - m_calo_WPs.push_back("FixedCutBEff_50"); - m_calo_WPs.push_back("FixedCutBEff_80"); - m_calo_WPs.push_back("FixedCutBEff_90"); - - // working points for track jets (AntiKt2) - m_trackAntiKt2_WPs_calib = {"FixedCutBEff_60", - "FixedCutBEff_70", - "FixedCutBEff_77", - "FixedCutBEff_85", - "Continuous" }; - m_trackAntiKt2_WPs = m_trackAntiKt2_WPs_calib; - m_trackAntiKt2_WPs.push_back("FixedCutBEff_30");// some other WPs are defined in addition to the calibrated ones - m_trackAntiKt2_WPs.push_back("FixedCutBEff_50"); - m_trackAntiKt2_WPs.push_back("FixedCutBEff_80"); - m_trackAntiKt2_WPs.push_back("FixedCutBEff_90"); - - // working points for track jets (AntiKt4) - m_trackAntiKt4_WPs_calib = {"FixedCutBEff_70", - "FixedCutBEff_77" }; - m_trackAntiKt4_WPs = m_trackAntiKt4_WPs_calib; - m_trackAntiKt4_WPs.push_back("FixedCutBEff_60");// some other WPs are defined in addition to the calibrated ones - m_trackAntiKt4_WPs.push_back("FixedCutBEff_85"); - m_trackAntiKt4_WPs.push_back("FixedCutBEff_30"); - m_trackAntiKt4_WPs.push_back("FixedCutBEff_50"); - m_trackAntiKt4_WPs.push_back("FixedCutBEff_80"); - m_trackAntiKt4_WPs.push_back("FixedCutBEff_90"); - - const std::string calib_file_path = PathResolverFindCalibFile(m_cdi_file); - const std::string excludedSysts = m_config->bTagSystsExcludedFromEV()=="none"?"":m_config->bTagSystsExcludedFromEV(); - - //------------------------------------------------------------ - // Loop through all the different working points we have and create a - // BTaggingSelectionTool and corresponding BTaggingEfficiencyTool if the working point is calibrated. - //------------------------------------------------------------ - - // special stuff to use AntiKt4EMTopoJets scale-factors and tagger WPs when using AntiKt4EMPFlowJets or AntiKt4LCTopoJets, for which no SF is yet available - std::string caloJets_collection = m_config->sgKeyJets(); - if (caloJets_collection == "AntiKt4EMPFlowJets" || caloJets_collection == "AntiKt4LCTopoJets" || caloJets_collection == "AntiKt4EMTopoNoElJets") { - ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize" ); - std::cout << " No b-tagging calibration available for jet collection " << caloJets_collection << std::endl; - std::cout << " We'll use the calibration for AntiKt4EMTopoJets instead" << std::endl; - std::cout << " Be carefull!!" << std::endl; - caloJets_collection = "AntiKt4EMTopoJets"; - } - // check if the WP requested by the user are available, and if yes, initialize the tools - // loop through all btagging WPs requested - for (auto btagWP : m_config->bTagWP()) { - if(std::find(m_calo_WPs.begin(), m_calo_WPs.end(), btagWP) == m_calo_WPs.end()) { - ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize" ); - std::cerr << " b-tagging WP: " << btagWP << " not supported for jet collection " << m_config->sgKeyJets() << std::endl; - std::cerr << " it will therefore be ignored" << std::endl; + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::FlavorTaggingCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; } - else { - //------------------------------------------------------------ - // Setup BTaggingSelectionTool - //------------------------------------------------------------ - std::string btagsel_tool_name = "BTaggingSelectionTool_"+btagWP+"_"+m_config->sgKeyJets(); - BTaggingSelectionTool* btagsel = new BTaggingSelectionTool(btagsel_tool_name); - top::check(btagsel->setProperty("TaggerName", m_tagger), - "Failed to set b-tagging selecton tool TaggerName"); - top::check(btagsel->setProperty("JetAuthor", caloJets_collection), - "Failed to set b-tagging selection JetAuthor"); - top::check(btagsel->setProperty("FlvTagCutDefinitionsFileName", - m_cdi_file), - "Failed to set b-tagging selection tool CDI file"); - top::check(btagsel->setProperty("OperatingPoint", btagWP), - "Failed to set b-tagging selection tool OperatingPoint"); - top::check(btagsel->setProperty("MinPt", - static_cast<double>(m_config->jetPtcut())), - "Failed to set b-tagging selection tool MinPt"); - top::check(btagsel->setProperty("MaxEta", - static_cast<double>(m_config->jetEtacut())), - "Failed to set b-tagging selection tool MaxEta"); - top::check(btagsel->initialize(), - "Failed to initialize b-tagging selection tool"); - m_btagging_selection_tools.push_back(btagsel); - - if(std::find( m_calo_WPs_calib.begin(), - m_calo_WPs_calib.end(), btagWP) == m_calo_WPs_calib.end()) { - ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize" ); - std::cerr << " b-tagging WP: " << btagWP << " is not calibrated for jet collection " << m_config->sgKeyJets() << std::endl; - std::cerr << " it will therefore be ignored for the scale-factors, although the tagging decisions will be saved" << std::endl; - } - else { - //------------------------------------------------------------ - // Setup BTaggingEfficiencyTool - //------------------------------------------------------------ - std::string btageff_tool_name = "BTaggingEfficiencyTool_"+btagWP+"_"+m_config->sgKeyJets(); - BTaggingEfficiencyTool* btageff = new BTaggingEfficiencyTool(btageff_tool_name); - top::check(btageff->setProperty("TaggerName", m_tagger), - "Failed to set b-tagging TaggerName"); - top::check(btageff->setProperty("OperatingPoint", btagWP), - "Failed to set b-tagging OperatingPoint"); - top::check(btageff->setProperty("JetAuthor", caloJets_collection), - "Failed to set b-tagging JetAuthor"); - top::check(btageff->setProperty("EfficiencyFileName", calib_file_path), - "Failed to set path to b-tagging CDI file"); - top::check(btageff->setProperty("ScaleFactorFileName", calib_file_path), - "Failed to set path to b-tagging CDI file"); - top::check(btageff->setProperty("ScaleFactorBCalibration", m_config->bTaggingCalibration_B()), - "Failed to set b-tagging calibration (B): "+m_config->bTaggingCalibration_B()); - top::check(btageff->setProperty("ScaleFactorCCalibration", m_config->bTaggingCalibration_C()), - "Failed to set b-tagging calibration (C): "+m_config->bTaggingCalibration_C()); - // using same calibration for T as for C - top::check(btageff->setProperty("ScaleFactorTCalibration", m_config->bTaggingCalibration_C()), - "Failed to set b-tagging calibration (T): "+m_config->bTaggingCalibration_C()); - top::check(btageff->setProperty("ScaleFactorLightCalibration", m_config->bTaggingCalibration_Light()), - "Failed to set b-tagging calibration (Light): "+m_config->bTaggingCalibration_Light()); - for (auto jet_flav : m_jet_flavors) { - top::check(btageff->setProperty("Efficiency"+jet_flav+"Calibrations", m_efficiency_maps), - "Failed to set "+jet_flav+"-calibrations efficiency maps"); - } - top::check(btageff->setProperty("ExcludeFromEigenVectorTreatment", excludedSysts), - "Failed to set b-tagging systematics to exclude from EV treatment"); - top::check(btageff->initialize(), "Failed to initialize "+btagWP); - m_btagging_efficiency_tools.push_back(btageff); - m_config->setBTagWP_calibrated(btagWP); - } - m_config->setBTagWP_available(btagWP); + + if (!m_config->useJets()) { + ATH_MSG_INFO("top::FlavorTaggingCPTools: no need to initialise anything since not using jets"); + return StatusCode::SUCCESS; } - if (m_config->useTrackJets()) { - std::vector<std::string> track_WPs = {}; - std::vector<std::string> track_WPs_calib = {}; - if (m_config->sgKeyTrackJets() == "AntiKt2PV0TrackJets") { - track_WPs = m_trackAntiKt2_WPs; - track_WPs_calib = m_trackAntiKt2_WPs_calib; - } - else if (m_config->sgKeyTrackJets() == "AntiKt4PV0TrackJets") { - track_WPs = m_trackAntiKt4_WPs; - track_WPs_calib = m_trackAntiKt4_WPs_calib; - } - - if(std::find(track_WPs.begin(), track_WPs.end(), btagWP) == track_WPs.end()) { - ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize" ); - std::cerr << " b-tagging WP: " << btagWP << " not supported for jet collection " << m_config->sgKeyTrackJets() << std::endl; - std::cerr << " it will therefore be ignored" << std::endl; + static const std::string cdi_file_default = + "xAODBTaggingEfficiency/13TeV/2020-21-13TeV-MC16-CDI-2020-03-11_Sh228_v3.root"; + + m_tagger = ""; // Extract in the loop + if (m_config->bTaggingCDIPath() != "Default") { + if (m_config->bTaggingCDIPath() != cdi_file_default) { + m_config->setPrintCDIpathWarning(true); } - else { + m_cdi_file = m_config->bTaggingCDIPath(); + } else { + m_cdi_file = cdi_file_default; + } + // This ordering needs to match the indexing in TDP (for missing cases, we use default which gives a MC/MC of 1 as + // its the same as the eff used in the calibration + // Pythia6;Herwigpp;Pythia8;Sherpa(2.2);Sherpa(2.1);aMC@NLO+Pythia8;Herwig7.1.3;Sherpa228 + // Default changed from 410501 to 410470 in the CDI release of October 2018 + m_efficiency_maps = "default;410558;410470;410250;default;410464;411233;421152"; + + // Configure all tagger/WP/calibration with helper function touching member variables + // Calibrated and uncalibrated working points for EMTopo jets for all algorithms + top::check(setTaggerWorkingPoints("AntiKt4EMTopoJets", true, "MV2c10", + {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", + "Continuous"}), + "Error setting AntiKt4EMTopoJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMTopoJets", true, "DL1", + {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", + "Continuous"}), "Error setting AntiKt4EMTopoJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMTopoJets", false, "DL1r", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt4EMTopoJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMTopoJets", false, "DL1rmu", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "CTag_Loose", "CTag_Tight", "Continuous"}), "Error setting AntiKt4EMTopoJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMTopoJets", false, "DL1", {"CTag_Loose", "CTag_Tight"}), "Error setting AntiKt4EMTopoJets WP"); + + // Calibrated and uncalibrated working points for EMPflow jets for all algorithms + top::check(setTaggerWorkingPoints("AntiKt4EMPFlowJets", false, "MV2c10", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt4EMPFlowJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMPFlowJets", true, "DL1", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt4EMPFlowJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMPFlowJets", true, "DL1r", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt4EMPFlowJets WP"); + top::check(setTaggerWorkingPoints("AntiKt4EMPFlowJets", false, "DL1rmu", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt4EMPFlowJets WP"); + + // Calibrated and uncalibrated working points for R=0.2 track jets for all algorithms + top::check(setTaggerWorkingPoints("AntiKt2PV0TrackJets", true, "MV2c10", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt2PV0TrackJets WP"); + top::check(setTaggerWorkingPoints("AntiKt2PV0TrackJets", true, "DL1", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt2PV0TrackJets WP"); + top::check(setTaggerWorkingPoints("AntiKt2PV0TrackJets", false, "DL1r", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt2PV0TrackJets WP"); + top::check(setTaggerWorkingPoints("AntiKt2PV0TrackJets", false, "DL1rmu", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKt2PV0TrackJets WP"); + + // Calibrated and uncalibrated working points for VR track jets for all algorithms + top::check(setTaggerWorkingPoints("AntiKtVR30Rmax4Rmin02TrackJets", true, "MV2c10", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKtVR30Rmax4Rmin02TrackJets WP"); + top::check(setTaggerWorkingPoints("AntiKtVR30Rmax4Rmin02TrackJets", true, "DL1", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKtVR30Rmax4Rmin02TrackJets WP"); + top::check(setTaggerWorkingPoints("AntiKtVR30Rmax4Rmin02TrackJets", false, "DL1r", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKtVR30Rmax4Rmin02TrackJets WP"); + top::check(setTaggerWorkingPoints("AntiKtVR30Rmax4Rmin02TrackJets", false, "DL1rmu", {"FixedCutBEff_60", "FixedCutBEff_70", "FixedCutBEff_77", "FixedCutBEff_85", "Continuous"}), "Error setting AntiKtVR30Rmax4Rmin02TrackJets WP"); + + + std::string caloJets_type = m_config->sgKeyJetsType(); + std::string caloJets_collection = m_config->sgKeyJets(); + + std::string trackJets_type = m_config->sgKeyTrackJetsType(); + std::string trackJets_collection = m_config->sgKeyTrackJets(); + + const std::string calib_file_path = PathResolverFindCalibFile(m_cdi_file); + const std::string excludedSysts = m_config->bTagSystsExcludedFromEV() == "none" ? "" : m_config->bTagSystsExcludedFromEV(); + + //------------------------------------------------------------ + // Loop through all the different working points we have and create a + // BTaggingSelectionTool and corresponding BTaggingEfficiencyTool if the working point is calibrated. + //------------------------------------------------------------ + + // check if the WP requested by the user are available, and if yes, initialize the tools + // loop through all btagging WPs requested + for (auto TaggerBtagWP : m_config->bTagWP()) { + // Overwrite m_tagger anyway (default has to be mv2c10 for R20.7 + m_tagger = TaggerBtagWP.first; + std::string btagWP = TaggerBtagWP.second; + std::string bTagWPName = m_tagger + "_" + btagWP; + if ((caloJets_type == "AntiKt4EMTopoJets" && std::find(m_calo_WPs.begin(), m_calo_WPs.end(), bTagWPName) == m_calo_WPs.end()) || + (caloJets_type == "AntiKt4EMPFlowJets" && std::find(m_pflow_WPs.begin(), m_pflow_WPs.end(), bTagWPName) == m_pflow_WPs.end())) { + ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize"); + ATH_MSG_WARNING(" b-tagging WP: " + bTagWPName + " not supported for jet collection " + caloJets_collection + " with algorithm " + m_tagger); + ATH_MSG_WARNING(" it will therefore be ignored"); + } else { //------------------------------------------------------------ // Setup BTaggingSelectionTool //------------------------------------------------------------ - std::string btagsel_tool_name = "BTaggingSelectionTool_"+btagWP+"_"+m_config->sgKeyTrackJets(); + // Updated name to use m_tagger + std::string btagsel_tool_name = "BTaggingSelectionTool_" + bTagWPName + "_" + caloJets_collection; BTaggingSelectionTool* btagsel = new BTaggingSelectionTool(btagsel_tool_name); top::check(btagsel->setProperty("TaggerName", m_tagger), - "Failed to set b-tagging selecton tool TaggerName"); - top::check(btagsel->setProperty("JetAuthor", m_config->sgKeyTrackJets()), - "Failed to set b-tagging selection JetAuthor"); + "Failed to set b-tagging selecton tool TaggerName"); + top::check(btagsel->setProperty("JetAuthor", caloJets_collection), + "Failed to set b-tagging selection JetAuthor"); top::check(btagsel->setProperty("FlvTagCutDefinitionsFileName", m_cdi_file), - "Failed to set b-tagging selection tool CDI file"); + "Failed to set b-tagging selection tool CDI file"); top::check(btagsel->setProperty("OperatingPoint", btagWP), - "Failed to set b-tagging selection tool OperatingPoint"); + "Failed to set b-tagging selection tool OperatingPoint"); top::check(btagsel->setProperty("MinPt", static_cast<double>(m_config->jetPtcut())), - "Failed to set b-tagging selection tool MinPt"); + "Failed to set b-tagging selection tool MinPt"); top::check(btagsel->setProperty("MaxEta", static_cast<double>(m_config->jetEtacut())), - "Failed to set b-tagging selection tool MaxEta"); + "Failed to set b-tagging selection tool MaxEta"); top::check(btagsel->initialize(), - "Failed to initialize b-tagging selection tool"); + "Failed to initialize b-tagging selection tool"); m_btagging_selection_tools.push_back(btagsel); - - if(std::find( track_WPs_calib.begin(), - track_WPs_calib.end(), btagWP) == track_WPs_calib.end()) { - ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize" ); - std::cerr << " b-tagging WP: " << btagWP << " is not calibrated for jet collection " << m_config->sgKeyTrackJets() << std::endl; - std::cerr << " it will therefore be ignored for the scale-factors, although the tagging decisions will be saved" << std::endl; - } - else { + m_config->setBTagAlgo_available(m_tagger, btagsel_tool_name); + + if ((caloJets_type == "AntiKt4EMTopoJets" && std::find(m_calo_WPs_calib.begin(), m_calo_WPs_calib.end(), bTagWPName) == m_calo_WPs_calib.end()) || + (caloJets_type == "AntiKt4EMPFlowJets" && std::find(m_pflow_WPs_calib.begin(), m_pflow_WPs_calib.end(), bTagWPName) == m_pflow_WPs_calib.end())) { + ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize"); + ATH_MSG_WARNING(" b-tagging WP: " + bTagWPName + " is not calibrated for jet collection " + caloJets_collection); + ATH_MSG_WARNING(" it will therefore be ignored for the scale-factors, although the tagging decisions will be saved"); + } else { //------------------------------------------------------------ // Setup BTaggingEfficiencyTool //------------------------------------------------------------ - std::string btageff_tool_name = "BTaggingEfficiencyTool_"+btagWP+"_"+m_config->sgKeyTrackJets(); + std::string btageff_tool_name = "BTaggingEfficiencyTool_" + bTagWPName + "_" + caloJets_collection; BTaggingEfficiencyTool* btageff = new BTaggingEfficiencyTool(btageff_tool_name); top::check(btageff->setProperty("TaggerName", m_tagger), - "Failed to set b-tagging TaggerName"); + "Failed to set b-tagging TaggerName"); top::check(btageff->setProperty("OperatingPoint", btagWP), - "Failed to set b-tagging OperatingPoint"); - top::check(btageff->setProperty("JetAuthor", m_config->sgKeyTrackJets()), - "Failed to set b-tagging JetAuthor"); + "Failed to set b-tagging OperatingPoint"); + top::check(btageff->setProperty("JetAuthor", caloJets_collection), + "Failed to set b-tagging JetAuthor"); + top::check(btageff->setProperty("MinPt", + static_cast<double>(m_config->jetPtcut())), + "Failed to set b-tagging selection tool MinPt"); top::check(btageff->setProperty("EfficiencyFileName", calib_file_path), - "Failed to set path to b-tagging CDI file"); + "Failed to set path to b-tagging CDI file"); top::check(btageff->setProperty("ScaleFactorFileName", calib_file_path), - "Failed to set path to b-tagging CDI file"); + "Failed to set path to b-tagging CDI file"); top::check(btageff->setProperty("ScaleFactorBCalibration", m_config->bTaggingCalibration_B()), - "Failed to set b-tagging calibration (B): "+m_config->bTaggingCalibration_B()); + "Failed to set b-tagging calibration (B): " + m_config->bTaggingCalibration_B()); top::check(btageff->setProperty("ScaleFactorCCalibration", m_config->bTaggingCalibration_C()), - "Failed to set b-tagging calibration (C): "+m_config->bTaggingCalibration_C()); + "Failed to set b-tagging calibration (C): " + m_config->bTaggingCalibration_C()); // using same calibration for T as for C top::check(btageff->setProperty("ScaleFactorTCalibration", m_config->bTaggingCalibration_C()), - "Failed to set b-tagging calibration (T): "+m_config->bTaggingCalibration_C()); + "Failed to set b-tagging calibration (T): " + m_config->bTaggingCalibration_C()); top::check(btageff->setProperty("ScaleFactorLightCalibration", m_config->bTaggingCalibration_Light()), - "Failed to set b-tagging calibration (Light): "+m_config->bTaggingCalibration_Light()); + "Failed to set b-tagging calibration (Light): " + m_config->bTaggingCalibration_Light()); for (auto jet_flav : m_jet_flavors) { - top::check(btageff->setProperty("Efficiency"+jet_flav+"Calibrations", m_efficiency_maps), - "Failed to set "+jet_flav+"-calibrations efficiency maps"); + // 09/02/18 IC: The pseudo-continuous does not have MC/MC SF so we need to only apply default for this case + // 08/05/18 Francesco La Ruffa: The pseudo-continuous has now its own MC/MC SFs, no needed to set default + top::check(btageff->setProperty("Efficiency" + jet_flav + "Calibrations", m_efficiency_maps), + "Failed to set " + jet_flav + "-calibrations efficiency maps"); } top::check(btageff->setProperty("ExcludeFromEigenVectorTreatment", excludedSysts), - "Failed to set b-tagging systematics to exclude from EV treatment"); - top::check(btageff->initialize(), "Failed to initialize "+btagWP); + "Failed to set b-tagging systematics to exclude from EV treatment"); + top::check(btageff->initialize(), "Failed to initialize " + bTagWPName); + // Check the excludedSysts - Cannot check before the tool is initialised + top::check(this->checkExcludedSysts(btageff, excludedSysts), + "Incorrect excluded systematics have been provided."); m_btagging_efficiency_tools.push_back(btageff); - m_config->setBTagWP_calibrated_trkJet(btagWP); + m_config->setBTagWP_calibrated(bTagWPName); } - m_config->setBTagWP_available_trkJet(btagWP); + m_config->setBTagWP_available(bTagWPName); } } + if (m_config->useTrackJets()) { + for (auto TaggerBtagWP : m_config->bTagWP_trkJet()) { + m_tagger = TaggerBtagWP.first; + std::string btagWP = TaggerBtagWP.second; + std::string bTagWPName = m_tagger + "_" + btagWP; + std::vector<std::string> track_WPs = {}; + std::vector<std::string> track_WPs_calib = {}; + if (trackJets_type == "AntiKtVR30Rmax4Rmin02TrackJets") { + track_WPs = m_trackAntiKtVR_WPs; + track_WPs_calib = m_trackAntiKtVR_WPs_calib; + } else if (trackJets_type == "AntiKt2PV0TrackJets") { + track_WPs = m_trackAntiKt2_WPs; + track_WPs_calib = m_trackAntiKt2_WPs_calib; + } else if (trackJets_type == "AntiKt4PV0TrackJets") { + track_WPs = m_trackAntiKt4_WPs; + track_WPs_calib = m_trackAntiKt4_WPs_calib; + } + + if (std::find(track_WPs.begin(), track_WPs.end(), bTagWPName) == track_WPs.end()) { + ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize"); + ATH_MSG_WARNING(" b-tagging WP: " + bTagWPName + " not supported for jet collection " + trackJets_collection); + ATH_MSG_WARNING(" it will therefore be ignored"); + } else { + //------------------------------------------------------------ + // Setup BTaggingSelectionTool + //------------------------------------------------------------ + std::string btagsel_tool_name = "BTaggingSelectionTool_" + bTagWPName + "_" + trackJets_collection; + BTaggingSelectionTool* btagsel = new BTaggingSelectionTool(btagsel_tool_name); + top::check(btagsel->setProperty("TaggerName", m_tagger), + "Failed to set b-tagging selecton tool TaggerName"); + top::check(btagsel->setProperty("JetAuthor", trackJets_collection), + "Failed to set b-tagging selection JetAuthor"); + top::check(btagsel->setProperty("FlvTagCutDefinitionsFileName", + m_cdi_file), + "Failed to set b-tagging selection tool CDI file"); + top::check(btagsel->setProperty("OperatingPoint", btagWP), + "Failed to set b-tagging selection tool OperatingPoint"); + top::check(btagsel->setProperty("MinPt", + static_cast<double>(m_config->trackJetPtcut())), + "Failed to set b-tagging selection tool MinPt"); + top::check(btagsel->setProperty("MaxEta", + static_cast<double>(m_config->trackJetEtacut())), + "Failed to set b-tagging selection tool MaxEta"); + top::check(btagsel->initialize(), + "Failed to initialize b-tagging selection tool"); + m_btagging_selection_tools.push_back(btagsel); + m_config->setBTagAlgo_available_trkJet(m_tagger, btagsel_tool_name); + + if (std::find(track_WPs_calib.begin(), + track_WPs_calib.end(), bTagWPName) == track_WPs_calib.end()) { + ATH_MSG_WARNING("top::FlavorTaggingCPTools::initialize"); + ATH_MSG_WARNING(" b-tagging WP: " + bTagWPName + " is not calibrated for jet collection " + trackJets_collection); + ATH_MSG_WARNING(" it will therefore be ignored for the scale-factors, although the tagging decisions will be saved"); + } else { + //------------------------------------------------------------ + // Setup BTaggingEfficiencyTool + //------------------------------------------------------------ + std::string btageff_tool_name = "BTaggingEfficiencyTool_" + bTagWPName + "_" + trackJets_collection; + BTaggingEfficiencyTool* btageff = new BTaggingEfficiencyTool(btageff_tool_name); + top::check(btageff->setProperty("TaggerName", m_tagger), + "Failed to set b-tagging TaggerName"); + top::check(btageff->setProperty("OperatingPoint", btagWP), + "Failed to set b-tagging OperatingPoint"); + top::check(btageff->setProperty("JetAuthor", trackJets_collection), + "Failed to set b-tagging JetAuthor"); + top::check(btageff->setProperty("MinPt", + static_cast<double>(m_config->trackJetPtcut())), + "Failed to set b-tagging selection tool MinPt"); + top::check(btageff->setProperty("EfficiencyFileName", calib_file_path), + "Failed to set path to b-tagging CDI file"); + top::check(btageff->setProperty("ScaleFactorFileName", calib_file_path), + "Failed to set path to b-tagging CDI file"); + top::check(btageff->setProperty("ScaleFactorBCalibration", m_config->bTaggingCalibration_B()), + "Failed to set b-tagging calibration (B): " + m_config->bTaggingCalibration_B()); + top::check(btageff->setProperty("ScaleFactorCCalibration", m_config->bTaggingCalibration_C()), + "Failed to set b-tagging calibration (C): " + m_config->bTaggingCalibration_C()); + // using same calibration for T as for C + top::check(btageff->setProperty("ScaleFactorTCalibration", m_config->bTaggingCalibration_C()), + "Failed to set b-tagging calibration (T): " + m_config->bTaggingCalibration_C()); + top::check(btageff->setProperty("ScaleFactorLightCalibration", m_config->bTaggingCalibration_Light()), + "Failed to set b-tagging calibration (Light): " + m_config->bTaggingCalibration_Light()); + for (auto jet_flav : m_jet_flavors) { + top::check(btageff->setProperty("Efficiency" + jet_flav + "Calibrations", m_efficiency_maps), + "Failed to set " + jet_flav + "-calibrations efficiency maps"); + } + + top::check(btageff->setProperty("ExcludeFromEigenVectorTreatment", excludedSysts), + "Failed to set b-tagging systematics to exclude from EV treatment"); + top::check(btageff->initialize(), "Failed to initialize " + bTagWPName); + // Check the excludedSysts - Cannot check before the tool is initialised + top::check(this->checkExcludedSysts(btageff, excludedSysts), + "Incorrect excluded systematics have been provided."); + m_btagging_efficiency_tools.push_back(btageff); + m_config->setBTagWP_calibrated_trkJet(bTagWPName); + } + m_config->setBTagWP_available_trkJet(bTagWPName); + } + } + } + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} + StatusCode FlavorTaggingCPTools::checkExcludedSysts(BTaggingEfficiencyTool* btageff, std::string excludedSysts) { + // We pass the pointer to the btagging efficiency tool which is being created and also the excludedSysts string + // which will be used + // If the string is empty, then nothing to check + if (excludedSysts == "") return StatusCode::SUCCESS; + + // Split by a semi-colon delimiter and then check the individual syst strings against the list from the CDI + std::vector<std::string> listOfExcludedSysts; + top::tokenize(excludedSysts, listOfExcludedSysts, ";"); + ATH_MSG_INFO(" ------------------------------------------------ "); + ATH_MSG_INFO(" ------------- EXPERIMENTAL FEATURE ------------- "); + ATH_MSG_INFO(" ------ Please provide feedback to TopReco ------ "); + ATH_MSG_INFO(" ------------- EXPERIMENTAL FEATURE ------------- "); + ATH_MSG_INFO(" ------------------------------------------------ "); + ATH_MSG_INFO(" AnalysisTop - Checking excludedSysts for flavour tagging EV"); + ATH_MSG_INFO(" This has been split on the semi-colon delimiter to find..."); + for (auto s : listOfExcludedSysts) ATH_MSG_INFO("... " + s); + // Get the map(string, vector<string>) from the CDI tool + // Don't care about the flavours (this will be handled in the CDI) + std::vector<std::string> listOfScaleFactorSystematics; + for (auto flavour : btageff->listScaleFactorSystematics(false)) { + for (auto sys : flavour.second) { + listOfScaleFactorSystematics.push_back(sys); + } + } + // Make this a unique set and then we need to check that all systematics provided by the user are expected by the + // CDI + std::set<std::string> setOfExcludedSysts, setOfScaleFactorSystematics; + + for (auto sys : listOfExcludedSysts) { + if (setOfExcludedSysts.find(sys) == setOfExcludedSysts.end()) setOfExcludedSysts.insert(sys); + } + + for (auto sys : listOfScaleFactorSystematics) { + if (setOfScaleFactorSystematics.find(sys) == setOfScaleFactorSystematics.end()) setOfScaleFactorSystematics.insert(sys); + } + + // + std::vector<std::string> unionOfSystematics; + std::set_intersection(setOfExcludedSysts.begin(), setOfExcludedSysts.end(), + setOfScaleFactorSystematics.begin(), setOfScaleFactorSystematics.end(), + std::back_inserter(unionOfSystematics)); + // Check we have the same systematics listed in unionOfSystematics + if (unionOfSystematics.size() != listOfExcludedSysts.size()) { + ATH_MSG_WARNING("Have not found all systematics listed to be excluded from b-tagging eigenvector method"); + ATH_MSG_INFO("Permitted values are..."); + for (auto sys : setOfScaleFactorSystematics) { + ATH_MSG_INFO(" ... " + sys); + } + return StatusCode::FAILURE; + } else { + ATH_MSG_INFO(" Summary of EV impact "); + for (auto sysRemove : listOfExcludedSysts) { + std::string flavourAffected = ""; + for (auto flavour : btageff->listScaleFactorSystematics(false)) { + for (auto sysCDI : flavour.second) { + if (sysRemove == sysCDI) flavourAffected += flavour.first; + } + } + ATH_MSG_INFO(" ... " + sysRemove + " -> Removed from calibration(s) : [" + flavourAffected + "]"); + } + ATH_MSG_INFO(" These will be dynamically matched to systematic tree names (if available)"); + ATH_MSG_INFO(" All systematics are accepted by CDI file "); + } + // We have passed all the tests so now we store the systematics removed from the EV method and use a mapping to + // ASG/AT naming and return + ATH_MSG_INFO(" ------------------------------------------------ "); + return StatusCode::SUCCESS; + } + + StatusCode FlavorTaggingCPTools::setTaggerWorkingPoints(std::string jetcollection, bool isCalibrated, std::string tagger, std::vector<std::string> list_of_WP) { + // To try to reduce errors, make a helper function for setting the lists of tagger_WP which are required + if (jetcollection == "AntiKt4EMTopoJets" && isCalibrated) { + // use m_calo_WPs_calib + for (auto s : list_of_WP) { + m_calo_WPs_calib.push_back(tagger + "_" + s); + m_calo_WPs.push_back(tagger + "_" + s); + } + } else if (jetcollection == "AntiKt4EMTopoJets" && !isCalibrated) { + // use m_calo_WPs + for (auto s : list_of_WP) m_calo_WPs.push_back(tagger + "_" + s); + } else if (jetcollection == "AntiKt4EMPFlowJets" && isCalibrated) { + // use m_pflow_WPs_calib + for (auto s : list_of_WP) { + m_pflow_WPs_calib.push_back(tagger + "_" + s); + m_pflow_WPs.push_back(tagger + "_" + s); + } + } else if (jetcollection == "AntiKt4EMPFlowJets" && !isCalibrated) { + // use m_pflow_WPs + for (auto s : list_of_WP) m_pflow_WPs.push_back(tagger + "_" + s); + } else if (jetcollection == "AntiKtVR30Rmax4Rmin02TrackJets" && isCalibrated) { + // use m_trackAntiKt2_WPs_calib + for (auto s : list_of_WP) { + m_trackAntiKtVR_WPs_calib.push_back(tagger + "_" + s); + m_trackAntiKtVR_WPs.push_back(tagger + "_" + s); + } + } else if (jetcollection == "AntiKtVR30Rmax4Rmin02TrackJets" && !isCalibrated) { + // use m_trackAntiKt2_WPs + for (auto s : list_of_WP) m_trackAntiKtVR_WPs.push_back(tagger + "_" + s); + } else if (jetcollection == "AntiKt2PV0TrackJets" && isCalibrated) { + // use m_trackAntiKt2_WPs_calib + for (auto s : list_of_WP) { + m_trackAntiKt2_WPs_calib.push_back(tagger + "_" + s); + m_trackAntiKt2_WPs.push_back(tagger + "_" + s); + } + } else if (jetcollection == "AntiKt2PV0TrackJets" && !isCalibrated) { + // use m_trackAntiKt2_WPs + for (auto s : list_of_WP) m_trackAntiKt2_WPs.push_back(tagger + "_" + s); + } else if (jetcollection == "AntiKt4PV0TrackJets" && isCalibrated) { + // use m_trackAntiKt4_WPs_calib + for (auto s : list_of_WP) { + m_trackAntiKt4_WPs_calib.push_back(tagger + "_" + s); + m_trackAntiKt4_WPs.push_back(tagger + "_" + s); + } + } else if (jetcollection == "AntiKt4PV0TrackJets" && !isCalibrated) { + // use m_trackAntiKt2_WPs_calib + for (auto s : list_of_WP) m_trackAntiKt4_WPs.push_back(tagger + "_" + s); + } else { + ATH_MSG_ERROR("Unknown jet collection and calibration options"); + return StatusCode::FAILURE; + } + return StatusCode::SUCCESS; + } + + void FlavorTaggingCPTools::printConfigurations() { + // Debugging function, not used in release + ATH_MSG_INFO("AntiKt4EMTopoJets - Calibrated WP"); + for (auto s : m_calo_WPs_calib) ATH_MSG_INFO(" -> " << s); + ATH_MSG_INFO("AntiKt4EMTopoJets - Available selection WP"); + for (auto s : m_calo_WPs) ATH_MSG_INFO(" -> " << s); + + return; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopGhostTrackCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopGhostTrackCPTools.cxx index 65b026849d931c8826b1a88557e360b8810febbb..c6175c32e9837eb69ab0b6c5337b3f981cba25ac 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopGhostTrackCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopGhostTrackCPTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopGhostTrackCPTools.h" @@ -17,158 +17,189 @@ namespace top { - -GhostTrackCPTools::GhostTrackCPTools(const std::string& name) : + GhostTrackCPTools::GhostTrackCPTools(const std::string& name) : asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); -} + declareProperty("config", m_config); + } -StatusCode GhostTrackCPTools::initialize() { - ATH_MSG_INFO("top::GhostTrackCPTools initialize..."); + StatusCode GhostTrackCPTools::initialize() { + ATH_MSG_INFO("top::GhostTrackCPTools initialize..."); - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::GhostTrackCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; - } + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::GhostTrackCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; + } + + if (!m_config->useJets() || !m_config->useJetGhostTrack()) { + ATH_MSG_INFO( + "top::GhostTrackCPTools: no need to initialise anything since not using jets or tracks ghost-matched to jets"); + return StatusCode::SUCCESS; + } + + if (!m_config->makeAllCPTools()) { + ATH_MSG_INFO("top::GhostTrackCPTools: no need to initialise for mini-xAOD"); + return StatusCode::SUCCESS; + } + + + // This defines the run period (ranges) that are used by the + // InDet::InDetTrackBiasingTool. The following inputs are possible: + // - No / empty input: Use the maximum range, that is [0; + // UInt32_t::max) as allowed run number value range. Initialise + // the tool with run number 0 (which will use 2015 precriptions). + // - A single run number: Configure the tool with this run number + // and to not apply checks / selection on the random run number of + // the actual events. + // - At least two values: Use this to define adjacent ranges, each + // of which is processed using a unique instance of the tool which + // was initialised using the lower bound of the range. From an + // input of size n, n-1 ranges are formed. The i-th element is the + // lower bound (incl) of the i-th range; the (i+1)-th element is + // the upper bound (excl) of the i-th range. + m_runPeriods = { + 276262, 297730, 300909, 311482, 334738, 341650, 364486 + }; + + m_config->runPeriodJetGhostTrack(m_runPeriods); + + top::check(setupSmearingTool(), "Failed to setup track smearing tools"); + top::check(setupBiasingTools(), "Failed to setup track biasing tools"); + top::check(setupTruthFilterTool(), "Failed to setup truth filter tools"); + top::check(setupJetTrackFilterTool(), "Failed to setup track filter tools"); + top::check(setupSelectionTool(), "Failed to setup track selection tools"); - if (!m_config->useJets() || !m_config->useJetGhostTrack()) { - ATH_MSG_INFO("top::GhostTrackCPTools: no need to initialise anything since not using jets or tracks ghost-matched to jets"); return StatusCode::SUCCESS; } - if (!m_config->makeAllCPTools()) { - ATH_MSG_INFO("top::GhostTrackCPTools: no need to initialise for mini-xAOD"); + StatusCode GhostTrackCPTools::setupSelectionTool() { + + if (asg::ToolStore::contains<InDet::InDetTrackSelectionTool>(m_TrkSelName)) { + m_trackseltool = asg::ToolStore::get<InDet::InDetTrackSelectionTool>(m_TrkSelName); + } else { + auto selTool = std::make_unique<InDet::InDetTrackSelectionTool>( m_TrkSelName ,m_config->ghostTracksQuality()); + top::check(selTool -> initialize(), "Failed to initialize InDetTrackSelectionTool for GA tracks"); + m_trackseltool = selTool.release(); + ATH_MSG_INFO("Creating selection tool " + m_TrkSelName); + } + return StatusCode::SUCCESS; + } - // This defines the run period (ranges) that are used by the - // InDet::InDetTrackBiasingTool. The following inputs are possible: - // - No / empty input: Use the maximum range, that is [0; - // UInt32_t::max) as allowed run number value range. Initialise - // the tool with run number 0 (which will use 2015 precriptions). - // - A single run number: Configure the tool with this run number - // and to not apply checks / selection on the random run number of - // the actual events. - // - At least two values: Use this to define adjacent ranges, each - // of which is processed using a unique instance of the tool which - // was initialised using the lower bound of the range. From an - // input of size n, n-1 ranges are formed. The i-th element is the - // lower bound (incl) of the i-th range; the (i+1)-th element is - // the upper bound (excl) of the i-th range. - m_runPeriods = {276262, 297730, 300909, 999999}; - - m_config->runPeriodJetGhostTrack(m_runPeriods); - - top::check(setupSmearingTool(), "Failed to setup track smearing tools"); - top::check(setupBiasingTools(), "Failed to setup track biasing tools"); - top::check(setupTruthFilterTool(), "Failed to setup truth filter tools"); - top::check(setupJetTrackFilterTool(), "Failed to setup track filter tools"); - - return StatusCode::SUCCESS; -} - -StatusCode GhostTrackCPTools::setupSmearingTool(){ - - if (asg::ToolStore::contains<InDet::InDetTrackSmearingTool>(m_smearingToolName)){ - m_smearingTool = asg::ToolStore::get<InDet::InDetTrackSmearingTool>(m_smearingToolName); - } else { - auto tool = new InDet::InDetTrackSmearingTool(m_smearingToolName); - top::check(tool->initialize(), "Failure to initialize InDetTrackSmearingTool"); - m_smearingTool = tool; - ATH_MSG_INFO(" Creating smearing tool "+m_smearingToolName ); + StatusCode GhostTrackCPTools::setupSmearingTool() { + if (asg::ToolStore::contains<InDet::InDetTrackSmearingTool>(m_smearingToolName)) { + m_smearingTool = asg::ToolStore::get<InDet::InDetTrackSmearingTool>(m_smearingToolName); + } else { + auto tool = new InDet::InDetTrackSmearingTool(m_smearingToolName); + top::check(tool->initialize(), "Failure to initialize InDetTrackSmearingTool"); + m_smearingTool = tool; + ATH_MSG_INFO(" Creating smearing tool " + m_smearingToolName); + } + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} - -StatusCode GhostTrackCPTools::setupBiasingTools() { - top::check(not m_runPeriods.empty(), "Assertion failed"); + StatusCode GhostTrackCPTools::setupBiasingTools() { + top::check(not m_runPeriods.empty(), "Assertion failed"); - // Two cases are possible: - // - Either a single run number was specified to the runPeriods - // parameter in which case we'll use exactly that run number, or - // - at least two numbers have been specified, which then define - // (potentially multiple) run number ranges. + // Two cases are possible: + // - Either a single run number was specified to the runPeriods + // parameter in which case we'll use exactly that run number, or + // - at least two numbers have been specified, which then define + // (potentially multiple) run number ranges. - if (m_runPeriods.size() == 1){ - m_runPeriods.resize(1); + if (m_runPeriods.size() == 1) { + m_runPeriods.resize(1); - const std::string biasToolName{m_biasToolPrefix + "_" + std::to_string(m_runPeriods[0])}; + const std::string biasToolName { + m_biasToolPrefix + "_" + std::to_string(m_runPeriods[0]) + }; - if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)){ - m_biasingTool[0] = asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)) { + m_biasingTool[0] = asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + } else { + auto tool = new InDet::InDetTrackBiasingTool(biasToolName); + top::check(tool->setProperty("runNumber", m_runPeriods[0]), + "Failure to setProperty runNumber of InDetTrackBiasingTool " + biasToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackBiasingTool " + biasToolName); + m_biasingTool[0] = tool; + } + ATH_MSG_INFO(" Creating biasing tool to calibrate for run#=" << m_runPeriods[0] << ": " + biasToolName); } else { - auto tool = new InDet::InDetTrackBiasingTool(biasToolName); - top::check(tool->setProperty("runNumber", m_runPeriods[0]), - "Failure to setProperty runNumber of InDetTrackBiasingTool "+biasToolName); - top::check(tool->initialize(), - "Failure to initialize InDetTrackBiasingTool "+biasToolName); - m_biasingTool[0] = tool; - } - ATH_MSG_INFO(" Creating biasing tool to calibrate for run#=" << m_runPeriods[0] <<": "+biasToolName ); - - } else { - m_biasingTool.resize(m_runPeriods.size() - 1); - for (std::size_t i=0; i<m_runPeriods.size() - 1; ++i){ - const std::string biasToolName{m_biasToolPrefix - + "_" + std::to_string(m_runPeriods[i]) - + "_" + std::to_string(m_runPeriods[i + 1])}; - ATH_MSG_INFO(" Creating biasing tool to calibrate for period [" << m_runPeriods[i] << ", " << m_runPeriods[i + 1] << "): "<<biasToolName ); - if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)){ + m_biasingTool.resize(m_runPeriods.size() - 1); + for (std::size_t i = 0; i < m_runPeriods.size() - 1; ++i) { + const std::string biasToolName { + m_biasToolPrefix + + "_" + std::to_string(m_runPeriods[i]) + + "_" + std::to_string(m_runPeriods[i + 1]) + }; + ATH_MSG_INFO( + " Creating biasing tool to calibrate for period [" << m_runPeriods[i] << ", " << m_runPeriods[i + 1] << "): " << + biasToolName); + if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)) { m_biasingTool[i] = - asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); - } else { + asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + } else { auto tool = new InDet::InDetTrackBiasingTool(biasToolName); top::check(tool->setProperty("runNumber", m_runPeriods[i]), - "Failure to setProperty runNumber of InDetTrackBiasingTool "+biasToolName); + "Failure to setProperty runNumber of InDetTrackBiasingTool " + biasToolName); top::check(tool->initialize(), - "Failure to initialize InDetTrackBiasingTool "+biasToolName); + "Failure to initialize InDetTrackBiasingTool " + biasToolName); m_biasingTool[i] = tool; + } } } - } - return StatusCode::SUCCESS; -} - -StatusCode GhostTrackCPTools::setupTruthFilterTool(){ - - if (asg::ToolStore::contains<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName)){ - m_truthOriginTool = asg::ToolStore::get<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName); - } else { - auto tool = new InDet::InDetTrackTruthOriginTool(m_truthOriginToolName); - top::check(tool->initialize(), - "Failure to initialize InDetTrackTruthOriginTool "+m_truthOriginToolName); - m_truthOriginTool = tool; - ATH_MSG_INFO(" Creating truth origin tool "+m_truthOriginToolName ); + return StatusCode::SUCCESS; } - if (asg::ToolStore::contains<InDet::InDetTrackTruthFilterTool>(m_truthFilterToolName)){ - m_truthFilterTool = asg::ToolStore::get<InDet::InDetTrackTruthFilterTool>(m_truthFilterToolName); - } else { - auto tool = new InDet::InDetTrackTruthFilterTool(m_truthFilterToolName); - top::check(tool->setProperty("trackOriginTool", - ToolHandle<InDet::IInDetTrackTruthOriginTool>{&(* m_truthOriginTool)}), - "Failed to setProperty trackOriginTool of InDetTrackTruthFilterTool "+m_truthFilterToolName); - top::check(tool->initialize(), - "Failure to initialize InDetTrackTruthFilterTool "+m_truthFilterToolName); - m_truthFilterTool = tool; - ATH_MSG_INFO(" Creating truth filter tool "+m_truthFilterToolName ); - } - return StatusCode::SUCCESS; -} - -StatusCode GhostTrackCPTools::setupJetTrackFilterTool(){ - - if (asg::ToolStore::contains<InDet::JetTrackFilterTool>(m_jetTrackFilterToolName)){ - m_jetTrackFilterTool = asg::ToolStore::get<InDet::JetTrackFilterTool>(m_jetTrackFilterToolName); - } else { - auto tool = new InDet::JetTrackFilterTool(m_jetTrackFilterToolName); - top::check(tool->initialize(), "Failure to initialize JetTrackFilterTool"); - m_jetTrackFilterTool = tool; - ATH_MSG_INFO(" Creating jet track filter tool" ); + StatusCode GhostTrackCPTools::setupTruthFilterTool() { + if (asg::ToolStore::contains<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName)) { + m_truthOriginTool = asg::ToolStore::get<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName); + } else { + auto tool = new InDet::InDetTrackTruthOriginTool(m_truthOriginToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackTruthOriginTool " + m_truthOriginToolName); + m_truthOriginTool = tool; + ATH_MSG_INFO(" Creating truth origin tool " + m_truthOriginToolName); + } + + if (asg::ToolStore::contains<InDet::InDetTrackTruthFilterTool>(m_truthFilterToolName)) { + m_truthFilterTool = asg::ToolStore::get<InDet::InDetTrackTruthFilterTool>(m_truthFilterToolName); + } else { + auto tool = new InDet::InDetTrackTruthFilterTool(m_truthFilterToolName); + top::check(tool->setProperty("trackOriginTool", + ToolHandle<InDet::IInDetTrackTruthOriginTool>{&(*m_truthOriginTool)}), + "Failed to setProperty trackOriginTool of InDetTrackTruthFilterTool " + m_truthFilterToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackTruthFilterTool " + m_truthFilterToolName); + m_truthFilterTool = tool; + ATH_MSG_INFO(" Creating truth filter tool " + m_truthFilterToolName); + } + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} + StatusCode GhostTrackCPTools::setupJetTrackFilterTool() { + if (asg::ToolStore::contains<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName)) { + m_truthOriginTool = asg::ToolStore::get<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName); + } else { + auto tool = new InDet::InDetTrackTruthOriginTool(m_truthOriginToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackTruthOriginTool " + m_truthOriginToolName); + m_truthOriginTool = tool; + ATH_MSG_INFO(" Creating truth origin tool " + m_truthOriginToolName); + } + + if (asg::ToolStore::contains<InDet::JetTrackFilterTool>(m_jetTrackFilterToolName)) { + m_jetTrackFilterTool = asg::ToolStore::get<InDet::JetTrackFilterTool>(m_jetTrackFilterToolName); + } else { + auto tool = new InDet::JetTrackFilterTool(m_jetTrackFilterToolName); + top::check(tool->setProperty("trackOriginTool", + ToolHandle<InDet::IInDetTrackTruthOriginTool>{&(*m_truthOriginTool)}), + "Failed to setProperty trackOriginTool of InDetTrackTruthFilterTool " + m_truthFilterToolName); + top::check(tool->initialize(), "Failure to initialize JetTrackFilterTool"); + m_jetTrackFilterTool = tool; + ATH_MSG_INFO(" Creating jet track filter tool"); + } + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopIsolationCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopIsolationCPTools.cxx index 7d9bc98441bb3e61ca607cbb5cc1aa63205e2422..4528701ee5e781b22d07f3d0da4b74a6e7210192 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopIsolationCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopIsolationCPTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopIsolationCPTools.h" @@ -16,90 +16,149 @@ // Isolation include(s): #include "IsolationSelection/IsolationSelectionTool.h" +//#include "IsolationSelection/IsolationLowPtPLVTool.h" #include "IsolationCorrections/IsolationCorrectionTool.h" namespace top { - -IsolationCPTools::IsolationCPTools(const std::string& name) : + IsolationCPTools::IsolationCPTools(const std::string& name) : asg::AsgTool(name), - m_isolationCalibFile("IsolationSelection/v1/MC15_Z_Jpsi_cutMap.root"){ - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); + m_isolationCalibFile("IsolationSelection/v1/MC15_Z_Jpsi_cutMap.root") { + declareProperty("config", m_config); - declareProperty( "IsolationCorrectionTool" , m_isolationCorr); -} + declareProperty("IsolationCorrectionTool", m_isolationCorr); + } -StatusCode IsolationCPTools::initialize() { - ATH_MSG_INFO("top::IsolationCPTools initialize..."); + StatusCode IsolationCPTools::initialize() { + ATH_MSG_INFO("top::IsolationCPTools initialize..."); - if (!m_config->makeAllCPTools()) { - ATH_MSG_INFO("top::IsolationCPTools: no need to initialise for mini-xAOD"); - return StatusCode::SUCCESS; - } + if (!m_config->makeAllCPTools()) { + ATH_MSG_INFO("top::IsolationCPTools: no need to initialise for mini-xAOD"); + return StatusCode::SUCCESS; + } - if (!m_config->useElectrons() && m_config->useMuons()) { - ATH_MSG_INFO("top::IsolationCPTools: no need to initialise since neither using electrons nor muons"); + if (!m_config->useElectrons() && !m_config->useMuons()) { + ATH_MSG_INFO("top::IsolationCPTools: no need to initialise since neither using electrons nor muons"); + return StatusCode::SUCCESS; + } + top::check(setupIsolation(), "Failed to setup Isolation tools"); return StatusCode::SUCCESS; } - top::check(setupIsolation(), "Failed to setup Isolation tools"); - return StatusCode::SUCCESS; -} - -StatusCode IsolationCPTools::setupIsolation() { - // needed both for electrons and photons to apply the leakage correction, - // [http://cern.ch/go/j6Lx] - std::string iso_corr_tool_name = "CP::IsolationCorrectionTool"; - if (asg::ToolStore::contains<CP::IIsolationCorrectionTool>(iso_corr_tool_name)) { - m_isolationCorr = asg::ToolStore::get<CP::IIsolationCorrectionTool>(iso_corr_tool_name); - } else { - CP::IIsolationCorrectionTool* isolationCorr = new CP::IsolationCorrectionTool(iso_corr_tool_name); - top::check(asg::setProperty(isolationCorr, "IsMC", m_config->isMC()), - "Failed to setProperty"); // if MC, else false - top::check(isolationCorr->initialize(), "Failed to initialize"); - - m_isolationCorr = isolationCorr; - } - // Muon Isolation WPs - std::set<std::string> muon_isolations = {"LooseTrackOnly", "Loose", - "Gradient", "GradientLoose", - "FixedCutTightTrackOnly", - "FixedCutLoose"}; - // Electron Isolation WPs include all of those defined for - // muons + FixedCutTight - std::set<std::string> electron_isolations; - electron_isolations.insert(muon_isolations.begin(), muon_isolations.end()); - electron_isolations.insert("FixedCutTight"); - // Photon Isolation WPs - std::set<std::string> photon_isolations = {"FixedCutTightCaloOnly", - "FixedCutTight", - "FixedCutLoose"}; - - std::set<std::string> all_isolations; - all_isolations.insert(muon_isolations.begin(), muon_isolations.end()); - all_isolations.insert(electron_isolations.begin(), electron_isolations.end()); - all_isolations.insert(photon_isolations.begin(), photon_isolations.end()); - - for (const std::string& isoWP : all_isolations) { - std::string tool_name = "CP::IsolationTool_"+isoWP; - if (!asg::ToolStore::contains<CP::IIsolationSelectionTool>(tool_name)) { - CP::IIsolationSelectionTool* iso_tool = new CP::IsolationSelectionTool(tool_name); - top::check(asg::setProperty(iso_tool, "CalibFileName", m_isolationCalibFile), - "Failed to set CalibFileName for " + tool_name); - if (electron_isolations.find(isoWP) != electron_isolations.end()) - top::check(asg::setProperty(iso_tool, "ElectronWP", isoWP), - "Failed to set electron WP for " + tool_name); - if (muon_isolations.find(isoWP) != muon_isolations.end()) - top::check(asg::setProperty(iso_tool, "MuonWP", isoWP), - "Failed to set muon WP for " + tool_name); - if (photon_isolations.find(isoWP) != photon_isolations.end()) - top::check(asg::setProperty(iso_tool, "PhotonWP", isoWP), - "Failed to set photon WP for " + tool_name); - top::check(iso_tool->initialize(), "Failed to initialize " + tool_name); - m_isolationTools.push_back(iso_tool); + StatusCode IsolationCPTools::setupIsolation() { + // needed both for electrons and photons to apply the leakage correction, + // [http://cern.ch/go/j6Lx] + std::string iso_corr_tool_name = "CP::IsolationCorrectionTool"; + if (asg::ToolStore::contains<CP::IIsolationCorrectionTool>(iso_corr_tool_name)) { + m_isolationCorr = asg::ToolStore::get<CP::IIsolationCorrectionTool>(iso_corr_tool_name); + } else { + CP::IIsolationCorrectionTool* isolationCorr = new CP::IsolationCorrectionTool(iso_corr_tool_name); + top::check(asg::setProperty(isolationCorr, "IsMC", m_config->isMC()), + "Failed to setProperty IsMC"); // if MC, else false + top::check(asg::setProperty(isolationCorr, "AFII_corr", m_config->isAFII()), + "Failed to setProperty AFII_corr"); // if AFII, else false + if (m_config->useEgammaLeakageCorrection()) { + top::check(asg::setProperty(isolationCorr, "Apply_SC_leakcorr", true), + "Failed to setProperty Apply_SC_leakcorr"); // super cluster based core correction + top::check(asg::setProperty(isolationCorr, "Apply_etaEDParPU_correction", true), + "Failed to setProperty Apply_etaEDParPU_correction"); // improved energy density based pileup + // correction with eta variations + top::check(asg::setProperty(isolationCorr, "Apply_etaEDPar_mc_correction", m_config->isMC()), + "Failed to setProperty Apply_etaEDPar_mc_correction"); // pileup dependent correction to MC + } + top::check(isolationCorr->initialize(), "Failed to initialize"); + + m_isolationCorr = isolationCorr; } - } - return StatusCode::SUCCESS; -} + // Muon Isolation WPs + std::set<std::string> muon_isolations {{ + "FCTight", + "FCLoose", + "FCTightTrackOnly", + "FCTightTrackOnly_FixedRad", + "FCLoose_FixedRad", + "FCTight_FixedRad", + "FixedCutPflowTight", + "FixedCutPflowLoose", + "PflowTight_FixedRad", + "PflowLoose_FixedRad", + "PflowTight_VarRad", + "PflowLoose_VarRad", + "HighPtTrackOnly", + "TightTrackOnly_VarRad", + "TightTrackOnly_FixedRad", + "PLVTight", + "PLVLoose", + "Tight_VarRad", + "Tight_FixedRad", + "Loose_VarRad", + "Loose_FixedRad", + }}; + + // Electron Isolation WPs + std::set<std::string> electron_isolations {{ + "Gradient", + "FCHighPtCaloOnly", + "FCTight", + "FCLoose", + "HighPtCaloOnly", + "Loose", + "Tight", + "TightTrackOnly", + "TightTrackOnly_FixedRad", + "PflowTight", + "PflowLoose", + "PLVTight", + "PLVLoose", + }}; + + // Photon Isolation WPs + std::set<std::string> photon_isolations {{ + "FixedCutTightCaloOnly", + "FixedCutTight", + "FixedCutLoose", + "TightCaloOnly", + "Tight", + "Loose", + }}; + + std::set<std::string> all_isolations; + all_isolations.insert(muon_isolations.begin(), muon_isolations.end()); + all_isolations.insert(electron_isolations.begin(), electron_isolations.end()); + all_isolations.insert(photon_isolations.begin(), photon_isolations.end()); + + for (const std::string& isoWP : all_isolations) { + std::string tool_name; +// if (isoWP.find("PLV") != std::string::npos){ +// tool_name = "CP::IsolationTool_LowPtPLV"; +// if(!asg::ToolStore::contains<CP::IIsolationLowPtPLVTool>(tool_name)) { +// CP::IIsolationLowPtPLVTool* iso_tool = new CP::IsolationLowPtPLVTool(tool_name); +// top::check(iso_tool->initialize(), "Failed to initialize " + tool_name); +// m_isolationToolsLowPtPLV.push_back(iso_tool); +// } +// } + tool_name = "CP::IsolationTool_" + isoWP; + if (!asg::ToolStore::contains<CP::IIsolationSelectionTool>(tool_name)) { + CP::IIsolationSelectionTool* iso_tool = new CP::IsolationSelectionTool(tool_name); + top::check(asg::setProperty(iso_tool, "CalibFileName", m_isolationCalibFile), + "Failed to set CalibFileName for " + tool_name); + if (electron_isolations.find(isoWP) != + electron_isolations.end()) top::check(asg::setProperty(iso_tool, "ElectronWP", + isoWP), + "Failed to set electron WP for " + + tool_name); + if (muon_isolations.find(isoWP) != muon_isolations.end()) top::check(asg::setProperty(iso_tool, "MuonWP", + isoWP), + "Failed to set muon WP for " + tool_name); + if (photon_isolations.find(isoWP) != + photon_isolations.end()) top::check(asg::setProperty(iso_tool, "PhotonWP", + isoWP), + "Failed to set photon WP for " + + tool_name); + top::check(iso_tool->initialize(), "Failed to initialize " + tool_name); + m_isolationTools.push_back(iso_tool); + } + } + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopJetMETCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopJetMETCPTools.cxx index 80ccb2b803934308aacdef2e1bf7adeccb9f3d96..bb3e3d380abbc73b1ece46e007e4464ff0a96cf2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopJetMETCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopJetMETCPTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopJetMETCPTools.h" @@ -20,480 +20,667 @@ #include "JetMomentTools/JetVertexTaggerTool.h" #include "JetMomentTools/JetForwardJvtTool.h" #include "JetSelectorTools/JetCleaningTool.h" -#include "JetResolution/JERTool.h" -#include "JetResolution/JERSmearingTool.h" #include "JetJvtEfficiency/JetJvtEfficiency.h" +#include "JetSelectorTools/EventCleaningTool.h" // MET include(s): #include "METUtilities/METMaker.h" #include "METUtilities/METSystematicsTool.h" namespace top { - -JetMETCPTools::JetMETCPTools(const std::string& name) : + JetMETCPTools::JetMETCPTools(const std::string& name) : asg::AsgTool(name), m_jetJVT_ConfigFile("JVTlikelihood_20140805.root"), - // Updated to December 2016 recommendations - // config names are the same for Data and FS, for EM or LC jets - m_jetAntiKt4_Data_ConfigFile("JES_data2016_data2015_Recommendation_Dec2016.config"), - m_jetAntiKt4_Data_CalibSequence("JetArea_Residual_Origin_EtaJES_GSC_Insitu"), + // Calibration strings for R21 only + m_jetAntiKt4_Data_ConfigFile("JES_MC16Recommendation_Consolidated_EMTopo_Apr2019_Rel21.config"), + m_jetAntiKt4_Data_CalibSequence("JetArea_Residual_EtaJES_GSC_Insitu"), - m_jetAntiKt4_MCFS_ConfigFile("JES_data2016_data2015_Recommendation_Dec2016.config"), - m_jetAntiKt4_MCFS_CalibSequence("JetArea_Residual_Origin_EtaJES_GSC"), + m_jetAntiKt4_MCFS_ConfigFile("JES_MC16Recommendation_Consolidated_EMTopo_Apr2019_Rel21.config"), + m_jetAntiKt4_MCFS_CalibSequence("JetArea_Residual_EtaJES_GSC_Smear"), - // AFII is different - still June 2015 pre-recommendations - m_jetAntiKt4_MCAFII_ConfigFile("JES_MC15Prerecommendation_AFII_June2015.config"), - m_jetAntiKt4_MCAFII_CalibSequence("JetArea_Residual_Origin_EtaJES_GSC"), + m_jetAntiKt4_MCAFII_ConfigFile("JES_MC16Recommendation_AFII_EMTopo_Apr2019_Rel21.config"), + m_jetAntiKt4_MCAFII_CalibSequence("JetArea_Residual_EtaJES_GSC_Smear"), - // Particle-Flow jets, August 2016 recommendations, no GSC - m_jetAntiKt4_PFlow_MCFS_ConfigFile("JES_MC15cRecommendation_PFlow_Aug2016.config"), - m_jetAntiKt4_PFlow_MCFS_CalibSequence("JetArea_Residual_EtaJES_GSC") { + m_jetAntiKt4_MCAFII_PFlow_ConfigFile("JES_MC16Recommendation_AFII_PFlow_Apr2019_Rel21.config"), + m_jetAntiKt4_MCAFII_PFlow_CalibSequence("JetArea_Residual_EtaJES_GSC_Smear"), - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); + m_jetAntiKt4_PFlow_MCFS_ConfigFile("JES_MC16Recommendation_Consolidated_PFlow_Apr2019_Rel21.config"), + m_jetAntiKt4_PFlow_MCFS_CalibSequence("JetArea_Residual_EtaJES_GSC_Smear"), - declareProperty( "JetCalibrationTool" , m_jetCalibrationTool ); - declareProperty( "JetCalibrationToolLargeR" , m_jetCalibrationToolLargeR ); + m_jetAntiKt4_Data_PFlow_ConfigFile("JES_MC16Recommendation_Consolidated_PFlow_Apr2019_Rel21.config"), + m_jetAntiKt4_Data_PFlow_CalibSequence("JetArea_Residual_EtaJES_GSC_Insitu") { + declareProperty("config", m_config); - declareProperty( "JetUncertaintiesTool" , m_jetUncertaintiesTool); - declareProperty( "JetUncertaintiesToolReducedNPScenario1" , m_jetUncertaintiesToolReducedNPScenario1 ); - declareProperty( "JetUncertaintiesToolReducedNPScenario2" , m_jetUncertaintiesToolReducedNPScenario2 ); - declareProperty( "JetUncertaintiesToolReducedNPScenario3" , m_jetUncertaintiesToolReducedNPScenario3 ); - declareProperty( "JetUncertaintiesToolReducedNPScenario4" , m_jetUncertaintiesToolReducedNPScenario4 ); + declareProperty("JetCalibrationTool", m_jetCalibrationTool); + declareProperty("JetCalibrationToolLargeR", m_jetCalibrationToolLargeR); - declareProperty( "JetCleaningToolLooseBad" , m_jetCleaningToolLooseBad ); - declareProperty( "JetCleaningToolTightBad" , m_jetCleaningToolTightBad ); + declareProperty("JetUncertaintiesTool", m_jetUncertaintiesTool); + declareProperty("JetUncertaintiesToolFrozenJMS", m_jetUncertaintiesToolFrozenJMS); + declareProperty("JetUncertaintiesToolReducedNPScenario1", m_jetUncertaintiesToolReducedNPScenario1); + declareProperty("JetUncertaintiesToolReducedNPScenario2", m_jetUncertaintiesToolReducedNPScenario2); + declareProperty("JetUncertaintiesToolReducedNPScenario3", m_jetUncertaintiesToolReducedNPScenario3); + declareProperty("JetUncertaintiesToolReducedNPScenario4", m_jetUncertaintiesToolReducedNPScenario4); - declareProperty( "JetJERTool" , m_jetJERTool ); - declareProperty( "JetJERSmearingTool" , m_jetJERSmearingTool ); - declareProperty( "JetUpdateJvtTool" , m_jetUpdateJvtTool ); + declareProperty("JetCleaningToolLooseBad", m_jetCleaningToolLooseBad); + declareProperty("JetCleaningToolTightBad", m_jetCleaningToolTightBad); - declareProperty( "JES_data2016_data2015_Recommendation_Dec2016.config", m_jetAntiKt4_MCFS_ConfigFile); - declareProperty( "JetCalibrationSequenceFS", m_jetAntiKt4_MCFS_CalibSequence ); + declareProperty("JetEventCleaningToolLooseBad", m_jetEventCleaningToolLooseBad); + declareProperty("JetEventCleaningToolTightBad", m_jetEventCleaningToolTightBad); - declareProperty( "JES_MC15cRecommendation_PFlow_Aug2016.config", m_jetAntiKt4_PFlow_MCFS_ConfigFile); - declareProperty( "JetArea_Residual_EtaJES_GSC", m_jetAntiKt4_PFlow_MCFS_CalibSequence ); + declareProperty("JetUpdateJvtTool", m_jetUpdateJvtTool); + declareProperty("JetSelectfJvtTool", m_jetSelectfJvtTool); + declareProperty("TruthJetCollectionForHSTagging", m_truthJetCollForHS = "AntiKt4TruthJets"); - declareProperty( "met_maker" , m_met_maker ); - declareProperty( "met_systematics" , m_met_systematics ); -} + declareProperty("JES_data2016_data2015_Recommendation_Dec2016.config", m_jetAntiKt4_MCFS_ConfigFile); + declareProperty("JetCalibrationSequenceFS", m_jetAntiKt4_MCFS_CalibSequence); -StatusCode JetMETCPTools::initialize() { - ATH_MSG_INFO("top::JetMETCPTools initialize..."); - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::JetMETCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; + declareProperty("JES_MC15cRecommendation_PFlow_Aug2016.config", m_jetAntiKt4_PFlow_MCFS_ConfigFile); + declareProperty("JetArea_Residual_EtaJES_GSC", m_jetAntiKt4_PFlow_MCFS_CalibSequence); + + declareProperty("met_maker", m_met_maker); + declareProperty("met_systematics", m_met_systematics); } - if (m_config->useJets()) { - if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs - top::check(setupJetsCalibration(), "Failed to setup jet calibration tools"); + StatusCode JetMETCPTools::initialize() { + ATH_MSG_INFO("top::JetMETCPTools initialize..."); + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::JetMETCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; } - // JVT tool needed for both MC and data (for both selection and SFs) - top::check(setupJetsScaleFactors(), "Failed to setup jet scale-factor tools"); - } - if (m_config->useLargeRJets()) - top::check(setupLargeRJetsCalibration(), "Failed to setup large-R jet calibration"); + if (m_config->getDerivationStream() == "PHYS") { + m_truthJetCollForHS = "AntiKt4TruthDressedWZJets"; + } - if (m_config->makeAllCPTools()) {// MET not needed on mini-xAODs - top::check(setupMET(), "Failed to setup MET tools"); - } + if (m_config->useJets()) { + if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs + top::check(setupJetsCalibration(), "Failed to setup jet calibration tools"); + } + // JVT tool needed for both MC and data (for both selection and SFs) + top::check(setupJetsScaleFactors(), "Failed to setup jet scale-factor tools"); + } - return StatusCode::SUCCESS; -} - -StatusCode JetMETCPTools::setupJetsCalibration() { - - // Release 21 specific - // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/ApplyJetCalibration2016#Calibrating_jets_in_Release_21 - if(m_release_series == 25){ - ATH_MSG_INFO("Updating configuration options for Rel21"); - // Data - m_jetAntiKt4_Data_ConfigFile = "JES_data2016_data2015_Recommendation_Dec2016_rel21.config"; - m_jetAntiKt4_Data_CalibSequence = "JetArea_Residual_EtaJES_GSC_Insitu"; - // FS EM/LC - m_jetAntiKt4_MCFS_ConfigFile = "JES_data2016_data2015_Recommendation_Dec2016_rel21.config"; - m_jetAntiKt4_MCFS_CalibSequence = "JetArea_Residual_EtaJES_GSC"; - // AFII EM/LC - m_jetAntiKt4_MCAFII_ConfigFile = ""; // No Rel21 - m_jetAntiKt4_MCAFII_CalibSequence = ""; - // FS PFlow - m_jetAntiKt4_PFlow_MCFS_ConfigFile = "JES_MC15cRecommendation_PFlow_Aug2016.config"; // MC15c? - m_jetAntiKt4_PFlow_MCFS_CalibSequence = "JetArea_Residual_EtaJES_GSC"; - // Note there are suggestions for PFlow in Data - // JES_MC15cRecommendation_PFlow_Aug2016.config - // JetArea_Residual_EtaJES_GSC - } + if (m_config->useLargeRJets()) top::check(setupLargeRJetsCalibration(), "Failed to setup large-R jet calibration"); - // Get jet calibration name and erase "Jets" from the end - std::string caloJets_collection = m_config->sgKeyJets(); - std::string jetCalibrationName; - if (caloJets_collection == "AntiKt4EMTopoNoElJets"){ - jetCalibrationName="AntiKt4EMTopoJets"; - } - else{ - jetCalibrationName = caloJets_collection ; - } - jetCalibrationName.erase(jetCalibrationName.length() - 4); + if (m_config->makeAllCPTools()) {// MET not needed on mini-xAODs + top::check(setupMET(), "Failed to setup MET tools"); + } - // In case of using JMS calibration - if ( m_config->jetCalibSequence() == "JMS" ) { - m_jetAntiKt4_MCFS_ConfigFile.erase(m_jetAntiKt4_MCFS_ConfigFile.length() - 7);//erase ".config" at the end - m_jetAntiKt4_MCFS_ConfigFile += "_JMS.config"; - m_jetAntiKt4_MCFS_CalibSequence += "_JMS"; + return StatusCode::SUCCESS; } - ///-- Calibration --/// - if (asg::ToolStore::contains<IJetCalibrationTool>("JetCalibrationTool")) { - m_jetCalibrationTool = asg::ToolStore::get<IJetCalibrationTool>("JetCalibrationTool"); - } else { - std::string calibConfig, calibSequence; - if (m_config->isMC()) { - if (m_config->isAFII()) { - calibConfig = m_jetAntiKt4_MCAFII_ConfigFile; - calibSequence = m_jetAntiKt4_MCAFII_CalibSequence; - } else { - calibConfig = m_jetAntiKt4_MCFS_ConfigFile; - calibSequence = m_jetAntiKt4_MCFS_CalibSequence; - } + StatusCode JetMETCPTools::setupJetsCalibration() { + // Release 21 specific + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/JetEtmissRecommendationsR21 + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/ApplyJetCalibrationR21 + + // Get jet calibration name and erase "Jets" from the end + std::string caloJets_type = m_config->sgKeyJetsType(); + std::string jetCalibrationName; + if (caloJets_type == "AntiKt4EMTopoNoElJets") { + jetCalibrationName = "AntiKt4EMTopoJets"; } else { - calibConfig = m_jetAntiKt4_Data_ConfigFile; - calibSequence = m_jetAntiKt4_Data_CalibSequence; + jetCalibrationName = caloJets_type; } - if (m_config->useParticleFlowJets()) { - calibConfig = m_jetAntiKt4_PFlow_MCFS_ConfigFile; - calibSequence = m_jetAntiKt4_PFlow_MCFS_CalibSequence; + jetCalibrationName.erase(jetCalibrationName.length() - 4); + + // In case of using JMS calibration + if (m_config->jetCalibSequence() == "JMS") { + ATH_MSG_ERROR("Unable to calibrate jets with JMS calib sequence in release 21: No recommendations! "); + return StatusCode::FAILURE; + + // If this is functional, remove the error above and reconfigure the calibration sequence + m_jetAntiKt4_MCFS_ConfigFile.erase(m_jetAntiKt4_MCFS_ConfigFile.length() - 7);//erase ".config" at the end + m_jetAntiKt4_MCFS_ConfigFile += "_JMS.config"; + m_jetAntiKt4_MCFS_CalibSequence += "_JMS"; } - JetCalibrationTool* jetCalibrationTool = new JetCalibrationTool("JetCalibrationTool"); - top::check(asg::setProperty(jetCalibrationTool, "JetCollection", jetCalibrationName), - "Failed to set JetCollection " + jetCalibrationName); - top::check(asg::setProperty(jetCalibrationTool, "ConfigFile", calibConfig), - "Failed to set ConfigFile " + calibConfig); - top::check(asg::setProperty(jetCalibrationTool, "CalibSequence", calibSequence), - "Failed to set CalibSequence " + calibSequence); - top::check(asg::setProperty(jetCalibrationTool, "IsData", !m_config->isMC()), - "Failed to set IsData " + !m_config->isMC()); - - top::check(jetCalibrationTool->initializeTool(jetCalibrationName), - "Failed to initialize JetCalibrationTool"); - m_jetCalibrationTool = jetCalibrationTool; - } + ///-- Calibration --/// + if (asg::ToolStore::contains<IJetCalibrationTool>("JetCalibrationTool")) { + m_jetCalibrationTool = asg::ToolStore::get<IJetCalibrationTool>("JetCalibrationTool"); + } else { + std::string calibConfig, calibSequence; + if (m_config->isMC()) { + // AFII + if (m_config->isAFII()) { + if (m_config->useParticleFlowJets()) { + calibConfig = m_jetAntiKt4_MCAFII_PFlow_ConfigFile; + calibSequence = m_jetAntiKt4_MCAFII_PFlow_CalibSequence; + } else { + calibConfig = m_jetAntiKt4_MCAFII_ConfigFile; + calibSequence = m_jetAntiKt4_MCAFII_CalibSequence; + } + } + // FS - PFlow + else if (m_config->useParticleFlowJets()) { + calibConfig = m_jetAntiKt4_PFlow_MCFS_ConfigFile; + calibSequence = m_jetAntiKt4_PFlow_MCFS_CalibSequence; + } + // FS + else { + calibConfig = m_jetAntiKt4_MCFS_ConfigFile; + calibSequence = m_jetAntiKt4_MCFS_CalibSequence; + } + } else { + if (m_config->useParticleFlowJets()) { + calibConfig = m_jetAntiKt4_Data_PFlow_ConfigFile; + calibSequence = m_jetAntiKt4_Data_PFlow_CalibSequence; + } else { + calibConfig = m_jetAntiKt4_Data_ConfigFile; + calibSequence = m_jetAntiKt4_Data_CalibSequence; + } + } - ///-- Update JVT --/// - const std::string jvt_update_name = "JetUpdateJvtTool"; - if (asg::ToolStore::contains<IJetUpdateJvt>(jvt_update_name)) { - m_jetUpdateJvtTool = asg::ToolStore::get<IJetUpdateJvt>(jvt_update_name); - } else { - IJetUpdateJvt* jetUpdateJvtTool = new JetVertexTaggerTool(jvt_update_name); - top::check(asg::setProperty(jetUpdateJvtTool, "JVTFileName", "JetMomentTools/" + m_jetJVT_ConfigFile), - "Failed to set JVTFileName for JetUpdateJvtTool"); - top::check(jetUpdateJvtTool->initialize(), "Failed to initialize"); - m_jetUpdateJvtTool = jetUpdateJvtTool; - } + // Print out some information + ATH_MSG_INFO("Configuration JES tools with "); + ATH_MSG_INFO("JES Calibration Configuration : " << calibConfig); + ATH_MSG_INFO("JES Calibration Sequence : " << calibSequence); + + JetCalibrationTool* jetCalibrationTool = new JetCalibrationTool("JetCalibrationTool"); + top::check(asg::setProperty(jetCalibrationTool, "JetCollection", jetCalibrationName), + "Failed to set JetCollection " + jetCalibrationName); + top::check(asg::setProperty(jetCalibrationTool, "ConfigFile", calibConfig), + "Failed to set ConfigFile " + calibConfig); + top::check(asg::setProperty(jetCalibrationTool, "CalibSequence", calibSequence), + "Failed to set CalibSequence " + calibSequence); + top::check(asg::setProperty(jetCalibrationTool, "IsData", !m_config->isMC()), + "Failed to set IsData " + std::to_string (!m_config->isMC())); + + top::check(jetCalibrationTool->initializeTool(jetCalibrationName), + "Failed to initialize JetCalibrationTool"); + m_jetCalibrationTool = jetCalibrationTool; + } - ///-- Update fJVT --/// - const std::string fjvt_tool_name = "fJVTTool"; - if (asg::ToolStore::contains<IJetModifier>(fjvt_tool_name)) { - m_fjvtTool = asg::ToolStore::get<IJetModifier>(fjvt_tool_name); - } else { - IJetModifier* fJVTTool = new JetForwardJvtTool(fjvt_tool_name); - top::check(asg::setProperty(fJVTTool, "JvtMomentName", "AnalysisTop_JVT"), - "Failed to set JvtMomentName for JetForwardJvtTool"); - // following instructions from: - // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/METUtilities#MET_with_forward_JVT - if (m_config->fwdJetAndMET() == "fJVT") { - top::check(asg::setProperty(fJVTTool, "CentralMaxPt", 60e3), - "Failed to set CentralMaxPt for JetForwardJvtTool"); + ///-- Update JVT --/// + const std::string jvt_update_name = "JetUpdateJvtTool"; + if (asg::ToolStore::contains<IJetUpdateJvt>(jvt_update_name)) { + m_jetUpdateJvtTool = asg::ToolStore::get<IJetUpdateJvt>(jvt_update_name); + } else { + IJetUpdateJvt* jetUpdateJvtTool = new JetVertexTaggerTool(jvt_update_name); + top::check(asg::setProperty(jetUpdateJvtTool, "JVTFileName", "JetMomentTools/" + m_jetJVT_ConfigFile), + "Failed to set JVTFileName for JetUpdateJvtTool"); + top::check(jetUpdateJvtTool->initialize(), "Failed to initialize"); + m_jetUpdateJvtTool = jetUpdateJvtTool; } - top::check(fJVTTool->initialize(), "Failed to initialize " + fjvt_tool_name); - m_fjvtTool = fJVTTool; - } - // TODO(tom.neep@cern.ch): Currently we don't have uncertainties for - // particle flow jets, so return successfully - // here. Keep an eye on this in the future. - // Also: no jet cleaning for particle-flow jets. - if (m_config->useParticleFlowJets()) - return StatusCode::SUCCESS; + ///-- Calculate fJVT --/// + //Only setup fJVT tool if user actually wants it + if (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None") { + + const std::string fjvt_tool_name = "JetSelectfJvtTool"; + if (asg::ToolStore::contains<IJetModifier>(fjvt_tool_name)) { + m_jetSelectfJvtTool = asg::ToolStore::get<IJetModifier>(fjvt_tool_name); + } else { + IJetModifier* JetSelectfJvtTool = new JetForwardJvtTool(fjvt_tool_name); + top::check(asg::setProperty(JetSelectfJvtTool, "JvtMomentName", "AnalysisTop_JVT"), //fJVT uses JVT decision + "Failed to set JvtMomentName for JetForwardJvtTool"); + + //Default fJVT WP is medium but this can't be used with default Tight MET WP + //MET WP takes precidence so making ATop default fJVT=Tight + if (m_config->getfJVTWP() != "Medium"){ + top::check(asg::setProperty(JetSelectfJvtTool, "UseTightOP", true), + "Failed to set UseTightOP for JetForwardJvtTool"); + } + top::check(asg::setProperty(JetSelectfJvtTool, "OutputDec", "AnalysisTop_fJVTdecision"), //Adds custom decorator, 'AnalysisTop_fJVTdecision', to all jets + "Failed to set OutputDec for JetForwardJvtTool"); + + top::check(JetSelectfJvtTool->initialize(), "Failed to initialize " + fjvt_tool_name); + m_jetSelectfJvtTool = JetSelectfJvtTool; + } + } - ///-- Jet Cleaning Tools --/// - m_jetCleaningToolLooseBad = setupJetCleaningTool("LooseBad"); - m_jetCleaningToolTightBad = setupJetCleaningTool("TightBad"); - - // Uncertainties - // Is our MC full or fast simulation? - std::string MC_type = (m_config->isAFII()) ? "AFII" : "MC15"; - - std::string conference = "Moriond2017"; - - // Are we doing multiple JES for the reduced NP senarios? - if (!m_config->doMultipleJES()) { - m_jetUncertaintiesTool - = setupJetUncertaintiesTool("JetUncertaintiesTool", - jetCalibrationName, MC_type, - "JES_2016/" - + conference - +"/JES2016_" - + m_config->jetUncertainties_NPModel() - + ".config",nullptr); - } else { - m_jetUncertaintiesToolReducedNPScenario1 - = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario1", - jetCalibrationName, MC_type, - "JES_2016/" - + conference - + "/JES2016_SR_Scenario1.config",nullptr); - m_jetUncertaintiesToolReducedNPScenario2 - = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario2", - jetCalibrationName, MC_type, - "JES_2016/" - + conference - + "/JES2016_SR_Scenario2.config",nullptr); - m_jetUncertaintiesToolReducedNPScenario3 - = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario3", - jetCalibrationName, MC_type, - "JES_2016/" - + conference - + "/JES2016_SR_Scenario3.config",nullptr); - m_jetUncertaintiesToolReducedNPScenario4 - = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario4", - jetCalibrationName, MC_type, - "JES_2016/" - + conference - + "/JES2016_SR_Scenario4.config",nullptr); - } + ///-- Jet Cleaning Tools --/// + m_jetCleaningToolLooseBad = setupJetCleaningTool("LooseBad"); + m_jetCleaningToolTightBad = setupJetCleaningTool("TightBad"); - // JER Tool - if (asg::ToolStore::contains<IJERTool>("JetJERTool")) { - m_jetJERTool = asg::ToolStore::get<IJERTool>("JetJERTool"); - } else { - IJERTool* jetJERTool = new JERTool("JetJERTool"); - top::check(asg::setProperty(jetJERTool, "CollectionName", "AntiKt4EMTopoJets"), - "Failed to set CollectionName to JetJERTool"); - top::check(jetJERTool->initialize(), "Failed to initialize"); - m_jetJERTool = jetJERTool; - } + m_jetEventCleaningToolLooseBad = setupJetEventCleaningTool("LooseBad", m_jetCleaningToolLooseBad); + m_jetEventCleaningToolTightBad = setupJetEventCleaningTool("TightBad", m_jetCleaningToolTightBad); - // JER Smearing - const std::string jersmear_name = "JetJERSmearingTool"; - if (asg::ToolStore::contains<IJERSmearingTool>(jersmear_name)) { - m_jetJERSmearingTool = asg::ToolStore::get<IJERSmearingTool>(jersmear_name); - } else { - IJERSmearingTool* jetJERSmearingTool = new JERSmearingTool(jersmear_name); - top::check(asg::setProperty(jetJERSmearingTool, "JERTool" , m_jetJERTool), - "Failed to JERTool to " + jersmear_name); - top::check(asg::setProperty(jetJERSmearingTool, "ApplyNominalSmearing", false), - "Failed to ApplyNominalSmearing for " + jersmear_name); - top::check(asg::setProperty(jetJERSmearingTool, "isMC", m_config->isMC()), - "Failed to isMC to " + jersmear_name); - top::check(asg::setProperty(jetJERSmearingTool, "SystematicMode", m_config->jetJERSmearingModel()), - "Failed to SystematicMode for " + jersmear_name); - top::check(jetJERSmearingTool->initialize(), - "Failed to initialize " + jersmear_name); - m_jetJERSmearingTool = jetJERSmearingTool; - } + // Uncertainties + // Is our MC full or fast simulation? + std::string MC_type = (m_config->isAFII()) ? "AFII" : "MC16"; + + // Moriond2018 - AF2 JES + // Summer2019 - JES/JER update + std::string conference = "Summer2019"; - return StatusCode::SUCCESS; -} - -StatusCode JetMETCPTools::setupLargeRJetsCalibration() { - std::string jetCalibrationNameLargeR = m_config->sgKeyLargeRJets(); - // erase "Jets" from the end - jetCalibrationNameLargeR.erase(jetCalibrationNameLargeR.length() - 4); - - if (asg::ToolStore::contains<IJetCalibrationTool>("JetCalibrationToolLargeR")) { - m_jetCalibrationToolLargeR = asg::ToolStore::get<IJetCalibrationTool>("JetCalibrationToolLargeR"); - } else { - // Only a single calib config/sequence for MC and data - // so just put it here for now. - std::string calibConfigLargeR = ""; - const std::string calibChoice = m_config->largeRJESJMSConfig(); - if (calibChoice == "CombinedMass") { - calibConfigLargeR = "JES_MC15recommendation_FatJet_Nov2016_QCDCombinationUncorrelatedWeights.config"; + // If JMS is allowed then there should also be extrapolation and frozen uncertainties configured + std::string JMS_Uncertainty = ""; + if (m_config->jetCalibSequence() == "JMS") JMS_Uncertainty = "_JMSExtrap"; + + // By setting calib_area to "None" we pick up the default from the JES group + std::string calib_area = "None"; + + // JER string option configuration + bool JERisMC = m_config->isMC(); + std::string JERSmearModel = m_config->jetJERSmearingModel(); + // Any PseudoData Option (Smear MC as data) + if (JERSmearModel == "Full_PseudoData") { + if (JERisMC) JERisMC = false; + JERSmearModel = "Full"; + ATH_MSG_INFO("JER PseudoData option provided - Treating MC as if it is data for JER uncertainty"); } - else if (calibChoice == "CaloMass") { - calibConfigLargeR = "JES_MC15recommendation_FatJet_June2015.config"; + if (JERSmearModel == "All_PseudoData") { + if (JERisMC) JERisMC = false; + JERSmearModel = "All"; + ATH_MSG_INFO("JER PseudoData option provided - Treating MC as if it is data for JER uncertainty"); } + + // Strings need to be defined clearly for jet tool + if (JERSmearModel == "All") JERSmearModel = "_AllJERNP"; + else if (JERSmearModel == "Full") JERSmearModel = "_FullJER"; + else if (JERSmearModel == "Simple") JERSmearModel = "_SimpleJER"; else { - ATH_MSG_ERROR("Unknown largeRJESJMSConfig "+calibChoice); + ATH_MSG_ERROR("Incorrect JER option: All, All_PseudoData, Full, Full_PseudoData, Simple"); return StatusCode::FAILURE; } - const std::string calibSequenceLargeR = "EtaJES_JMS"; - - JetCalibrationTool* jetCalibrationToolLargeR - = new JetCalibrationTool("JetCalibrationToolLargeR"); - top::check(asg::setProperty(jetCalibrationToolLargeR, "JetCollection", jetCalibrationNameLargeR), - "Failed to set JetCollection " + jetCalibrationNameLargeR); - top::check(asg::setProperty(jetCalibrationToolLargeR, "ConfigFile", calibConfigLargeR), - "Failed to set ConfigFile " + calibConfigLargeR); - top::check(asg::setProperty(jetCalibrationToolLargeR, "CalibSequence", calibSequenceLargeR), - "Failed to set CalibSequence " + calibSequenceLargeR); - top::check(asg::setProperty(jetCalibrationToolLargeR, "IsData", !m_config->isMC()), - "Failed to set IsData " + !m_config->isMC()); - - top::check(jetCalibrationToolLargeR->initializeTool(jetCalibrationNameLargeR), - "Failed to initialize JetCalibrationToolLargeR"); - m_jetCalibrationToolLargeR = jetCalibrationToolLargeR; - } - // Moriond2017 uncertainty recommendations: - // names = "UJ_2016/Moriond2017/UJ2016_CaloMass_strong.config" // strong,medium,weak - // names = "UJ_2016/Moriond2017/UJ2016_CombinedMass_strong.config" // strong,medium,weak - - std::string conference(""); - std::string configDir(""); - std::vector<std::string>* variables = nullptr; - std::string largeRJES_config = m_config->largeRJESUncertaintyConfig(); - std::string MC_type = "MC15"; - - conference = "Moriond2017"; - configDir = "UJ_2016"; - MC_type += "c"; - - variables = new std::vector<std::string>; - variables->push_back("pT"); - std::string variable; - size_t pos_end = 0; - while( (pos_end = largeRJES_config.find(",")) != std::string::npos) { - variable = largeRJES_config.substr(0,pos_end); - variables->push_back(variable); - largeRJES_config.erase(0,pos_end+1); + // Are we doing multiple JES for the reduced NP senarios? + if (!m_config->doMultipleJES()) { + m_jetUncertaintiesTool = setupJetUncertaintiesTool("JetUncertaintiesTool", + jetCalibrationName, + MC_type, + JERisMC, + "rel21/" + conference + + "/R4_" + m_config->jetUncertainties_NPModel() + + JMS_Uncertainty + + JERSmearModel + + ".config", + nullptr, + m_config->jetUncertainties_QGFracFile(), + calib_area + ); + + // Implement additional tool for frozen config when using JMS + if (JMS_Uncertainty == "_JMSExtrap") { + JMS_Uncertainty = "_JMSFrozen"; + m_jetUncertaintiesToolFrozenJMS = setupJetUncertaintiesTool("JetUncertaintiesToolFrozenJMS", + jetCalibrationName, + MC_type, + JERisMC, + "rel21/" + conference + + "/R4_" + m_config->jetUncertainties_NPModel() + + JMS_Uncertainty + + ".config", + nullptr, + m_config->jetUncertainties_QGFracFile(), + calib_area + ); + } + } else { + // Strong reductions now enabled. If you want to run a single scenario please note the new config file names + // R4_SR_Scenario*_SimpleJER + m_jetUncertaintiesToolReducedNPScenario1 + = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario1", + jetCalibrationName, + MC_type, + JERisMC, + "rel21/" + + conference + + "/R4_SR_Scenario1_SimpleJER.config", + nullptr, + m_config->jetUncertainties_QGFracFile(), + calib_area); + m_jetUncertaintiesToolReducedNPScenario2 + = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario2", + jetCalibrationName, + MC_type, + JERisMC, + "rel21/" + + conference + + "/R4_SR_Scenario2_SimpleJER.config", + nullptr, + m_config->jetUncertainties_QGFracFile(), + calib_area); + m_jetUncertaintiesToolReducedNPScenario3 + = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario3", + jetCalibrationName, + MC_type, + JERisMC, + "rel21/" + + conference + + "/R4_SR_Scenario3_SimpleJER.config", + nullptr, + m_config->jetUncertainties_QGFracFile(), + calib_area); + m_jetUncertaintiesToolReducedNPScenario4 + = setupJetUncertaintiesTool("JetUncertaintiesToolReducedNPScenario4", + jetCalibrationName, + MC_type, + JERisMC, + "rel21/" + + conference + + "/R4_SR_Scenario4_SimpleJER.config", + nullptr, + m_config->jetUncertainties_QGFracFile(), + calib_area); + } + + return StatusCode::SUCCESS; } - variables->push_back(largeRJES_config); - - largeRJES_config = m_config->largeRJESJMSConfig(); - if (largeRJES_config.find("UJ2016_") != 0) largeRJES_config.insert(0, "UJ2016_"); - - m_jetUncertaintiesToolLargeR_strong - = setupJetUncertaintiesTool("JetUncertaintiesToolLargeR_Strong", - jetCalibrationNameLargeR, MC_type, - configDir+"/"+conference - + "/"+largeRJES_config+"_strong.config",variables); - m_jetUncertaintiesToolLargeR_medium - = setupJetUncertaintiesTool("JetUncertaintiesToolLargeR_Medium", - jetCalibrationNameLargeR, MC_type, - configDir+"/"+conference - + "/"+largeRJES_config+"_medium.config",variables); - m_jetUncertaintiesToolLargeR_weak - = setupJetUncertaintiesTool("JetUncertaintiesToolLargeR_Weak", - jetCalibrationNameLargeR, MC_type, - configDir+"/"+conference - + "/"+largeRJES_config+"_weak.config",variables); - - if (variables) delete variables; - return StatusCode::SUCCESS; -} - -StatusCode JetMETCPTools::setupJetsScaleFactors() { - // <tom.neep@cern.ch> Added 16th Feb 2016. - // Jet JVT tool - can be used for both selection and for SFs - // Since we use this for jet selection we also need it for data - const std::string jvt_tool_name = "JetJvtEfficiencyTool"; - const std::string JVT_SFFile = - (m_config->sgKeyJets()=="AntiKt4LCTopoJets")? - "JetJvtEfficiency/Moriond2017/JvtSFFile_LC.root": - "JetJvtEfficiency/Moriond2017/JvtSFFile_EM.root";// default is EM jets - if (asg::ToolStore::contains<CP::IJetJvtEfficiency>(jvt_tool_name)) { - m_jetJvtTool = asg::ToolStore::get<CP::IJetJvtEfficiency>(jvt_tool_name); - } else { - CP::JetJvtEfficiency* jetJvtTool = new CP::JetJvtEfficiency(jvt_tool_name); - // Medium WP default for EM or LC jets; special WP for PFlow jets - top::check(jetJvtTool->setProperty("WorkingPoint", (m_config->useParticleFlowJets())?"PFlow":"Medium"), - "Failed to set JVT WP"); - top::check(jetJvtTool->setProperty("SFFile", JVT_SFFile), - "Failed to set JVT SFFile name"); - top::check(jetJvtTool->setProperty("JetJvtMomentName", "AnalysisTop_JVT"), - "Failed to set JVT decoration name"); - top::check(jetJvtTool->setProperty("TruthLabel", "AnalysisTop_isHS"), - "Failed to set JVT TruthLabel decoration name"); - top::check(jetJvtTool->initialize(), "Failed to initialize JVT tool"); - m_jetJvtTool = jetJvtTool; + + StatusCode JetMETCPTools::setupLargeRJetsCalibration() { + std::string jetCalibrationNameLargeR = m_config->sgKeyLargeRJets(); + // erase "Jets" from the end + jetCalibrationNameLargeR.erase(jetCalibrationNameLargeR.length() - 4); + + if (asg::ToolStore::contains<IJetCalibrationTool>("JetCalibrationToolLargeR")) { + m_jetCalibrationToolLargeR = asg::ToolStore::get<IJetCalibrationTool>("JetCalibrationToolLargeR"); + } else { + // Only a single calib config/sequence for MC and data + // so just put it here for now. + std::string calibConfigLargeR = ""; + const std::string calibChoice = m_config->largeRJESJMSConfig(); + if (m_config->isMC()) { + if (calibChoice == "CombMass") { + calibConfigLargeR = "JES_MC16recommendation_FatJet_Trimmed_JMS_comb_17Oct2018.config"; + } else if (calibChoice == "TAMass") { + calibConfigLargeR = "JES_MC16recommendation_FatJet_Trimmed_JMS_TA_12Oct2018.config"; + } else if (calibChoice == "CaloMass") { + calibConfigLargeR = "JES_MC16recommendation_FatJet_Trimmed_JMS_calo_12Oct2018.config"; + } else if (calibChoice == "TCCMass") { + calibConfigLargeR = "JES_MC16recommendation_FatJet_TCC_JMS_calo_30Oct2018.config"; + } else { + ATH_MSG_ERROR( + "Unknown largeRJESJMSConfig (Available options: TAMass, CaloMass, CombMass and TCCMass)) : " + calibChoice); + return StatusCode::FAILURE; + } + } else { //Insitu calibration for Data + if ((calibChoice == "CombMass") || (calibChoice == "TAMass") || (calibChoice == "CaloMass")) { + calibConfigLargeR = "JES_MC16recommendation_FatJet_Trimmed_JMS_comb_3April2019.config"; //Data has only one + // config file + } else if (calibChoice == "TCCMass") { + calibConfigLargeR = "JES_MC16recommendation_FatJet_TCC_JMS_calo_30Oct2018.config"; //There's no insitu + // calibration yet + } else { + ATH_MSG_ERROR( + "Unknown largeRJESJMSConfig (Available options: TAMass, CaloMass, CombMass and TCCMass) : " + calibChoice); + return StatusCode::FAILURE; + } + } + std::string calibSequenceLargeR = "EtaJES_JMS"; + if ((!m_config->isMC()) && + (calibChoice != "TCCMass")) calibSequenceLargeR = "EtaJES_JMS_Insitu_InsituCombinedMass"; //For data, there's + // is insitu + // calibration for + // lc-topo jets + const std::string calibAreaLargeR = "00-04-82"; + JetCalibrationTool* jetCalibrationToolLargeR + = new JetCalibrationTool("JetCalibrationToolLargeR"); + top::check(asg::setProperty(jetCalibrationToolLargeR, "JetCollection", jetCalibrationNameLargeR), + "Failed to set JetCollection " + jetCalibrationNameLargeR); + top::check(asg::setProperty(jetCalibrationToolLargeR, "ConfigFile", calibConfigLargeR), + "Failed to set ConfigFile " + calibConfigLargeR); + top::check(asg::setProperty(jetCalibrationToolLargeR, "CalibSequence", calibSequenceLargeR), + "Failed to set CalibSequence " + calibSequenceLargeR); + top::check(asg::setProperty(jetCalibrationToolLargeR, "CalibArea", calibAreaLargeR), + "Failed to set CalibArea " + calibAreaLargeR); + top::check(asg::setProperty(jetCalibrationToolLargeR, "IsData", !m_config->isMC()), + "Failed to set IsData " + std::to_string (!m_config->isMC())); + top::check(jetCalibrationToolLargeR->initializeTool(jetCalibrationNameLargeR), + "Failed to initialize JetCalibrationToolLargeR"); + m_jetCalibrationToolLargeR = jetCalibrationToolLargeR; + } + + // Moriond2017 uncertainty recommendations: + // names = "UJ_2016/Moriond2017/UJ2016_CaloMass_strong.config" // strong,medium,weak + // names = "UJ_2016/Moriond2017/UJ2016_CombinedMass_strong.config" // strong,medium,weak + + std::string configDir(""); + std::string largeRJESJMS_config = m_config->largeRJetUncertainties_NPModel(); + std::string calibArea = "None"; // Take the default JetUncertainties CalibArea tag + std::string MC_type = "MC16"; + + configDir = m_config->largeRJetUncertaintiesConfigDir(); + + //This has zero impact on the JES uncertainties, but controls how the JER uncertainties (currently only for small-R + // jets) are applied + bool JERisMC = true; + + m_jetUncertaintiesToolLargeR + = setupJetUncertaintiesTool("JetUncertaintiesToolLargeR", + jetCalibrationNameLargeR, MC_type, JERisMC, + configDir + "/R10_" + largeRJESJMS_config + ".config", nullptr, "", calibArea); + + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} -StatusCode JetMETCPTools::setupMET() -{ - if ( asg::ToolStore::contains<IMETMaker>("met::METMaker") ) { - m_met_maker = asg::ToolStore::get<IMETMaker>("met::METMaker"); - } else { - met::METMaker* metMaker = new met::METMaker("met::METMaker"); - top::check( metMaker->setProperty("JetJvtMomentName", "AnalysisTop_JVT"), "Failed to set METMaker JVT moment name" ); - // following instructions from: - // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/EtmissRecommendationsRel20p7Temp#Working_Points_NEW - // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/METUtilities#MET_with_forward_JVT - if (m_config->fwdJetAndMET() == "Tight") { - top::check( metMaker->setProperty("JetSelection", "Tight"), "Failed to set METMaker JetSelection to Tight" ); + StatusCode JetMETCPTools::setupJetsScaleFactors() { + // <tom.neep@cern.ch> Added 16th Feb 2016. + // Jet JVT tool - can be used for both selection and for SFs + // Since we use this for jet selection we also need it for data + const std::string jvt_tool_name = "JetJvtEfficiencyTool"; + const std::string JVT_SFFile = + (m_config->sgKeyJets() == "AntiKt4LCTopoJets") ? + "JetJvtEfficiency/Moriond2018/JvtSFFile_LC.root" : // LC jets + (m_config->useParticleFlowJets()) ? + "JetJvtEfficiency/Moriond2018/JvtSFFile_EMPFlow.root" : // pflow jets + "JetJvtEfficiency/Moriond2018/JvtSFFile_EMTopoJets.root"; // default is EM jets + + const std::string JVT_WP = m_config->getJVTWP(); + + if (asg::ToolStore::contains<CP::IJetJvtEfficiency>(jvt_tool_name)) { + m_jetJvtTool = asg::ToolStore::get<CP::IJetJvtEfficiency>(jvt_tool_name); + } else { + CP::JetJvtEfficiency* jetJvtTool = new CP::JetJvtEfficiency(jvt_tool_name); + top::check(jetJvtTool->setProperty("WorkingPoint", JVT_WP), + "Failed to set JVT WP"); + top::check(jetJvtTool->setProperty("SFFile", JVT_SFFile), + "Failed to set JVT SFFile name"); + top::check(jetJvtTool->setProperty("JetJvtMomentName", "AnalysisTop_JVT"), + "Failed to set JVT decoration name"); + top::check(jetJvtTool->setProperty("TruthLabel", "AnalysisTop_isHS"), + "Failed to set JVT TruthLabel decoration name"); + top::check(jetJvtTool->setProperty("TruthJetContainerName", m_truthJetCollForHS), + "Failed to set JVT TruthJetContainerName decoration name"); + top::check(jetJvtTool->initialize(), "Failed to initialize JVT tool"); + m_jetJvtTool = jetJvtTool; } - else if (m_config->fwdJetAndMET() == "fJVT") { - top::check( metMaker->setProperty("JetRejectionDec", "passFJVT"), "Failed to set METMaker JetRejectionDec to passFJVT" ); + + // <jonathan.jamieson@cern.ch> Added 9th June 2020. + // Jet fJVT tool - uses same tool as for JVT, + // Only setup fJVT Efficiency tool if user actually wants it + if (m_config->getfJVTWP() != "None") { + const std::string fjvt_tool_name = "JetForwardJvtEfficiencyTool"; + const std::string fJVT_SFFile = + (m_config->useParticleFlowJets()) ? + "JetJvtEfficiency/May2020/fJvtSFFile.EMPFlow.root" : // pflow jets + "JetJvtEfficiency/May2020/fJvtSFFile.EMtopo.root"; // default is EM jets + + std::string fJVT_WP = m_config->getfJVTWP(); + if (fJVT_WP == "Medium"){ + fJVT_WP = "Loose"; //Efficiency tool still uses old WP names... + } + + if (asg::ToolStore::contains<CP::IJetJvtEfficiency>(fjvt_tool_name)) { + m_jetfJvtTool = asg::ToolStore::get<CP::IJetJvtEfficiency>(fjvt_tool_name); + } else { + CP::JetJvtEfficiency* jetfJvtTool = new CP::JetJvtEfficiency(fjvt_tool_name); + top::check(jetfJvtTool->setProperty("WorkingPoint", fJVT_WP), + "Failed to set fJVT WP"); + top::check(jetfJvtTool->setProperty("SFFile", fJVT_SFFile), + "Failed to set fJVT SFFile name"); + top::check(jetfJvtTool->setProperty("UseMuSFFormat", true), + "Failed to set fJVT SFFile to updated mu binning"); + top::check(jetfJvtTool->setProperty("ScaleFactorDecorationName", "fJVTSF"), + "Failed to set fJVT SF decoration name"); + top::check(jetfJvtTool->setProperty("JetfJvtMomentName", "AnalysisTop_fJVTdecision"), + "Failed to set fJVT pass/fail decoration name"); + top::check(jetfJvtTool->setProperty("TruthLabel", "AnalysisTop_isHS"), + "Failed to set fJVT TruthLabel decoration name"); + top::check(jetfJvtTool->setProperty("TruthJetContainerName", m_truthJetCollForHS), + "Failed to set fJVT TruthJetContainerName decoration name"); + top::check(jetfJvtTool->initialize(), "Failed to initialize fJVT Efficiency tool"); + m_jetfJvtTool = jetfJvtTool; + } } - top::check( metMaker->initialize() , "Failed to initialize" ); - metMaker->msg().setLevel( MSG::INFO ); - m_met_maker = metMaker; + return StatusCode::SUCCESS; } - if ( asg::ToolStore::contains<IMETSystematicsTool>("met::METSystematicsTool") ) { - m_met_systematics = asg::ToolStore::get<IMETSystematicsTool>("met::METSystematicsTool"); - } else { - met::METSystematicsTool* metSyst = new met::METSystematicsTool("met::METSystematicsTool"); + StatusCode JetMETCPTools::setupMET() { + // See https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/EtmissRecommendationsRel21p2 + // METMaker tool + if (asg::ToolStore::contains<IMETMaker>("met::METMaker")) { + m_met_maker = asg::ToolStore::get<IMETMaker>("met::METMaker"); + } else { + met::METMaker* metMaker = new met::METMaker("met::METMaker"); + top::check(metMaker->setProperty("JetJvtMomentName", "AnalysisTop_JVT"), + "Failed to set METMaker JVT moment name"); - top::check( metSyst->setProperty("ConfigSoftTrkFile", "TrackSoftTerms.config"), "Failed to set property" ); + if (m_config->useParticleFlowJets()) { + top::check(metMaker->setProperty("DoPFlow", true), "Failed to set METMaker DoPFlow to true"); + } + + if (m_config->doForwardJVTinMET()) { + if (m_config->getfJVTWP() == "Medium") { + top::check(metMaker->setProperty("JetSelection", "Tenacious"), "Failed to set METMaker JetSelection to Tenacious"); + } + top::check(metMaker->setProperty("JetRejectionDec","AnalysisTop_fJVTdecision"), "Failed to set METMaker JetRejectionDec to AnalysisTop_fJVTdecision"); + top::check(metMaker->initialize(), "Failed to initialize"); + metMaker->msg().setLevel(MSG::INFO); + m_met_maker = metMaker; + } + } - // Turn off soft calo term systematics... if left on we get some warnings - top::check( metSyst->setProperty("ConfigSoftCaloFile", "" ), "Failed to set property" ); - top::check( metSyst->initialize() , "Failed to initialize" ); - m_met_systematics = metSyst; - } + // MET Systematics tool + if (asg::ToolStore::contains<IMETSystematicsTool>("met::METSystematicsTool")) { + m_met_systematics = asg::ToolStore::get<IMETSystematicsTool>("met::METSystematicsTool"); + } else { + met::METSystematicsTool* metSyst = new met::METSystematicsTool("met::METSystematicsTool"); + + std::string METconfigDir = m_config->METUncertaintiesConfigDir(); + if (METconfigDir == "Latest") METconfigDir = "METUtilities/run2_13TeV/"; //Find calib files here: /cvmfs/atlas.cern.ch/repo/sw/database/GroupData/METUtilities/ + top::check(metSyst->setProperty("ConfigPrefix", METconfigDir), "Failed to set METsyst calibration area"); //Set calib area explicitly - removes potential for crash when default area is changed in METSyst code + // TST (Track soft terms) + if (m_config->useParticleFlowJets()) { + top::check(metSyst->setProperty("ConfigSoftTrkFile", "TrackSoftTerms-pflow.config"), "Failed to set property"); + } else { + if (m_config->isAFII() && METconfigDir == "METUtilities/data17_13TeV/prerec_Jan16/") { + top::check(metSyst->setProperty("ConfigSoftTrkFile", "TrackSoftTerms_AFII.config"), "Failed to set property"); + } else { + top::check(metSyst->setProperty("ConfigSoftTrkFile", "TrackSoftTerms.config"), "Failed to set property"); + } + } + // Deactivate CST terms + top::check(metSyst->setProperty("ConfigSoftCaloFile", ""), "Failed to set property"); + top::check(metSyst->initialize(), "Failed to initialize"); + m_met_systematics = metSyst; + } + return StatusCode::SUCCESS; + } - return StatusCode::SUCCESS; -} - -ICPJetUncertaintiesTool* -JetMETCPTools::setupJetUncertaintiesTool(const std::string& name, - const std::string& jet_def, - const std::string& mc_type, - const std::string& config_file, - std::vector<std::string>* variables) { - ICPJetUncertaintiesTool* tool = nullptr; - if (asg::ToolStore::contains<ICPJetUncertaintiesTool>(name)) { - tool = asg::ToolStore::get<ICPJetUncertaintiesTool>(name); - } else { - tool = new JetUncertaintiesTool(name); - top::check(asg::setProperty(tool, "JetDefinition", jet_def), - "Failed to set JetDefinition for " + name); - top::check(asg::setProperty(tool, "MCType", mc_type), - "Failed to set MCType for " + name); - top::check(asg::setProperty(tool, "ConfigFile", config_file), - "Failed to set ConfigFile for " + name); - if (variables != nullptr){ - top::check(asg::setProperty(tool, "VariablesToShift", *variables), - "Failed to set VariablesToShift for LargeR Jes Uncertainty "+ name); + ICPJetUncertaintiesTool* + JetMETCPTools::setupJetUncertaintiesTool(const std::string& name, + const std::string& jet_def, + const std::string& mc_type, + bool isMC, + const std::string& config_file, + std::vector<std::string>* variables, + const std::string& analysis_file, + const std::string& calib_area + ) { + ICPJetUncertaintiesTool* tool = nullptr; + + if (asg::ToolStore::contains<ICPJetUncertaintiesTool>(name)) { + tool = asg::ToolStore::get<ICPJetUncertaintiesTool>(name); + } else { + tool = new JetUncertaintiesTool(name); + top::check(asg::setProperty(tool, "JetDefinition", jet_def), + "Failed to set JetDefinition for " + name); + top::check(asg::setProperty(tool, "MCType", mc_type), + "Failed to set MCType for " + name); + top::check(asg::setProperty(tool, "IsData", !isMC), + "Failed to set IsData (for JER only)"); + top::check(asg::setProperty(tool, "ConfigFile", config_file), + "Failed to set ConfigFile for " + name); + if (variables != nullptr) { + top::check(asg::setProperty(tool, "VariablesToShift", *variables), + "Failed to set VariablesToShift for LargeR Jes Uncertainty " + name); + } + if (analysis_file != "None") { + if (m_config->jetUncertainties_QGHistPatterns().size() == 0 || analysis_file == "") { // no histogram pattern to + // look for, or empty + // analysis_file argument + top::check(asg::setProperty(tool, "AnalysisFile", analysis_file), + "Failed to set AnalysisFile for " + name); + } else if (m_config->jetUncertainties_QGHistPatterns().size() == 1) { // a single pattern was specified - let's + // use it for all DSIDs + top::check(asg::setProperty(tool, "AnalysisFile", analysis_file), + "Failed to set AnalysisFile for " + name); + top::check(asg::setProperty(tool, "AnalysisHistPattern", m_config->jetUncertainties_QGHistPatterns()[0]), + "Failed to set AnalysisHistPattern for " + name); + } else { // a list of DSIDs was specified + int DSID = m_config->getDSID(); + for (auto s : m_config->jetUncertainties_QGHistPatterns()) { + if (std::atoi(s.c_str()) == DSID) { + top::check(asg::setProperty(tool, "AnalysisFile", analysis_file), + "Failed to set AnalysisFile for " + name); + top::check(asg::setProperty(tool, "AnalysisHistPattern", s), + "Failed to set AnalysisHistPattern for " + name); + break; + } + }// if the DSID is not found in the list, we don't try to use the AnalysisFile, so we get the default 50 +/- + // 50% + } + } + if (calib_area != "None") { + top::check(asg::setProperty(tool, "CalibArea", calib_area), + "Failed to set CalibArea " + calib_area); + } + top::check(tool->initialize(), "Failed to initialize " + name); } - top::check(tool->initialize(), "Failed to initialize " + name); + return tool; } - return tool; -} - -IJetSelector* JetMETCPTools::setupJetCleaningTool(const std::string& WP) { - IJetSelector* tool = nullptr; - std::string name = "JetCleaningTool" + WP; - if (asg::ToolStore::contains<IJetSelector>(name)) { - tool = asg::ToolStore::get<IJetSelector>(name); - } else { - tool = new JetCleaningTool(name); + + IJetSelector* JetMETCPTools::setupJetCleaningTool(const std::string& WP) { + IJetSelector* tool = nullptr; + + std::string name = "JetCleaningTool" + WP; + if (asg::ToolStore::contains<IJetSelector>(name)) { + tool = asg::ToolStore::get<IJetSelector>(name); + } else { + tool = new JetCleaningTool(name); top::check(asg::setProperty(tool, "CutLevel", WP), - "Failed to set CutLevel to " + WP + " for " + name); + "Failed to set CutLevel to " + WP + " for " + name); top::check(asg::setProperty(tool, "DoUgly", false), - "Failed to set DoUgly for " + name); + "Failed to set DoUgly for " + name); + top::check(asg::setProperty(tool, "UseDecorations", true), + "Failed to set UserDecorations for " + name); top::check(tool->initialize(), "Failed to initialize " + name); } - return tool; -} + return tool; + } + ECUtils::IEventCleaningTool* JetMETCPTools::setupJetEventCleaningTool(const std::string& WP, + ToolHandle<IJetSelector> JetCleaningToolHandle) + { + ECUtils::IEventCleaningTool* tool = nullptr; + std::string name = "JetEventCleaningTool" + WP; + if (asg::ToolStore::contains<ECUtils::IEventCleaningTool>(name)) { + tool = asg::ToolStore::get<ECUtils::IEventCleaningTool>(name); + } else { + tool = new ECUtils::EventCleaningTool(name); + top::check(asg::setProperty(tool, "PtCut", std::to_string(m_config->jetPtcut())), + "Failed to set jet pt cut in JetEventCleaningTool"); + top::check(asg::setProperty(tool, "EtaCut", std::to_string(m_config->jetEtacut())), + "Failed to set jet eta cut in JetEventCleaningTool"); + top::check(asg::setProperty(tool, "JvtDecorator", "passJVT"), + "Failed to set JVT property in JetEventCleaningTool"); + std::string OrDecorator = ""; + if (m_config->doLooseEvents()) OrDecorator = "ORToolDecorationLoose"; + else OrDecorator = "ORToolDecoration"; + top::check(asg::setProperty(tool, "OrDecorator", OrDecorator), + "Failed to set jet OR decoration in JetEventCleaningTool"); + top::check(asg::setProperty(tool, "CleaningLevel", WP), + "Failed to set jet WP " + WP + " in JetEventCleaningTool"); + top::check(asg::setProperty(tool, "JetCleaningTool", JetCleaningToolHandle), + "Failed to associate the JetCleaningTool object to JetEventCleaningTool"); + top::check(tool->initialize(), "Failed to initialize " + name); + } + + return tool; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopMuonCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopMuonCPTools.cxx index 6b26f420da28348a767cf97efd7723e81462c634..2f645b9c118040ee1d1ec2910d86f14a6a48e519 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopMuonCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopMuonCPTools.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration */ #include "TopCPTools/TopMuonCPTools.h" @@ -21,241 +21,291 @@ #include "MuonEfficiencyCorrections/MuonEfficiencyScaleFactors.h" namespace top { - -MuonCPTools::MuonCPTools(const std::string& name) : + MuonCPTools::MuonCPTools(const std::string& name) : asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); + declareProperty("config", m_config); - declareProperty( "MuonCalibrationAndSmearingTool" , m_muonCalibrationAndSmearingTool ); - declareProperty( "MuonSelectionTool" , m_muonSelectionTool ); - declareProperty( "MuonSelectionToolLoose" , m_muonSelectionToolLoose ); - declareProperty( "MuonSelectionToolVeryLooseVeto" , m_muonSelectionToolVeryLooseVeto ); + declareProperty("MuonCalibrationPeriodTool", m_muonCalibrationPeriodTool); - declareProperty( "MuonEfficiencyCorrectionsTool" , m_muonEfficiencyCorrectionsTool ); - declareProperty( "MuonEfficiencyCorrectionsToolLoose" , m_muonEfficiencyCorrectionsToolLoose ); - declareProperty( "MuonEfficiencyCorrectionsToolIso" , m_muonEfficiencyCorrectionsToolIso ); - declareProperty( "MuonEfficiencyCorrectionsToolLooseIso" , m_muonEfficiencyCorrectionsToolLooseIso ); -} + declareProperty("MuonSelectionTool", m_muonSelectionTool); + declareProperty("MuonSelectionToolLoose", m_muonSelectionToolLoose); + declareProperty("MuonSelectionToolVeryLooseVeto", m_muonSelectionToolVeryLooseVeto); -StatusCode MuonCPTools::initialize() { - ATH_MSG_INFO("top::MuonCPTools initialize..."); + declareProperty("MuonEfficiencyCorrectionsTool", m_muonEfficiencyCorrectionsTool); + declareProperty("MuonEfficiencyCorrectionsToolLoose", m_muonEfficiencyCorrectionsToolLoose); + declareProperty("MuonEfficiencyCorrectionsToolIso", m_muonEfficiencyCorrectionsToolIso); + declareProperty("MuonEfficiencyCorrectionsToolLooseIso", m_muonEfficiencyCorrectionsToolLooseIso); + + declareProperty("SoftMuonSelectionTool", m_softmuonSelectionTool); + declareProperty("SoftMuonEfficiencyCorrectionsTool", m_softmuonEfficiencyCorrectionsTool); - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::MuonCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; } - if (!m_config->useMuons()) { - ATH_MSG_INFO("top::MuonCPTools: no need to initialise anything since not using muons"); + StatusCode MuonCPTools::initialize() { + ATH_MSG_INFO("top::MuonCPTools initialize..."); + + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::MuonCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; + } + + if (!m_config->useMuons() && !m_config->useSoftMuons()) { + ATH_MSG_INFO("top::MuonCPTools: no need to initialise anything since not using muons"); + return StatusCode::SUCCESS; + } + + if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs + top::check(setupCalibration(), "Failed to setup Muon calibration tools"); + } + if (m_config->isMC()) {// scale-factors are only for MC + top::check(setupScaleFactors(), "Failed to setup Muon scale-factor tools"); + } return StatusCode::SUCCESS; } - if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs - top::check(setupCalibration(), "Failed to setup Muon calibration tools"); - } - if (m_config->isMC()) {// scale-factors are only for MC - top::check(setupScaleFactors(), "Failed to setup Muon scale-factor tools"); - } - return StatusCode::SUCCESS; -} - -StatusCode MuonCPTools::setupCalibration() { - ///-- Calibration and smearing --/// - using IMuCalibSmearTool = CP::IMuonCalibrationAndSmearingTool; - const std::string mu_calib_smearing_name = "CP::MuonCalibrationAndSmearingTool"; - if (asg::ToolStore::contains<IMuCalibSmearTool>(mu_calib_smearing_name)) { - m_muonCalibrationAndSmearingTool - = asg::ToolStore::get<IMuCalibSmearTool>(mu_calib_smearing_name); - } else { - IMuCalibSmearTool* muonCalibrationAndSmearingTool - = new CP::MuonCalibrationAndSmearingTool(mu_calib_smearing_name); - top::check(muonCalibrationAndSmearingTool->initialize(), - "Failed to initialize " + mu_calib_smearing_name); - m_muonCalibrationAndSmearingTool = muonCalibrationAndSmearingTool; - } + StatusCode MuonCPTools::setupCalibration() { + ///-- Selection --/// + m_muonSelectionTool = setupMuonSelectionTool("CP::MuonSelectionTool", + m_config->muonQuality(), + m_config->muonEtacut(), + m_config->muonUseMVALowPt(), + m_config->muonUse2stationMuonsHighPt()); + m_muonSelectionToolLoose = setupMuonSelectionTool("CP::MuonSelectionToolLoose", + m_config->muonQualityLoose(), + m_config->muonEtacut(), + m_config->muonUseMVALowPtLoose(), + m_config->muonUse2stationMuonsHighPtLoose()); + // the following is needed to make sure all muons for which d0sig is calculated are at least Loose + m_muonSelectionToolVeryLooseVeto = setupMuonSelectionTool("CP::MuonSelectionToolVeryLooseVeto", + "Loose", + 2.5, + m_config->muonUseMVALowPt(), + m_config->muonUse2stationMuonsHighPt()); + ///-- Calibration and smearing --/// ---> now passing the flags (true/false) to CalibAndSmearingTool + m_muonCalibrationPeriodTool = setupMuonCalibrationAndSmearingTool("CP::MuonCalibrationPeriodTool", + m_config->muonMuonDoExtraSmearingHighPt(), + m_config->muonMuonDoSmearing2stationHighPt()); + //now the soft muon part + if (m_config->useSoftMuons()) { + m_softmuonSelectionTool = setupMuonSelectionTool("CP::SoftMuonSelectionTool", + m_config->softmuonQuality(), + m_config->softmuonEtacut(), + m_config->softmuonUseMVALowPt(), + false); + } - ///-- Selection --/// - m_muonSelectionTool = setupMuonSelectionTool("CP::MuonSelectionTool", - m_config->muonQuality(), - m_config->muonEtacut()); - m_muonSelectionToolLoose = setupMuonSelectionTool("CP::MuonSelectionToolLoose", - m_config->muonQualityLoose(), - m_config->muonEtacut()); - // the following is needed to make sure all muons for which d0sig is calculated are at least Loose - m_muonSelectionToolVeryLooseVeto = setupMuonSelectionTool("CP::MuonSelectionToolVeryLooseVeto", - "Loose", - 2.5); - return StatusCode::SUCCESS; -} - -StatusCode MuonCPTools::setupScaleFactors() { - // Setup muon SF tools - // However if we are running on data- we don't need these, - // so carry on. - if (!m_config->isMC()) return StatusCode::SUCCESS; - /************************************************************ + } + + StatusCode MuonCPTools::setupScaleFactors() { + // Setup muon SF tools + // However if we are running on data- we don't need these, + // so carry on. + if (!m_config->isMC()) return StatusCode::SUCCESS; + + /************************************************************ * * Muon Scale Factors: * muonSF = trigSF*effSF*isoSF*TTVASF * ************************************************************/ - // Muon SF tools now require you to have setup an instance of - // the pileup reweighting tool! - // If we haven't set it up then tell the user this and exit. - if (!m_config->doPileupReweighting()) { - ATH_MSG_ERROR("\nThe Muon SF tools now require that you have" - " previously setup an instance of " - "the pileup reweighting tool.\n\n" - "To do this set the options:\n\n\t" - "PRWLumiCalcFiles\n and \n\tPRWConfigFiles \n\n" - "in your config file."); - return StatusCode::FAILURE; - } - - /************************************************************ + // Muon SF tools now require you to have setup an instance of + // the pileup reweighting tool! + // If we haven't set it up then tell the user this and exit. + if (!m_config->doPileupReweighting()) { + ATH_MSG_ERROR("\nThe Muon SF tools now require that you have" + " previously setup an instance of " + "the pileup reweighting tool.\n\n" + "To do this set the options:\n\n\t" + "PRWLumiCalcFiles\n and \n\tPRWConfigFiles \n\n" + "in your config file."); + return StatusCode::FAILURE; + } + + /************************************************************ * Trigger Scale Factors: * setup trigger SFs for nominal and 'loose' muon WPs * recommendation for EOYE not to pass any isolation to tool * as SFs very similar for all WPs. - ************************************************************/ - - m_muonTriggerScaleFactors_2015 - = setupMuonTrigSFTool("CP::MuonTriggerScaleFactors_2015", - m_config->muonQuality(), "2015"); - m_muonTriggerScaleFactorsLoose_2015 - = setupMuonTrigSFTool("CP::MuonTriggerScaleFactorsLoose_2015", - m_config->muonQualityLoose(), "2015"); - m_muonTriggerScaleFactors_2016 - = setupMuonTrigSFTool("CP::MuonTriggerScaleFactors_2016", - m_config->muonQuality(), "2016"); - m_muonTriggerScaleFactorsLoose_2016 - = setupMuonTrigSFTool("CP::MuonTriggerScaleFactorsLoose_2016", - m_config->muonQualityLoose(), "2016"); - - - /************************************************************ + ************************************************************/ + + // In R21 now, we only need one instance of the tool + // and do not need to set the year as it is handled + // internally with PRW tool + m_muonTriggerScaleFactors_R21 + = setupMuonTrigSFTool("CP::MuonTriggerScaleFactors_R21", + m_config->muonQuality()); + m_muonTriggerScaleFactorsLoose_R21 + = setupMuonTrigSFTool("CP::MuonTriggerScaleFactorsLoose_R21", + m_config->muonQualityLoose()); + + /************************************************************ * Efficiency Scale Factors: - * setup muon efficiency SFs for the nominal and + * setup muon efficiency SFs for the nominal and * 'loose' muon WPs. - ************************************************************/ - m_muonEfficiencyCorrectionsTool - = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsTool", - m_config->muonQuality()); - - m_muonEfficiencyCorrectionsToolLoose - = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolLoose", - m_config->muonQualityLoose()); - - /************************************************************ - * Isolation Scale Factors: - * setup muon isolation SFs for the nominal and 'loose' + ************************************************************/ + + //if !Use2stationMuonsHighPt, HighPt -> HighPt3Layers + //if UseMVALowPt, LowPt -> LowPtMVA + std::string muonQuality_name = m_config->muonQuality(); + if (m_config->muonQuality() == "HighPt" && !(m_config->muonUse2stationMuonsHighPt()) ) muonQuality_name = "HighPt3Layers"; + if (m_config->muonQuality() == "LowPt" && m_config->muonUseMVALowPt()) muonQuality_name = "LowPtMVA"; + m_muonEfficiencyCorrectionsTool + = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsTool", + muonQuality_name); + + std::string muonQualityLoose_name = m_config->muonQualityLoose(); + if (m_config->muonQualityLoose() == "HighPt" && !(m_config->muonUse2stationMuonsHighPtLoose()) ) muonQualityLoose_name = "HighPt3Layers"; + if (m_config->muonQualityLoose() == "LowPt" && m_config->muonUseMVALowPtLoose()) muonQualityLoose_name = "LowPtMVA"; + m_muonEfficiencyCorrectionsToolLoose + = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolLoose", + muonQualityLoose_name); + + //now the soft muon part + std::string softmuonQuality_name = m_config->softmuonQuality(); + if (m_config->softmuonQuality() == "LowPt" && m_config->softmuonUseMVALowPt()) softmuonQuality_name = "LowPtMVA"; + if (m_config->useSoftMuons()) { + m_softmuonEfficiencyCorrectionsTool + = setupMuonSFTool("CP::SoftMuonEfficiencyScaleFactorsTool", + softmuonQuality_name); + } + + /************************************************************ + * Isolation Scale Factors: + * setup muon isolation SFs for the nominal and 'loose' * muons * * Note: if isolation WP is None, then don't setup the tool ************************************************************/ - // If we don't want isolation then we don't need the tool - if (m_config->muonIsolation() != "None") { - // Add iso as a suffix (see above for consistency between tools :) ) - std::string muon_isolation = m_config->muonIsolation(); - muon_isolation += "Iso"; - m_muonEfficiencyCorrectionsToolIso - = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolIso", + // If we don't want isolation then we don't need the tool + if (m_config->muonIsolationSF() != "None") { + // Add iso as a suffix (see above for consistency between tools :) ) + std::string muon_isolation = m_config->muonIsolationSF() + "Iso"; + m_muonEfficiencyCorrectionsToolIso = + setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolIso", muon_isolation); - } - - // Do we have isolation on our loose muons? If not no need for the tool... - if (m_config->muonIsolationLoose() != "None") { - // Add iso as a suffix (see above for consistency between tools :) ) - // Note: now loose isolation - std::string muon_isolation = m_config->muonIsolationLoose(); - muon_isolation += "Iso"; - m_muonEfficiencyCorrectionsToolLooseIso = - setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolLooseIso", - muon_isolation); - } + } + + // Do we have isolation on our loose muons? If not no need for the tool... + if (m_config->muonIsolationSFLoose() != "None") { + // Add iso as a suffix (see above for consistency between tools :) ) + std::string muon_isolation = m_config->muonIsolationSFLoose() + "Iso"; + m_muonEfficiencyCorrectionsToolLooseIso = + setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolLooseIso", + muon_isolation); + } - /************************************************************ + /************************************************************ * Muon TTVA SF: * Track-to-vertex association. This depends on whether or * not we apply the tracking groups recommended impact * parameter cuts to associate muon to vertex. ************************************************************/ - m_muonEfficiencyCorrectionsToolTTVA - = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolTTVA", - "TTVA"); - - return StatusCode::SUCCESS; -} - -CP::IMuonSelectionTool* -MuonCPTools::setupMuonSelectionTool(const std::string& name, const std::string& quality, double max_eta) { - std::map<std::string, int> muon_quality_map = { - {"Tight" , 0}, {"Medium", 1}, {"Loose", 2}, {"VeryLoose", 3}}; - int qual_int; - try { - qual_int = muon_quality_map.at(quality); - } catch (const std::out_of_range& oor_exc) { - ATH_MSG_ERROR("\n Invalid muon quality (" - + quality + ") for " + name - + ". Valid options are: " - " \n\t- Tight" - " \n\t- Medium" - " \n\t- Loose" - " \n\t- VeryLoose"); - throw; // Re-throw + m_muonEfficiencyCorrectionsToolTTVA + = setupMuonSFTool("CP::MuonEfficiencyScaleFactorsToolTTVA", + "TTVA"); + + // WARNING - The PromptLeptonIsolation scale factors are only derived with respect to the loose PID + // - Hence we need to fail if this has occured + if ((m_config->muonQuality() != "Loose" && m_config->muonIsolationSF() == "PromptLepton") + || (m_config->muonQualityLoose() != "Loose" && m_config->muonIsolationSFLoose() == "PromptLepton")) { + ATH_MSG_ERROR( + "Cannot use PromptLeptonIsolation on muons without using Loose quality - Scale factors are not available"); + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; } - CP::IMuonSelectionTool* tool = nullptr; - if (asg::ToolStore::contains<CP::IMuonSelectionTool>(name)) { - tool = asg::ToolStore::get<CP::IMuonSelectionTool>(name); - } else { - tool = new CP::MuonSelectionTool(name); - top::check(asg::setProperty(tool, "MuQuality", qual_int), - "Failed to set MuQuality for " + name); - top::check(asg::setProperty(tool, "MaxEta", max_eta), - "Failed to set MaxEta for " + name); - top::check(tool->initialize(), "Failed to initialize " + name); + CP::IMuonSelectionTool* + MuonCPTools::setupMuonSelectionTool(const std::string& name, const std::string& quality, double max_eta, const bool& useMVALowPt, const bool& use2stationMuonsHighPt) { + std::map<std::string, int> muon_quality_map = { + {"Tight", 0}, {"Medium", 1}, {"Loose", 2}, {"VeryLoose", 3}, {"HighPt", 4}, {"LowPt", 5} + }; + int qual_int; + try { + qual_int = muon_quality_map.at(quality); + } catch (const std::out_of_range& oor_exc) { + ATH_MSG_ERROR("\n Invalid muon quality (" + + quality + ") for " + name + + ". Valid options are: " + " \n\t- Tight" + " \n\t- Medium" + " \n\t- Loose" + " \n\t- VeryLoose" + " \n\t- HighPt" + " \n\t- LowPt"); + throw; // Re-throw + } + + CP::IMuonSelectionTool* tool = nullptr; + if (asg::ToolStore::contains<CP::IMuonSelectionTool>(name)) { + tool = asg::ToolStore::get<CP::IMuonSelectionTool>(name); + } else { + tool = new CP::MuonSelectionTool(name); + top::check(asg::setProperty(tool, "MuQuality", qual_int), + "Failed to set MuQuality for " + name); + top::check(asg::setProperty(tool, "MaxEta", max_eta), + "Failed to set MaxEta for " + name); + top::check(asg::setProperty(tool, "UseMVALowPt", useMVALowPt), + "Failed to set UseMVALowPt for " + name + " tool"); + top::check(asg::setProperty(tool, "Use2stationMuonsHighPt", use2stationMuonsHighPt), + "Failed to set Use2stationMuonsHighPt for " + name + " tool"); + top::check(tool->initialize(), "Failed to initialize " + name); + } + return tool; } - return tool; -} - - -CP::IMuonTriggerScaleFactors* -MuonCPTools::setupMuonTrigSFTool(const std::string& name, const std::string& quality, const std::string& year) { - CP::IMuonTriggerScaleFactors* tool = nullptr; - if (asg::ToolStore::contains<CP::IMuonTriggerScaleFactors>(name)) { - tool = asg::ToolStore::get<CP::IMuonTriggerScaleFactors>(name); - } else { - tool = new CP::MuonTriggerScaleFactors(name); - top::check(asg::setProperty(tool, "MuonQuality", quality), - "Failed to set MuonQuality for " + name); - top::check(asg::setProperty(tool, "Year", year), - "Failed to set Year for " + name); - std::string MC_version = "mc15c"; - top::check(asg::setProperty(tool, "MC", MC_version), - "Failed to set MC for " + name); - top::check(tool->initialize(), "Failed to init. " + name); + + CP::IMuonTriggerScaleFactors* + MuonCPTools::setupMuonTrigSFTool(const std::string& name, const std::string& quality) { + CP::IMuonTriggerScaleFactors* tool = nullptr; + if (asg::ToolStore::contains<CP::IMuonTriggerScaleFactors>(name)) { + tool = asg::ToolStore::get<CP::IMuonTriggerScaleFactors>(name); + } else { + tool = new CP::MuonTriggerScaleFactors(name); + top::check(asg::setProperty(tool, "MuonQuality", quality), + "Failed to set MuonQuality for " + name); + top::check(asg::setProperty(tool, "AllowZeroSF", true), + "Failed to set AllowZeroSF for " + name); + top::check(tool->initialize(), "Failed to init. " + name); + } + return tool; } - return tool; -} - - -CP::IMuonEfficiencyScaleFactors* -MuonCPTools::setupMuonSFTool(const std::string& name, const std::string& WP) { - CP::IMuonEfficiencyScaleFactors* tool = nullptr; - if (asg::ToolStore::contains<CP::IMuonEfficiencyScaleFactors>(name)) { - tool = asg::ToolStore::get<CP::MuonEfficiencyScaleFactors>(name); - } else { - tool = new CP::MuonEfficiencyScaleFactors(name); - top::check(asg::setProperty(tool, "WorkingPoint", WP), - "Failed to set WP for " + name + " tool"); - top::check(tool->initialize(), - "Failed to set initialize " + name); + + CP::IMuonEfficiencyScaleFactors* + MuonCPTools::setupMuonSFTool(const std::string& name, const std::string& WP) { + CP::IMuonEfficiencyScaleFactors* tool = nullptr; + if (asg::ToolStore::contains<CP::IMuonEfficiencyScaleFactors>(name)) { + tool = asg::ToolStore::get<CP::MuonEfficiencyScaleFactors>(name); + } else { + tool = new CP::MuonEfficiencyScaleFactors(name); + top::check(asg::setProperty(tool, "WorkingPoint", WP), + "Failed to set WP for " + name + " tool"); + top::check(asg::setProperty(tool, "CloseJetDRDecorator", "dRMuJet_AT_usingWeirdNameToAvoidUsingOnTheFlyCalculation"), + "Failed to set WP for " + name + " tool"); //in this way we'll only read the dR(mu,jet) from the derivation, IF the variable is there, but we'll not use on-the-fly calculation, which is tricky in AT + top::check(tool->initialize(), + "Failed to set initialize " + name); + } + return tool; } - return tool; -} + + CP::IMuonCalibrationAndSmearingTool* + MuonCPTools::setupMuonCalibrationAndSmearingTool(const std::string& name, const bool& doExtraSmearingHighPt, const bool& do2StationsHighPt) { + CP::IMuonCalibrationAndSmearingTool* tool = nullptr; + if (asg::ToolStore::contains<CP::IMuonCalibrationAndSmearingTool>(name)) { + tool = asg::ToolStore::get<CP::IMuonCalibrationAndSmearingTool>(name); + } else { + tool = new CP::MuonCalibrationPeriodTool(name); + + top::check(asg::setProperty(tool, "doExtraSmearing", doExtraSmearingHighPt), + "Failed to set doExtraSmearing for " + name + " tool"); + top::check(asg::setProperty(tool, "do2StationsHighPt", do2StationsHighPt), + "Failed to set do2StationsHighPt for " + name + " tool"); + top::check(tool->initialize(), + "Failed to set initialize " + name); + } + return tool; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOtherCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOtherCPTools.cxx index f90263bece1f467080d5a7ebb710fde72cd4a441..f207c57a6e1a4f5f5d2693e124c46e8da0fed142 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOtherCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOtherCPTools.cxx @@ -1,11 +1,12 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopOtherCPTools.h" #include <map> #include <string> +#include <cstdio> // Top includes #include "TopConfiguration/TopConfig.h" @@ -20,128 +21,202 @@ // Pileup Reweighting include(s): #include "PileupReweighting/PileupReweightingTool.h" -namespace top { +// PMG include(s): +#include "PMGTools/PMGTruthWeightTool.h" -OtherCPTools::OtherCPTools(const std::string& name) : +namespace top { + OtherCPTools::OtherCPTools(const std::string& name) : asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); - - declareProperty( "GRLTool" , m_grlTool ); -} - -StatusCode OtherCPTools::initialize() { - ATH_MSG_INFO("top::OtherCPTools initialize..."); - - if (!m_config->isMC() || m_config->PileupUseGRLTool()) - top::check(setupGRL(), "Failed to setup GRL tool"); - - if (m_config->doPileupReweighting()) - top::check(setupPileupReweighting(), "Failed to setup pile-up reweighting"); - - if (m_config->isMC()) - top::check(setupPMGTools(), "Failed to setup PMG tools"); - - return StatusCode::SUCCESS; -} - -StatusCode OtherCPTools::setupGRL() { - using IGRLTool = IGoodRunsListSelectionTool; - const std::string grl_tool_name = "GoodRunsListSelectionTool"; - if (asg::ToolStore::contains<IGRLTool>(grl_tool_name)) { - m_grlTool = asg::ToolStore::get<IGRLTool>(grl_tool_name); - } else { - if (!m_config->grlFile().size()) { - // do not configure GRL tool - std::cout << "No GRL files provided. " - "Will NOT setup GoodRunsListSelectionTool." << std::endl; - return StatusCode::SUCCESS; - } - - IGRLTool* grlTool = new GoodRunsListSelectionTool(grl_tool_name); - std::vector<std::string> names = {}; - std::string grlDir = m_config->grlDir(); - if (grlDir.size()) grlDir += "/"; - for (const std::string& grl : m_config->grlFile()) { - names.push_back(PathResolverFindCalibFile(grlDir + grl)); - } - - top::check(asg::setProperty(grlTool, "GoodRunsListVec", names), - "GRLSelector failed to set GRL"); - top::check( grlTool->initialize() , - "Failed to initialize GRLSelectionTool" ); - m_grlTool = grlTool; + declareProperty("config", m_config); + + declareProperty("GRLTool", m_grlTool); } - return StatusCode::SUCCESS; -} - -StatusCode OtherCPTools::setupPileupReweighting() { - const std::string prw_tool_name = "CP::PileupReweightingTool"; - if (asg::ToolStore::contains<CP::IPileupReweightingTool>(prw_tool_name)) { - m_pileupReweightingTool = asg::ToolStore::get<CP::IPileupReweightingTool>(prw_tool_name); - } else { - CP::IPileupReweightingTool* pileupReweightingTool - = new CP::PileupReweightingTool(prw_tool_name); - - std::vector<std::string> pileup_config = m_config->PileupConfig(); - for (std::string& s : pileup_config) - s = PathResolverFindCalibFile(s); - - // now using by default the nominal mc15c definition - the config file is appended to the list provided by the user - ATH_MSG_INFO("Now appending the default pile-up profile mc15c_v2_defaults.NotRecommended.prw.root to list of PRW config files."); - ATH_MSG_INFO("This is required because we can't provide a default channel number anymore."); - pileup_config.push_back(PathResolverFindCalibFile("dev/PileupReweighting/mc15c_v2_defaults.NotRecommended.prw.root")); - - std::vector<std::string> pileup_lumi_calc = m_config->PileupLumiCalc(); - for (std::string& s : pileup_lumi_calc) - s = PathResolverFindCalibFile(s); - - if (m_config->PileupUseGRLTool()) - top::check(asg::setProperty(pileupReweightingTool, "GRLTool", m_grlTool), - "Failed to give GRLtool to pileup reweighting tool"); - - // Config file is not needed on Data - // see "Just random run numbers and lumi corrections" - // case in twiki page below - // However, the tool would spit out warnings for Data if we didn't supply ConfigFiles. - top::check(asg::setProperty(pileupReweightingTool, "ConfigFiles", pileup_config), - "Failed to set pileup reweighting config files"); - - top::check(asg::setProperty(pileupReweightingTool, "LumiCalcFiles", pileup_lumi_calc), - "Failed to set pileup reweighting lumicalc files"); - // see [http://cern.ch/go/hx7d] - top::check(asg::setProperty(pileupReweightingTool, "DataScaleFactor", 1/1.09), - "Failed to set pileup reweighting data scale factor"); - top::check(asg::setProperty(pileupReweightingTool, "DataScaleFactorUP", 1.0), - "Failed to set pileup reweighting data scale factor up"); - top::check(asg::setProperty(pileupReweightingTool, "DataScaleFactorDOWN", 1/1.18), - "Failed to set pileup reweighting data scale factor down"); - top::check(pileupReweightingTool->initialize(), - "Failed to initialize pileup reweighting tool"); - - m_pileupReweightingTool = pileupReweightingTool; + + StatusCode OtherCPTools::initialize() { + ATH_MSG_INFO("top::OtherCPTools initialize..."); + + if (!m_config->isMC() || m_config->PileupUseGRLTool()) top::check(setupGRL(), "Failed to setup GRL tool"); + + if (m_config->doPileupReweighting()) top::check(setupPileupReweighting(), "Failed to setup pile-up reweighting"); + + if (m_config->isMC()) top::check(setupPMGTools(), "Failed to setup PMG tools"); + + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} - - -StatusCode OtherCPTools::setupPMGTools() { - // Setup any PMG tools - // Currently only a single tool for reweighting - // Sherpa 2.2 V+jets samples based on the number of truth jets - const std::string name = "PMGSherpa22VJetsWeightTool"; - PMGTools::PMGSherpa22VJetsWeightTool* tool = nullptr; - if (asg::ToolStore::contains<PMGTools::PMGSherpa22VJetsWeightTool>(name)) { - tool = asg::ToolStore::get<PMGTools::PMGSherpa22VJetsWeightTool>(name); - } else { - tool = new PMGTools::PMGSherpa22VJetsWeightTool(name); - top::check(asg::setProperty(tool, "TruthJetContainer", - m_config->sgKeyTruthJets()), - "Failed to set TruthJetContainer to " + name); - top::check(tool->initialize(), "Failed to initialize " + name); + + StatusCode OtherCPTools::setupGRL() { + using IGRLTool = IGoodRunsListSelectionTool; + const std::string grl_tool_name = "GoodRunsListSelectionTool"; + if (asg::ToolStore::contains<IGRLTool>(grl_tool_name)) { + m_grlTool = asg::ToolStore::get<IGRLTool>(grl_tool_name); + } else { + if (!m_config->grlFile().size()) { + // do not configure GRL tool + ATH_MSG_WARNING("No GRL files provided -> Will NOT setup GoodRunsListSelectionTool."); + return StatusCode::SUCCESS; + } + + IGRLTool* grlTool = new GoodRunsListSelectionTool(grl_tool_name); + std::vector<std::string> names = {}; + std::string grlDir = m_config->grlDir(); + if (grlDir.size()) grlDir += "/"; + for (const std::string& grl : m_config->grlFile()) { + names.push_back(PathResolverFindCalibFile(grlDir + grl)); + } + + top::check(asg::setProperty(grlTool, "GoodRunsListVec", names), + "GRLSelector failed to set GRL"); + top::check(grlTool->initialize(), + "Failed to initialize GRLSelectionTool"); + m_grlTool = grlTool; + } + return StatusCode::SUCCESS; + } + + StatusCode OtherCPTools::setupPileupReweighting() { + const std::string prw_tool_name = "CP::PileupReweightingTool"; + + if (asg::ToolStore::contains<CP::IPileupReweightingTool>(prw_tool_name)) { + m_pileupReweightingTool = asg::ToolStore::get<CP::IPileupReweightingTool>(prw_tool_name); + } else { + CP::IPileupReweightingTool* pileupReweightingTool + = new CP::PileupReweightingTool(prw_tool_name); + + std::vector<std::string> pileup_config = m_config->PileupConfig(); + for (std::string& s : pileup_config) + s = PathResolverFindCalibFile(s); + + std::vector<std::string> pileup_lumi_calc = m_config->PileupLumiCalc(); + for (std::string& s : pileup_lumi_calc) + s = PathResolverFindCalibFile(s); + + std::vector<std::string> pileup_config_FS = m_config->PileupConfig_FS(); + for (std::string& s : pileup_config_FS) + s = PathResolverFindCalibFile(s); + + std::vector<std::string> pileup_config_AF = m_config->PileupConfig_AF(); + for (std::string& s : pileup_config_AF) + s = PathResolverFindCalibFile(s); + + std::vector<std::string> actual_mu_FS = m_config->PileupActualMu_FS(); + for (std::string& s : actual_mu_FS) + s = PathResolverFindCalibFile(s); + + std::vector<std::string> actual_mu_AF = m_config->PileupActualMu_AF(); + for (std::string& s : actual_mu_AF) + s = PathResolverFindCalibFile(s); + + // New checks - If FS or AF size != 0, then the general option should be empty + if ((pileup_config_AF.size() > 0 || pileup_config_FS.size() > 0) && (pileup_config.size() > 0)) { + ATH_MSG_ERROR("You have used PRWConfigFiles as well as PRWConfigFiles_FS and/or PRWConfigFiles_AF"); + ATH_MSG_ERROR("We do not know how to configure with all these options"); + return StatusCode::FAILURE; + } + + if (m_config->PileupUseGRLTool()) top::check(asg::setProperty(pileupReweightingTool, "GRLTool", m_grlTool), + "Failed to give GRLtool to pileup reweighting tool"); + + // Config file is not needed on Data + // see "Just random run numbers and lumi corrections" + // case in twiki page below + // However, the tool would spit out warnings for Data if we didn't supply ConfigFiles. + if (pileup_config.size() > 0) { + ATH_MSG_INFO("PRW tool is being configured without any FS/AF information"); + top::check(asg::setProperty(pileupReweightingTool, "ConfigFiles", pileup_config), + "Failed to set pileup reweighting config files"); + } else if (m_config->isAFII() && pileup_config_AF.size() > 0) { + // concatenate the config and the actual mu files + std::vector<std::string> final_config_AF = pileup_config_AF; + final_config_AF.insert(final_config_AF.end(), actual_mu_AF.begin(), actual_mu_AF.end()); + ATH_MSG_INFO("This sample is fast sim"); + ATH_MSG_INFO("PRW tool is being configured only with fast simulation (AF) config files"); + top::check(asg::setProperty(pileupReweightingTool, "ConfigFiles", final_config_AF), + "Failed to set pileup reweighting config files"); + } else if (!m_config->isAFII() && pileup_config_FS.size() > 0) { + // concatenate the config and the actual mu files + std::vector<std::string> final_config_FS = pileup_config_FS; + final_config_FS.insert(final_config_FS.end(), actual_mu_FS.begin(), actual_mu_FS.end()); + ATH_MSG_INFO("This sample is full sim"); + ATH_MSG_INFO("PRW tool is being configured only with full simulation (FS) config files"); + top::check(asg::setProperty(pileupReweightingTool, "ConfigFiles", final_config_FS), + "Failed to set pileup reweighting config files"); + } else { + ATH_MSG_ERROR("There are not any PRW config files provided with any allowed options"); + return StatusCode::FAILURE; + } + // data scale-factors, initialised to recommended values + // can also be customised, thanks to PRWCustomScaleFactor option + double SF_nominal = 1.0 / 1.03; + double SF_up = 1.0 / 0.99; + double SF_down = 1.0 / 1.07; + + // if custom data SFs + if (m_config->PileUpCustomScaleFactors().size() != 0) { + SF_nominal = m_config->PileUpCustomScaleFactors()[0]; + SF_up = m_config->PileUpCustomScaleFactors()[1]; + SF_down = m_config->PileUpCustomScaleFactors()[2]; + ATH_MSG_INFO("Using custom Data Scale-Factors for pile-up reweighting"); + std::ostringstream oss; + oss << "Nominal:" << SF_nominal << " up:" << SF_up << " down:" << SF_down << std::endl; + ATH_MSG_INFO(oss.str()); + } + + top::check(asg::setProperty(pileupReweightingTool, "LumiCalcFiles", pileup_lumi_calc), + "Failed to set pileup reweighting lumicalc files"); + // see [http://cern.ch/go/hx7d] + top::check(asg::setProperty(pileupReweightingTool, "DataScaleFactor", static_cast<Float_t>(SF_nominal)), + "Failed to set pileup reweighting data scale factor"); + top::check(asg::setProperty(pileupReweightingTool, "DataScaleFactorUP", SF_up), + "Failed to set pileup reweighting data scale factor up"); + top::check(asg::setProperty(pileupReweightingTool, "DataScaleFactorDOWN", SF_down), + "Failed to set pileup reweighting data scale factor down"); + // Set the unrepresented data tolerence (default is 5% same as the PRW tool) + top::check(asg::setProperty(pileupReweightingTool, "UnrepresentedDataThreshold", m_config->PileupDataTolerance()), + "Failed to set pileup reweighting data tolerance"); + if (m_config->PileupPeriodAssignments().size() > 0) { + // Set the period assignments associated with different running periods + top::check(asg::setProperty(pileupReweightingTool, "PeriodAssignments", m_config->PileupPeriodAssignments()), + "Failed to set pileup reweighting period assignments"); + } + top::check(pileupReweightingTool->initialize(), + "Failed to initialize pileup reweighting tool"); + + m_pileupReweightingTool = pileupReweightingTool; + } + return StatusCode::SUCCESS; } - m_pmg_sherpa22_vjets_tool = tool; - return StatusCode::SUCCESS; -} + StatusCode OtherCPTools::setupPMGTools() { + // Setup any PMG tools + + // Sherpa 2.2 V+jets samples based on the number of truth jets + const std::string name = "PMGSherpa22VJetsWeightTool"; + + PMGTools::PMGSherpa22VJetsWeightTool* tool = nullptr; + if (asg::ToolStore::contains<PMGTools::PMGSherpa22VJetsWeightTool>(name)) { + tool = asg::ToolStore::get<PMGTools::PMGSherpa22VJetsWeightTool>(name); + } else { + tool = new PMGTools::PMGSherpa22VJetsWeightTool(name); + top::check(asg::setProperty(tool, "TruthJetContainer", + m_config->sgKeyTruthJets()), + "Failed to set TruthJetContainer to " + name); + top::check(tool->initialize(), "Failed to initialize " + name); + } + m_pmg_sherpa22_vjets_tool = tool; + + // Tool for access truth weights via names + const std::string truthWeightToolName = "PMGTruthWeightTool"; + PMGTools::PMGTruthWeightTool* truthweightTool = new PMGTools::PMGTruthWeightTool(truthWeightToolName); + if (truthweightTool->initialize()) { + m_pmg_weightTool = truthweightTool; + } else { + // delete the tool instance, it is half-initialized at best = broken + // elsewere we won't be able to retrieve a ToolHandle, which indicates to us + // that we cannot rely on it for this MC sample + delete truthweightTool; + ATH_MSG_WARNING("Failed to initialize " << truthWeightToolName << ". Any features depending on PMGTruthWeightTool will not work!"); + } + + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOverlapRemovalCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOverlapRemovalCPTools.cxx index 706e8b9021d4240adffd8d25a6eed42388b4ee3c..fdd41fb4da823faaa73d6c8d056777fca15b2017 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOverlapRemovalCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopOverlapRemovalCPTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopOverlapRemovalCPTools.h" @@ -19,169 +19,286 @@ #include "AssociationUtils/OverlapRemovalTool.h" namespace top { - -OverlapRemovalCPTools::OverlapRemovalCPTools(const std::string& name) : + OverlapRemovalCPTools::OverlapRemovalCPTools(const std::string& name) : asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); -} + declareProperty("config", m_config); + } -StatusCode OverlapRemovalCPTools::initialize() { - ATH_MSG_INFO("top::OverlapRemovalCPTools initialize..."); + StatusCode OverlapRemovalCPTools::initialize() { + ATH_MSG_INFO("top::OverlapRemovalCPTools initialize..."); - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::OverlapRemovalCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; - } + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::OverlapRemovalCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; + } - if (!m_config->makeAllCPTools()) { - ATH_MSG_INFO("top::OverlapRemovalCPTools: no need to initialise for mini-xAOD"); + if (!m_config->makeAllCPTools()) { + ATH_MSG_INFO("top::OverlapRemovalCPTools: no need to initialise for mini-xAOD"); + return StatusCode::SUCCESS; + } + + top::check(setupOverlapRemoval(), "Failed to setup Overlap Removal"); return StatusCode::SUCCESS; } - top::check(setupOverlapRemoval(), "Failed to setup Overlap Removal"); - return StatusCode::SUCCESS; -} - -StatusCode OverlapRemovalCPTools::setupOverlapRemoval() { - // Allowed overlap removal options - std::set<std::string> allowed_OR_procedures = {"recommended", "jetmuApplyRelPt", "harmonized", - "Boosted", "BoostedSlidingDREl", "BoostedSlidingDRMu", "BoostedSlidingDRElMu", "noTauJetOLR"}; - std::string OR_procedure = m_config->overlapRemovalProcedure(); - - // If the requested OR procedure is unknown then fail. - // This is mostly to avoid me writing 'harmonised' by mistake ;) - if (allowed_OR_procedures.find(OR_procedure) - == allowed_OR_procedures.end()) { - ATH_MSG_ERROR(OR_procedure << " is not a valid option.\n" - "Valid options are currently: " - "recommended [default], jetmuApplyRelPt, harmonized, " - "Boosted, BoostedSlidingDREl, BoostedSlidingDRMu, BoostedSlidingDRElMu, noTauJetOLR"); - return StatusCode::FAILURE; - } - - ATH_MSG_INFO("Overlap removal procedure = " << OR_procedure); + StatusCode OverlapRemovalCPTools::setupOverlapRemoval() { + // Allowed overlap removal options + std::set<std::string> allowed_OR_procedures = { + "recommended", "jetmuApplyRelPt", "harmonized", + "Boosted", "BoostedSlidingDREl", "BoostedSlidingDRMu", "BoostedSlidingDRElMu", "noTauJetOLR", "noPhotonMuOR", "noPhotonMuOrJetOR" + }; + std::string OR_procedure = m_config->overlapRemovalProcedure(); + + float overlapRemovalSlidingInnerDRel = m_config->overlapRemovalSlidingInnerDRel(); + float overlapRemovalSlidingInnerDRmu = m_config->overlapRemovalSlidingInnerDRmu(); + + // if this is set, turns OFF ele-jet OR completely (it's taken care of by the electronInJetSubtraction tool) + bool applyElectronInJetSubtraction = m_config->applyElectronInJetSubtraction(); + + // If the requested OR procedure is unknown then fail. + // This is mostly to avoid me writing 'harmonised' by mistake ;) + if (allowed_OR_procedures.find(OR_procedure) + == allowed_OR_procedures.end()) { + ATH_MSG_ERROR(OR_procedure << " is not a valid option.\n" + "Valid options are currently: " + "recommended [default], jetmuApplyRelPt, harmonized, " + "Boosted, BoostedSlidingDREl, BoostedSlidingDRMu, BoostedSlidingDRElMu, noTauJetOLR"); + return StatusCode::FAILURE; + } + + ATH_MSG_INFO("Overlap removal procedure = " << OR_procedure); // ORUtils::ORFlags OR_flags("OverlapRemovalTool", // "passPreORSelection"); - ORUtils::ORFlags OR_flags("OverlapRemovalTool", - "ORToolDecoration"); - - OR_flags.doElectrons = m_config->useElectrons(); - OR_flags.doMuons = m_config->useMuons(); - OR_flags.doJets = m_config->useJets(); - OR_flags.doTaus = m_config->useTaus(); - OR_flags.doPhotons = m_config->usePhotons(); - if (OR_procedure == "Boosted" || - OR_procedure == "BoostedSlidingDREl" || - OR_procedure == "BoostedSlidingDRMu" || - OR_procedure == "BoostedSlidingDRElMu") { - OR_flags.boostedLeptons = true; - } - OR_flags.doFatJets = (m_config->useLargeRJets() && m_config->doLargeJetOverlapRemoval()); - - const float floatMax = std::numeric_limits<float>::max(); - - top::check(ORUtils::recommendedTools(OR_flags, m_ORtoolBox), - "Failed to setup OR Tool box"); - if (OR_procedure == "harmonized") { - if (m_config->useMuons() && m_config->useElectrons()) - top::check(m_ORtoolBox.eleMuORT.setProperty("RemoveCaloMuons", false), - "Failed to set RemoveCaloMuons in eleMuORT"); - if (m_config->useMuons() && m_config->useJets()) { - top::check(m_ORtoolBox.muJetORT.setProperty("MuJetPtRatio", floatMax), - "Failed to set MuJetPtRatio in muJetORT"); - top::check(m_ORtoolBox.muJetORT.setProperty("MuJetTrkPtRatio", floatMax), - "Failed to set MuJetTrkPtRatio in muJetORT"); - top::check(m_ORtoolBox.muJetORT.setProperty("UseGhostAssociation", false), - "Failed to set UseGhostAssociation in muJetORT"); - top::check(m_ORtoolBox.muJetORT.setProperty("InnerDR", 0.4), - "Failed to set InnerDR in muJetORT"); + ORUtils::ORFlags OR_flags("OverlapRemovalTool", + "ORToolDecoration"); + + OR_flags.doElectrons = m_config->useElectrons(); + OR_flags.doMuons = m_config->useMuons(); + OR_flags.doJets = m_config->useJets(); + OR_flags.doTaus = m_config->useTaus(); + OR_flags.doPhotons = m_config->usePhotons(); + if (OR_procedure == "Boosted" || + OR_procedure == "BoostedSlidingDREl" || + OR_procedure == "BoostedSlidingDRMu" || + OR_procedure == "BoostedSlidingDRElMu") { + OR_flags.boostedLeptons = true; } - } - else if (OR_procedure == "jetmuApplyRelPt") { + OR_flags.doFatJets = (m_config->useLargeRJets() && m_config->doLargeJetOverlapRemoval()); + OR_flags.doMuPFJetOR = (m_config->useParticleFlowJets()); + + const float floatMax = std::numeric_limits<float>::max(); + + top::check(ORUtils::recommendedTools(OR_flags, m_ORtoolBox), + "Failed to setup OR Tool box"); + for (auto&& tool : m_ORtoolBox.getOverlapTools()) { + top::check(tool->setProperty("EnableUserPriority", true), + "Failed to set EnableUserPriority"); + } + if (OR_procedure == "harmonized") { + if (m_config->useMuons() && + m_config->useElectrons()) top::check(m_ORtoolBox.eleMuORT.setProperty("RemoveCaloMuons", false), + "Failed to set RemoveCaloMuons in eleMuORT"); + if (m_config->useMuons() && m_config->useJets()) { + top::check(m_ORtoolBox.muJetORT.setProperty("MuJetPtRatio", floatMax), + "Failed to set MuJetPtRatio in muJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("MuJetTrkPtRatio", floatMax), + "Failed to set MuJetTrkPtRatio in muJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("UseGhostAssociation", false), + "Failed to set UseGhostAssociation in muJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("InnerDR", 0.4), + "Failed to set InnerDR in muJetORT"); + } + } else if (OR_procedure == "jetmuApplyRelPt") { top::check(m_ORtoolBox.muJetORT.setProperty("ApplyRelPt", true), - "Failed to set ApplyRelPt in muJetORT"); - } - else if ( OR_procedure == "BoostedSlidingDREl" || - OR_procedure == "BoostedSlidingDRMu" || - OR_procedure == "BoostedSlidingDRElMu") { - if ( m_config->useElectrons() && m_config->useJets() && - (OR_procedure == "BoostedSlidingDREl" || OR_procedure == "BoostedSlidingDRElMu") ) { - top::check(m_ORtoolBox.eleJetORT.setProperty("UseSlidingDR", true), - "Failed to setSliding DR in ElJetORT"); - top::check(m_ORtoolBox.eleJetORT.setProperty("InnerDR", 0.0), - "Failed to setting inner radius equal to 0.0 in EleJetORT"); + "Failed to set ApplyRelPt in muJetORT"); + } else if (OR_procedure == "BoostedSlidingDREl" || + OR_procedure == "BoostedSlidingDRMu" || + OR_procedure == "BoostedSlidingDRElMu") { + if (m_config->useElectrons() && m_config->useJets() && + OR_procedure == "BoostedSlidingDREl") { + top::check(m_ORtoolBox.eleJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox.eleJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRel), + "Failed to setting inner radius equal to SlidingInnerDRel in EleJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("UseSlidingDR", false), + "Failed to setSliding DR in MuJetORT"); + } + if (m_config->useMuons() && m_config->useJets() && + OR_procedure == "BoostedSlidingDRMu") { + top::check(m_ORtoolBox.eleJetORT.setProperty("UseSlidingDR", false), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in MuJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRmu), + "Failed to setting inner radius equal to SlidingInnerDRmu in MuJetORT"); + } + if (m_config->useElectrons() && m_config->useMuons() && m_config->useJets() && + OR_procedure == "BoostedSlidingDRElMu") { + top::check(m_ORtoolBox.eleJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox.eleJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRel), + "Failed to setting inner radius equal to SlidingInnerDRel in EleJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in MuJetORT"); + top::check(m_ORtoolBox.muJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRmu), + "Failed to setting inner radius equal to SlidingInnerDRmu in MuJetORT"); + } + } else if (OR_procedure == "noTauJetOLR") { + top::check(m_ORtoolBox.tauJetORT.setProperty("DR", 0.0), + "Failed to set DR in TauJetORT to zero"); + } else if (OR_procedure == "noPhotonMuOR") { + top::check(m_ORtoolBox.phoMuORT.setProperty("DR", 0.0), + "Failed to set DR in phoMuonORT to zero"); + } else if (OR_procedure == "noPhotonMuOrJetOR") { + top::check(m_ORtoolBox.phoMuORT.setProperty("DR", 0.0), + "Failed to set DR in phoMuonORT to zero"); + top::check(m_ORtoolBox.phoJetORT.setProperty("DR", 0.0), + "Failed to set DR in phoJetORT to zero"); } - if ( m_config->useMuons() && m_config->useJets() && - (OR_procedure == "BoostedSlidingDRMu" || OR_procedure == "BoostedSlidingDRElMu") ) { - top::check(m_ORtoolBox.muJetORT.setProperty("UseSlidingDR", true), - "Failed to setSliding DR in MuJetORT"); - top::check(m_ORtoolBox.muJetORT.setProperty("InnerDR", 0.0), - "Failed to setting inner radius equal to 0.0 in MuJetORT"); + + if (applyElectronInJetSubtraction) { + top::check(m_ORtoolBox.eleJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox.eleJetORT.setProperty("InnerDR", 0), + "Failed to setting inner radius equal to SlidingInnerDRel in EleJetORT"); + top::check(m_ORtoolBox.eleJetORT.setProperty("SlidingDRC1", 0), + "Failed to set SlidingDRC1"); + top::check(m_ORtoolBox.eleJetORT.setProperty("SlidingDRC2", 0), + "Failed to set SlidingDRC2"); + top::check(m_ORtoolBox.eleJetORT.setProperty("SlidingDRMaxCone", 0), + "Failed to set SlidingDRMaxCone"); } - } - else if( OR_procedure == "noTauJetOLR"){ - top::check(m_ORtoolBox.tauJetORT.setProperty("DR", 0.0), - "Failed to set DR in TauJetORT to zero"); - } - top::check(m_ORtoolBox.initialize(), - "Failed to initialize overlap removal tools"); - m_overlapRemovalTool = std::move(m_ORtoolBox.masterTool); + + top::check(m_ORtoolBox.initialize(), + "Failed to initialize overlap removal tools"); + m_overlapRemovalTool = std::move(m_ORtoolBox.masterTool); - OR_flags.masterName = "OverlapRemovalToolLoose"; + OR_flags.masterName = "OverlapRemovalToolLoose"; // OR_flags.inputLabel = "passPreORSelectionLoose"; - OR_flags.inputLabel = "ORToolDecorationLoose"; - - top::check(ORUtils::recommendedTools(OR_flags, m_ORtoolBox_Loose), - "Failed to setup OR Tool box"); - if (OR_procedure == "harmonized") { - if (m_config->useMuons() && m_config->useElectrons()) - top::check(m_ORtoolBox_Loose.eleMuORT.setProperty("RemoveCaloMuons", - false), - "Failed to set RemoveCaloMuons in eleMuORT"); - if (m_config->useMuons() && m_config->useJets()) { - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("MuJetPtRatio", floatMax), - "Failed to set MuJetPtRatio in muJetORT"); - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("MuJetTrkPtRatio", floatMax), - "Failed to set MuJetTrkPtRatio in muJetORT"); - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("UseGhostAssociation", false), - "Failed to set UseGhostAssociation in muJetORT"); - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("InnerDR", 0.4), - "Failed to set InnerDR in muJetORT"); + OR_flags.inputLabel = "ORToolDecorationLoose"; + + top::check(ORUtils::recommendedTools(OR_flags, m_ORtoolBox_Loose), + "Failed to setup OR Tool box"); + for (auto&& tool : m_ORtoolBox_Loose.getOverlapTools()) { + top::check(tool->setProperty("EnableUserPriority", true), + "Failed to set EnableUserPriority"); } - } - else if (OR_procedure == "jetmuApplyRelPt") { - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("ApplyRelPt", false), - "Failed to set ApplyRelPt in muJetORT"); - } - else if ( OR_procedure == "BoostedSlidingDREl" || - OR_procedure == "BoostedSlidingDRMu" || - OR_procedure == "BoostedSlidingDRElMu") { - if ( m_config->useElectrons() && m_config->useJets() && - (OR_procedure == "BoostedSlidingDREl" || OR_procedure == "BoostedSlidingDRElMu") ) { + if (OR_procedure == "harmonized") { + if (m_config->useMuons() && m_config->useElectrons()) + top::check(m_ORtoolBox_Loose.eleMuORT.setProperty("RemoveCaloMuons", + false), + "Failed to set RemoveCaloMuons in eleMuORT"); + if (m_config->useMuons() && m_config->useJets()) { + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("MuJetPtRatio", floatMax), + "Failed to set MuJetPtRatio in muJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("MuJetTrkPtRatio", floatMax), + "Failed to set MuJetTrkPtRatio in muJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("UseGhostAssociation", false), + "Failed to set UseGhostAssociation in muJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("InnerDR", 0.4), + "Failed to set InnerDR in muJetORT"); + } + } else if (OR_procedure == "jetmuApplyRelPt") { + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("ApplyRelPt", false), + "Failed to set ApplyRelPt in muJetORT"); + } else if (OR_procedure == "BoostedSlidingDREl" || + OR_procedure == "BoostedSlidingDRMu" || + OR_procedure == "BoostedSlidingDRElMu") { + if (m_config->useElectrons() && m_config->useJets() && + OR_procedure == "BoostedSlidingDREl") { + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRel), + "Failed to setting inner radius equal to SlidingInnerDRel in EleJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("UseSlidingDR", false), + "Failed to setSliding DR in MuJetORT"); + } + if (m_config->useMuons() && m_config->useJets() && + OR_procedure == "BoostedSlidingDRMu") { + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("UseSlidingDR", false), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in MuJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRmu), + "Failed to setting inner radius equal to SlidingInnerDRmu in MuJetORT"); + } + if (m_config->useElectrons() && m_config->useMuons() && m_config->useJets() && + OR_procedure == "BoostedSlidingDRElMu") { + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRel), + "Failed to setting inner radius equal to SlidingInnerDRel in EleJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("UseSlidingDR", true), + "Failed to setSliding DR in MuJetORT"); + top::check(m_ORtoolBox_Loose.muJetORT.setProperty("InnerDR", overlapRemovalSlidingInnerDRmu), + "Failed to setting inner radius equal to SlidingInnerDRmu in MuJetORT"); + } + } else if (OR_procedure == "noTauJetOLR") { + top::check(m_ORtoolBox_Loose.tauJetORT.setProperty("DR", 0.0), + "Failed to set DR in TauJetORT to zero"); + } else if (OR_procedure == "noPhotonMuOR") { + top::check(m_ORtoolBox_Loose.phoMuORT.setProperty("DR", 0.0), + "Failed to set DR in phoMuonORT to zero"); + } else if (OR_procedure == "noPhotonMuOrJetOR") { + top::check(m_ORtoolBox_Loose.phoMuORT.setProperty("DR", 0.0), + "Failed to set DR in phoMuonORT to zero"); + top::check(m_ORtoolBox_Loose.phoJetORT.setProperty("DR", 0.0), + "Failed to set DR in phoJetORT to zero"); + } + + if (applyElectronInJetSubtraction) { top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("UseSlidingDR", true), - "Failed to setSliding DR in ElJetORT"); - top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("InnerDR", 0.0), - "Failed to setting inner radius equal to 0.0 in EleJetORT"); + "Failed to setSliding DR in ElJetORT"); + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("InnerDR", 0), + "Failed to setting inner radius equal to SlidingInnerDRel in EleJetORT"); + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("SlidingDRC1", 0), + "Failed to set SlidingDRC1"); + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("SlidingDRC2", 0), + "Failed to set SlidingDRC2"); + top::check(m_ORtoolBox_Loose.eleJetORT.setProperty("SlidingDRMaxCone", 0), + "Failed to set SlidingDRMaxCone"); } - if ( m_config->useMuons() && m_config->useJets() && - (OR_procedure == "BoostedSlidingDRMu" || OR_procedure == "BoostedSlidingDRElMu") ) { - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("UseSlidingDR", true), - "Failed to setSliding DR in MuJetORT"); - top::check(m_ORtoolBox_Loose.muJetORT.setProperty("InnerDR", 0.0), - "Failed to setting inner radius equal to 0.0 in MuJetORT"); + + top::check(m_ORtoolBox_Loose.initialize(), + "Failed to initialize loose overlap removal tools"); + m_overlapRemovalTool_Loose = std::move(m_ORtoolBox_Loose.masterTool); + + ATH_MSG_INFO("Setting up special OR tools for soft muons"); + ORUtils::ORFlags OR_flags_sm_PFjets("OverlapRemovalTool_softMuons_PFjets","ORToolDecoration", "AT_fail_softMuons_OR_PFjets"); + OR_flags_sm_PFjets.doElectrons = false; + OR_flags_sm_PFjets.doMuons = true; + OR_flags_sm_PFjets.doJets = false; + OR_flags_sm_PFjets.doTaus = false; + OR_flags_sm_PFjets.doPhotons = false; + OR_flags_sm_PFjets.boostedLeptons = false; + OR_flags_sm_PFjets.doFatJets = false; + OR_flags_sm_PFjets.doMuPFJetOR = true; + + top::check(ORUtils::recommendedTools(OR_flags_sm_PFjets, m_ORtoolBox_softMuons_PFjets), "Failed to setup OR Tool box for soft muons-PFjets"); + for (auto&& tool : m_ORtoolBox_softMuons_PFjets.getOverlapTools()) { + top::check(tool->setProperty("EnableUserPriority", true), "Failed to set EnableUserPriority"); } + top::check(m_ORtoolBox_softMuons_PFjets.initialize(),"Failed to initialize soft muons overlap removal tools"); + m_overlapRemovalTool_softMuons_PFjets = std::move(m_ORtoolBox_softMuons_PFjets.masterTool); + + ORUtils::ORFlags OR_flags_sm_Alljets("OverlapRemovalTool_softMuons_Alljets","ORToolDecoration", "AT_fail_softMuons_OR_Alljets"); + OR_flags_sm_Alljets.doElectrons = false; + OR_flags_sm_Alljets.doMuons = true; + OR_flags_sm_Alljets.doJets = true; + OR_flags_sm_Alljets.doTaus = false; + OR_flags_sm_Alljets.doPhotons = false; + OR_flags_sm_Alljets.boostedLeptons = false; + OR_flags_sm_Alljets.doFatJets = false; + OR_flags_sm_Alljets.doMuPFJetOR = false; + + top::check(ORUtils::recommendedTools(OR_flags_sm_Alljets, m_ORtoolBox_softMuons_Alljets), "Failed to setup OR Tool box for soft muons-Alljets"); + for (auto&& tool : m_ORtoolBox_softMuons_Alljets.getOverlapTools()) { + top::check(tool->setProperty("EnableUserPriority", true), "Failed to set EnableUserPriority"); + } + top::check(m_ORtoolBox_softMuons_Alljets.initialize(),"Failed to initialize soft muons overlap removal tools"); + m_overlapRemovalTool_softMuons_Alljets = std::move(m_ORtoolBox_softMuons_Alljets.masterTool); + + return StatusCode::SUCCESS; } - else if( OR_procedure == "noTauJetOLR"){ - top::check(m_ORtoolBox_Loose.tauJetORT.setProperty("DR", 0.0), - "Failed to set DR in TauJetORT to zero"); - } - top::check(m_ORtoolBox_Loose.initialize(), - "Failed to initialize loose overlap removal tools"); - m_overlapRemovalTool_Loose = std::move(m_ORtoolBox_Loose.masterTool); - - return StatusCode::SUCCESS; -} - } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTauCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTauCPTools.cxx index 250e78f39100483e975283f7379e97f3089dcaf9..9244882e6d08bbb9ce3e79e9993dfd5f1c2a7829 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTauCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTauCPTools.cxx @@ -1,12 +1,9 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopTauCPTools.h" -#include <map> -#include <string> - // Top includes #include "TopConfiguration/TopConfig.h" #include "TopEvent/EventTools.h" @@ -21,40 +18,45 @@ #include "TauAnalysisTools/TauTruthMatchingTool.h" #include "TauAnalysisTools/Enums.h" +// c++ includes +#include <map> +#include <memory> +#include <string> + namespace top { + TauCPTools::TauCPTools(const std::string& name) : + asg::AsgTool(name), + m_pileupReweightingTool("CP::PileupReweightingTool") { + declareProperty("config", m_config); -TauCPTools::TauCPTools(const std::string& name) : - asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); + declareProperty("TauSmearingTool", m_tauSmearingTool); + declareProperty("TauTruthMatchingTool", m_truthMatchingTool); + } - declareProperty( "TauSmearingTool" , m_tauSmearingTool ); -} + StatusCode TauCPTools::initialize() { + ATH_MSG_INFO("top::TauCPTools initialize..."); -StatusCode TauCPTools::initialize() { - ATH_MSG_INFO("top::TauCPTools initialize..."); + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::TauCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; + } - if (m_config->isTruthDxAOD()) { - ATH_MSG_INFO("top::TauCPTools: no need to initialise anything on truth DxAOD"); - return StatusCode::SUCCESS; - } + if (!m_config->useTaus()) { + ATH_MSG_INFO("top::TauCPTools: no need to initialise anything since not using taus"); + return StatusCode::SUCCESS; + } - if (!m_config->useTaus()) { - ATH_MSG_INFO("top::TauCPTools: no need to initialise anything since not using taus"); + if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs + top::check(setupCalibration(), "Failed to setup Tau calibration tools"); + } + if (m_config->isMC()) {// scale-factors are only for MC + top::check(setupScaleFactors(), "Failed to setup Tau scale-factor tools"); + } return StatusCode::SUCCESS; } - if (m_config->makeAllCPTools()) {// skiping calibrations on mini-xAODs - top::check(setupCalibration(), "Failed to setup Tau calibration tools"); - } - if (m_config->isMC()) {// scale-factors are only for MC - top::check(setupScaleFactors(), "Failed to setup Tau scale-factor tools"); - } - return StatusCode::SUCCESS; -} - -StatusCode TauCPTools::setupCalibration() { - /************************************************************ + StatusCode TauCPTools::setupCalibration() { + /************************************************************ * * Setup the tools needed for Tau Analysis * ---------------------------------------- @@ -69,233 +71,290 @@ StatusCode TauCPTools::setupCalibration() { * ************************************************************/ - //============================================================ - // Convert tau jet IDWP string to int - // see: [http://cern.ch/go/z6cq] - // Updated: using enums from TauAnalysisTools package - //============================================================ - - auto tau_JetIDWP_to_enum = [](const std::string& s) { - if (s == "None") return TauAnalysisTools::JETIDNONE; - if (s == "Loose") return TauAnalysisTools::JETIDBDTLOOSE; - if (s == "Medium") return TauAnalysisTools::JETIDBDTMEDIUM; - if (s == "Tight") return TauAnalysisTools::JETIDBDTTIGHT; - if (s == "LooseNotMedium") return TauAnalysisTools::JETIDBDTLOOSENOTMEDIUM; - if (s == "LooseNotTight") return TauAnalysisTools::JETIDBDTLOOSENOTTIGHT; - if (s == "MediumNotTight") return TauAnalysisTools::JETIDBDTMEDIUMNOTTIGHT; - if (s == "NotLoose") return TauAnalysisTools::JETIDBDTNOTLOOSE; - - // If we haven't found the correct WP, then return -1 - return TauAnalysisTools::JETIDNONEUNCONFIGURED; - }; - - // convert taujetIDWP from string to int and check it's valid - int tauJetIDWP = tau_JetIDWP_to_enum(m_config->tauJetIDWP()); - top::check(tauJetIDWP >= 0, m_config->tauJetIDWP() + " is not a valid tau WP"); - - // convert taujetIDWPLoose from string to int and check it's valid - int tauJetIDWPLoose = tau_JetIDWP_to_enum(m_config->tauJetIDWPLoose()); - top::check(tauJetIDWPLoose >= 0, m_config->tauJetIDWPLoose() + " is not a valid tau WP"); - - auto tau_EleBDTWP_to_enum = [](const std::string& s) { - if (s == "None") return TauAnalysisTools::ELEIDNONE; - if (s == "Loose") return TauAnalysisTools::ELEIDBDTLOOSE; - if (s == "Medium") return TauAnalysisTools::ELEIDBDTMEDIUM; - if (s == "Tight") return TauAnalysisTools::ELEIDBDTTIGHT; - - // If we haven't found the correct WP, then return -1 - return TauAnalysisTools::ELEIDNONEUNCONFIGURED; - }; - - // convert tauEleBDTWP from string to int and check it's valid - int tauEleBDTWP = tau_EleBDTWP_to_enum(m_config->tauEleBDTWP()); - top::check(tauEleBDTWP >= 0, m_config->tauEleBDTWP() + " is not a valid tau WP"); - - // convert tauEleBDTWPLoose from string to int and check it's valid - int tauEleBDTWPLoose = tau_EleBDTWP_to_enum(m_config->tauEleBDTWPLoose()); - top::check(tauEleBDTWPLoose >= 0, m_config->tauEleBDTWPLoose() + " is not a valid tau WP"); - - const std::vector<float> absEtaRegion = {0., 1.37, 1.37, 1.52, 1.52, 2.5}; - const double absCharge = 1.; - const std::vector<size_t> nTracks = {1,3}; - - //============================================================ - // PathResolve tau config files. If set to default then - // set to empty string. - //============================================================ - - std::string tauJetConfigFile = m_config->tauJetConfigFile(); - if (tauJetConfigFile != "Default") - tauJetConfigFile = PathResolverFindCalibFile(tauJetConfigFile); - else - tauJetConfigFile.clear(); - std::string tauJetConfigFileLoose = m_config->tauJetConfigFileLoose(); - if (tauJetConfigFileLoose != "Default") - tauJetConfigFileLoose = PathResolverFindCalibFile(tauJetConfigFileLoose); - else - tauJetConfigFileLoose.clear(); - - // bitmap in case not using the config files - //WARNING: if we add more configurable cuts, they need to be added in this list - // a priori we alway apply these cuts below - int iSelectionCuts = 0; - iSelectionCuts |= TauAnalysisTools::CutPt; - iSelectionCuts |= TauAnalysisTools::CutAbsEta; - iSelectionCuts |= TauAnalysisTools::CutAbsCharge; - iSelectionCuts |= TauAnalysisTools::CutNTrack; - iSelectionCuts |= TauAnalysisTools::CutJetIDWP; - iSelectionCuts |= TauAnalysisTools::CutEleBDTWP; - - //WARNING the CutEleOLR is special, and has to be added only in the map if needed - int iSelectionCutsLoose = iSelectionCuts; - if (m_config->tauEleOLR()) iSelectionCuts |= TauAnalysisTools::CutEleOLR; - if (m_config->tauEleOLRLoose()) iSelectionCutsLoose |= TauAnalysisTools::CutEleOLR; - - //============================================================ - // Nominal Tau Selection - //============================================================ - - - // Alias long tool names - using ITauSelTool = TauAnalysisTools::ITauSelectionTool; - using ITauEffCorrTool = TauAnalysisTools::ITauEfficiencyCorrectionsTool; - // Names of tools here for a little clarity - std::string tauSelName = "TauAnalysisTools::TauSelectionTool"; - std::string tauEffCorrName = "TauAnalysisTools::TauEfficiencyCorrectionsTool"; - - ///-- Setup the tau selection tool --/// - if (asg::ToolStore::contains<ITauSelTool>(tauSelName)) { - m_tauSelectionTool = asg::ToolStore::get<ITauSelTool>(tauSelName); - } else { - ITauSelTool* tauSelectionTool = new TauAnalysisTools::TauSelectionTool(tauSelName); - if (!tauJetConfigFile.empty()) { - top::check(asg::setProperty(tauSelectionTool, "ConfigPath",tauJetConfigFile), - "Failed to set tau selection tool configuration path"); - top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), - "Failed to set tau OutputLevel"); - } else { - // set the ConfigPath to empty value is no file was provided (otherwise it creates conflicts) - top::check(asg::setProperty(tauSelectionTool, "ConfigPath", ""), - "Failed to set tau selection tool configuration path"); - top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), - "Failed to set tau OutputLevel"); - //WARNING: if we add more configurable cuts, they need to be added in the iSelectionCuts (see above) - top::check(asg::setProperty(tauSelectionTool, "SelectionCuts", iSelectionCuts), - "Failed to set tau SelectionCuts"); - top::check(asg::setProperty(tauSelectionTool, "PtMin", static_cast<double>(m_config->tauPtcut()/1e3)), - "Failed to set tau pT cut"); - top::check(asg::setProperty(tauSelectionTool, "AbsEtaRegion", absEtaRegion), - "Failed to set tau AbsEtaRegion"); - top::check(asg::setProperty(tauSelectionTool, "AbsCharge", absCharge), - "Failed to set tau AbsCharge"); - top::check(asg::setProperty(tauSelectionTool, "NTracks", nTracks), - "Failed to set tau NTracks"); - top::check(asg::setProperty(tauSelectionTool, "JetIDWP", tauJetIDWP), - "Failed to set tau JetIDWP"); - top::check(asg::setProperty(tauSelectionTool, "EleBDTWP", tauEleBDTWP), - "Failed to set tau EleBDTWP"); - top::check(asg::setProperty(tauSelectionTool, "EleOLR", m_config->tauEleOLR()), - "Failed to set tau-electron overlap removal in tau selection tool"); - } - top::check(tauSelectionTool->initialize(), "Failed to initialize tauSelectionTool"); - m_tauSelectionTool = tauSelectionTool; + //============================================================ + // Convert tau jet IDWP string to int + // see: [http://cern.ch/go/z6cq] + // Updated: using enums from TauAnalysisTools package + //============================================================ + + auto tau_JetIDWP_to_enum = [](const std::string& s) { + if (s == "None") return TauAnalysisTools::JETIDNONE; + + if (s == "Loose") return TauAnalysisTools::JETIDBDTLOOSE; + + if (s == "Medium") return TauAnalysisTools::JETIDBDTMEDIUM; + + if (s == "Tight") return TauAnalysisTools::JETIDBDTTIGHT; + + if (s == "LooseNotMedium") return TauAnalysisTools::JETIDBDTLOOSENOTMEDIUM; + + if (s == "LooseNotTight") return TauAnalysisTools::JETIDBDTLOOSENOTTIGHT; + + if (s == "MediumNotTight") return TauAnalysisTools::JETIDBDTMEDIUMNOTTIGHT; + + if (s == "NotLoose") return TauAnalysisTools::JETIDBDTNOTLOOSE; + + if (s == "RNNLoose") return TauAnalysisTools::JETIDRNNLOOSE; + + if (s == "RNNMedium") return TauAnalysisTools::JETIDRNNMEDIUM; + + if (s == "RNNTight") return TauAnalysisTools::JETIDRNNTIGHT; + + // If we haven't found the correct WP, then return -1 + return TauAnalysisTools::JETIDNONEUNCONFIGURED; + }; + + // convert taujetIDWP from string to int and check it's valid + int tauJetIDWP = tau_JetIDWP_to_enum(m_config->tauJetIDWP()); - ///-- Setup the EfficiencyCorrectionsTool while seting up the selection tool --/// - if (asg::ToolStore::contains<ITauEffCorrTool>(tauEffCorrName)) { - m_tauEffCorrTool = asg::ToolStore::get<ITauEffCorrTool>(tauEffCorrName); + top::check(tauJetIDWP >= 0, m_config->tauJetIDWP() + " is not a valid tau WP"); + + // convert taujetIDWPLoose from string to int and check it's valid + int tauJetIDWPLoose = tau_JetIDWP_to_enum(m_config->tauJetIDWPLoose()); + top::check(tauJetIDWPLoose >= 0, m_config->tauJetIDWPLoose() + " is not a valid tau WP"); + + auto tau_EleBDTWP_to_enum = [](const std::string& s) { + if (s == "None") return TauAnalysisTools::ELEIDNONE; + + if (s == "Loose") return TauAnalysisTools::ELEIDBDTLOOSE; + + if (s == "Medium") return TauAnalysisTools::ELEIDBDTMEDIUM; + + if (s == "Tight") return TauAnalysisTools::ELEIDBDTTIGHT; + + // If we haven't found the correct WP, then return 0 + return TauAnalysisTools::ELEIDNONEUNCONFIGURED; + }; + + // convert tauEleBDTWP from string to int and check it's valid + int tauEleBDTWP = tau_EleBDTWP_to_enum(m_config->tauEleBDTWP()); + top::check(tauEleBDTWP >= 0, m_config->tauEleBDTWP() + " is not a valid tau WP"); + + // convert tauEleBDTWPLoose from string to int and check it's valid + int tauEleBDTWPLoose = tau_EleBDTWP_to_enum(m_config->tauEleBDTWPLoose()); + top::check(tauEleBDTWPLoose >= 0, m_config->tauEleBDTWPLoose() + " is not a valid tau WP"); + + const double absCharge = 1.; + const std::vector<size_t> nTracks = { + 1, 3 + }; + + //============================================================ + // PathResolve tau config files. If set to default then + // set to empty string. + //============================================================ + + std::string tauJetConfigFile = m_config->tauJetConfigFile(); + if (tauJetConfigFile != "Default") tauJetConfigFile = PathResolverFindCalibFile(tauJetConfigFile); + else tauJetConfigFile.clear(); + std::string tauJetConfigFileLoose = m_config->tauJetConfigFileLoose(); + if (tauJetConfigFileLoose != "Default") tauJetConfigFileLoose = PathResolverFindCalibFile(tauJetConfigFileLoose); + else tauJetConfigFileLoose.clear(); + + // bitmap in case not using the config files + //WARNING: if we add more configurable cuts, they need to be added in this list + // a priori we alway apply these cuts below + int iSelectionCuts = 0; + iSelectionCuts |= TauAnalysisTools::CutPt; + iSelectionCuts |= TauAnalysisTools::CutAbsEta; + iSelectionCuts |= TauAnalysisTools::CutAbsCharge; + iSelectionCuts |= TauAnalysisTools::CutNTrack; + iSelectionCuts |= TauAnalysisTools::CutJetIDWP; + iSelectionCuts |= TauAnalysisTools::CutEleBDTWP; + + //WARNING the CutEleOLR is special, and has to be added only in the map if needed + int iSelectionCutsLoose = iSelectionCuts; + if (m_config->tauEleOLR()) iSelectionCuts |= TauAnalysisTools::CutEleOLR; + if (m_config->tauEleOLRLoose()) iSelectionCutsLoose |= TauAnalysisTools::CutEleOLR; + + //add warning for special case of using EleIDBDT AND ELEOLR outdated->can just use oldBDT + + if (m_config->tauEleOLR()&& tauEleBDTWP >=2){ + ATH_MSG_WARNING("Using TauELeOLR is just usable together with the old EleBDT options" + "use OldLoose or OldMedium if you really want to use both (outdated)"); + } + if (m_config->tauEleOLRLoose() && tauEleBDTWPLoose >=2 ){ + ATH_MSG_WARNING("Using TauELeOLR is just usable together with the old EleBDT options. " + "Use OldLoose or OldMedium if you really want to use both (outdated)"); + } + + //============================================================ + // Nominal Tau Selection + //============================================================ + + + // Alias long tool names + using ITauSelTool = TauAnalysisTools::ITauSelectionTool; + using ITauEffCorrTool = TauAnalysisTools::ITauEfficiencyCorrectionsTool; + // Names of tools here for a little clarity + std::string tauSelName = "TauAnalysisTools::TauSelectionTool"; + std::string tauEffCorrName = "TauAnalysisTools::TauEfficiencyCorrectionsTool"; + + ///-- Setup the tau selection tool --/// + if (asg::ToolStore::contains<ITauSelTool>(tauSelName)) { + m_tauSelectionTool = asg::ToolStore::get<ITauSelTool>(tauSelName); } else { - ITauEffCorrTool* tauEffCorrTool - = new TauAnalysisTools::TauEfficiencyCorrectionsTool(tauEffCorrName); - top::check(asg::setProperty(tauEffCorrTool, "TauSelectionTool", m_tauSelectionTool), - "Failed to set TauSelectionTool for " + tauEffCorrName); - top::check(tauEffCorrTool->initialize() , "Failed to initialize"); - m_tauEffCorrTool = tauEffCorrTool; + std::unique_ptr<ITauSelTool> tauSelectionTool = std::make_unique<TauAnalysisTools::TauSelectionTool>(tauSelName); + if (!tauJetConfigFile.empty()) { + top::check(asg::setProperty(tauSelectionTool, "ConfigPath", tauJetConfigFile), + "Failed to set tau selection tool configuration path"); + top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), + "Failed to set tau OutputLevel"); + } else { + // set the ConfigPath to empty value is no file was provided (otherwise it creates conflicts) + top::check(asg::setProperty(tauSelectionTool, "ConfigPath", ""), + "Failed to set tau selection tool configuration path"); + top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), + "Failed to set tau OutputLevel"); + //WARNING: if we add more configurable cuts, they need to be added in the iSelectionCuts (see above) + top::check(asg::setProperty(tauSelectionTool, "SelectionCuts", iSelectionCuts), + "Failed to set tau SelectionCuts"); + top::check(asg::setProperty(tauSelectionTool, "PtMin", static_cast<double>(m_config->tauPtcut() / 1e3)), + "Failed to set tau pT cut"); + top::check(asg::setProperty(tauSelectionTool, "AbsEtaRegion", m_config->tauEtaRegions() ), + "Failed to set tau AbsEtaRegion"); + top::check(asg::setProperty(tauSelectionTool, "AbsCharge", absCharge), + "Failed to set tau AbsCharge"); + top::check(asg::setProperty(tauSelectionTool, "NTracks", nTracks), + "Failed to set tau NTracks"); + top::check(asg::setProperty(tauSelectionTool, "JetIDWP", tauJetIDWP), + "Failed to set tau JetIDWP"); + top::check(asg::setProperty(tauSelectionTool, "EleBDTWP", tauEleBDTWP), + "Failed to set tau EleBDTWP"); + top::check(asg::setProperty(tauSelectionTool, "EleOLR", m_config->tauEleOLR()), + "Failed to set tau-electron overlap removal in tau selection tool"); + } + top::check(tauSelectionTool->initialize(), "Failed to initialize tauSelectionTool"); + m_tauSelectionTool = tauSelectionTool.release(); + + ///-- Setup the EfficiencyCorrectionsTool while seting up the selection tool --/// + if (asg::ToolStore::contains<ITauEffCorrTool>(tauEffCorrName)) { + m_tauEffCorrTool = asg::ToolStore::get<ITauEffCorrTool>(tauEffCorrName); + } else { + std::unique_ptr<ITauEffCorrTool> tauEffCorrTool + = std::make_unique<TauAnalysisTools::TauEfficiencyCorrectionsTool>(tauEffCorrName); + if (m_config->isMC()) { + top::check(m_pileupReweightingTool.retrieve(), "Failed to retireve pileup reweighting tool"); + top::check(asg::setProperty(tauEffCorrTool, "PileupReweightingTool", m_pileupReweightingTool), + "Failed to set PileupReweightingTool for " + tauEffCorrName); + + top::check(asg::setProperty(tauEffCorrTool, "UseTauSubstructure", m_config->tauSubstructureSF()), + "Failed to set UseTauSubstructure for " + tauEffCorrName); + + top::check(asg::setProperty(tauEffCorrTool, "isAFII", m_config->isAFII()), + "Failed to set isAFII for " + tauEffCorrName); + } + top::check(asg::setProperty(tauEffCorrTool, "TauSelectionTool", m_tauSelectionTool), + "Failed to set TauSelectionTool for " + tauEffCorrName); + top::check(tauEffCorrTool->initialize(), "Failed to initialize"); + m_tauEffCorrTool = tauEffCorrTool.release(); + } } - } - //============================================================ - // 'Loose' Tau Selection - //============================================================ - - ///-- Names of tools here for a little clarity --/// - std::string tauSelNameLoose = "TauAnalysisTools::TauSelectionToolLoose"; - std::string tauEffCorrNameLoose = "TauAnalysisTools::TauEfficiencyCorrectionsToolLoose"; - - ///-- Setup the tau selection tool --/// - if (asg::ToolStore::contains<ITauSelTool>(tauSelNameLoose)) { - m_tauSelectionToolLoose = asg::ToolStore::get<ITauSelTool>(tauSelNameLoose); - } else { - ITauSelTool* tauSelectionTool = new TauAnalysisTools::TauSelectionTool(tauSelNameLoose); - if (!tauJetConfigFileLoose.empty()) { - top::check(asg::setProperty(tauSelectionTool, "ConfigPath",tauJetConfigFileLoose), - "Failed to set tau selection tool configuration path"); - top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), - "Failed to set tau OutputLevel"); + //============================================================ + // 'Loose' Tau Selection + //============================================================ + + ///-- Names of tools here for a little clarity --/// + std::string tauSelNameLoose = "TauAnalysisTools::TauSelectionToolLoose"; + std::string tauEffCorrNameLoose = "TauAnalysisTools::TauEfficiencyCorrectionsToolLoose"; + + ///-- Setup the tau selection tool --/// + if (asg::ToolStore::contains<ITauSelTool>(tauSelNameLoose)) { + m_tauSelectionToolLoose = asg::ToolStore::get<ITauSelTool>(tauSelNameLoose); } else { - // set the ConfigPath to empty value is no file was provided (otherwise it creates conflicts) - top::check(asg::setProperty(tauSelectionTool, "ConfigPath", ""), - "Failed to set tau selection tool configuration path"); - top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), - "Failed to set tau OutputLevel"); - //WARNING: if we add more configurable cuts, they need to be added in the iSelectionCuts (see above) - top::check(asg::setProperty(tauSelectionTool, "SelectionCuts", iSelectionCutsLoose), - "Failed to set tau SelectionCuts"); - top::check(asg::setProperty(tauSelectionTool, "PtMin", static_cast<double>(m_config->tauPtcut()/1e3)), - "Failed to set tau pT cut"); - top::check(asg::setProperty(tauSelectionTool, "AbsEtaRegion", absEtaRegion), - "Failed to set loose tau AbsEtaRegion"); - top::check(asg::setProperty(tauSelectionTool, "AbsCharge", absCharge), - "Failed to set loose tau AbsCharge"); - top::check(asg::setProperty(tauSelectionTool, "NTracks", nTracks), - "Failed to set loose tau NTracks"); - top::check(asg::setProperty(tauSelectionTool, "JetIDWP", tauJetIDWPLoose), - "Failed to set loose tau JetIDWP"); - top::check(asg::setProperty(tauSelectionTool, "EleBDTWP", tauEleBDTWPLoose), - "Failed to set loose tau EleBDTWP"); - top::check(asg::setProperty(tauSelectionTool, "EleOLR", m_config->tauEleOLRLoose()), - "Failed to set tau-electron overlap removal in loose tau selection tool"); + std::unique_ptr<ITauSelTool> tauSelectionTool = std::make_unique<TauAnalysisTools::TauSelectionTool>(tauSelNameLoose); + if (!tauJetConfigFileLoose.empty()) { + top::check(asg::setProperty(tauSelectionTool, "ConfigPath", tauJetConfigFileLoose), + "Failed to set tau selection tool configuration path"); + top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), + "Failed to set tau OutputLevel"); + } else { + // set the ConfigPath to empty value is no file was provided (otherwise it creates conflicts) + top::check(asg::setProperty(tauSelectionTool, "ConfigPath", ""), + "Failed to set tau selection tool configuration path"); + top::check(asg::setProperty(tauSelectionTool, "OutputLevel", MSG::DEBUG), + "Failed to set tau OutputLevel"); + //WARNING: if we add more configurable cuts, they need to be added in the iSelectionCuts (see above) + top::check(asg::setProperty(tauSelectionTool, "SelectionCuts", iSelectionCutsLoose), + "Failed to set tau SelectionCuts"); + top::check(asg::setProperty(tauSelectionTool, "PtMin", static_cast<double>(m_config->tauPtcut() / 1e3)), + "Failed to set tau pT cut"); + top::check(asg::setProperty(tauSelectionTool, "AbsEtaRegion", m_config->tauEtaRegions()), + "Failed to set loose tau AbsEtaRegion"); + top::check(asg::setProperty(tauSelectionTool, "AbsCharge", absCharge), + "Failed to set loose tau AbsCharge"); + top::check(asg::setProperty(tauSelectionTool, "NTracks", nTracks), + "Failed to set loose tau NTracks"); + top::check(asg::setProperty(tauSelectionTool, "JetIDWP", tauJetIDWPLoose), + "Failed to set loose tau JetIDWP"); + top::check(asg::setProperty(tauSelectionTool, "EleBDTWP", tauEleBDTWPLoose), + "Failed to set loose tau EleBDTWP"); + top::check(asg::setProperty(tauSelectionTool, "EleOLR", m_config->tauEleOLRLoose()), + "Failed to set tau-electron overlap removal in loose tau selection tool"); + } + top::check(tauSelectionTool->initialize(), "Failed to initialize tauSelectionTool"); + m_tauSelectionToolLoose = tauSelectionTool.release(); + + ///-- Setup the EfficiencyCorrectionsTool while seting up the selection tool --/// + if (asg::ToolStore::contains<ITauEffCorrTool>(tauEffCorrNameLoose)) { + m_tauEffCorrTool = asg::ToolStore::get<ITauEffCorrTool>(tauEffCorrNameLoose); + } else { + std::unique_ptr<ITauEffCorrTool> tauEffCorrTool + = std::make_unique<TauAnalysisTools::TauEfficiencyCorrectionsTool>(tauEffCorrNameLoose); + if (m_config->isMC()) { + top::check(m_pileupReweightingTool.retrieve(), "Failed to retireve pileup reweighting tool"); + top::check(asg::setProperty(tauEffCorrTool, "PileupReweightingTool", m_pileupReweightingTool), + "Failed to set PileupReweightingTool for " + tauEffCorrNameLoose); + top::check(asg::setProperty(tauEffCorrTool, "UseTauSubstructure", m_config->tauSubstructureSFLoose()), + "Failed to set UseTauSubstructure for " + tauEffCorrNameLoose); + + top::check(asg::setProperty(tauEffCorrTool, "isAFII", m_config->isAFII()), + "Failed to set isAFII for " + tauEffCorrNameLoose); + } + top::check(asg::setProperty(tauEffCorrTool, "TauSelectionTool", m_tauSelectionToolLoose), + "Failed to set TauSelectionTool for " + tauEffCorrNameLoose); + + top::check(tauEffCorrTool->initialize(), "Failed to initialize"); + m_tauEffCorrToolLoose = tauEffCorrTool.release(); + } } - top::check(tauSelectionTool->initialize(), "Failed to initialize tauSelectionTool"); - m_tauSelectionToolLoose = tauSelectionTool; - ///-- Setup the EfficiencyCorrectionsTool while seting up the selection tool --/// - if (asg::ToolStore::contains<ITauEffCorrTool>(tauEffCorrNameLoose)) { - m_tauEffCorrTool = asg::ToolStore::get<ITauEffCorrTool>(tauEffCorrNameLoose); + ///-- Calibration and smearing --/// + static const std::string tauSmearName = "TauAnalysisTools::TauSmearingTool"; + if (asg::ToolStore::contains<TauAnalysisTools::ITauSmearingTool>(tauSmearName)) { + m_tauSmearingTool = asg::ToolStore::get<TauAnalysisTools::ITauSmearingTool>(tauSmearName); } else { - ITauEffCorrTool* tauEffCorrTool - = new TauAnalysisTools::TauEfficiencyCorrectionsTool(tauEffCorrNameLoose); - top::check(asg::setProperty(tauEffCorrTool, "TauSelectionTool", m_tauSelectionToolLoose), - "Failed to set TauSelectionTool for " + tauEffCorrNameLoose); - top::check(tauEffCorrTool->initialize() , "Failed to initialize"); - m_tauEffCorrToolLoose = tauEffCorrTool; + std::unique_ptr<TauAnalysisTools::TauSmearingTool> tauSmearingTool = std::make_unique<TauAnalysisTools::TauSmearingTool>(tauSmearName); + top::check(asg::setProperty(tauSmearingTool, "isAFII", m_config->isAFII()), + "Failed to set TauSmearingTools isAFII property"); + top::check(tauSmearingTool->initialize(), "Failed to initialize"); + m_tauSmearingTool = tauSmearingTool.release(); } - } - - ///-- Calibration and smearing --/// - std::string tauSmearName = "TauAnalysisTools::TauSmearingTool"; - if (asg::ToolStore::contains<TauAnalysisTools::ITauSmearingTool>(tauSmearName)) { - m_tauSmearingTool = asg::ToolStore::get<TauAnalysisTools::ITauSmearingTool>(tauSmearName); - } else { - TauAnalysisTools::TauSmearingTool* tauSmearingTool = new TauAnalysisTools::TauSmearingTool(tauSmearName); - if (m_config->applyTauMVATES()) { - top::check(tauSmearingTool->setProperty("ApplyMVATES", true) , "Failed to enable MVA TES for tau smearing tool"); + + ///-- Truth matching --/// + static const std::string tauTruthMatchingName = "TauAnalysisTools::TauTruthMatchingTool"; + if (asg::ToolStore::contains<TauAnalysisTools::ITauTruthMatchingTool>(tauTruthMatchingName)) { + m_truthMatchingTool = asg::ToolStore::get<TauAnalysisTools::ITauTruthMatchingTool>(tauTruthMatchingName); + } else { + std::unique_ptr<TauAnalysisTools::TauTruthMatchingTool> tauMatchingTool = std::make_unique<TauAnalysisTools::TauTruthMatchingTool>(tauTruthMatchingName); + top::check(tauMatchingTool->setProperty("TruthJetContainerName", "AntiKt4TruthDressedWZJets"), "Failed to set truth collection for tau truth matching tool"); + top::check(tauMatchingTool->initialize(), "Failed to initialize"); + m_truthMatchingTool = tauMatchingTool.release(); } - top::check(tauSmearingTool->initialize() , "Failed to initialize"); - m_tauSmearingTool = tauSmearingTool; - } - return StatusCode::SUCCESS; -} -StatusCode TauCPTools::setupScaleFactors() { - /** - * - * Fill this in at some point... - * - * ...or maybe we don't need to - * - **/ - return StatusCode::SUCCESS; -} + return StatusCode::SUCCESS; + } + StatusCode TauCPTools::setupScaleFactors() { + /** + * + * Fill this in at some point... + * + * ...or maybe we don't need to + * + **/ + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopToolStore.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopToolStore.cxx index e3033990983b5e7f1361aa4c50ae8023d0518c04..00c48b5f074ebaa44208238c2de16ac55488a5a7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopToolStore.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopToolStore.cxx @@ -1,8 +1,8 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: TopToolStore.cxx 803886 2017-04-27 21:27:58Z iconnell $ +// $Id: TopToolStore.cxx 808118 2017-07-11 17:41:22Z tpelzer $ #include "TopCPTools/TopToolStore.h" #include <vector> @@ -17,126 +17,93 @@ #include "TopEvent/EventTools.h" namespace top { - -TopToolStore::TopToolStore( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr) { - declareProperty( "config" , m_config ); -} - -StatusCode TopToolStore::initialize() { - ATH_MSG_INFO("top::TopToolStore initialize..."); - - std::string release_series = ""; - const char* rel_temp = std::getenv("ROOTCORE_RELEASE_SERIES"); - if (rel_temp) { - release_series = std::string(rel_temp); - } else { - ATH_MSG_WARNING("Can not access ROOTCORE_RELEASE_SERIES"); + TopToolStore::TopToolStore(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr) { + declareProperty("config", m_config); } - ATH_MSG_INFO( "Release variable : "+release_series ); - - if (release_series == "23") { - ATH_MSG_INFO("Setting release series to 2.3"); - m_release_series = 23; - } else if (release_series == "24") { - m_release_series = 24; - ATH_MSG_INFO("Setting release series to 2.4"); - } else if (release_series == "25" ){ - m_release_series = 25; - ATH_MSG_INFO("Setting release series to 2.6"); - } else { - m_release_series = 24; - ATH_MSG_WARNING("Unknown release series, assuming 2.4"); + StatusCode TopToolStore::initialize() { + ATH_MSG_INFO("top::TopToolStore initialize..."); + + m_trigger_CP_tools = std::make_unique<top::TriggerCPTools>("top::TriggerCPTools"); + top::check(m_trigger_CP_tools->setProperty("config", m_config), + "Failed to share config with trigger CP tools"); + top::check(m_trigger_CP_tools->initialize(), + "Failed to initialize trigger tools"); + + m_other_CP_tools = std::make_unique<top::OtherCPTools>("top::OtherCPTools"); + top::check(m_other_CP_tools->setProperty("config", m_config), + "Failed to share config with other CP tools"); + top::check(m_other_CP_tools->initialize(), + "Failed to initialize other tools"); + + m_egamma_CP_tools = std::make_unique<top::EgammaCPTools>("top::EgammaCPTools"); + top::check(m_egamma_CP_tools->setProperty("config", m_config), + "Failed to share config with egamma CP tools"); + top::check(m_egamma_CP_tools->initialize(), + "Failed to initialize egamma tools"); + + m_muon_CP_tools = std::make_unique<top::MuonCPTools>("top::MuonCPTools"); + top::check(m_muon_CP_tools->setProperty("config", m_config), + "Failed to share config with muon CP tools"); + top::check(m_muon_CP_tools->initialize(), + "Failed to initialize muon tools"); + + m_tau_CP_tools = std::make_unique<top::TauCPTools>("top::TauCPTools"); + top::check(m_tau_CP_tools->setProperty("config", m_config), + "Failed to share config with tau CP tools"); + top::check(m_tau_CP_tools->initialize(), + "Failed to initialize tau tools"); + + m_flavor_tagging_CP_tools = std::make_unique<top::FlavorTaggingCPTools>("top::FlavorTaggingCPTools"); + top::check(m_flavor_tagging_CP_tools->setProperty("config", m_config), + "Failed to share config with flavour tagging CP tools"); + top::check(m_flavor_tagging_CP_tools->initialize(), + "Failed to initialize flavor tagging tools"); + + m_boosted_tagging_CP_tools = std::make_unique<top::BoostedTaggingCPTools>("top::BoostedTaggingCPTools"); + top::check(m_boosted_tagging_CP_tools->setProperty("config", m_config), + "Failed to share config with flavour tagging CP tools"); + top::check(m_boosted_tagging_CP_tools->initialize(), + "Failed to initialize boosted tagging tools"); + + m_jetMET_CP_tools = std::make_unique<top::JetMETCPTools>("top::JetMETCPTools"); + top::check(m_jetMET_CP_tools->setProperty("config", m_config), + "Failed to share config with Jet/MET CP tools"); + top::check(m_jetMET_CP_tools->initialize(), + "Failed to initialize Jet/MET tools"); + + m_isolation_CP_tools = std::make_unique<top::IsolationCPTools>("top::IsolationCPTools"); + top::check(m_isolation_CP_tools->setProperty("config", m_config), + "Failed to share config with isolation CP tools"); + top::check(m_isolation_CP_tools->initialize(), + "Failed to initialize isolation tools"); + + m_OR_CP_tools = std::make_unique<top::OverlapRemovalCPTools>("top::OverlapRemovalCPTools"); + top::check(m_OR_CP_tools->setProperty("config", m_config), + "Failed to share config with overlap removal CP tools"); + top::check(m_OR_CP_tools->initialize(), + "Failed to initialize overlap removal tools"); + + m_ghost_track_CP_tools = std::make_unique<top::GhostTrackCPTools>("top::GhostTrackCPTools"); + top::check(m_ghost_track_CP_tools->setProperty("config", m_config), + "Failed to share config with ghost track CP tools"); + top::check(m_ghost_track_CP_tools->initialize(), + "Failed to initialize ghost track tools"); + + m_track_CP_tools = std::make_unique<top::TrackCPTools>("top::TrackCPTools"); + top::check(m_track_CP_tools->setProperty("config", m_config), + "Failed to share config with track CP tools"); + top::check(m_track_CP_tools->initialize(), + "Failed to initialize track tools"); + + + return StatusCode::SUCCESS; } - m_trigger_CP_tools = std::make_unique<top::TriggerCPTools>("top::TriggerCPTools"); - top::check(m_trigger_CP_tools->setProperty("config", m_config), - "Failed to share config with trigger CP tools"); - top::check(m_trigger_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with trigger CP tools"); - top::check(m_trigger_CP_tools->initialize(), - "Failed to initialize trigger tools"); - - m_other_CP_tools = std::make_unique<top::OtherCPTools>("top::OtherCPTools"); - top::check(m_other_CP_tools->setProperty("config", m_config), - "Failed to share config with other CP tools"); - top::check(m_other_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with other CP tools"); - top::check(m_other_CP_tools->initialize(), - "Failed to initialize other tools"); - - m_egamma_CP_tools = std::make_unique<top::EgammaCPTools>("top::EgammaCPTools"); - top::check(m_egamma_CP_tools->setProperty("config", m_config), - "Failed to share config with egamma CP tools"); - top::check(m_egamma_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with egamma CP tools"); - top::check(m_egamma_CP_tools->initialize(), - "Failed to initialize egamma tools"); - - m_muon_CP_tools = std::make_unique<top::MuonCPTools>("top::MuonCPTools"); - top::check(m_muon_CP_tools->setProperty("config", m_config), - "Failed to share config with muon CP tools"); - top::check(m_muon_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with muon CP tools"); - top::check(m_muon_CP_tools->initialize(), - "Failed to initialize muon tools"); - - m_tau_CP_tools = std::make_unique<top::TauCPTools>("top::TauCPTools"); - top::check(m_tau_CP_tools->setProperty("config", m_config), - "Failed to share config with tau CP tools"); - top::check(m_tau_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with tau CP tools"); - top::check(m_tau_CP_tools->initialize(), - "Failed to initialize tau tools"); - - m_flavor_tagging_CP_tools = std::make_unique<top::FlavorTaggingCPTools>("top::FlavorTaggingCPTools"); - top::check(m_flavor_tagging_CP_tools->setProperty("config", m_config), - "Failed to share config with flavour tagging CP tools"); - top::check(m_flavor_tagging_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with flavour tagging CP tools"); - top::check(m_flavor_tagging_CP_tools->initialize(), - "Failed to initialize flavor tagging tools"); - - m_jetMET_CP_tools = std::make_unique<top::JetMETCPTools>("top::JetMETCPTools"); - top::check(m_jetMET_CP_tools->setProperty("config", m_config), - "Failed to share config with Jet/MET CP tools"); - top::check(m_jetMET_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with Jet/MET CP tools"); - top::check(m_jetMET_CP_tools->initialize(), - "Failed to initialize Jet/MET tools"); - - m_isolation_CP_tools = std::make_unique<top::IsolationCPTools>("top::IsolationCPTools"); - top::check(m_isolation_CP_tools->setProperty("config", m_config), - "Failed to share config with isolation CP tools"); - top::check(m_isolation_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with isolation CP tools"); - top::check(m_isolation_CP_tools->initialize(), - "Failed to initialize isolation tools"); - - m_OR_CP_tools = std::make_unique<top::OverlapRemovalCPTools>("top::OverlapRemovalCPTools"); - top::check(m_OR_CP_tools->setProperty("config", m_config), - "Failed to share config with overlap removal CP tools"); - top::check(m_OR_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with overlap removal CP tools"); - top::check(m_OR_CP_tools->initialize(), - "Failed to initialize overlap removal tools"); - - m_ghost_track_CP_tools = std::make_unique<top::GhostTrackCPTools>("top::GhostTrackCPTools"); - top::check(m_ghost_track_CP_tools->setProperty("config", m_config), - "Failed to share config with ghost track CP tools"); - top::check(m_ghost_track_CP_tools->setProperty("release_series", m_release_series), - "Failed to release_series series with ghost track CP tools"); - top::check(m_ghost_track_CP_tools->initialize(), - "Failed to initialize ghost track tools"); - - return StatusCode::SUCCESS; -} - -StatusCode TopToolStore::finalize() { - ATH_MSG_INFO("top::TopToolStore finalize"); - return StatusCode::SUCCESS; -} - + StatusCode TopToolStore::finalize() { + ATH_MSG_INFO("top::TopToolStore finalize"); + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTrackCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTrackCPTools.cxx new file mode 100644 index 0000000000000000000000000000000000000000..7c9ac0a4ffb83f1ffe6ec32dd0526be02636f387 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTrackCPTools.cxx @@ -0,0 +1,177 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopCPTools/TopTrackCPTools.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" + +#include <map> +#include <string> +#include <utility> + +// Top includes +#include "TopConfiguration/TopConfig.h" +#include "TopEvent/EventTools.h" + +// PathResolver include(s): +#include "PathResolver/PathResolver.h" + + +namespace top { + TrackCPTools::TrackCPTools(const std::string& name) : + asg::AsgTool(name) { + declareProperty("config", m_config); + declareProperty("TrkSelTool", m_trkseltool); + } + + StatusCode TrackCPTools::initialize() { + ATH_MSG_INFO("top::TrackCPTools initialize..."); + + if (m_config->isTruthDxAOD()) { + ATH_MSG_INFO("top::TrackCPTools: no need to initialise anything on truth DxAOD"); + return StatusCode::SUCCESS; + } + + if (!m_config->useTracks()) { + ATH_MSG_INFO( + "top::TrackCPTools: no need to initialise anything since not using tracks"); + return StatusCode::SUCCESS; + } + + if (!m_config->makeAllCPTools()) { + ATH_MSG_INFO("top::TrackCPTools: no need to initialise for mini-xAOD"); + return StatusCode::SUCCESS; + } + + // This defines the run period (ranges) that are used by the + // InDet::InDetTrackBiasingTool. The following inputs are possible: + // - No / empty input: Use the maximum range, that is [0; + // UInt32_t::max) as allowed run number value range. Initialise + // the tool with run number 0 (which will use 2015 precriptions). + // - A single run number: Configure the tool with this run number + // and to not apply checks / selection on the random run number of + // the actual events. + // - At least two values: Use this to define adjacent ranges, each + // of which is processed using a unique instance of the tool which + // was initialised using the lower bound of the range. From an + // input of size n, n-1 ranges are formed. The i-th element is the + // lower bound (incl) of the i-th range; the (i+1)-th element is + // the upper bound (excl) of the i-th range. + + m_runPeriods = { + 276262, 297730, 300909, 311482, 334738, 341650, 364486 + }; + + m_config->runPeriodTrack(m_runPeriods); + + top::check(setupSmearingTool(), "Failed to setup track smearing tools"); + top::check(setupBiasingTools(), "Failed to setup track biasing tools"); + top::check(setupTruthFilterTool(), "Failed to setup truth filter tools"); + + if(m_trkseltool.empty()) { + InDet::InDetTrackSelectionTool *selTool = new InDet::InDetTrackSelectionTool( "TrkSelTool" , m_config->trackQuality()); + top::check(selTool -> initialize(), "Failed to initialize InDetTrackSelectionTool"); + m_trkseltool = ToolHandle<InDet::IInDetTrackSelectionTool>(selTool); + } + top::check(m_trkseltool.retrieve(), "Failed to retrieve InDetTrackSelectionTool"); + + return StatusCode::SUCCESS; + } + + StatusCode TrackCPTools::setupSmearingTool() { + if (asg::ToolStore::contains<InDet::InDetTrackSmearingTool>(m_smearingToolName)) { + m_smearingTool = asg::ToolStore::get<InDet::InDetTrackSmearingTool>(m_smearingToolName); + } else { + auto tool = new InDet::InDetTrackSmearingTool(m_smearingToolName); + top::check(tool->initialize(), "Failure to initialize InDetTrackSmearingTool"); + m_smearingTool = tool; + ATH_MSG_INFO(" Creating smearing tool " + m_smearingToolName); + } + return StatusCode::SUCCESS; + } + + StatusCode TrackCPTools::setupBiasingTools() { + top::check(not m_runPeriods.empty(), "Assertion failed"); + + // Two cases are possible: + // - Either a single run number was specified to the runPeriods + // parameter in which case we'll use exactly that run number, or + // - at least two numbers have been specified, which then define + // (potentially multiple) run number ranges. + + if (m_runPeriods.size() == 1) { + m_runPeriods.resize(1); + + const std::string biasToolName { + m_biasToolPrefix + "_" + std::to_string(m_runPeriods[0]) + }; + + if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)) { + m_biasingTool[0] = asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + } else { + auto tool = new InDet::InDetTrackBiasingTool(biasToolName); + top::check(tool->setProperty("runNumber", m_runPeriods[0]), + "Failure to setProperty runNumber of InDetTrackBiasingTool " + biasToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackBiasingTool " + biasToolName); + m_biasingTool[0] = tool; + } + ATH_MSG_INFO(" Creating biasing tool to calibrate for run#=" << m_runPeriods[0] << ": " + biasToolName); + } else { + m_biasingTool.resize(m_runPeriods.size() - 1); + for (std::size_t i = 0; i < m_runPeriods.size() - 1; ++i) { + const std::string biasToolName { + m_biasToolPrefix + + "_" + std::to_string(m_runPeriods[i]) + + "_" + std::to_string(m_runPeriods[i + 1]) + }; + ATH_MSG_INFO( + " Creating biasing tool to calibrate for period [" << m_runPeriods[i] << ", " << m_runPeriods[i + 1] << "): " << + biasToolName); + if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)) { + m_biasingTool[i] = + asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + } else { + auto tool = new InDet::InDetTrackBiasingTool(biasToolName); + top::check(tool->setProperty("runNumber", m_runPeriods[i]), + "Failure to setProperty runNumber of InDetTrackBiasingTool " + biasToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackBiasingTool " + biasToolName); + m_biasingTool[i] = tool; + } + } + } + return StatusCode::SUCCESS; + } + + StatusCode TrackCPTools::setupTruthFilterTool() { + + // for track reconstruction efficiency uncertainties and fake rate uncertainties + + if (asg::ToolStore::contains<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName)) { + m_truthOriginTool = asg::ToolStore::get<InDet::InDetTrackTruthOriginTool>(m_truthOriginToolName); + } else { + auto tool = new InDet::InDetTrackTruthOriginTool(m_truthOriginToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackTruthOriginTool " + m_truthOriginToolName); + m_truthOriginTool = tool; + ATH_MSG_INFO(" Creating truth origin tool " + m_truthOriginToolName); + } + + if (asg::ToolStore::contains<InDet::InDetTrackTruthFilterTool>(m_truthFilterToolName)) { + m_truthFilterTool = asg::ToolStore::get<InDet::InDetTrackTruthFilterTool>(m_truthFilterToolName); + } else { + auto tool = new InDet::InDetTrackTruthFilterTool(m_truthFilterToolName); + top::check(tool->setProperty("trackOriginTool", + ToolHandle<InDet::IInDetTrackTruthOriginTool>{&(*m_truthOriginTool)}), + "Failed to setProperty trackOriginTool of InDetTrackTruthFilterTool " + m_truthFilterToolName); + top::check(tool->initialize(), + "Failure to initialize InDetTrackTruthFilterTool " + m_truthFilterToolName); + m_truthFilterTool = tool; + ATH_MSG_INFO(" Creating truth filter tool " + m_truthFilterToolName); + } + return StatusCode::SUCCESS; + } + + +} // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTriggerCPTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTriggerCPTools.cxx index 5028e3e0a21ca508d69f0f135d3e3076fa1a1100..590a07ae27370d6cd2ceaff76242cf3c7704191b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTriggerCPTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/Root/TopTriggerCPTools.cxx @@ -1,11 +1,14 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopCPTools/TopTriggerCPTools.h" #include <map> +#include <set> #include <string> +#include <vector> +#include <unordered_map> // Top includes #include "TopConfiguration/TopConfig.h" @@ -17,85 +20,405 @@ // Trigger include(s): #include "TrigConfxAOD/xAODConfigTool.h" #include "TriggerMatchingTool/MatchingTool.h" +#include "TriggerMatchingTool/MatchFromCompositeTool.h" #include "TrigTauMatching/TrigTauMatching.h" +//#include "TrigGlobalEfficiencyCorrection/TrigGlobalEfficiencyCorrectionTool.h" +//#include "TrigGlobalEfficiencyCorrection/ImportData.h" +#include "EgammaAnalysisInterfaces/IAsgElectronEfficiencyCorrectionTool.h" +#include "MuonAnalysisInterfaces/IMuonTriggerScaleFactors.h" +#include "MuonEfficiencyCorrections/MuonTriggerScaleFactors.h" +#include "PATCore/PATCoreEnums.h" +#include "xAODBase/ObjectType.h" +#include <boost/algorithm/string.hpp> +#include <boost/algorithm/string/join.hpp> namespace top { - -TriggerCPTools::TriggerCPTools(const std::string& name) : + TriggerCPTools::TriggerCPTools(const std::string& name) : asg::AsgTool(name) { - declareProperty("config", m_config); - declareProperty("release_series", m_release_series ); - - declareProperty( "TrigConfigTool", m_trigConfTool ); - declareProperty( "TrigDecisionTool", m_trigDecisionTool ); - declareProperty( "TrigMatchTool", m_trigMatchTool ); -} - -StatusCode TriggerCPTools::initialize() { - ATH_MSG_INFO("top::TriggerCPTools initialize..."); - - if (m_config->makeAllCPTools()) { - if (!m_config->isTruthDxAOD()) { - ///-- The configuration tool --/// - const std::string trig_config_name = "TrigConf::xAODConfigTool"; - if ( asg::ToolStore::contains<TrigConf::ITrigConfigTool>(trig_config_name) ) { - m_trigConfTool = asg::ToolStore::get<TrigConf::ITrigConfigTool>(trig_config_name); - } else { - TrigConf::xAODConfigTool* configTool = new TrigConf::xAODConfigTool(trig_config_name); - top::check( configTool->initialize() , "Failed to initialize trigger config tool" ); - m_trigConfTool = configTool; - } + declareProperty("config", m_config); - ///-- The decision tool --/// - const std::string trig_decision_name = "Trig::TrigDecisionTool"; - if ( asg::ToolStore::contains<Trig::TrigDecisionTool>(trig_decision_name) ) { - m_trigDecisionTool = asg::ToolStore::get<Trig::TrigDecisionTool>(trig_decision_name); - } else { - Trig::TrigDecisionTool* trigDecTool = new Trig::TrigDecisionTool(trig_decision_name); - top::check( trigDecTool->setProperty("ConfigTool", m_trigConfTool ) , "Failed to setProperty" ); - top::check( trigDecTool->setProperty("TrigDecisionKey", "xTrigDecision") , "Failed to setProperty" ); - top::check( trigDecTool->initialize() , "Failed to initialize trigger decision tool" ); - m_trigDecisionTool = trigDecTool; - } + declareProperty("TrigConfigTool", m_trigConfTool); + declareProperty("TrigDecisionTool", m_trigDecisionTool); + declareProperty("TrigMatchTool", m_trigMatchTool); +// declareProperty("GlobalTriggerEffTool", m_globalTriggerEffTool); +// declareProperty("GlobalTriggerEffToolLoose", m_globalTriggerEffToolLoose); - // Trigger matching tool - const std::string trig_match_name = "Trig::MatchingTool"; - if (asg::ToolStore::contains<Trig::IMatchingTool>(trig_match_name)) { - m_trigMatchTool = asg::ToolStore::get<Trig::IMatchingTool>(trig_match_name); - } else { - Trig::MatchingTool* trigMatchTool = new Trig::MatchingTool(trig_match_name); - top::check(trigMatchTool->setProperty("TrigDecisionTool", m_trigDecisionTool), - "Failed to set trigger decision tool to trigger matching tool"); - top::check(trigMatchTool->initialize(), - "Failed to initialize trig. matching tool"); - m_trigMatchTool = trigMatchTool; - } + m_muonTool = asg::AnaToolHandle<CP::IMuonTriggerScaleFactors>("CP::MuonTriggerScaleFactors/MuonTrigEff"); + m_muonToolLoose = asg::AnaToolHandle<CP::IMuonTriggerScaleFactors>("CP::MuonTriggerScaleFactors/MuonTrigEffLoose"); + } + + StatusCode TriggerCPTools::initialize() { + ATH_MSG_INFO("top::TriggerCPTools initialize..."); - ///-- Tau matching --/// - if( m_config->useTaus() ){ - const std::string tauMatchName = "Trig::TrigTauMatchingTool"; - if ( asg::ToolStore::contains<Trig::ITrigTauMatchingTool>(tauMatchName) ) { - m_trigMatchTauTool = asg::ToolStore::get<Trig::ITrigTauMatchingTool>(tauMatchName); + if (m_config->makeAllCPTools()) { + if (!m_config->isTruthDxAOD()) { + ///-- The configuration tool --/// + const std::string trig_config_name = "TrigConf::xAODConfigTool"; + if (asg::ToolStore::contains<TrigConf::ITrigConfigTool>(trig_config_name)) { + m_trigConfTool = asg::ToolStore::get<TrigConf::ITrigConfigTool>(trig_config_name); + } else { + TrigConf::xAODConfigTool* configTool = new TrigConf::xAODConfigTool(trig_config_name); + top::check(configTool->initialize(), "Failed to initialize trigger config tool"); + m_trigConfTool = configTool; } - else { - Trig::TrigTauMatchingTool* trigMatchTauTool = new Trig::TrigTauMatchingTool(tauMatchName); - top::check( trigMatchTauTool->setProperty("TrigDecisionTool", m_trigDecisionTool), - "Failed to set trig dec tool for tau matching" ); - top::check( trigMatchTauTool->initialize(), - "Failed to initialize tau trigger matching tool" ); - m_trigMatchTauTool = trigMatchTauTool; + + ///-- The decision tool --/// + const std::string trig_decision_name = "Trig::TrigDecisionTool"; + if (asg::ToolStore::contains<Trig::TrigDecisionTool>(trig_decision_name)) { + m_trigDecisionTool = asg::ToolStore::get<Trig::TrigDecisionTool>(trig_decision_name); + } else { + Trig::TrigDecisionTool* trigDecTool = new Trig::TrigDecisionTool(trig_decision_name); + top::check(trigDecTool->setProperty("ConfigTool", m_trigConfTool), "Failed to setProperty"); + top::check(trigDecTool->setProperty("TrigDecisionKey", "xTrigDecision"), "Failed to setProperty"); + top::check(trigDecTool->initialize(), "Failed to initialize trigger decision tool"); + m_trigDecisionTool = trigDecTool; } + + // Trigger matching tool + static const std::string trig_match_name = "Trig::MatchingTool"; + if (asg::ToolStore::contains<Trig::IMatchingTool>(trig_match_name)) { + m_trigMatchTool = asg::ToolStore::get<Trig::IMatchingTool>(trig_match_name); + } else { + if (m_config->getDerivationStream() == "PHYS") { + Trig::MatchFromCompositeTool* trigMatchTool = new Trig::MatchFromCompositeTool(trig_match_name); + top::check(trigMatchTool->initialize(), + "Failed to initialize trig. matching tool"); + m_trigMatchTool = trigMatchTool; + + } else { + Trig::MatchingTool* trigMatchTool = new Trig::MatchingTool(trig_match_name); + top::check(trigMatchTool->setProperty("TrigDecisionTool", m_trigDecisionTool), + "Failed to set trigger decision tool to trigger matching tool"); + top::check(trigMatchTool->initialize(), + "Failed to initialize trig. matching tool"); + m_trigMatchTool = trigMatchTool; + } + } + + ///-- Tau matching --/// + if (m_config->useTaus()) { + const std::string tauMatchName = "Trig::TrigTauMatchingTool"; + if (asg::ToolStore::contains<Trig::ITrigTauMatchingTool>(tauMatchName)) { + m_trigMatchTauTool = asg::ToolStore::get<Trig::ITrigTauMatchingTool>(tauMatchName); + } else { + Trig::TrigTauMatchingTool* trigMatchTauTool = new Trig::TrigTauMatchingTool(tauMatchName); + top::check(trigMatchTauTool->setProperty("TrigDecisionTool", m_trigDecisionTool), + "Failed to set trig dec tool for tau matching"); + top::check(trigMatchTauTool->initialize(), + "Failed to initialize tau trigger matching tool"); + m_trigMatchTauTool = trigMatchTauTool; + } + } + ///-- Trigger global efficiency corrections --/// + if (m_config->useGlobalTrigger()) { + top::check(this->initialiseGlobalTriggerEff(), + "Failed to construct global trigger efficiencies"); + } + } else { + ATH_MSG_INFO("top::TriggerCPTools: no need to initialise anything on truth DxAOD"); } + } else { + ATH_MSG_INFO("top::TriggerCPTools: no need to initialise anything in mini-xAOD mode"); } - else { - ATH_MSG_INFO("top::TriggerCPTools: no need to initialise anything on truth DxAOD"); - } + + return StatusCode::SUCCESS; } - else { - ATH_MSG_INFO("top::TriggerCPTools: no need to initialise anything in mini-xAOD mode"); + + StatusCode TriggerCPTools::initialiseGlobalTriggerEff() { + StatusCode statusCode = StatusCode::SUCCESS; + + // utilities for TrigGlobEffCorr::ImportData + //TrigGlobEffCorr::ImportData triggerData; + //top::check(triggerData.importTriggers(), "failed to import trigger data"); + //auto const& triggerDict = triggerData.getDictionary(); + //std::unordered_map<std::string, TrigGlobEffCorr::ImportData::TrigDef> triggerDefs; + //for (auto&& kv : triggerData.getTriggerDefs()) { + // auto it = triggerDict.find(kv.first); + // if (it != triggerDict.end()) { + // triggerDefs[it->second] = kv.second; + // } + //} + //auto getTriggerLegs = + // [&](std::unordered_map<std::string, std::vector<std::string> > const& triggerCombination, + // std::unordered_map<std::string, std::set<std::string> >& electronLegsByPeriod) { + // for (auto&& kv : triggerCombination) { + // std::string const& period = kv.first; + // for (auto const& trigKey : kv.second) { + // auto triggerDefsIt = triggerDefs.find(trigKey); + // if (triggerDefsIt == triggerDefs.end()) { + // statusCode = StatusCode::FAILURE; + // ATH_MSG_ERROR("unrecognized trigger `" << trigKey << "'"); + // continue; + // } + // auto const& trigDef = triggerDefsIt->second; + // for (auto const& leg : trigDef.leg) { + // if (!leg) continue; + // std::string const& legname = triggerDict.at(leg); + // bool ok = true; + // xAOD::Type::ObjectType legtype = triggerData.associatedLeptonFlavour(legname, ok); + // if (!ok) { + // statusCode = StatusCode::FAILURE; + // ATH_MSG_ERROR("could not determine object type for trigger leg `" << legname << + // "'"); + // continue; + // } + // switch (legtype) { + // case xAOD::Type::Electron: + // electronLegsByPeriod[period].insert(legname); + // break; + + // case xAOD::Type::Muon: + // break; + + // default: + // statusCode = StatusCode::FAILURE; + // ATH_MSG_ERROR( + // "trigger leg `" << legname << "' has unsupported object type `" << legtype << "'"); + // continue; + // } + // } + // } + // } + // }; + + //// Get trigger strings from configuration + //std::map<std::string, std::string> triggerCombination, triggerCombinationLoose; + //std::vector<std::string> electronSystematics, muonSystematics, electronToolNames, muonToolNames; + //std::unordered_map<std::string, std::vector<std::string> > const emptymap; + //std::unordered_map<std::string, std::vector<std::string> > const& + //triggersByPeriod = (m_config->doTightEvents() ? m_config->getGlobalTriggers() : emptymap), + // triggersByPeriodLoose = (m_config->doLooseEvents() ? m_config->getGlobalTriggersLoose() : emptymap); + + //std::unordered_map<std::string, std::set<std::string> > electronLegsByPeriod, electronLegsByPeriodLoose; + //getTriggerLegs(triggersByPeriod, electronLegsByPeriod); + //getTriggerLegs(triggersByPeriodLoose, electronLegsByPeriodLoose); + + //// Get quality + //std::string electronID, electronIDLoose, electronIsolation, electronIsolationLoose, muonQuality, muonQualityLoose; + //if (m_config->doTightEvents()) { + // electronID = m_config->electronID(); + // electronIsolation = m_config->electronIsolationSF(); + // muonQuality = m_config->muonQuality(); + //} + //if (m_config->doLooseEvents()) { + // electronIDLoose = m_config->electronIDLoose(); + // electronIsolationLoose = m_config->electronIsolationSFLoose(); + // muonQualityLoose = m_config->muonQualityLoose(); + //} + + //// Tidy name for e/gamma + //electronID = mapWorkingPoints(electronID); + //electronIDLoose = mapWorkingPoints(electronIDLoose); + //// This is hopefully only temporary + //electronIsolation = mapWorkingPoints(electronIsolation); + //electronIsolationLoose = mapWorkingPoints(electronIsolationLoose); + + //// Create electron trigger SF and Eff tools + //ToolHandleArray<IAsgElectronEfficiencyCorrectionTool> electronEffTools, electronSFTools, electronEffToolsLoose, + // electronSFToolsLoose; + //std::map<std::string, std::string> legsPerTool, legsPerToolLoose; + //int nTools = 0; + + //// Loop over the triggers found (electrons - tight) + //for (auto& y_t : electronLegsByPeriod) { + // std::string year = y_t.first; + // for (auto& trigKey : y_t.second) { + // nTools++; + // for (int j = 0; j < 2; ++j) { // one tool instance for efficiencies, another for scale factors + // ATH_MSG_INFO("TIGHT " << year << " " << trigKey << " " << electronID << " " << electronIsolation); + // auto t = m_electronToolsFactory.emplace( + // m_electronToolsFactory.end(), "AsgElectronEfficiencyCorrectionTool/ElTrigEff_" + std::to_string( + // j) + "_" + std::to_string(nTools)); + // top::check(t->setProperty("MapFilePath", + // "ElectronEfficiencyCorrection/2015_2017/rel21.2/Consolidation_September2018_v1/map3.txt"), + // "Fail"); + // top::check(t->setProperty("TriggerKey", + // (j ? year + "_" + trigKey : "Eff_" + year + "_" + trigKey)), + // "Failed to set TriggerKey"); + // if (electronID != "None") top::check(t->setProperty("IdKey", electronID), "Failed to set IdKey"); + // if (electronIsolation != "None") top::check(t->setProperty("IsoKey", + // electronIsolation), "Failed to set IsoKey"); + // top::check(t->setProperty("CorrelationModel", "TOTAL"), "Failed to set CorrelationModel"); + // top::check(t->setProperty("ForceDataType", + // (int) PATCore::ParticleDataType::Full), "Failed to set ForceDataType"); + // top::check(t->setProperty("OutputLevel", MSG::INFO), "Failed to set OutputLevel"); + // top::check(t->initialize(), "Failed to initalise"); + // // Using syntax from examples + // auto& handles = j ? electronSFTools : electronEffTools; + // handles.push_back(t->getHandle()); + // std::string name = handles[handles.size() - 1].name(); + // legsPerTool[name] = trigKey + " [" + year + "]"; + // ATH_MSG_INFO("TIGHT " << name << " -> " << trigKey); + // electronToolNames.push_back(name); + // // Special - Record the systematic names from the efficiency tool (not SF tool) + // if (electronSystematics.size() == 0 && j == 1) { + // for (auto& s : + // handles[handles.size() - 1]->recommendedSystematics().getBaseNames()) electronSystematics.push_back(s); + + // } + // } + // } + //} + + //// Loop over the triggers found (electrons - loose) + //nTools = 0; + //for (auto& y_t : electronLegsByPeriodLoose) { + // std::string year = y_t.first; + // for (auto& trigKey : y_t.second) { + // nTools++; + // for (int j = 0; j < 2; ++j) { // one tool instance for efficiencies, another for scale factors + // ATH_MSG_INFO("LOOSE " << year << " " << trigKey << " " << electronIDLoose << " " << electronIsolationLoose); + // auto tLoose = m_electronToolsFactoryLoose.emplace( + // m_electronToolsFactoryLoose.end(), "AsgElectronEfficiencyCorrectionTool/ElTrigEffLoose_" + std::to_string( + // j) + "_" + std::to_string(nTools)); + // top::check(tLoose->setProperty("MapFilePath", + // "ElectronEfficiencyCorrection/2015_2017/rel21.2/Consolidation_September2018_v1/map3.txt"), + // "Fail"); + // top::check(tLoose->setProperty("TriggerKey", + // (j ? year + "_" + trigKey : "Eff_" + year + "_" + trigKey)), + // "Failed to set TriggerKey"); + // if (electronIDLoose != + // "None") top::check(tLoose->setProperty("IdKey", electronIDLoose), "Failed to set IdKey"); + // if (electronIsolationLoose != "None") top::check(tLoose->setProperty("IsoKey", + // electronIsolationLoose), + // "Failed to set IsoKey"); + // top::check(tLoose->setProperty("CorrelationModel", "TOTAL"), "Failed to set CorrelationModel"); + // top::check(tLoose->setProperty("ForceDataType", + // (int) PATCore::ParticleDataType::Full), "Failed to set ForceDataType"); + // top::check(tLoose->setProperty("OutputLevel", MSG::INFO), "Failed to set OutputLevel"); + // top::check(tLoose->initialize(), "Failed to initalise"); + // // Using syntax from examples + // auto& handlesLoose = j ? electronSFToolsLoose : electronEffToolsLoose; + // handlesLoose.push_back(tLoose->getHandle()); + // std::string name = handlesLoose[handlesLoose.size() - 1].name(); + // legsPerToolLoose[name] = trigKey + " [" + year + "]"; + // ATH_MSG_INFO("LOOSE " << name << " -> " << trigKey); + // electronToolNames.push_back(name); + // // Special - Record the systematic names from the efficiency tool (not SF tool) + // if (electronSystematics.size() == 0 && j == 1) { + // for (auto& s : + // handlesLoose[handlesLoose.size() - + // 1]->recommendedSystematics().getBaseNames()) electronSystematics.push_back(s); + // } + // } + // } + //} + + //// Create muon trigger SF tool + //ToolHandleArray<CP::IMuonTriggerScaleFactors> muonTools; + //ToolHandleArray<CP::IMuonTriggerScaleFactors> muonToolsLoose; + + //if (m_config->doTightEvents()) { + // if (muonQuality != "None") top::check(m_muonTool.setProperty("MuonQuality", + // muonQuality), "Failed to set MuonQuality"); + // top::check(m_muonTool.setProperty("AllowZeroSF", true), "Failed to set AllowZeroSF"); + // top::check(m_muonTool.initialize(), "Failed to initialise"); + // muonTools.push_back(m_muonTool.getHandle()); + // ATH_MSG_INFO("Muon tool name (tight) " << muonTools[muonTools.size() - 1].name()); + // muonToolNames.push_back(muonTools[muonTools.size() - 1].name()); + // // Special - Get muon systematics + // if (muonSystematics.size() == 0) { + // for (auto& s: + // muonTools[muonTools.size() - 1]->recommendedSystematics().getBaseNames()) muonSystematics.push_back(s); + // } + //} + + //if (m_config->doLooseEvents()) { + // if (muonQualityLoose != "None") top::check(m_muonToolLoose.setProperty("MuonQuality", + // muonQualityLoose), + // "Failed to set MuonQuality"); + // top::check(m_muonToolLoose.setProperty("AllowZeroSF", true), "Failed to set AllowZeroSF"); + // top::check(m_muonToolLoose.initialize(), "Failed to initialise"); + // muonToolsLoose.push_back(m_muonToolLoose.getHandle()); + // ATH_MSG_INFO("Muon tool name (loose) " << muonToolsLoose[muonToolsLoose.size() - 1].name()); + // muonToolNames.push_back(muonToolsLoose[muonToolsLoose.size() - 1].name()); + // // Special - Get muon systematics + // if (muonSystematics.size() == 0) { + // for (auto& s: muonToolsLoose[muonToolsLoose.size() - 1]->recommendedSystematics().getBaseNames()) muonSystematics.push_back(s); + // } + //} + + //for (auto& key : triggersByPeriod) { + // if (triggerCombination.find(key.first) == triggerCombination.end()) { + // triggerCombination[key.first] = ""; + // } else { + // triggerCombination[key.first] += " || "; + // } + // triggerCombination[key.first] += boost::algorithm::join(key.second, " || "); + //} + //for (auto& key : triggersByPeriodLoose) { + // if (triggerCombinationLoose.find(key.first) == triggerCombinationLoose.end()) { + // triggerCombinationLoose[key.first] = ""; + // } else { + // triggerCombinationLoose[key.first] += " || "; + // } + // triggerCombinationLoose[key.first] += boost::algorithm::join(key.second, " || "); + //} + + //// Print out what we configured + //for (auto kv: triggerCombination) ATH_MSG_DEBUG("TRIG (TIGHT): " << kv.first << " -> " << kv.second); + //for (auto kv: triggerCombinationLoose) ATH_MSG_DEBUG("TRIG (LOOSE): " << kv.first << " -> " << kv.second); + + // Make the global trigger tool +// if (m_config->doTightEvents()) { +// TrigGlobalEfficiencyCorrectionTool* globalTriggerEffTool = new TrigGlobalEfficiencyCorrectionTool("TrigGlobalEfficiencyCorrectionTool::TrigGlobal"); +// top::check(globalTriggerEffTool->setProperty("ElectronEfficiencyTools", electronEffTools), "Failed to attach electron efficiency tools"); +// top::check(globalTriggerEffTool->setProperty("ElectronScaleFactorTools", electronSFTools), "Failed to attach electron scale factor tools"); +// top::check(globalTriggerEffTool->setProperty("MuonTools", muonTools), "Failed to attach muon tools"); +// top::check(globalTriggerEffTool->setProperty("ListOfLegsPerTool", legsPerTool), "Failed to define list of legs per tool"); +// top::check(globalTriggerEffTool->setProperty("TriggerCombination", triggerCombination), "Failed to define trigger combination"); +// top::check(globalTriggerEffTool->setProperty("TriggerMatchingTool", m_trigMatchTool), "Failed to set TriggerMatchingTool"); +// // Setting MSG::ERROR to avoid flooding output with invalid efficiency warnings before event selection is complete +// top::check(globalTriggerEffTool->setProperty("OutputLevel", MSG::ERROR), "Failed to set message level"); +// top::check(globalTriggerEffTool->initialize(), "Failed to initalise"); +// m_globalTriggerEffTool = globalTriggerEffTool; +// } +// if (m_config->doLooseEvents()) { +// TrigGlobalEfficiencyCorrectionTool* globalTriggerEffToolLoose = new TrigGlobalEfficiencyCorrectionTool("TrigGlobalEfficiencyCorrectionTool::TrigGlobalLoose"); +// top::check(globalTriggerEffToolLoose->setProperty("ElectronEfficiencyTools", electronEffToolsLoose), "Failed to attach electron efficiency tools"); +// top::check(globalTriggerEffToolLoose->setProperty("ElectronScaleFactorTools", electronSFToolsLoose), "Failed to attach electron scale factor tools"); +// top::check(globalTriggerEffToolLoose->setProperty("MuonTools", muonToolsLoose), "Failed to attach muon tools"); +// top::check(globalTriggerEffToolLoose->setProperty("ListOfLegsPerTool", legsPerToolLoose), "Failed to define list of legs per tool"); +// top::check(globalTriggerEffToolLoose->setProperty("TriggerCombination", triggerCombinationLoose), "Failed to define trigger combination"); +// top::check(globalTriggerEffToolLoose->setProperty("TriggerMatchingTool", m_trigMatchTool), "Failed to set TriggerMatchingTool"); +// // Setting MSG::ERROR to avoid flooding output with invalid efficiency warnings before event selection is complete +// top::check(globalTriggerEffToolLoose->setProperty("OutputLevel", MSG::ERROR), "Failed to set message level"); +// top::check(globalTriggerEffToolLoose->initialize(), "Failed to initalise"); +// m_globalTriggerEffToolLoose = globalTriggerEffToolLoose; +// } + + // Set information about systematics inside TopConfig +// m_config->setGlobalTriggerConfiguration(electronSystematics, muonSystematics, electronToolNames, muonToolNames); + + return statusCode; } - return StatusCode::SUCCESS; -} + std::string TriggerCPTools::mapWorkingPoints(const std::string& type) { + std::string working_point = ""; + // ID + if (type == "LooseAndBLayerLLH" || type == "LooseBLayer" || type == "LooseAndBLayerLH") { + working_point = "LooseBLayer"; + } + if (type == "MediumLLH" || type == "Medium" || type == "MediumLH") { + working_point = "Medium"; + } + if (type == "TightLLH" || type == "Tight" || type == "TightLH") { + working_point = "Tight"; + } + // Temporary ISO map to handle the mess that is EGamma+IFF right now... + if (type.find("Pflow") != std::string::npos) { + ATH_MSG_WARNING("You selected a Pflow isolation WP for at least one of your electron collections - BE WARNED THAT THESE ARE NOT YET READY TO BE RELEASED FOR USE IN PHYSICS ANALYSES AND OF COURSE DON'T HAVE ASSOCIATED SCALE FACTORS YET!!!"); + if (type == "PflowLoose") working_point = "FCLoose"; + if (type == "PflowTight") working_point = "FCTight"; + } + if (type == "Tight") working_point = "FCTight"; + if (type == "Loose") working_point = "FCLoose"; + if (type == "HighPtCaloOnly") working_point = "FCHighPtCaloOnly"; + if (type == "TightTrackOnly") working_point = "Gradient"; + if (type == "TightTrackOnly_FixedRad") working_point = "Gradient"; + if (type == "FCTight" || type == "FCLoose" || type == "FCHighPtCaloOnly" || type == "Gradient") working_point = type; + + return working_point; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopBoostedTaggingCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopBoostedTaggingCPTools.h new file mode 100644 index 0000000000000000000000000000000000000000..523d678de379860ad134dd983b122db41fab3253 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopBoostedTaggingCPTools.h @@ -0,0 +1,38 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TOPCPTOOLS_TOPBOOSTEDTAGGINGCPTOOLS_H_ +#define TOPCPTOOLS_TOPBOOSTEDTAGGINGCPTOOLS_H_ + +// Include what you use +#include <vector> +#include <string> +#include <map> + +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "AsgTools/ToolHandleArray.h" +#include "AsgTools/AnaToolHandle.h" +#include "JetAnalysisInterfaces/IJetSelectorTool.h" +#include "JetCPInterfaces/ICPJetUncertaintiesTool.h" + +namespace top { + class TopConfig; + + class BoostedTaggingCPTools final: public asg::AsgTool { + public: + explicit BoostedTaggingCPTools(const std::string& name); + virtual ~BoostedTaggingCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::unordered_map<std::string, asg::AnaToolHandle<IJetSelectorTool> > m_taggers; + std::unordered_map<std::string, ToolHandle<ICPJetUncertaintiesTool> > m_tagSFuncertTool; + }; +} // namespace top + +#endif // TOPCPTOOLS_TOPBOOSTEDTAGGINGCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopEgammaCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopEgammaCPTools.h index 073366660585adb27b51f3f56faed8464988d17c..a1623edc12c28a108f02a1b72586a4864a901f35 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopEgammaCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopEgammaCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPEGAMMACPTOOLS_H_ #define TOPCPTOOLS_TOPEGAMMACPTOOLS_H_ @@ -21,69 +21,112 @@ #include "EgammaAnalysisInterfaces/IElectronPhotonShowerShapeFudgeTool.h" #include "EgammaAnalysisInterfaces/IAsgPhotonEfficiencyCorrectionTool.h" #include "EgammaAnalysisInterfaces/IAsgPhotonIsEMSelector.h" +//#include "ElectronPhotonSelectorTools/AsgForwardElectronLikelihoodTool.h" +//#include "TrigBunchCrossingTool/WebBunchCrossingTool.h" -namespace top { - -class TopConfig; - -class EgammaCPTools final : public asg::AsgTool { - public: - explicit EgammaCPTools(const std::string& name); - virtual ~EgammaCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - std::string m_electronEffTriggerFile; - std::string m_electronEffTriggerLooseFile; - std::string m_electronEffSFTriggerFile; - std::string m_electronEffSFTriggerLooseFile; - std::string m_electronEffSFRecoFile; - std::string m_electronEffSFIDFile; - std::string m_electronEffSFIDLooseFile; - std::string m_electronEffSFIsoFile; - std::string m_electronEffSFIsoLooseFile; - std::string m_electronEffSFChargeIDFile; - - ToolHandle<CP::IEgammaCalibrationAndSmearingTool> m_egammaCalibrationAndSmearingTool; - - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTrigger; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerLoose; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTrigger; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerLoose; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFReco; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFID; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLoose; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIso; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoLoose; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeID; +#include "TopConfiguration/Tokenize.h" - ToolHandle<IElectronPhotonShowerShapeFudgeTool> m_photonFudgeTool; - ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonEffSF; - ToolHandleArray<IAsgPhotonEfficiencyCorrectionTool> m_photonIsoSFTools; - - ToolHandle<IAsgPhotonIsEMSelector> m_photonTightIsEMSelector; - ToolHandle<IAsgPhotonIsEMSelector> m_photonMediumIsEMSelector; - ToolHandle<IAsgPhotonIsEMSelector> m_photonLooseIsEMSelector; - - - - StatusCode setupCalibration(); - StatusCode setupScaleFactors(); - - IAsgElectronEfficiencyCorrectionTool* - setupElectronSFTool(const std::string& name, const std::vector<std::string>& file_list, int data_type); - - // Helper function to deal with path resolving the - // egamma groups very long file names for SFs and efficiencies. - std::string electronSFFilePath(const std::string& type, const std::string& ID = "", const std::string& isolation = ""); - - -}; +namespace top { + class TopConfig; + + class EgammaCPTools final: public asg::AsgTool { + public: + explicit EgammaCPTools(const std::string& name); + virtual ~EgammaCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::string m_electronEffTriggerFile; + std::string m_electronEffTriggerLooseFile; + std::string m_electronEffSFTriggerFile; + std::string m_electronEffSFTriggerLooseFile; + std::string m_electronEffSFRecoFile; + std::string m_electronEffSFIDFile; + std::string m_electronEffSFIDLooseFile; + std::string m_electronEffSFIsoFile; + std::string m_electronEffSFIsoLooseFile; + std::string m_electronEffSFChargeIDFile; + std::string m_electronEffSFChargeIDLooseFile; + std::string m_electronEffSFChargeMisIDFile; + std::string m_electronEffSFChargeMisIDLooseFile; + +// std::string m_fwdElectronEffSFIDFile; +// std::string m_fwdElectronEffSFIDLooseFile; + + ToolHandle<CP::IEgammaCalibrationAndSmearingTool> m_egammaCalibrationAndSmearingTool; + + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTrigger; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerLoose; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTrigger; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerLoose; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFReco; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFID; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLoose; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIso; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoLoose; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeID; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeIDLoose; + + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerLooseCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerLooseCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFRecoCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLooseCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoLooseCorrModel; + + ToolHandle<IElectronPhotonShowerShapeFudgeTool> m_photonFudgeTool; + ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonEffSF; + ToolHandleArray<IAsgPhotonEfficiencyCorrectionTool> m_photonIsoSFTools; + + ToolHandle<IAsgPhotonIsEMSelector> m_photonTightIsEMSelector; + ToolHandle<IAsgPhotonIsEMSelector> m_photonMediumIsEMSelector; + ToolHandle<IAsgPhotonIsEMSelector> m_photonLooseIsEMSelector; + +// ToolHandle<AsgForwardElectronLikelihoodTool> m_fwdElectronSelector; +// ToolHandle<AsgForwardElectronLikelihoodTool> m_fwdElectronSelectorLoose; +// ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_fwdElectronEffSFID; +// ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_fwdElectronEffSFIDLoose; + +// ToolHandle<Trig::WebBunchCrossingTool> m_webBunchCrossingTool; + + StatusCode setupSelectors(); + StatusCode setupCalibration(); + StatusCode setupScaleFactors(); + + IAsgElectronEfficiencyCorrectionTool* setupElectronSFTool(const std::string& name, + const std::vector<std::string>& file_list, + const int& data_type, + const std::string& correlation_model="TOTAL", + const std::string& correlationModelEtaBinning="", + const std::string& correlationModelEtBinning=""); + + // Helper function to deal with path resolving the + // egamma groups very long file names for SFs and efficiencies. + std::string electronSFFilePath(const std::string& type, const std::string& ID, const std::string& ISO); + + // Helper for using maps from egamma groups + IAsgElectronEfficiencyCorrectionTool* setupElectronSFToolWithMap(const std::string& name, + const std::string& map_path, + const std::string& reco_key, + const std::string& ID_key, + const std::string& iso_key, + const std::string& trigger_key, + const int& data_type, + const std::string& correlationModel, + const std::string& correlationModelEtaBinning, + const std::string& correlationModelEtBinning); + + std::string electronSFMapFilePath(const std::string& type); + void setCorrelationModelBinning(IAsgElectronEfficiencyCorrectionTool* tool, const std::string& binningName, + const std::string& binning); + + std::string mapWorkingPoints(const std::string& type); + }; } // namespace top #endif // TOPCPTOOLS_TOPEGAMMACPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopFlavorTaggingCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopFlavorTaggingCPTools.h index 44ef30105db319a3fa300f4548a303d85e6a2c89..c463b71fe62b5d48db5811d15084fb571715ba4e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopFlavorTaggingCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopFlavorTaggingCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPFLAVORTAGGINGCPTOOLS_H_ #define TOPCPTOOLS_TOPFLAVORTAGGINGCPTOOLS_H_ @@ -8,6 +8,7 @@ // Include what you use #include <vector> #include <string> +#include <map> // Framework include(s): #include "AsgTools/AsgTool.h" @@ -18,39 +19,50 @@ #include "TopConfiguration/TopConfig.h" // Flavor tagging include(s): -#include "xAODBTaggingEfficiency/IBTaggingEfficiencyTool.h" -#include "xAODBTaggingEfficiency/IBTaggingSelectionTool.h" +#include "FTagAnalysisInterfaces/IBTaggingEfficiencyTool.h" +#include "FTagAnalysisInterfaces/IBTaggingSelectionTool.h" +// Need a pointer for excluded systematic functions +#include "xAODBTaggingEfficiency/BTaggingEfficiencyTool.h" namespace top { + class TopConfig; -class TopConfig; - -class FlavorTaggingCPTools final : public asg::AsgTool { - public: - explicit FlavorTaggingCPTools(const std::string& name); - virtual ~FlavorTaggingCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - std::string m_tagger = ""; - std::string m_cdi_file = ""; - std::string m_efficiency_maps; - const std::vector<std::string> m_jet_flavors = {"B", "C", "T", "Light"}; - std::vector<std::string> m_calo_WPs_calib; - std::vector<std::string> m_calo_WPs; - std::vector<std::string> m_trackAntiKt2_WPs_calib; - std::vector<std::string> m_trackAntiKt2_WPs; - std::vector<std::string> m_trackAntiKt4_WPs_calib; - std::vector<std::string> m_trackAntiKt4_WPs; - // Some tools here - ToolHandleArray<IBTaggingEfficiencyTool> m_btagging_efficiency_tools; - ToolHandleArray<IBTaggingSelectionTool> m_btagging_selection_tools; -}; + class FlavorTaggingCPTools final: public asg::AsgTool { + public: + explicit FlavorTaggingCPTools(const std::string& name); + virtual ~FlavorTaggingCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::string m_tagger = ""; + std::string m_cdi_file = ""; + std::string m_efficiency_maps; + const std::vector<std::string> m_jet_flavors = { + "B", "C", "T", "Light" + }; + std::vector<std::string> m_calo_WPs_calib; + std::vector<std::string> m_calo_WPs; + std::vector<std::string> m_trackAntiKtVR_WPs_calib; + std::vector<std::string> m_trackAntiKtVR_WPs; + std::vector<std::string> m_trackAntiKt2_WPs_calib; + std::vector<std::string> m_trackAntiKt2_WPs; + std::vector<std::string> m_trackAntiKt4_WPs_calib; + std::vector<std::string> m_trackAntiKt4_WPs; + std::vector<std::string> m_pflow_WPs_calib; + std::vector<std::string> m_pflow_WPs; + // Some tools here + ToolHandleArray<IBTaggingEfficiencyTool> m_btagging_efficiency_tools; + ToolHandleArray<IBTaggingSelectionTool> m_btagging_selection_tools; + // EV decomposition functions + StatusCode checkExcludedSysts(BTaggingEfficiencyTool*, std::string); + void createExcludedSystMapping(std::vector<std::string>); + std::map<std::string, std::string> m_mapped_excluded_systs; + // Helper function for tracking tagger/WP/Calibration + StatusCode setTaggerWorkingPoints(std::string, bool, std::string, std::vector<std::string>); + void printConfigurations(); + }; } // namespace top #endif // TOPCPTOOLS_TOPFLAVORTAGGINGCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopGhostTrackCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopGhostTrackCPTools.h index 9cbc57f50c248a432a621b546eebf41c26a122c6..a756e83fbc3553ec2859578c901c58a495d11250 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopGhostTrackCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopGhostTrackCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPGHOSTTRACKCPTOOLS_H_ #define TOPCPTOOLS_TOPGHOSTTRACKCPTOOLS_H_ @@ -22,45 +22,60 @@ #include "InDetTrackSystematicsTools/InDetTrackTruthFilterTool.h" #include "InDetTrackSystematicsTools/InDetTrackTruthOriginTool.h" #include "InDetTrackSystematicsTools/JetTrackFilterTool.h" +#include "InDetTrackSystematicsTools/JetTrackFilterTool.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" -namespace top { - -class TopConfig; - -class GhostTrackCPTools final : public asg::AsgTool { - public: - explicit GhostTrackCPTools(const std::string& name); - virtual ~GhostTrackCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - std::vector<std::uint32_t> m_runPeriods; - - const std::string m_smearingToolName{"top::GhostTrackCPTools::InDetTrackSmearingTool"}; - const std::string m_biasToolPrefix{"top::GhostTrackCPTools::InDetTrackBiasingTool"}; - const std::string m_truthOriginToolName{"top::GhostTrackCPTools::InDetTrackTruthOriginTool"}; - const std::string m_truthFilterToolName{"top::GhostTrackCPTools::InDetTrackTruthFilterTool"}; - const std::string m_jetTrackFilterToolName{"top::GhostTrackCPTools::JetTrackFilterTool"}; - - ToolHandle<InDet::InDetTrackSmearingTool> m_smearingTool; - ToolHandle<InDet::InDetTrackTruthOriginTool> m_truthOriginTool; - ToolHandle<InDet::InDetTrackTruthFilterTool> m_truthFilterTool; - ToolHandle<InDet::JetTrackFilterTool> m_jetTrackFilterTool; - - std::vector<ToolHandle<InDet::InDetTrackBiasingTool> > m_biasingTool; - - StatusCode setupSmearingTool(); - StatusCode setupBiasingTools(); - StatusCode setupTruthFilterTool(); - StatusCode setupJetTrackFilterTool(); -}; +namespace top { + class TopConfig; + + class GhostTrackCPTools final: public asg::AsgTool { + public: + explicit GhostTrackCPTools(const std::string& name); + virtual ~GhostTrackCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::vector<std::uint32_t> m_runPeriods; + + const std::string m_smearingToolName { + "top::GhostTrackCPTools::InDetTrackSmearingTool" + }; + const std::string m_biasToolPrefix { + "top::GhostTrackCPTools::InDetTrackBiasingTool" + }; + const std::string m_truthOriginToolName { + "top::GhostTrackCPTools::InDetTrackTruthOriginTool" + }; + const std::string m_truthFilterToolName { + "top::GhostTrackCPTools::InDetTrackTruthFilterTool" + }; + const std::string m_jetTrackFilterToolName { + "top::GhostTrackCPTools::JetTrackFilterTool" + }; + + const std::string m_TrkSelName { + "top::GhostTrackCPTools::TrkSelTool" + }; + + ToolHandle<InDet::InDetTrackSmearingTool> m_smearingTool; + ToolHandle<InDet::InDetTrackTruthOriginTool> m_truthOriginTool; + ToolHandle<InDet::InDetTrackTruthFilterTool> m_truthFilterTool; + ToolHandle<InDet::JetTrackFilterTool> m_jetTrackFilterTool; + ToolHandle<InDet::InDetTrackSelectionTool> m_trackseltool; + + + std::vector<ToolHandle<InDet::InDetTrackBiasingTool> > m_biasingTool; + + StatusCode setupSmearingTool(); + StatusCode setupBiasingTools(); + StatusCode setupTruthFilterTool(); + StatusCode setupJetTrackFilterTool(); + StatusCode setupSelectionTool(); + }; } // namespace top #endif // TOPCPTOOLS_TOPGHOSTTRACKCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopIsolationCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopIsolationCPTools.h index 86d416765d2efe44de58202c6f6c7ae338ffdf45..ec82cd6d167c5275e82172625769f22242698dd2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopIsolationCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopIsolationCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPISOLATIONCPTOOLS_H_ #define TOPCPTOOLS_TOPISOLATIONCPTOOLS_H_ @@ -17,31 +17,29 @@ // Isolation include(s): #include "IsolationSelection/IIsolationSelectionTool.h" +//#include "IsolationSelection/IIsolationLowPtPLVTool.h" #include "IsolationCorrections/IIsolationCorrectionTool.h" namespace top { + class TopConfig; -class TopConfig; + class IsolationCPTools final: public asg::AsgTool { + public: + explicit IsolationCPTools(const std::string& name); + virtual ~IsolationCPTools() {} -class IsolationCPTools final : public asg::AsgTool { - public: - explicit IsolationCPTools(const std::string& name); - virtual ~IsolationCPTools() {} + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; - StatusCode initialize(); + std::string m_isolationCalibFile; - private: - std::shared_ptr<top::TopConfig> m_config; + ToolHandle<CP::IIsolationCorrectionTool> m_isolationCorr; + ToolHandleArray<CP::IIsolationSelectionTool> m_isolationTools; +// ToolHandleArray<CP::IIsolationLowPtPLVTool> m_isolationToolsLowPtPLV; - int m_release_series = 24; // Default to 2.4 - - std::string m_isolationCalibFile; - - ToolHandle<CP::IIsolationCorrectionTool> m_isolationCorr; - ToolHandleArray<CP::IIsolationSelectionTool> m_isolationTools; - - StatusCode setupIsolation(); -}; + StatusCode setupIsolation(); + }; } // namespace top #endif // TOPCPTOOLS_TOPISOLATIONCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopJetMETCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopJetMETCPTools.h index cf55a3545aec334b8d64ca589dd96cff44e4a898..6f353590e53d74f9c2f609df871074d1c8e45b66 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopJetMETCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopJetMETCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPJETMETCPTOOLS_H_ #define TOPCPTOOLS_TOPJETMETCPTOOLS_H_ @@ -8,6 +8,7 @@ // Include what you use #include <vector> #include <string> +#include <cstdlib> // Framework include(s): #include "AsgTools/AsgTool.h" @@ -21,86 +22,95 @@ #include "JetInterface/IJetUpdateJvt.h" #include "JetInterface/IJetSelector.h" #include "JetInterface/IJetModifier.h" -#include "JetResolution/IJERTool.h" -#include "JetResolution/IJERSmearingTool.h" -#include "JetJvtEfficiency/IJetJvtEfficiency.h" +#include "JetAnalysisInterfaces/IJetJvtEfficiency.h" +#include "JetSelectorTools/IEventCleaningTool.h" // MET include(s): #include "METInterface/IMETMaker.h" #include "METInterface/IMETSystematicsTool.h" namespace top { + class TopConfig; -class TopConfig; + class JetMETCPTools final: public asg::AsgTool { + public: + explicit JetMETCPTools(const std::string& name); + virtual ~JetMETCPTools() {} -class JetMETCPTools final : public asg::AsgTool { - public: - explicit JetMETCPTools(const std::string& name); - virtual ~JetMETCPTools() {} + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; - StatusCode initialize(); + std::string m_jetJVT_ConfigFile; + std::string m_truthJetCollForHS; - private: - std::shared_ptr<top::TopConfig> m_config; + std::string m_jetAntiKt4_Data_ConfigFile; + std::string m_jetAntiKt4_Data_CalibSequence; - int m_release_series = 24; // Default to 2.4 + std::string m_jetAntiKt4_MCFS_ConfigFile; + std::string m_jetAntiKt4_MCFS_CalibSequence; - std::string m_jetJVT_ConfigFile; + std::string m_jetAntiKt4_MCAFII_ConfigFile; + std::string m_jetAntiKt4_MCAFII_CalibSequence; - std::string m_jetAntiKt4_Data_ConfigFile; - std::string m_jetAntiKt4_Data_CalibSequence; + std::string m_jetAntiKt4_MCAFII_PFlow_ConfigFile; + std::string m_jetAntiKt4_MCAFII_PFlow_CalibSequence; - std::string m_jetAntiKt4_MCFS_ConfigFile; - std::string m_jetAntiKt4_MCFS_CalibSequence; + std::string m_jetAntiKt4_PFlow_MCFS_ConfigFile; + std::string m_jetAntiKt4_PFlow_MCFS_CalibSequence; - std::string m_jetAntiKt4_MCAFII_ConfigFile; - std::string m_jetAntiKt4_MCAFII_CalibSequence; + std::string m_jetAntiKt4_Data_PFlow_ConfigFile; + std::string m_jetAntiKt4_Data_PFlow_CalibSequence; - std::string m_jetAntiKt4_PFlow_MCFS_ConfigFile; - std::string m_jetAntiKt4_PFlow_MCFS_CalibSequence; + ToolHandle<IJetCalibrationTool> m_jetCalibrationTool; + ToolHandle<IJetCalibrationTool> m_jetCalibrationToolLargeR; - ToolHandle<IJetCalibrationTool> m_jetCalibrationTool; - ToolHandle<IJetCalibrationTool> m_jetCalibrationToolLargeR; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR_strong; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR_medium; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR_weak; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesTool; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolFrozenJMS; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario1; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario2; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario3; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario4; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesTool; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario1; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario2; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario3; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario4; + ToolHandle<IJetSelector> m_jetCleaningToolLooseBad; + ToolHandle<IJetSelector> m_jetCleaningToolTightBad; - ToolHandle<IJetSelector> m_jetCleaningToolLooseBad; - ToolHandle<IJetSelector> m_jetCleaningToolTightBad; + // Implement event object cleaning tool + ToolHandle<ECUtils::IEventCleaningTool> m_jetEventCleaningToolLooseBad; + ToolHandle<ECUtils::IEventCleaningTool> m_jetEventCleaningToolTightBad; - ToolHandle<IJERTool> m_jetJERTool; - ToolHandle<IJERSmearingTool> m_jetJERSmearingTool; - ToolHandle<IJetUpdateJvt> m_jetUpdateJvtTool; - ToolHandle<IJetModifier> m_fjvtTool; + ToolHandle<IJetUpdateJvt> m_jetUpdateJvtTool; + ToolHandle<IJetModifier> m_jetSelectfJvtTool; - ToolHandle<CP::IJetJvtEfficiency> m_jetJvtTool; + ToolHandle<CP::IJetJvtEfficiency> m_jetJvtTool; + ToolHandle<CP::IJetJvtEfficiency> m_jetfJvtTool; - ToolHandle<IMETMaker> m_met_maker; - ToolHandle<IMETSystematicsTool> m_met_systematics; + ToolHandle<IMETMaker> m_met_maker; + ToolHandle<IMETSystematicsTool> m_met_systematics; - StatusCode setupJetsCalibration(); - StatusCode setupLargeRJetsCalibration(); - StatusCode setupJetsScaleFactors(); - StatusCode setupMET(); + StatusCode setupJetsCalibration(); + StatusCode setupLargeRJetsCalibration(); + StatusCode setupJetsScaleFactors(); + StatusCode setupMET(); - ICPJetUncertaintiesTool* + ICPJetUncertaintiesTool* setupJetUncertaintiesTool(const std::string& name, const std::string& jet_def, const std::string& mc_type, + bool isMC, const std::string& config_file, - std::vector<std::string>* variables); - - IJetSelector* setupJetCleaningTool(const std::string& WP); -}; + std::vector<std::string>* variables, + const std::string& analysis_file = "", + const std::string& calib_area = "None"); + + IJetSelector* setupJetCleaningTool(const std::string& WP); + ECUtils::IEventCleaningTool* setupJetEventCleaningTool(const std::string& WP, + ToolHandle<IJetSelector> JetCleaningToolHandle); + }; } // namespace top #endif // TOPCPTOOLS_TOPJETMETCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopMuonCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopMuonCPTools.h index 3ed0e73dfa51e29c70d9b51df79b9fe3bfeb6b59..95381e9c6d6813111d5e015608eeb730b2d89c1d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopMuonCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopMuonCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPMUONCPTOOLS_H_ #define TOPCPTOOLS_TOPMUONCPTOOLS_H_ @@ -20,54 +20,61 @@ #include "MuonAnalysisInterfaces/IMuonSelectionTool.h" #include "MuonAnalysisInterfaces/IMuonTriggerScaleFactors.h" #include "MuonAnalysisInterfaces/IMuonEfficiencyScaleFactors.h" +#include "MuonMomentumCorrections/MuonCalibrationPeriodTool.h" namespace top { + class TopConfig; -class TopConfig; + class MuonCPTools final: public asg::AsgTool { + public: + explicit MuonCPTools(const std::string& name); + virtual ~MuonCPTools() {} -class MuonCPTools final : public asg::AsgTool { - public: - explicit MuonCPTools(const std::string& name); - virtual ~MuonCPTools() {} + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; - StatusCode initialize(); + ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_muonCalibrationPeriodTool; - private: - std::shared_ptr<top::TopConfig> m_config; + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolLoose; + // the following is needed to make sure all muons for which d0sig is calculated are at least Loose + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolVeryLooseVeto; - int m_release_series = 24; // Default to 2.4 + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2015; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2015; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2016; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2016; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_R21; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_R21; - ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_muonCalibrationAndSmearingTool; - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolLoose; - // the following is needed to make sure all muons for which d0sig is calculated are at least Loose - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolVeryLooseVeto; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsTool; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLoose; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolIso; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLooseIso; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolPromptLeptonIso; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolTTVA; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2015; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2015; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2016; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2016; + ToolHandle<CP::IMuonSelectionTool> m_softmuonSelectionTool; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_softmuonEfficiencyCorrectionsTool; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsTool; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLoose; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolIso; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLooseIso; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolTTVA; + StatusCode setupCalibration(); + StatusCode setupScaleFactors(); - StatusCode setupCalibration(); - StatusCode setupScaleFactors(); + CP::IMuonSelectionTool* + setupMuonSelectionTool(const std::string& name, const std::string& quality, double max_eta, const bool& useMVALowPt, const bool& use2stationMuonsHighPt); - CP::IMuonSelectionTool* - setupMuonSelectionTool(const std::string& name, const std::string& quality, double max_eta); + CP::IMuonTriggerScaleFactors* + setupMuonTrigSFTool(const std::string& name, const std::string& quality); - CP::IMuonTriggerScaleFactors* - setupMuonTrigSFTool(const std::string& name, const std::string& quality, const std::string& year); - - CP::IMuonEfficiencyScaleFactors* + CP::IMuonEfficiencyScaleFactors* setupMuonSFTool(const std::string& name, const std::string& WP); -}; + + CP::IMuonCalibrationAndSmearingTool* + setupMuonCalibrationAndSmearingTool(const std::string& name, const bool& doExtraSmearingHighPt, const bool& do2StationsHighPt); + }; } // namespace top #endif // TOPCPTOOLS_TOPMUONCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOtherCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOtherCPTools.h index ff31a0d349a14208f47a2196d2cbbf8f6a17e547..d0e1525adc610e401673921d0caa9897a01a46a8 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOtherCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOtherCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPOTHERCPTOOLS_H_ #define TOPCPTOOLS_TOPOTHERCPTOOLS_H_ @@ -23,31 +23,29 @@ // PMG Tools #include "PMGTools/PMGSherpa22VJetsWeightTool.h" +#include "PMGAnalysisInterfaces/IPMGTruthWeightTool.h" namespace top { - -class TopConfig; - -class OtherCPTools final : public asg::AsgTool { - public: - explicit OtherCPTools(const std::string& name); - virtual ~OtherCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - ToolHandle<IGoodRunsListSelectionTool> m_grlTool; - ToolHandle<CP::IPileupReweightingTool> m_pileupReweightingTool; - ToolHandle<PMGTools::PMGSherpa22VJetsWeightTool> m_pmg_sherpa22_vjets_tool; - - StatusCode setupGRL(); - StatusCode setupPileupReweighting(); - StatusCode setupPMGTools(); -}; + class TopConfig; + + class OtherCPTools final: public asg::AsgTool { + public: + explicit OtherCPTools(const std::string& name); + virtual ~OtherCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + ToolHandle<IGoodRunsListSelectionTool> m_grlTool; + ToolHandle<CP::IPileupReweightingTool> m_pileupReweightingTool; + ToolHandle<PMGTools::PMGSherpa22VJetsWeightTool> m_pmg_sherpa22_vjets_tool; + ToolHandle<PMGTools::IPMGTruthWeightTool> m_pmg_weightTool; + + StatusCode setupGRL(); + StatusCode setupPileupReweighting(); + StatusCode setupPMGTools(); + }; } // namespace top #endif // TOPCPTOOLS_TOPOTHERCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOverlapRemovalCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOverlapRemovalCPTools.h index f37987143de8bf48040474c07c91dd37776d7cb6..e3f9d552d4735697e984340510315f168fea5763 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOverlapRemovalCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopOverlapRemovalCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPOVERLAPREMOVALCPTOOLS_H_ #define TOPCPTOOLS_TOPOVERLAPREMOVALCPTOOLS_H_ @@ -20,28 +20,28 @@ #include "AssociationUtils/ToolBox.h" namespace top { - -class TopConfig; - -class OverlapRemovalCPTools final : public asg::AsgTool { - public: - explicit OverlapRemovalCPTools(const std::string& name); - virtual ~OverlapRemovalCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - ORUtils::ToolBox m_ORtoolBox; - ORUtils::ToolBox m_ORtoolBox_Loose; - asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool; - asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool_Loose; - - StatusCode setupOverlapRemoval(); -}; + class TopConfig; + + class OverlapRemovalCPTools final: public asg::AsgTool { + public: + explicit OverlapRemovalCPTools(const std::string& name); + virtual ~OverlapRemovalCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + ORUtils::ToolBox m_ORtoolBox; + ORUtils::ToolBox m_ORtoolBox_Loose; + ORUtils::ToolBox m_ORtoolBox_softMuons_PFjets; + ORUtils::ToolBox m_ORtoolBox_softMuons_Alljets; + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool; + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool_Loose; + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool_softMuons_PFjets; + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool_softMuons_Alljets; + + StatusCode setupOverlapRemoval(); + }; } // namespace top #endif // TOPCPTOOLS_TOPOVERLAPREMOVALCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTauCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTauCPTools.h index 685c3101b4fbc34327c42489c1d585ed167c41d8..6683cdaab55b49382b85c9c016f4f588b3389709 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTauCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTauCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPTAUCPTOOLS_H_ #define TOPCPTOOLS_TOPTAUCPTOOLS_H_ @@ -15,38 +15,40 @@ #include "AsgTools/ToolHandleArray.h" #include "AsgTools/AnaToolHandle.h" +//PileupReweighting include: +#include "AsgAnalysisInterfaces/IPileupReweightingTool.h" + // Tau include(s): #include "TauAnalysisTools/ITauSelectionTool.h" #include "TauAnalysisTools/ITauSmearingTool.h" #include "TauAnalysisTools/ITauEfficiencyCorrectionsTool.h" +#include "TauAnalysisTools/ITauTruthMatchingTool.h" namespace top { + class TopConfig; -class TopConfig; - -class TauCPTools final : public asg::AsgTool { - public: - explicit TauCPTools(const std::string& name); - virtual ~TauCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; + class TauCPTools final: public asg::AsgTool { + public: + explicit TauCPTools(const std::string& name); + virtual ~TauCPTools() {} - int m_release_series = 24; // Default to 2.4 + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; - ToolHandle<TauAnalysisTools::ITauSelectionTool> m_tauSelectionTool; - ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrTool; + ToolHandle<TauAnalysisTools::ITauSelectionTool> m_tauSelectionTool; + ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrTool; + ToolHandle<CP::IPileupReweightingTool> m_pileupReweightingTool; - ToolHandle<TauAnalysisTools::ITauSelectionTool> m_tauSelectionToolLoose; - ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrToolLoose; + ToolHandle<TauAnalysisTools::ITauSelectionTool> m_tauSelectionToolLoose; + ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrToolLoose; - ToolHandle<TauAnalysisTools::ITauSmearingTool> m_tauSmearingTool; + ToolHandle<TauAnalysisTools::ITauSmearingTool> m_tauSmearingTool; + ToolHandle<TauAnalysisTools::ITauTruthMatchingTool> m_truthMatchingTool; - StatusCode setupCalibration(); - StatusCode setupScaleFactors(); -}; + StatusCode setupCalibration(); + StatusCode setupScaleFactors(); + }; } // namespace top #endif // TOPCPTOOLS_TOPTAUCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopToolStore.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopToolStore.h index ae7f5a0b9800d0dc39ef84c23f1aed5a30a1e660..1475e81458cda62a6579896cfadae1edd645885d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopToolStore.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopToolStore.h @@ -1,31 +1,38 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: TopToolStore.h 802731 2017-04-11 16:35:41Z tpelzer $ +// $Id: TopToolStore.h 808118 2017-07-11 17:41:22Z tpelzer $ #ifndef ANALYSISTOP_TOPCPTOOLS_TOPTOOLSTORE_H #define ANALYSISTOP_TOPCPTOOLS_TOPTOOLSTORE_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief TopToolStore - * Configure all asg::AsgTools and place into asg::ToolStore - * This will allow other tools and algorithms to retrieve the tools - * This means that we can share tools and only configure them once - * - * $Revision: 802731 $ - * $Date: 2017-04-11 18:35:41 +0200 (Tue, 11 Apr 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief TopToolStore + * Configure all asg::AsgTools and place into asg::ToolStore + * This will allow other tools and algorithms to retrieve the tools + * This means that we can share tools and only configure them once + * + * $Revision: 808118 $ + * $Date: 2017-07-11 18:41:22 +0100 (Tue, 11 Jul 2017) $ + * + **/ // system include(s): #include <vector> #include <memory> +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "AsgTools/AnaToolHandle.h" + // Top includes +#include "TopCPTools/TopTrackCPTools.h" #include "TopCPTools/TopGhostTrackCPTools.h" #include "TopCPTools/TopFlavorTaggingCPTools.h" +#include "TopCPTools/TopBoostedTaggingCPTools.h" #include "TopCPTools/TopEgammaCPTools.h" #include "TopCPTools/TopMuonCPTools.h" #include "TopCPTools/TopIsolationCPTools.h" @@ -35,55 +42,38 @@ #include "TopCPTools/TopOverlapRemovalCPTools.h" #include "TopCPTools/TopOtherCPTools.h" -// Framework include(s): -#include "AsgTools/AsgTool.h" -#include "AsgTools/ToolHandle.h" -#include "AsgTools/AnaToolHandle.h" - -namespace top{ - +namespace top { // Forward declaration(s): class TopConfig; - class OverlapRemovalCPTools; - class OtherCPTools; - class FlavorTaggingCPTools; - class TriggerCPTools; - class EgammaCPTools; - class MuonCPTools; - class IsolationCPTools; - class TauCPTools; - class JetMETCPTools; - - class TopToolStore final : public asg::AsgTool { - public: - explicit TopToolStore( const std::string& name ); - virtual ~TopToolStore() {} - - TopToolStore(const TopToolStore& rhs) = delete; - TopToolStore(TopToolStore&& rhs) = delete; - TopToolStore& operator=(const TopToolStore& rhs) = delete; + class TopToolStore final: public asg::AsgTool { + public: + explicit TopToolStore(const std::string& name); + virtual ~TopToolStore() {} + + TopToolStore(const TopToolStore& rhs) = delete; + TopToolStore(TopToolStore&& rhs) = delete; + TopToolStore& operator = (const TopToolStore& rhs) = delete; + + StatusCode initialize(); + StatusCode finalize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::unique_ptr<OverlapRemovalCPTools> m_OR_CP_tools; + std::unique_ptr<OtherCPTools> m_other_CP_tools; + std::unique_ptr<FlavorTaggingCPTools> m_flavor_tagging_CP_tools; + std::unique_ptr<BoostedTaggingCPTools> m_boosted_tagging_CP_tools; + std::unique_ptr<TriggerCPTools> m_trigger_CP_tools; + std::unique_ptr<EgammaCPTools> m_egamma_CP_tools; + std::unique_ptr<MuonCPTools> m_muon_CP_tools; + std::unique_ptr<IsolationCPTools> m_isolation_CP_tools; + std::unique_ptr<TauCPTools> m_tau_CP_tools; + std::unique_ptr<JetMETCPTools> m_jetMET_CP_tools; + std::unique_ptr<GhostTrackCPTools> m_ghost_track_CP_tools; + std::unique_ptr<TrackCPTools> m_track_CP_tools; - StatusCode initialize(); - StatusCode finalize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - std::unique_ptr<top::OverlapRemovalCPTools> m_OR_CP_tools; - std::unique_ptr<top::OtherCPTools> m_other_CP_tools; - std::unique_ptr<top::FlavorTaggingCPTools> m_flavor_tagging_CP_tools; - std::unique_ptr<top::TriggerCPTools> m_trigger_CP_tools; - std::unique_ptr<top::EgammaCPTools> m_egamma_CP_tools; - std::unique_ptr<top::MuonCPTools> m_muon_CP_tools; - std::unique_ptr<top::IsolationCPTools> m_isolation_CP_tools; - std::unique_ptr<top::TauCPTools> m_tau_CP_tools; - std::unique_ptr<top::JetMETCPTools> m_jetMET_CP_tools; - std::unique_ptr<top::GhostTrackCPTools> m_ghost_track_CP_tools; }; - } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTrackCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTrackCPTools.h new file mode 100644 index 0000000000000000000000000000000000000000..a73eec9711e4d6370546a093f44bdd4a5002c277 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTrackCPTools.h @@ -0,0 +1,68 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TOPCPTOOLS_TOPTRACKCPTOOLS_H_ +#define TOPCPTOOLS_TOPTRACKCPTOOLS_H_ + +// Include what you use +#include <vector> +#include <string> + +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "AsgTools/ToolHandleArray.h" +#include "AsgTools/AnaToolHandle.h" + +// Tracking include(s): +#include "InDetTrackSystematicsTools/InDetTrackSystematics.h" +#include "InDetTrackSystematicsTools/InDetTrackSmearingTool.h" +#include "InDetTrackSystematicsTools/InDetTrackBiasingTool.h" +#include "InDetTrackSystematicsTools/InDetTrackTruthFilterTool.h" +#include "InDetTrackSystematicsTools/InDetTrackTruthOriginTool.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" + +namespace top { + class TopConfig; + + class TrackCPTools final: public asg::AsgTool { + public: + explicit TrackCPTools(const std::string& name); + virtual ~TrackCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::vector<std::uint32_t> m_runPeriods; + + const std::string m_smearingToolName { + "top::TrackCPTools::InDetTrackSmearingTool" + }; + const std::string m_biasToolPrefix { + "top::TrackCPTools::InDetTrackBiasingTool" + }; + const std::string m_truthOriginToolName { + "top::TrackCPTools::InDetTrackTruthOriginTool" + }; + const std::string m_truthFilterToolName { + "top::TrackCPTools::InDetTrackTruthFilterTool" + }; + + ToolHandle<InDet::InDetTrackSmearingTool> m_smearingTool; + ToolHandle<InDet::InDetTrackTruthOriginTool> m_truthOriginTool; + ToolHandle<InDet::InDetTrackTruthFilterTool> m_truthFilterTool; + + ToolHandle<InDet::IInDetTrackSelectionTool> m_trkseltool; + + std::vector<ToolHandle<InDet::InDetTrackBiasingTool> > m_biasingTool; + + StatusCode setupSmearingTool(); + StatusCode setupBiasingTools(); + StatusCode setupTruthFilterTool(); + + }; +} // namespace top + +#endif // TOPCPTOOLS_TOPTRACKCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTriggerCPTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTriggerCPTools.h index 5a62acbfc49cfcefdb670bfb651c4a4b39f37384..360014344fe29b04b0c58097572d7e5512e3960e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTriggerCPTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCPTools/TopCPTools/TopTriggerCPTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCPTOOLS_TOPTRIGGERCPTOOLS_H_ #define TOPCPTOOLS_TOPTRIGGERCPTOOLS_H_ @@ -20,29 +20,38 @@ #include "TrigDecisionTool/TrigDecisionTool.h" #include "TriggerMatchingTool/IMatchingTool.h" #include "TrigTauMatching/ITrigTauMatching.h" +//#include "TriggerAnalysisInterfaces/ITrigGlobalEfficiencyCorrectionTool.h" +// Need to have these tools held in the class +#include "EgammaAnalysisInterfaces/IAsgElectronEfficiencyCorrectionTool.h" +#include "MuonAnalysisInterfaces/IMuonTriggerScaleFactors.h" namespace top { - -class TopConfig; - -class TriggerCPTools final : public asg::AsgTool { - public: - explicit TriggerCPTools(const std::string& name); - virtual ~TriggerCPTools() {} - - StatusCode initialize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - int m_release_series = 24; // Default to 2.4 - - ToolHandle<TrigConf::ITrigConfigTool> m_trigConfTool; - ToolHandle<Trig::TrigDecisionTool> m_trigDecisionTool; - ToolHandle<Trig::IMatchingTool> m_trigMatchTool; - ToolHandle<Trig::ITrigTauMatchingTool> m_trigMatchTauTool; - -}; + class TopConfig; + + class TriggerCPTools final: public asg::AsgTool { + public: + explicit TriggerCPTools(const std::string& name); + virtual ~TriggerCPTools() {} + + StatusCode initialize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + ToolHandle<TrigConf::ITrigConfigTool> m_trigConfTool; + ToolHandle<Trig::TrigDecisionTool> m_trigDecisionTool; + ToolHandle<Trig::IMatchingTool> m_trigMatchTool; + ToolHandle<Trig::ITrigTauMatchingTool> m_trigMatchTauTool; +// ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerEffTool; +// ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerEffToolLoose; + StatusCode initialiseGlobalTriggerEff(); + std::string mapWorkingPoints(const std::string& type); + + // Tool handles for the CP tools, need to be members here, or inaccessible to global trigger tool + asg::AnaToolHandle<CP::IMuonTriggerScaleFactors> m_muonTool; + asg::AnaToolHandle<CP::IMuonTriggerScaleFactors> m_muonToolLoose; + std::vector<asg::AnaToolHandle<IAsgElectronEfficiencyCorrectionTool> > m_electronToolsFactory; + std::vector<asg::AnaToolHandle<IAsgElectronEfficiencyCorrectionTool> > m_electronToolsFactoryLoose; + }; } // namespace top #endif // TOPCPTOOLS_TOPTRIGGERCPTOOLS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/CMakeLists.txt index 4f7b254566bd7319e75728b627dd987045181dcb..cf7eef726ca3068f5aca1fea56babe848bdeba6d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/CMakeLists.txt @@ -1,34 +1,41 @@ - # Declare the name of this package: atlas_subdir( TopConfiguration ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC + xAODCore + Tools/PathResolver + TopDataPreparation PATInterfaces ) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) -find_package( Boost REQUIRED COMPONENTS iostreams ) +find_package( Boost REQUIRED COMPONENTS iostreams regex ) + +message( STATUS "${Boost_LIBRARIES}" ) # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopConfiguration _cintDictSource - ROOT_HEADERS TopConfiguration/TopPersistentSettings.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopConfiguration Root/*.cxx Root/*.h Root/*.icc TopConfiguration/*.h TopConfiguration/*.icc TopConfiguration/*/*.h TopConfiguration/*/*.icc ${_cintDictSource} PUBLIC_HEADERS TopConfiguration - LINK_LIBRARIES PATInterfaces + LINK_LIBRARIES xAODCore + PATInterfaces + PathResolver + TopDataPreparation ${ROOT_LIBRARIES} - ${Boost_LIBRARIES} - INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} - ${Boost_INCLUDE_DIRS}) + ${Boost_LIBRARIES} + INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} + ${Boost_INCLUDE_DIRS}) # Install data files from the package: atlas_install_data( share/* ) # Install the python modules from the package -atlas_install_python_modules( python/*.py ) +atlas_install_scripts( python/AodMetaDataReader.py ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/AodMetaDataAccess.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/AodMetaDataAccess.cxx index 621dd8fb92694fde900753e367f77b24e59935fa..0797bca977b0d2a63d7a6633bb44906caa9e15a3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/AodMetaDataAccess.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/AodMetaDataAccess.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopConfiguration/AodMetaDataAccess.h" @@ -14,132 +14,145 @@ #include <unistd.h> #include <utility> #include <vector> +#include <string> +#include <iostream> #include <boost/algorithm/string.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> #include <boost/scope_exit.hpp> +#include "PathResolver/PathResolver.h" -namespace top { - +#include "TopConfiguration/MsgCategory.h" +using namespace TopConfiguration; -AodMetaDataAccess::AodMetaDataAccess() : m_data(nullptr) { } +namespace top { + AodMetaDataAccess::AodMetaDataAccess() : m_data(nullptr) { } -AodMetaDataAccess::~AodMetaDataAccess() { - delete m_data; -} + AodMetaDataAccess::~AodMetaDataAccess() { + delete m_data; + } + void AodMetaDataAccess::loadWithFilesFrom(std::string const& fileListPath) { + // Implementation using PathResolver + std::string filename = "AodMetaDataReader.py"; + // Use the path resolver to find the script which is stored as an executable in bin (no package name) + std::string exePath = PathResolver::find_file(filename, "PATH"); -void AodMetaDataAccess::loadWithFilesFrom(std::string const & fileListPath) { + if (exePath == "") { + throw std::runtime_error("ERROR::AodMetaDataAccess - could not find file \n" + filename); + } + ATH_MSG_INFO("AodMetaDataAccess::Found " << exePath); - char const * rootCoreBin = getenv("ROOTCOREBIN"); - assert(rootCoreBin && rootCoreBin[0]); - std::string exePath(rootCoreBin); - if (exePath.back() != '/') - exePath.append("/"); - exePath.append("python/TopConfiguration/AodMetaDataReader.py"); - int pipefd[2] = { -1, -1 }; - if (pipe(pipefd) == -1) - throw std::runtime_error("pipe() failed"); - int pid = fork(); - if (pid == -1) { - std::for_each(pipefd, pipefd+2, close); + int pipefd[2] = { + -1, -1 + }; + if (pipe(pipefd) == -1) throw std::runtime_error("pipe() failed"); + int pid = fork(); + if (pid == -1) { + std::for_each(pipefd, pipefd + 2, close); throw std::runtime_error("fork() failed"); - } + } - if (pid == 0) { + if (pid == 0) { close(pipefd[0]); - if (dup2(pipefd[1], STDOUT_FILENO) != -1) - execlp(exePath.c_str(), "AodMetaDataReader.py", "--format", "plain", "--files-from", fileListPath.c_str(), nullptr); + if (dup2(pipefd[1], STDOUT_FILENO) != -1) execlp( + exePath.c_str(), "AodMetaDataReader.py", "--format", "plain", "--files-from", fileListPath.c_str(), nullptr); perror("popen(AodMetaDataReader.py)"); _exit(1); - } + } - BOOST_SCOPE_EXIT(pid) { + BOOST_SCOPE_EXIT(pid) { int status; - while (waitpid(pid, &status, 0) == -1 && errno == EINTR); - } BOOST_SCOPE_EXIT_END - close(pipefd[1]); - - boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle); - - auto * data = new std::map< std::string, std::map< std::string, std::string > >(); // FIXME memory leak on exception - bool eof = false; - for (std::string line; std::getline(stream, line); ) { - if (eof) - throw std::runtime_error("received data from AodMetaDataReader after end-of-stream marker"); - if (line.empty()) { - eof = true; - } - else { - std::vector<std::string> tokens; - boost::split(tokens, line, boost::is_any_of("\t")); - if (tokens.size() != 3) - throw std::runtime_error("received malformed record from AodMetaDataReader"); - auto & folder = (*data)[tokens[0]]; - bool inserted = folder.insert(std::make_pair(tokens[1], tokens[2])).second; - if (!inserted) - throw std::runtime_error("received duplicate entry from AodMetaDataReader"); - } - } - if (!eof) - throw std::runtime_error("data stream from AodMetaDataReader not properly terminated"); - m_data = data; -} + while (waitpid(pid, &status, 0) == -1 && errno == EINTR) ; + } BOOST_SCOPE_EXIT_END + close(pipefd[1]); -std::string AodMetaDataAccess::get(std::string const & folderName, std::string const & keyName) const { - if (m_data == nullptr) - throw std::logic_error("meta-data not loaded"); - auto it1 = m_data->find(folderName); - if (it1 == m_data->end()) - throw std::logic_error("the folderName "+folderName+" does not exist in the metadata"); - auto const & folder = it1->second; - auto it2 = folder.find(keyName); - if (it2 == folder.end()) - throw std::logic_error("the keyName "+keyName+" does not exist in the metadata"); - - return m_data->at(folderName).at(keyName); -} - - -std::string AodMetaDataAccess::get(std::string const & folderName, std::string const & keyName, std::string const & defaultValue) const { - if (m_data == nullptr) - throw std::logic_error("meta-data not loaded"); - auto it1 = m_data->find(folderName); - if (it1 == m_data->end()) - return defaultValue; - auto const & folder = it1->second; - auto it2 = folder.find(keyName); - if (it2 == folder.end()) - return defaultValue; - return it2->second; -} + boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], + boost::iostreams::close_handle); + auto* data = new std::map< std::string, std::map< std::string, std::string > >(); // FIXME memory leak on exception + bool eof = false; + for (std::string line; std::getline(stream, line); ) { + if (eof) throw std::runtime_error("received data from AodMetaDataReader after end-of-stream marker"); + if (line.empty()) { + eof = true; + } else { + std::vector<std::string> tokens; + boost::split(tokens, line, boost::is_any_of("\t")); + if (tokens.size() != 3) throw std::runtime_error("received malformed record from AodMetaDataReader"); + auto& folder = (*data)[tokens[0]]; + bool inserted = folder.insert(std::make_pair(tokens[1], tokens[2])).second; + if (!inserted) throw std::runtime_error("received duplicate entry from AodMetaDataReader"); + } + } + if (!eof) throw std::runtime_error("data stream from AodMetaDataReader not properly terminated"); + m_data = data; + } + + std::string AodMetaDataAccess::get(std::string const& folderName, std::string const& keyName) const { + if (m_data == nullptr) throw std::logic_error("meta-data not loaded"); + auto it1 = m_data->find(folderName); + if (it1 == + m_data->end()) throw std::logic_error("the folderName " + folderName + " does not exist in the metadata"); + auto const& folder = it1->second; + auto it2 = folder.find(keyName); + if (it2 == folder.end()) throw std::logic_error("the keyName " + keyName + " does not exist in the metadata"); + + return m_data->at(folderName).at(keyName); + } + + std::string AodMetaDataAccess::get(std::string const& folderName, std::string const& keyName, + std::string const& defaultValue) const { + if (m_data == nullptr) throw std::logic_error("meta-data not loaded"); + auto it1 = m_data->find(folderName); + if (it1 == m_data->end()) return defaultValue; + + auto const& folder = it1->second; + auto it2 = folder.find(keyName); + if (it2 == folder.end()) return defaultValue; + + return it2->second; + } + + bool AodMetaDataAccess::valid() const { + return(m_data != nullptr); + } + + bool AodMetaDataAccess::isSimulation() const { + auto projectName = get("/TagInfo", "project_name"); + + if (boost::equals(projectName, "IS_SIMULATION")) return true; + + if (boost::starts_with(projectName, "data")) return false; + + throw std::invalid_argument("unrecognized value in meta-data entry for key 'project_name'"); + } + + bool AodMetaDataAccess::IsEventOverlayInputSim() const { + std::string overlay; + try { + overlay = get("/Simulation/Parameters", "IsEventOverlayInputSim"); + } catch (const std::logic_error& e) { + // the key does not exists - is data most likely + return false; + } -bool AodMetaDataAccess::valid() const { - return (m_data != nullptr); -} + if (boost::iequals(overlay, "TRUE")) return true; + + return false; + } + bool AodMetaDataAccess::isAFII() const { + if (!isSimulation()) return false; // No need to check if not MC -bool AodMetaDataAccess::isSimulation() const { - auto projectName = get("/TagInfo", "project_name"); - if (boost::equals(projectName, "IS_SIMULATION")) + auto simulatorName = get("/Simulation/Parameters", "Simulator"); + if (boost::equals(simulatorName, "ATLFASTII")) // AFII will have this simulator return true; - if (boost::starts_with(projectName, "data")) - return false; - throw std::invalid_argument("unrecognized value in meta-data entry for key 'project_name'"); -} - -bool AodMetaDataAccess::isAFII() const{ - if (!isSimulation()) return false; // No need to check if not MC - auto simulatorName = get("/Simulation/Parameters","Simulator"); - if (boost::equals(simulatorName, "ATLFASTII")) // AFII will have this simulator - return true; - else return false; // Otherwise must be FullSim -} - + else return false; // Otherwise must be FullSim + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/ConfigurationSettings.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/ConfigurationSettings.cxx index e6ec9d370c875f8f6fd9e6011d69deab26734469..c519b907ff5c63db64cc3a130125c01d0733aa84 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/ConfigurationSettings.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/ConfigurationSettings.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopConfiguration/ConfigurationSettings.h" @@ -14,232 +14,507 @@ #include <boost/algorithm/string/trim_all.hpp> namespace top { + ConfigurationSettings* ConfigurationSettings::m_instance = 0; -ConfigurationSettings* ConfigurationSettings::m_instance = 0; - -ConfigurationSettings::ConfigurationSettings() : m_configured(false) { + ConfigurationSettings::ConfigurationSettings() : m_configured(false) { registerParameter("ElectronCollectionName", "Name of the Electron container"); + registerParameter("FwdElectronCollectionName", "Name of the Forward Electrons container, ForwardElectrons or None (default)", "None"); registerParameter("MuonCollectionName", "Name of the Muon container"); registerParameter("PhotonCollectionName", "Name of the Photon container"); registerParameter("JetCollectionName", "Name of the Jet container"); registerParameter("LargeJetCollectionName", "Name of the large-R Jet container"); - registerParameter("LargeJetSubstructure", "Setup to use when applying grooming on the large-R jet"); - registerParameter("TrackJetCollectionName", "Name of the track Jet container","None"); + registerParameter("LargeJetSubstructure", "Setup to use when applying grooming on the large-R jet", "None"); + registerParameter("TrackJetCollectionName", "Name of the track Jet container", "None"); + registerParameter("TrackCollectionName", "Name of the track container", "None"); registerParameter("TauCollectionName", "Name of the Tau container"); registerParameter("JetGhostTrackDecoName", "Name of the jet decoration that holds the ghost-associated track.", "None"); registerParameter("TruthCollectionName", "Name of the Truth container"); - registerParameter("TruthElectronCollectionName", "Name of the Truth Electron container", "TruthElectrons" ); + registerParameter("TruthElectronCollectionName", "Name of the Truth Electron container", "TruthElectrons"); registerParameter("TruthMuonCollectionName", "Name of the Truth Muon container", "TruthMuons"); registerParameter("TruthPhotonCollectionName", "Name of the Truth Photon container", "None"); registerParameter("TruthMETCollectionName", "Name of the Truth MET container", "MET_Truth"); registerParameter("TruthJetCollectionName", "Name of the Truth Jet container"); registerParameter("TruthLargeRJetCollectionName", "Name of the Truth Large R Jet container", "None"); + registerParameter("TruthTauCollectionName", "Name of the Truth tau container", "None"); registerParameter("applyTTVACut", "Decide if to apply lepton z0/d0 cuts", "True"); - - registerParameter("GRLDir","Location of GRL File","TopAnalysis"); - registerParameter("GRLFile","Name of GRL File", " "); - registerParameter("DumpBtagSystsInSystTrees", "Dump systematics-shifted b-tagging SFs in systematic TTrees, True or False (default: False)","False"); + registerParameter("GRLDir", "Location of GRL File", "TopAnalysis"); + registerParameter("GRLFile", "Name of GRL File", " "); + + registerParameter("TDPPath", "Path to TopDataPreparation file (accessible via PathResolver)", + "dev/AnalysisTop/TopDataPreparation/XSection-MC16-13TeV.data"); - registerParameter("ElectronID", "Type of electron. IsEM : Loose, Medium, Tight or Likelihood LooseAndBLayerLH, MediumLH, TightLH","TightLH"); - registerParameter("ElectronIDLoose", "Type of electron for background. IsEM : Loose, Medium, Tight or Likelihood LooseAndBLayerLH, MediumLH, TightLH","MediumLH"); + registerParameter("DumpBtagSystsInSystTrees", + "Dump systematics-shifted b-tagging SFs in systematic TTrees, True or False (default: False)", + "False"); + registerParameter("StorePerJetBtagSFs", "Store per-jet btag SFs", "False"); + + registerParameter("ElectronID", "Type of electron. Likelihood LooseAndBLayerLH, MediumLH, TightLH", "TightLH"); + registerParameter("ElectronIDLoose", + "Type of electron for background. Likelihood LooseAndBLayerLH, MediumLH, TightLH", "MediumLH"); registerParameter("ElectronPt", "Electron pT cut for object selection (in MeV). Default 25 GeV.", "25000."); - registerParameter("EgammaSystematicModel","Egamma Systematic model : FULL_v1 , FULL_ETACORRELATED_v1 , 1NP_v1 (default)","1NP_v1"); - registerParameter("ElectronIsolation","Isolation to use : Gradient, GradientLoose, FixedCutTight, FixedCutTightTrackOnly, FixedCutLoose, LooseTrackOnly, Loose, Tight, None","Gradient"); - registerParameter("ElectronIsolationLoose","Isolation to use : Gradient, GradientLoose, FixedCutTight, FixedCutTightTrackOnly, FixedCutLoose, LooseTrackOnly, Loose, Tight, None","None"); - registerParameter("ElectronIsoSFs", "True/False. Set to False to allow unsupported ID/isolation WP combinations to be used.", "True"); - registerParameter("ElectronVetoLArCrack", "True/False. Set to False to disable LAr crack veto (not recommended).", "True"); + registerParameter("EgammaSystematicModel", "Egamma Calibration Systematic model : FULL_v1 , 1NP_v1 (default)", + "1NP_v1"); + registerParameter("ElectronEfficiencySystematicModel", + "Electron Efficiency Systematic model : FULL, SIMPLIFIED, TOTAL (default)", "TOTAL"); + registerParameter("ElectronEfficiencySystematicModelEtaBinning", + "Electron Efficiency Systematic model eta binning (option for SIMPLIFIED model, do not specify to use default; format XXX:YYY:ZZZ, e.g. 0.0:1.37:4.9)", + "default"); + registerParameter("ElectronEfficiencySystematicModelEtBinning", + "Electron Efficiency Systematic model E_T binning (option for SIMPLIFIED model, do not specify to use default; format XXX:YYY:ZZZ. e.g. 4000:7000:10000:15000:13000000)", + "default"); + registerParameter("ElectronIsolation", + "Isolation to use : Gradient, FCLoose, FCTight, FCHighPtCaloOnly, PLVTight, PLVLoose, (EXPERIMENTAL: HighPtCaloOnly, Loose, Tight, TightTrackOnly, TightTrackOnly_FixedRad), (DANGEROUS: PflowTight, PflowLoose), None", + "FCTight"); + registerParameter("ElectronIsolationLoose", + "Isolation to use : Gradient, FCLoose, FCTight, FCHighPtCaloOnly, PLVTight, PLVLoose, (EXPERIMENTAL: HighPtCaloOnly, Loose, Tight, TightTrackOnly, TightTrackOnly_FixedRad), (DANGEROUS: PflowTight, PflowLoose), None", + "None"); + registerParameter("ElectronIsolationSF", "Force electron isolation SF (e.g. None). EXPERIMENTAL!", " "); + registerParameter("ElectronIsolationSFLoose", "Force electron isolation SF (e.g. None). EXPERIMENTAL!", " "); + registerParameter("ElectronVetoLArCrack", "True/False. Set to False to disable LAr crack veto (not recommended).", + "True"); + registerParameter("UseElectronChargeIDSelection", + "True/False. Switch on/off electron charge ID selection (Default False).", "False"); + registerParameter("UseEgammaLeakageCorrection", + "True/False. Switch on/off leakage correction -- REQUIRES ptag>p3947 (Default True).", "True"); + registerParameter("EnablePromptLeptonImprovedVetoStudies", + "True/False. Adds the (many!) variables necessary to validate the PromptLeptonImprovedVeto electron+muon isolation -- TEMPORARY, for studies only (Default False).", "False"); + + registerParameter("FwdElectronID", "Type of fwd electron. Loose, Medium, Tight (default)", "Tight"); + registerParameter("FwdElectronIDLoose", "Type of fwd loose electrons. Loose, Medium, Tight (default)", "Tight"); + registerParameter("FwdElectronPt", "Fwd Electron pT cut for object selection (in MeV). Default 25 GeV.", "25000."); + registerParameter("FwdElectronMinEta", "Fwd Electron lower |eta| cut for object selection. Default 2.5", "2.5"); + registerParameter("FwdElectronMaxEta", "Fwd Electron upper |eta| cut for object selection. Default 4.9", "4.9"); + registerParameter("FwdElectronBCIDCleaningRunRange", + "Specify run range for which the BCID cleaning must be applied for fwd el. in data: \"XXX:YYY\"; the cleaning will be applied for XXX<=runNumber<=YYY", + "266904:311481"); + registerParameter("PhotonPt", "Photon pT cut for object selection (in MeV). Default 25 GeV.", "25000."); registerParameter("PhotonEta", "Absolute Photon eta cut for object selection. Default 2.5.", "2.5"); - registerParameter("PhotonID","Type of photon. Definition to use : Tight, Loose and None.","Tight"); - registerParameter("PhotonIDLoose","Type of photon for background. Definition to use : Tight, Loose, None.","Loose"); - registerParameter("PhotonIsolation","Isolation to use : FixedCutTight, FixedCutLoose, None.","FixedCutTight"); - registerParameter("PhotonIsolationLoose","Isolation to use : FixedCutTight, FixedCutLoose, None.","FixedCutLoose"); - registerParameter("PhotonUseRadiativeZ", "True/False. Set to True to enable photon radiative Z up to 100 GeV.", "False"); + registerParameter("PhotonID", "Type of photon. Definition to use : Tight, Loose and None.", "Tight"); + registerParameter("PhotonIDLoose", "Type of photon for background. Definition to use : Tight, Loose, None.", + "Loose"); + registerParameter("PhotonIsolation", + "Isolation to use : FixedCutTightCaloOnly, FixedCutTight, FixedCutLoose, (EXPERIMENTAL: TightCaloOnly, Tight, Loose), None.", + "FixedCutTight"); + registerParameter("PhotonIsolationLoose", + "Isolation to use : FixedCutTightCaloOnly, FixedCutTight, FixedCutLoose, (EXPERIMENTAL: TightCaloOnly, Tight, Loose), None.", + "FixedCutLoose"); registerParameter("MuonPt", "Muon pT cut for object selection (in MeV). Default 25 GeV.", "25000"); - registerParameter("MuonEta", "Absolute Muon eta cut for object selection. Default 2.5.", "2.5" ); - registerParameter("MuonQuality", "Muon quality cut for object selection. Options are VeryLoose, Loose, Medium (default) and Tight", "Medium"); - registerParameter("MuonQualityLoose", "Muon quality cut for object selection. Options are VeryLoose, Loose, Medium (default) and Tight", "Medium"); - registerParameter("MuonIsolation","Isolation to use : Gradient, GradientLoose, Tight, Loose, LooseTrackOnly, FixedCutTightTrackOnly, FixedCutLoose, None","Gradient"); - registerParameter("MuonIsolationLoose","Isolation to use : Gradient, GradientLoose, Tight, Loose, LooseTrackOnly, FixedCutTightTrackOnly, FixedCutLoose, None","None"); + registerParameter("MuonEta", "Absolute Muon eta cut for object selection. Default 2.5.", "2.5"); + registerParameter("MuonQuality", + "Muon quality cut for object selection. Options are VeryLoose, Loose, Medium (default) and Tight", + "Medium"); + registerParameter("MuonQualityLoose", + "Muon quality cut for object selection. Options are VeryLoose, Loose, Medium (default) and Tight", + "Medium"); + registerParameter("MuonUseMVALowPt", + "Turn on MVA for low-pT muons (only for LowPt WP). Optimized to improve efficiency and hadron rejection. - Default: False", + "False"); + registerParameter("MuonUse2stationHighPt", + "Allows muon reconstruction using 2-station muons with missing inner MS station for |eta|<1.3 - Default: True (only for HighPt)", + "True"); + registerParameter("MuonUseMVALowPtLoose", + "Turn on MVA for low-pT muons (only for LowPt WP) for Loose tree. Optimized to improve efficiency and hadron rejection. - Default: False", + "False"); + registerParameter("MuonUse2stationHighPtLoose", + "Allows muon reconstruction using 2-station muons with missing inner MS station for |eta|<1.3 for Loose tree - Default: True (only for HighPt)", + "True"); + registerParameter("MuonIsolation", + "Isolation to use : PflowTight_VarRad, PflowTight_FixedRad, PflowLoose_VarRad, PflowLoose_FixedRad, HighPtTrackOnly, TightTrackOnly_VarRad, TightTrackOnly_FixedRad, PLVTight, PLVLoose, Tight_VarRad, Tight_FixedRad, Loose_VarRad, Loose_FixedRad, FCTight, FCLoose, FCTightTrackOnly, FCTightTrackOnly_FixedRad, FCLoose_FixedRad, FCTight_FixedRad, FixedCutPflowTight, FixedCutPflowLoose, FCTight_FixedRad, None", + "PflowTight_FixedRad"); + registerParameter("MuonIsolationLoose", + "Isolation to use : PflowTight_VarRad, PflowTight_FixedRad, PflowLoose_VarRad, PflowLoose_FixedRad, HighPtTrackOnly, TightTrackOnly_VarRad, TightTrackOnly_FixedRad, PLVTight, PLVLoose, Tight_VarRad, Tight_FixedRad, Loose_VarRad, Loose_FixedRad, FCTight, FCLoose, FCTightTrackOnly, FCTightTrackOnly_FixedRad, FCLoose_FixedRad, FCTight_FixedRad, FixedCutPflowTight, FixedCutPflowLoose, FCTight_FixedRad, None", + "None"); + registerParameter("MuonIsolationSF", "Force muon isolation SF (e.g. None). EXPERIMENTAL!", " "); + registerParameter("MuonIsolationSFLoose", "Force muon isolation SF (e.g. None). EXPERIMENTAL!", " "); + registerParameter("MuonDoSmearing2stationHighPt", "True/False, to turn on/off spacial corrections for 2-station muons reconstruction with missing inner MS station allowed for abs(eta)<1.3, only with MuonQuality HighPt. - Default: True", "True"); + registerParameter("MuonDoExtraSmearingHighPt", "True/False, To be used by analyses willing to check their sensitivity to momentum resolution effects at large muon momenta. - Default: false", "false"); registerParameter("UseAntiMuons", "Use AntiMuons for fake estimate. Default: false", "false"); + registerParameter("UseSoftMuons", "True to use soft muons, False (default) otherwise", "False"); + registerParameter("SoftMuonPt", "Soft Muon pT cut for object selection (in MeV). Default 4 GeV.", "4000"); + registerParameter("SoftMuonEta", "Absolute Soft Muon eta cut for object selection. Default 2.5.", "2.5"); + registerParameter("SoftMuonQuality", + "Soft Muon quality cut for object selection. Options are Loose, Medium, Tight (default), LowPt", + "Tight"); + registerParameter("SoftMuonUseMVALowPt", + "Turn on MVA for low-pT soft muons (only for LowPt WP). Optimized to improve efficiency and hadron rejection. - Default: False", + "False"); + registerParameter("SoftMuonDRJet", + "Soft Muon maximum dR wrt nearest selected jet. Can be set to 999. to keep all soft muons. Default 0.4", + "0.4"); + registerParameter("SoftMuonDRJetUseRapidity", + "How to calculate DR(soft muon,jet) for the SoftMuonDRJet cut: True -> use rapidity; False -> use pseudorapidity. Default False", + "False"); + registerParameter("SoftMuonAdditionalTruthInfo", + "Experimental: store additional truth information on soft muons particle-level origin: True or False (default)", + "False"); + registerParameter("SoftMuonAdditionalTruthInfoCheckPartonOrigin", + "Experimental: store additional truth information on soft muons parton-level origin; requires SoftMuonAdditionalTruthInfo to be true; automatically disabled if PS!=pythia8 and PS!=herwigpp : True or False (default)", + "False"); + registerParameter("SoftMuonAdditionalTruthInfoDoVerbose", + "Debug output for soft muon additional truth-level information: True or False (default)", + "False"); registerParameter("JetPt", "Jet pT cut for object selection (in MeV). Default 25 GeV.", "25000."); - registerParameter("JetEta", "Absolute Jet eta cut for object selection. Default 2.5.", "2.5" ); - registerParameter("FwdJetAndMET", "Forward jet selection and corresponding MET calculation." - "Default (does nothing on forward jets), fJVT (apply fJVT cut if pT<50GeV and |eta|>2.5), Tight (requires pT>30GeV if |eta|>2.5).", "Default"); - registerParameter("JetUncertainties_BunchSpacing", - "25ns (default) or 50ns - for JetUncertainties", - "25ns"); -// registerParameter("JetUncertainties_NPModel","AllNuisanceParameters, 19NP or 3NP (default) - for JetUncertainties","3NP"); - registerParameter("JetUncertainties_NPModel","AllNuisanceParameters, 29NP_ByCategory, or 21NP (default) - for JetUncertainties","21NP"); - registerParameter("LargeRSmallRCorrelations", - "Do large-small R jet correlation systematics - True or False (default)", - "False"); - registerParameter("JetJERSmearingModel","Full (inc data smearing) or Simple (default)","Simple"); - registerParameter("JetCalibSequence","Jet calibaration sequence, GSC (default) or JMS","GSC"); - registerParameter("JVTinMETCalculation", "Perfom a JVT cut on the jets in the MET recalculation? True (default) or False.", "True" ); - - registerParameter("JSF", "Used for top mass analysis, default is 1.0", "1.0"); + registerParameter("JetEta", "Absolute Jet eta cut for object selection. Default 2.5.", "2.5"); + + registerParameter("JVTinMETCalculation", + "Perfom a JVT cut on the jets in the MET recalculation? True (default) or False.", "True"); + registerParameter("SaveFailJVTJets", "Save the jets that failed the JVT cut? False (default) or True.", "False"); + registerParameter("JVTWP", "Set JVT WP, default is set to \'Default\' (Tight for PFlow and Medium for Topo).", + "Default"); + registerParameter("ForwardJVTWP", "Set fJVT Working Point for selecting forward jets (|eta|>2.5 & 20GeV<pT<60GeV)" + "\'None\': No fJVT (doesn't run tool for selection) - use this if you don't have forward jets in your selection or if using using PFlow jets with a derivation older than p4173, \'Tight\' (fJVT<0.4, recommended), \'Medium\': (fJVT<0.5, if combined with ForwardJVTinMETCalculation this will set MET WP to Tenacious with stricter JVTinMET requirements", + "None"); + registerParameter("ForwardJVTinMETCalculation", + "Use fJVT cut on forward jets to improve resolution in the MET recalculation? \'False\' (default - must set false if using pflow jets with derivations older than P4173), or \'True\'", "False"); + registerParameter("SaveFailForwardJVTJets", "Save the jets that failed the fJVT cut? \'False\' (default), or \'True\'", "False"); + registerParameter("AdvancedUsage_METUncertaintiesConfigDir", "Path to directory containing MET uncertainties configs (including trailing /) \'Latest\' (default), or previous \'METUtilities/data17_13TeV/prerec_Jan16/\'", "Latest"); + + registerParameter("JetPtGhostTracks", + "Jet pT threshold for ghost track systematic variations calculation (in MeV). Default 25 GeV.", + "25000."); + registerParameter("JetEtaGhostTracks", + "Jet eta threshold for ghost track systematic variations calculation. Default 2.5", + "2.5"); + registerParameter("GhostTrackspT", + "PT of the ghost tracks associated small-R jets (in MeV). Default 500 MeV.", + "500."); + registerParameter("GhostTracksVertexAssociation", + "WP of the ghost track vertex association. Option: none, nominal and tight. Default nominal.","nominal"); + registerParameter("GhostTracksQuality", + "WP of the ghost track quality. Option: TightPrimary, LoosePrimary. Loose, NoCut. Default TightPrimary.","TightPrimary"); + registerParameter("JetUncertainties_NPModel", + "AllNuisanceParameters, CategoryReduction (default), GlobalReduction, StrongReduction - for JetUncertainties", + "CategoryReduction"); + registerParameter("JetUncertainties_QGFracFile", "To specify a root file with quark/gluon fractions," + " in order to reduce FlavourComposition and response uncertainties." + " Default: None (i.e. no file is used and default flat 50+/-50% fraction is used).", + "None"); + registerParameter("JetUncertainties_QGHistPatterns", "To specify a pattern for the name of the quark/gluon fractions histograms, or a list of DSIDs which will have their specific histogram." + " Two syntaxes are possible, either a single string or a list of DSIDs separated by commas:" + " \"MyQGHisto\" (the histograms with \"MyQGHisto\" in their names will be used for all DSIDs)," + " \"410470,410472,345873,345874,345875\" (for the listed DSIDs, histograms with the processed DSID will be used, while the flat 50+/-50% fraction will be used for the other DSIDs)." + " Default: None (i.e. no specific pattern is looked for in the name of the provided histograms).", + "None"); + registerParameter("JetJERSmearingModel", + "All (inc. data smearing), All_PseudoData (use MC as pseudo-data), Full (inc. data smearing), Full_PseudoData (use MC as pseudo-data) or Simple (MC only - default)", + "Simple"); + registerParameter("JetCalibSequence", "Jet calibaration sequence, GSC (default) or JMS", "GSC"); + registerParameter("StoreJetTruthLabels", "Flag to store truth labels for jets - True (default) or False", "True"); + + registerParameter("JSF", "Used for top mass analysis, default is 1.0", "1.0"); registerParameter("bJSF", "Used for top mass analysis, default is 1.0", "1.0"); - registerParameter("LargeRJetPt", "Track Jet pT cut for object selection (in MeV). Default 7 GeV.", "25000."); - registerParameter("LargeRJetEta", "Absolute large-R jet eta cut for object selection. Default 2.0.", "2.0" ); - registerParameter("LargeRJESUncertaintyConfig", - "Variables to be varied with JES uncertainties. Options:D2Beta1,Tau21WTA,Tau32WTA,Split12,Split23,Qw ( default Split23,Tau32WTA)", - "Split23,Tau32WTA"); + registerParameter("LargeRJetPt", "LargeRJet pT cut for object selection (in MeV). Default 150 GeV.", "150000."); + registerParameter("LargeRJetEta", "Absolute large-R jet eta cut for object selection. Default 2.0.", "2.0"); + registerParameter("LargeRJetSubstructureVariables", "List of substructure variables stored in the output separated by commas. By default no variable is added to output.", " "); + registerParameter("LargeRJetUncertainties_NPModel", + "AllNuisanceParameters, CategoryReduction (default), GlobalReduction, - for LCTopo Large-R Jet Uncertainties or Scale_TCC_all - for TCC Large-R Jet Uncertainties", + "CategoryReduction"); + registerParameter("AdvancedUsage_LargeRJetUncertaintiesConfigDir", + "Path to directory containing large-R jet uncertainties config", + "rel21/Summer2019"); registerParameter("LargeRJESJMSConfig", - "Calibration for large-R JES/JMS. CombinedMass or CaloMass (default CombinedMass).", - "CombinedMass"); - - registerParameter("TrackJetPt", "Track Jet pT cut for object selection (in MeV). Default 7 GeV.", "7000."); - registerParameter("TrackJetEta", "Absolute Track Jet eta cut for object selection. Default 2.5.", "2.5" ); - - registerParameter("RCJetPt", "Reclustered Jet pT cut for object selection (in MeV). Default 100000 MeV.", "100000."); - registerParameter("RCJetEta", "Reclustered Jet eta cut for object selection. Default 2.0.", "2.0"); - registerParameter("RCJetTrim", "Reclustered Jet trimming cut for object selection. Default 0.05.", "0.05"); - registerParameter("RCJetRadius", "Reclustered Jet radius for object selection. Default 1.0", "1.0"); - registerParameter("UseRCJets", "Use Reclustered Jets. Default False.", "False"); - - registerParameter("VarRCJetPt", "Reclustered Jet (variable-R) pT cut for object selection (in MeV). Default 100000 MeV.", "100000."); - registerParameter("VarRCJetEta", "Reclustered Jet (variable-R) eta cut for object selection. Default 2.0.", "2.0"); - registerParameter("VarRCJetTrim", "Reclustered Jet (variable-R) trimming cut for object selection. Default 0.05.", "0.05"); - registerParameter("VarRCJetMaxRadius", "Reclustered Jet (variable-R) max. radius cut for object selection. Default 1.0", "1.0"); - registerParameter("VarRCJetRho", "Reclustered Jet (variable-R) list of rho values (). Default 2.", "2"); - registerParameter("VarRCJetMassScale", "Reclustered Jet (variable-R) list of mass scale values (m_w,m_z,m_h,m_t). By default use all.", "m_w,m_z,m_h,m_t"); - registerParameter("UseVarRCJets", "Use Reclustered Jets (Variable-R Jets). Default False.", "False"); + "Calibration for large-R JES/JMS. CombMass, CaloMass or TCCMass (default CombMass).", + "CombMass"); + registerParameter("BoostedJetTagging", + "Boosted jet taggers to use in the analysis, separated by commas or white spaces." + " By default, no tagger is used.", + " "); + + registerParameter("TrackJetPt", "Track Jet pT cut for object selection (in MeV). Default 10 GeV.", "10000."); + registerParameter("TrackJetEta", "Absolute Track Jet eta cut for object selection. Default 2.5.", "2.5"); + + registerParameter("TrackPt", "Track pT cut for object selection (in MeV). Default 0.5 GeV.", "0.5"); + registerParameter("TrackEta", "Absolute Track eta cut for object selection. Default 2.5.", "2.5"); + registerParameter("TrackQuality", + "Track quality cut for object selection. Options are TightPrimary,...", + "TightPrimary"); + + + registerParameter("RCJetPt", "Reclustered Jet pT cut for object selection (in MeV). Default 100000 MeV.", + "100000."); + registerParameter("RCJetEta", "Reclustered Jet eta cut for object selection. Default 2.0.", "2.0"); + registerParameter("RCInputJetPtMin", "Min Pt cut for RC jet inputs collection. Parameter is shared between RC and VarRC jets. Default 30000. [MeV]", "30000."); + registerParameter("RCInputJetEtaMax", "Max |Eta| cut for RC jet inputs collection. Parameter is shared between RC and VarRC jets. Default 2.5", "2.5"); + registerParameter("RCJetTrim", "Reclustered Jet trimming cut for object selection. Default 0.05.", "0.05"); + registerParameter("RCJetRadius", "Reclustered Jet radius for object selection. Default 1.0", "1.0"); + registerParameter("UseRCJetSubstructure", "Calculate Reclustered Jet Substructure Variables. Default False", + "False"); + registerParameter("UseRCJetAdditionalSubstructure", + "Calculate Additional Reclustered Jet Substructure Variables. Default False", "False"); + + registerParameter("UseRCJets", "Use Reclustered Jets. Default False.", "False"); + + registerParameter("VarRCJetPt", + "Reclustered Jet (variable-R) pT cut for object selection (in MeV). Default 100000 MeV.", + "100000."); + registerParameter("VarRCJetEta", "Reclustered Jet (variable-R) eta cut for object selection. Default 2.0.", "2.0"); + registerParameter("VarRCJetTrim", "Reclustered Jet (variable-R) trimming cut for object selection. Default 0.05.", + "0.05"); + registerParameter("VarRCJetMaxRadius", + "Reclustered Jet (variable-R) max. radius cut for object selection. Default 1.0", "1.0"); + registerParameter("VarRCJetRho", "Reclustered Jet (variable-R) list of rho values (). Default 2.", "2"); + registerParameter("VarRCJetMassScale", + "Reclustered Jet (variable-R) list of mass scale values (m_w,m_z,m_h,m_t). By default use all.", + "m_w,m_z,m_h,m_t"); + registerParameter("UseVarRCJets", "Use Reclustered Jets (Variable-R Jets). Default False.", "False"); + registerParameter("UseVarRCJetSubstructure", + "Calculate Variable-R Reclustered Jet Substructure Variables. Default False", "False"); + registerParameter("UseVarRCJetAdditionalSubstructure", + "Calculate Additional Variable-R Reclustered Jet Substructure Variables. Default False", "False"); registerParameter("TauPt", - "Pt cut applied to both tight and loose taus (in MeV)." - "Default 25 GeV.", - "25000"); + "Pt cut applied to both tight and loose taus (in MeV)." + "Default 25 GeV.", + "25000"); + registerParameter("TauEtaRegions", + "Eta regions used for both tight and loose taus." + "Default vetoing crack region [0., 1.37, 1.52, 2.5]", + "[0., 1.37, 1.52, 2.5]"); registerParameter("TauJetIDWP", - "Tau jet IDWP (None, Loose, Medium, Tight, LooseNotMedium, LooseNotTight, MediumNotTight, NotLoose)." - "Default Medium.", - "Medium"); + "Tau jet IDWP (None, Loose, Medium, Tight, LooseNotMedium, LooseNotTight, MediumNotTight, NotLoose, RNNLoose, RNNMedium, RNNTight)." + "Default RNNMedium.", + "RNNMedium"); registerParameter("TauJetIDWPLoose", - "Loose Tau jet IDWP (None, Loose, Medium, Tight, LooseNotMedium, LooseNotTight, MediumNotTight, NotLoose)." - "Default None.", - "Medium"); + "Loose Tau jet IDWP (None, Loose, Medium, Tight, LooseNotMedium, LooseNotTight, MediumNotTight, NotLoose)." + "Default RNNLoose.", + "RNNLoose"); registerParameter("TauEleBDTWP", - "Tau electron BDT WP (None, Loose, Medium, Tight)." + "Tau electron BDT WP (None, Loose, Medium, Tight, OldLoose, OldMedium)." "Default Loose.", "Loose"); registerParameter("TauEleBDTWPLoose", - "Loose Tau electron BDT WP (None, Loose, Medium, Tight)." + "Loose Tau electron BDT WP (None, Loose, Medium, Tight, OldLoose, OldMedium)." "Default Loose.", "Loose"); registerParameter("TauEleOLR", - "Apply tau-electron overlap removal (True/False)." - "Default False", - "False"); + "Apply tau-electron overlap removal (True/False)." + "Default False", + "False"); registerParameter("TauEleOLRLoose", - "Apply loose tau-electron overlap removal (True/False)." - "Default False", - "False"); + "Apply loose tau-electron overlap removal (True/False)." + "Default False", + "False"); registerParameter("TauJetConfigFile", - "Config file to configure tau selection. " - "If anything other than 'Default'" - "then all cuts are taken from the " - "config file rather than other options.", - "Default"); + "Config file to configure tau selection. " + "If anything other than 'Default'" + "then all cuts are taken from the " + "config file rather than other options.", + "Default"); registerParameter("TauJetConfigFileLoose", - "Config file to configure loose tau selection. " - "If anything other than 'Default'" - "then all cuts are taken from the " - "config file rather than other options.", - "Default"); + "Config file to configure loose tau selection. " + "If anything other than 'Default'" + "then all cuts are taken from the " + "config file rather than other options.", + "Default"); registerParameter("ApplyTauMVATES", - "Apply new Tau energy calibration based on substructure information and regression, True or False (default).", + "Apply new Tau energy calibration based on substructure information and regression. Must be True. Deprecated.", + "True"); + registerParameter("TauSFDoRNNID", + "Save SF for RNN tau ID True/False", + "True"); + registerParameter("TauSFDoBDTID", + "Save SF for BDT tau ID True/False", "False"); - - registerParameter("Systematics", "What to run? Nominal (just the nominal), All(do all systematics) " , "Nominal"); + + registerParameter("Systematics", "What to run? Nominal (just the nominal), All(do all systematics) ", "Nominal"); registerParameter("LibraryNames", "Names of any libraries that need loading"); - registerParameter("UseAodMetaData", "Whether to read xAOD meta-data from input files (default: False)", "False"); + registerParameter("UseAodMetaData", "Whether to read xAOD meta-data from input files (default: True)", "True"); + registerParameter("WriteTrackingData", "Whether to generate and store analysis-tracking data (default: True)", + "True"); registerParameter("ObjectSelectionName", "Code used to define objects, e.g. ObjectLoaderStandardCuts"); registerParameter("OutputFormat", "Format, can be user defined, e.g. top::EventSaverFlatNtuple"); - registerParameter("OutputEvents", "AllEvents (saves all events + decison bits), SelectedEvents (saves only the events passing your cuts)"); + registerParameter("OutputEvents", + "AllEvents (saves all events + decison bits), SelectedEvents (saves only the events passing your cuts)"); registerParameter("OutputFilename", "The file that will contain the output histograms and trees"); - registerParameter("OutputFileSetAutoFlushZero", "setAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround. Default False","False"); - - registerParameter("EventVariableSaveList", "The list of event variables to save (EventSaverxAODNext only).", "runNumber.eventNumber.eventTypeBitmask.averageInteractionsPerCrossing"); - registerParameter("PhotonVariableSaveList", "The list of photon variables to save (EventSaverxAODNext only).", "pt.eta.phi.m.charge.ptvarcone20.topoetcone20.passPreORSelection"); - registerParameter("ElectronVariableSaveList", "The list of electron variables to save (EventSaverxAODNext only).", "pt.eta.phi.m.charge.ptvarcone20.topoetcone20.passPreORSelection"); - registerParameter("MuonVariableSaveList", "The list of muon variables to save (EventSaverxAODNext only).", "pt.eta.phi.m.author.charge.ptvarcone30.topoetcone20.muonType.passPreORSelection"); - registerParameter("TauVariableSaveList", "The list of tau variables to save (EventSaverxAODNext only).", "pt.eta.phi.m.charge.passPreORSelection"); - registerParameter("JetVariableSaveList", "The list of jet variables to save (EventSaverxAODNext only).", "pt.eta.phi.m.passPreORSelection.btaggingLink.HadronConeExclTruthLabelID"); - registerParameter("BTagVariableSaveList", "The list of b-tag variables to save (EventSaverxAODNext only).", "MV2c20_discriminant"); - - registerParameter("NEvents", "The number of events that you want to run on (for testing). If 0 then all events are run.", "0"); - registerParameter("FirstEvent", "The number of events that you want to skip (for testing). If 0 then no events are skipped.", "0"); - registerParameter("PerfStats"," I/O Performance printouts. None, Summary or Full" , "None"); + registerParameter("OutputFileSetAutoFlushZero", + "setAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround. (default: False)", + "False"); + registerParameter("OutputFileNEventAutoFlush", + "Set the number of events after which the TTree cache is optimised, ie setAutoFlush(nEvents). (default: 1000)", + "1000"); + registerParameter("OutputFileBasketSizePrimitive", + "Set the TTree basket size for primitive objects (int, float, ...). (default: 4096)", "4096"); + registerParameter("OutputFileBasketSizeVector", "Set the TTree basket size for vector objects. (default: 40960)", + "40960"); + registerParameter("RecomputeCPVariables", + "Run the CP tools to force computation of variables that may already exist in derivations? (default: True)", + "True"); + registerParameter("EventVariableSaveList", "The list of event variables to save (EventSaverxAODNext only).", + "runNumber.eventNumber.eventTypeBitmask.averageInteractionsPerCrossing"); + registerParameter("PhotonVariableSaveList", "The list of photon variables to save (EventSaverxAODNext only).", + "pt.eta.phi.m.charge.ptvarcone20.topoetcone20.passPreORSelection"); + registerParameter("ElectronVariableSaveList", "The list of electron variables to save (EventSaverxAODNext only).", + "pt.eta.phi.m.charge.ptvarcone20.topoetcone20.passPreORSelection"); + registerParameter("MuonVariableSaveList", "The list of muon variables to save (EventSaverxAODNext only).", + "pt.eta.phi.m.author.charge.ptvarcone30.topoetcone20.muonType.passPreORSelection"); + registerParameter("TauVariableSaveList", "The list of tau variables to save (EventSaverxAODNext only).", + "pt.eta.phi.m.charge.passPreORSelection"); + registerParameter("JetVariableSaveList", "The list of jet variables to save (EventSaverxAODNext only).", + "pt.eta.phi.m.passPreORSelection.btaggingLink.HadronConeExclTruthLabelID"); + registerParameter("BTagVariableSaveList", "The list of b-tag variables to save (EventSaverxAODNext only).", + "MV2c20_discriminant"); + + registerParameter("NEvents", + "The number of events that you want to run on (for testing). If 0 then all events are run.", "0"); + registerParameter("FirstEvent", + "The number of events that you want to skip (for testing). If 0 then no events are skipped.", + "0"); + registerParameter("PerfStats", " I/O Performance printouts. None, Summary or Full", "None"); registerParameter("IsAFII", "Define if you are running over a fastsim sample: True or False", " "); + registerParameter("FilterBranches", + "Comma separated list of names of the branches that will be removed from the output", " "); + registerParameter("FilterPartonLevelBranches", + "Comma separated list of names of the parton-level branches that will be removed from the output", " "); + registerParameter("FilterParticleLevelBranches", + "Comma separated list of names of the particle-level branches that will be removed from the output", " "); + registerParameter("FilterNominalLooseBranches", + "Comma separated list of names of the nominal_Loose tree branches that will be removed from the output", " "); + registerParameter("FilterTrees", + "Comma separated list of names of the trees that will be removed from the output", " "); + + registerParameter("FakesMMWeightsIFF", + "Calculate matrix-method weights for fake leptons estimate using FakeBkgTools from IFF: True (calculate weights), False (does nothing)", + "False"); + registerParameter("FakesMMConfigIFF", + "Configurations for fake leptons estimate using FakeBkgTools from IFF: - default is $ROOTCOREBIN/data/TopFakes/efficiencies.xml:1T:1F[T]. Use as \n <ROOT/XML FILE>:<DEFNINITION>:<PROCESS>;<ROOT/XML FILE 2>:<DEFNINITION 2>:<PROCESS 2>; ...", + "$ROOTCOREBIN/data/TopFakes/efficiencies.xml:1T:1F[T]"); + registerParameter("FakesMMIFFDebug", + "Enables debug mode for matrix-method weight calculation using FakeBkgTools from IFF: True, False (default)", + "False"); - registerParameter("FakesControlRegionDoLooseMC","Run Loose events on MC : True (study fakes control regions), False (regular analysis)", "False"); - - registerParameter("FakesMMWeights","Calculate matrix-method weights for fake prompt leptons estimate : True (calculate weights), False (does nothing)", "False"); - registerParameter("FakesMMDir","Directory of files containing efficiencies for fake prompt leptons estimate - default is $ROOTCOREBIN/data/TopFakes", "$ROOTCOREBIN/data/TopFakes"); - registerParameter("FakesMMDebug","Enables debug mode for matrix-method weight calculation: True, False (default)", "False"); + registerParameter("DoTight", "Dumps the normal non-\"*_Loose\" trees : Data, MC, Both (default), False", "Both"); + registerParameter("DoLoose", "Run Loose selection and dumps the Loose trees : Data (default), MC, Both, False", + "Data"); + registerParameter("DoSysts", "Run systematics on given selection: Both (default), Tight, Loose", "Both"); + + registerParameter("UseLooseObjectsInMETInLooseTree","Experimental: use loose objects when rebuilding the MET for the loose tree : True or False (default = False)","False"); + registerParameter("UseLooseObjectsInMETInNominalTree","Experimental: use loose objects when rebuilding the MET for the nominal tree : True or False (default = False)","False"); + + registerParameter("WriteMETBuiltWithLooseObjects","Write a separate branch with the met built with loose objects in the output for tests: True or False (default = False)","False"); - registerParameter("OverlapRemovalLeptonDef","Run overlap removal on : Tight (top default) or Loose (not top default) lepton definitions", "Tight"); - registerParameter("DoLooseTreeOnly","Only dumps the Loose trees (and activate them for MC): True or False (default)", "False"); - registerParameter("ApplyTightSFsInLooseTree","In Loose trees, calculate lepton SFs with tight leptons only, and considering they are tight: True or False (default)", "False"); - registerParameter("ApplyElectronInJetSubtraction","Subtract electrons close to jets for boosted analysis : True or False(top default)", "False"); - registerParameter("TopPartonHistory","ttbar, tb, False (default)", "False"); + registerParameter("OverlapRemovalLeptonDef", + "Special: run overlap removal on : Tight (top default) or Loose (not top default) lepton definitions", + "Tight"); + registerParameter("ApplyTightSFsInLooseTree", + "Special: in Loose trees, calculate lepton SFs with tight leptons only, and considering they are tight: True or False (default)", + "False"); - registerParameter("TopParticleLevel", "Perform particle level selection? True or False", "False"); + registerParameter("ApplyElectronInJetSubtraction", + "Subtract electrons close to jets for boosted analysis : True or False(top default)", "False"); + registerParameter("TopPartonHistory", "ttbar, tb, Wtb, ttz, ttgamma, tHq, False (default)", "False"); + registerParameter("TopPartonLevel", "Perform parton level analysis (stored in truth tree)? True or False", "True"); + + registerParameter("TopParticleLevel", "Perform particle level selection (stored in particleLevel tree)? True or False", "False"); registerParameter("DoParticleLevelOverlapRemoval", "Perform overlap removal at particle level? True (default), False, or any combination (comma separated) of MuonJet, ElectronJet, JetPhoton", "True"); - registerParameter("PDFInfo","Do you want the PDF info? True (in truth tree), Nominal (save to the nominal tree if passes selection) or False (nothing, default)", "False"); - registerParameter("MCGeneratorWeights","Do you want the OTF-computed MC generator weights (if available)? True (in truth tree), Nominal (save to the nominal tree if passes selection) or False (nothing, default)", "False"); - registerParameter("TruthBlockInfo","Do you want to dump the full Truth block info? True or False", "False"); + registerParameter("PDFInfo", + "Do you want the PDF info? True (in truth tree), Nominal (save to the nominal tree if passes selection) or False (nothing, default)", + "False"); + registerParameter("MCGeneratorWeights", + "Do you want the OTF-computed MC generator weights (if available)? True (in truth tree), Nominal (save to the nominal tree if passes selection) or False (nothing, default)", + "False"); + registerParameter("NominalWeightNames", + "List of nominal weight names to attempt to retrieve. Attempts are made in the order as specified. If none of the names can be found, we will crash with error message. Use index instead in such case.", + "\" nominal \",\"nominal\",\"Default\",\"Weight\",\"1001\",\" muR=0.10000E+01 muF=0.10000E+01 \",\"\",\" \",\" dyn= 3 muR=0.10000E+01 muF=0.10000E+01 \",\" mur=1 muf=1 \""); + registerParameter("NominalWeightFallbackIndex", + "Index of nominal weight in MC weights vector. This option is only used in case the MC sample has broken metadata. (Default: -1 means no fallback index specified, rely on metadata and crash if metadata cannot be read)", + "-1"); + registerParameter("ForceNominalWeightFallbackIndex", + "Force usage of NominalWeightFallbackIndex, even if MC sample metadata is correct. (Default: False)", + "False"); - registerParameter("TruthElectronPt", "Electron pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); - registerParameter("TruthElectronEta", "Absolute electron eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5" ); + registerParameter("TruthBlockInfo", "Do you want to dump the full Truth block info? True or False", "False"); - registerParameter("TruthMuonPt", "Muon pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); - registerParameter("TruthMuonEta", "Absolute Muon eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5" ); + registerParameter("TruthElectronPt", + "Electron pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", + "25000"); + registerParameter("TruthElectronEta", + "Absolute electron eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5"); + registerParameter("TruthMuonPt", + "Muon pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); + registerParameter("TruthMuonEta", + "Absolute Muon eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5"); + + registerParameter("TruthSoftMuonPt", + "Soft Muon pT cut for [Particle Level / Truth] object selection (in MeV). Default 4 GeV.", "4000"); + registerParameter("TruthSoftMuonEta", + "Absolute Soft Muon eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5"); + registerParameter("TruthPhotonPt", "Photon pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); registerParameter("TruthPhotonEta", "Absolute Photon eta cut for [Particle Level / Truth] object selection. Default 2.5.", - "2.5" ); + "2.5"); registerParameter("TruthPhotonOrigin", "Potential origin of [Particle Level / Truth] photons. Comma separated list of particle origin values as given by MCTruthClassifier (string names).", - "WBoson,ZBoson,SinglePhot,Higgs,HiggsMSSM,WZMSSM,PromptPhot,SUSY,UndrPhot,FSRPhot" ); + "WBoson,ZBoson,SinglePhot,Higgs,HiggsMSSM,WZMSSM,PromptPhot,SUSY,UndrPhot,FSRPhot"); registerParameter("TruthPhotonIsolation", "Configuration option for isolation applied to [Particle Level / Truth] photons. " "This can be False / None (isolation requirement disabled), " "True (use default isolation), " "or a configuration in the format `VAR CUT`, where VAR is one of the isolation variables and CUT is the cut applied as `VAR / pt < CUT`.", - "ptcone30 0.1"); + "ptcone20 0.1"); - registerParameter("TruthJetPt", "Jet pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); - registerParameter("TruthJetEta", "Absolute Jet eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5" ); + registerParameter("TruthJetPt", + "Jet pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); + registerParameter("TruthJetEta", "Absolute Jet eta cut for [Particle Level / Truth] object selection. Default 2.5.", + "2.5"); - registerParameter("TruthLargeRJetPt", "Large R Jet pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); - registerParameter("TruthLargeRJetEta", "Absolute Large R Jet eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5" ); - - registerParameter("LHAPDFSets", "List of PDF sets to calculate weights for, seperated by spaces, use LHAPDF names e.g CT10nlo NNPDF30_nlo_as_0118 MMHT2014nlo68cl", " " ); - registerParameter("LHAPDFEventWeights", "Save per event weights for all PDF sets/members: True (lots of info in truth tree!), Nominal (save to the nominal tree if passes selection) or False (nothing, default).", "False" ); - registerParameter("LHAPDFBaseSet", "Base PDF set used to recalculate XF1,XF2 values if they are zero. Will be added to LHAPDFSets.", " " ); + registerParameter("TruthLargeRJetPt", + "Large R Jet pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", + "25000"); + registerParameter("TruthLargeRJetEta", + "Absolute Large R Jet eta cut for [Particle Level / Truth] object selection. Default 2.5.", + "2.5"); + + registerParameter("TruthTauPt", + "Tau pT cut for [Particle Level / Truth] object selection (in MeV). Default 25 GeV.", "25000"); + registerParameter("TruthTauEta", "Tau eta cut for [Particle Level / Truth] object selection. Default 2.5.", "2.5"); + + registerParameter("LHAPDFSets", + "List of PDF sets to calculate weights for, seperated by spaces, use LHAPDF names e.g CT10nlo NNPDF30_nlo_as_0118 MMHT2014nlo68cl", + " "); + registerParameter("LHAPDFEventWeights", + "Save per event weights for all PDF sets/members: True (lots of info in truth tree!), Nominal (save to the nominal tree if passes selection) or False (nothing, default).", + "False"); + registerParameter("LHAPDFBaseSet", + "Base PDF set used to recalculate XF1,XF2 values if they are zero. Will be added to LHAPDFSets.", + " "); + registerParameter("BTagCDIPath", "Path to the b-tagging CDI file. Default: Using the hardcoded path.", "Default"); registerParameter("BTaggingWP", - "b-tagging WPs to calculate SF for." - " Can be either a list of cut values written as in " - "the CDI files e.g. -0_4434 (default), or as -0.4434." - " More conviniently it can be a percentage: e.g. 77%.", - "-0_4434"); + "DEPRECATED OPTION, use BTaggingCaloJetWP and BTaggingTrackJetWP for specifying b-tagging WPs for jet collections using calorimeter information and for track jets respectively.", + " "); + + registerParameter("BTaggingTrackJetWP", + "b-tagging WPs to use for track jet collection in the analysis, separated by commas." + " The format should follow the convention of the b-tagging CP group, e.g. FixedCutBEff_60, FlatBEff_77, Continuous, etc." + " For fixed-cut WPs, the simpler format 60%, instead of FixedCutBEff_60, is also tolerated." + " The specified WPs which are calibrated for all flavours will have scale-factors computed." + " By default, no WP is used.", + " "); + + registerParameter("BTaggingCaloJetWP", + "b-tagging WPs to use for calorimeter jet collection (e.g. EMTopo, EMPFlow) in the analysis, separated by commas." + " The format should follow the convention of the b-tagging CP group, e.g. FixedCutBEff_60, FlatBEff_77, Continuous, etc." + " For fixed-cut WPs, the simpler format 60%, instead of FixedCutBEff_60, is also tolerated." + " The specified WPs which are calibrated for all flavours will have scale-factors computed." + " By default, no WP is used.", + " "); registerParameter("BTaggingSystExcludedFromEV", "User-defined list of b-tagging systematics to be dextracted from eigenvector decomposition, separated by semi-colons (none by default)", @@ -260,233 +535,442 @@ ConfigurationSettings::ConfigurationSettings() : m_configured(false) { " Default 'default'", "default"); - registerParameter("PRWConfigFiles", "List of PU config files, seperated by spaces (nothing by default)", " "); + registerParameter("PRWConfigFiles", + "List of PU config files, seperated by spaces (nothing by default) - Not compatible with FS/AF options", + " "); + registerParameter("PRWConfigFiles_FS", + "List of PU config files only for full sim samples, seperated by spaces (nothing by default)", + " "); + registerParameter("PRWConfigFiles_AF", + "List of PU config files only for fast sim samples, seperated by spaces (nothing by default)", + " "); + registerParameter("PRWActualMu_FS", + "List of actual mu files for full sim samples, seperated by spaces (nothing by default)", " "); + registerParameter("PRWActualMu_AF", + "List of actual mu files only for fast sim samples, seperated by spaces (nothing by default)", + " "); registerParameter("PRWLumiCalcFiles", "List of PU lumicalc files, seperated by spaces (nothing by default)", " "); registerParameter("PRWUseGRLTool", "Pass the GRL tool to the PU reweighting tool (False by default)", "False"); registerParameter("PRWMuDependent", "Use mu dependent random run numbers for MC. " "True or False (default True)", "True"); + registerParameter("PRWCustomScaleFactor", + "Specify custom scale-factor and up/down variations, for specific studies." + "Format is \'nominal:up:down\'." + "If nothing is set, the default values will be used (recommended).", + " "); + registerParameter("PRWUnrepresentedDataTolerance", + "Specify value between 0 and 1 to represent acceptable fraction of unrepresented data in PRW [default: 0.05]", + "0.05"); + registerParameter("PRWPeriodAssignments", + "Specify period number assignments to run numbers ranges in this form: \"XXX:XXX:XXX\", where XXX are runnumbers, first number is the associated run number, second number is the period block start, the third number is the period block end. You can pass any number of these sets (total number of provided RunNumbers needs to be divisible by 3). Default is used if not specified", + " "); registerParameter("MuonTriggerSF", "Muon trigger SFs to calculate", "HLT_mu20_iloose_L1MU15_OR_HLT_mu50"); - - registerParameter("KLFitterTransferFunctionsPath","Select the transfer functions to use","mc12a/akt4_LCtopo_PP6"); - registerParameter("KLFitterJetSelectionMode","kLeadingFour , kLeadingFive , kBtagPriorityFourJets , kBtagPriorityFiveJets","kBtagPriorityFourJets"); - registerParameter("KLFitterBTaggingMethod","Recommend use kNotag or kVetoNoFit - see KLFitter TWiki","kNotag"); - registerParameter("KLFitterLH", "Select likelihood depending on signal, ttbar or ttH.", "ttbar"); - registerParameter("KLFitterTopMassFixed","Fix the mass of the top quark? True or False","True"); - registerParameter("KLFitterSaveAllPermutations","Save All permutations to the output file (False will save only the best)","False"); + + registerParameter("KLFitterTransferFunctionsPath", "Select the transfer functions to use", "mc12a/akt4_LCtopo_PP6"); + registerParameter("KLFitterOutput", "Select the KLFitter output (FULL, FITTEDTOPS_ONLY, JETPERM_ONLY)", "FULL"); + registerParameter("KLFitterJetSelectionMode", + "kLeadingThree , kLeadingFour , kLeadingFive , kLeadingSix , kLeadingSeven , kLeadingEight , kBtagPriorityThreeJets , kBtagPriorityFourJets , kBtagPriorityFiveJets, kBtagPrioritySixJets , kBtagPrioritySevenJets , kBtagPriorityEightJets", + "kBtagPriorityFourJets"); + registerParameter("KLFitterBTaggingMethod", "Recommend use kNotag or kVetoNoFit - see KLFitter TWiki", "kNotag"); + registerParameter("KLFitterLH", + "Select likelihood depending on signal, ttbar, ttbar_angles, ttH, ttZTrilepton, ttbar_AllHadronic, ttbar_BoostedLJets", + "ttbar"); + registerParameter("KLFitterTopMassFixed", "Fix the mass of the top quark? True or False", "True"); + registerParameter("KLFitterSaveAllPermutations", + "Save All permutations to the output file (False will save only the best)", "False"); + registerParameter("KLFitterFailOnLessThanXJets", + "Fail if kLeadingX or kBtagPriorityXJets is set and the number of jets in the event is less than X (Default is False)", + "False"); registerParameter("DynamicKeys", "Additional dynamic key list seperated by ,", ""); registerParameter("OverlapRemovalProcedure", "Overlap removal procedure to be used. Options include:" - " recommended [default], jetmuApplyRelPt, harmonized," - " Boosted, BoostedSlidingDREl, BoostedSlidingDRMu, BoostedSlidingDRElMu, noTauJetOLR", + " recommended [default], jetmuApplyRelPt, harmonized," + " Boosted, BoostedSlidingDREl, BoostedSlidingDRMu, BoostedSlidingDRElMu, noTauJetOLR, " + " noPhotonMuOR, noPhotonMuOrJetOR", "recommended" - ); + ); + + registerParameter("OverlapRemovalSlidingInnerDRel", + "Overlap removal inner radius to be used for electron SlidingDR ,", "0.2"); + registerParameter("OverlapRemovalSlidingInnerDRmu", "Overlap removal inner radius to be used for muon SlidingDR ,", + "0.2"); - registerParameter("LargeJetOverlapRemoval", "Perform overlap removal including large-R jets. True or False (default: False).", "False"); + registerParameter("LargeJetOverlapRemoval", + "Perform overlap removal including large-R jets. True or False (default: False).", "False"); registerParameter("HLLHC", - "Set to run HL-LHC studies," - "True or False (default False)", - "False"); -} + "Set to run HL-LHC studies," + "True or False (default False)", + "False"); + + registerParameter("HLLHCFakes", + "Set to enable Fakes HL-LHC studies," + "True or False (default False)", + "False"); -ConfigurationSettings* ConfigurationSettings::get() { - if (!m_instance) - m_instance = new ConfigurationSettings(); + registerParameter("SaveBootstrapWeights", "Set to true in order to save Poisson bootstrap weights," + "True or False (default False)", "False"); + + registerParameter("NumberOfBootstrapReplicas", "Define integer number of replicas to be stored with bootstrapping, " + "Default 100", "100"); + + registerParameter("UseBadBatmanCleaning", "Switch to turn on BadBatman cleanig.", "False"); + registerParameter("BadBatmanCleaningRange", + "Set a range of RunNumbers where the cleaning is applied in the form of XXXXX:YYYYY", + "276262:311481"); + registerParameter("UseEventLevelJetCleaningTool", + "Switch to turn on event-level jet cleaning tool (for testing), True or False (default False)", + "False"); + + registerParameter("UseGlobalLeptonTriggerSF", + "Switch to activate event-level trigger scale factors allowing multiple OR of single-, di-, tri- lepton triggers, True or False (default False)", + "False"); + registerParameter("GlobalTriggers", + "Trigger list for GlobalLeptonTriggerSF - Format as 2015@trig1,trig2 2016@trig3,trig4 : Separate periods defined with @ using whitespace, triggers with comma (default: None)", + "None"); + registerParameter("GlobalTriggersLoose", + "Trigger list for GlobalLeptonTriggerSF - Format as 2015@trig1,trig2 2016@trig3,trig4 : Separate periods defined with @ using whitespace, triggers with comma (default: None)", + "None"); + registerParameter("ElectronTriggers", "Deprecated, use GlobalTriggers instead.", "None"); + registerParameter("ElectronTriggersLoose", "Deprecated, use GlobalTriggersLoose instead.", "None"); + registerParameter("MuonTriggers", "Deprecated, use GlobalTriggers instead.", "None"); + registerParameter("MuonTriggersLoose", "Deprecated, use GlobalTriggersLoose instead.", "None"); + + registerParameter("DemandPrimaryVertex", "Wether at least one primary vertex in event is required. Default True. For debugging purposes only!", "True"); + + registerParameter("KillExperimental", "Disable some specific experimental feature.", " "); + registerParameter("RedefineMCMCMap", "Dictionary for translating the shower names from TopDataPreparation. Format: \"shower1:shower2,shower3:shower4\".", " "); + } + + ConfigurationSettings* ConfigurationSettings::get() { + if (!m_instance) m_instance = new ConfigurationSettings(); return m_instance; -} + } -void ConfigurationSettings::loadFromFile(const std::string& filename) { + void ConfigurationSettings::loadFromFile(const std::string& filename) { std::ifstream input(filename.c_str()); if (!input) { - std::cout << "Configuration file does not exist, " << filename << std::endl; - std::cout << "Can't continue" << std::endl; - exit(1); + throw std::runtime_error("Configuration file does not exist: " + filename); } struct SelectionData { - std::string name; - bool isSub; - std::vector<std::string> cuts; + std::string name; + bool isSub; + std::vector<std::string> cuts; }; std::string line; std::vector<SelectionData> selections; //for the key-value pairs - while (std::getline( input, line )) { - std::string newstring(line); - //std::cout << newstring << '\n'; - - if (newstring.find("#") != std::string::npos) - newstring = newstring.substr(0, newstring.find("#")); - - // remove (multiple) spaces hanging around relevant information - boost::algorithm::trim_all(newstring); - if (newstring.empty()) - continue; - - // handle start of a (sub)selection (implies end of key-value section) - if (boost::algorithm::starts_with(newstring, "SELECTION ")) { - selections.push_back({newstring.substr(10), false, {}}); - continue; + while (std::getline(input, line)) { + std::string newstring(line); + + // search for '#' character to discard commented-out part of line + // however ignore '\#' -- used to be able to type # in our config + // and not be recognized as commenting character + size_t commentpos = size_t(-1); + while (true) { + // find next occurence of '#' -- after the already scanned chars + commentpos = newstring.find("#", commentpos+1); + if (commentpos == std::string::npos) + break; + if (commentpos == 0) { // the whole line is a comment, to be ignored + newstring = ""; + break; } - if (boost::algorithm::starts_with(newstring, "SUB ")) { - selections.push_back({newstring.substr(4), true, {}}); + // if it's '\#', then do not erase this part, but remove the '\' + if (newstring.compare(commentpos-1, 1, "\\") == 0) { + newstring.erase(commentpos-1, 1); + --commentpos; // the position of the '#' shifted after removing '\' continue; + } else { + newstring = newstring.substr(0, commentpos); + break; + } + } + + // remove (multiple) spaces hanging around relevant information + // if a pair of "" appears, the spaces in "" won't be touched + bool hasquote = (newstring.find("\"",0) != std::string::npos); + if (!hasquote) boost::algorithm::trim_all(newstring); + else { + //split the string into segments, separated by pairs of quotes + //e.g. the string "abc \"def\" ghi" + // becomes a vector of 3 strings: "abc", "\"def\"", "ghi" + std::vector<std::string> segments; + std::vector<bool> segments_isquote; + std::size_t strsize = newstring.size(); + std::size_t tmppos = 0; + bool leftquote = true; + while (tmppos <= strsize-1) { + // find the position of the 1st quote after newstring[tmppos] + std::size_t tmppos2 = newstring.find_first_of("\"",tmppos); + + // when the quote found has \ ahead of it, jump over and update tmppos2 + std::size_t tmppos3 = newstring.find_first_of("\\\"",tmppos); + while (tmppos2 == tmppos3+1) { + tmppos3 = newstring.find_first_of("\\\"",tmppos2+1); + tmppos2 = newstring.find_first_of("\"",tmppos2+1); + } + + // when no more quote found, save the segment from the last rightquote to the end, then quit the loop + if (tmppos2 == std::string::npos) { + segments.push_back(newstring.substr(tmppos,strsize-tmppos)); + segments_isquote.push_back(false); + break; + } + + // check it's a left quote or right quote + if (leftquote) { + segments.push_back(newstring.substr(tmppos,tmppos2-tmppos)); + segments_isquote.push_back(false); + + // update the position indicator and leftquote flag + tmppos = tmppos2+1; + leftquote = false; + } else { + segments.push_back(newstring.substr(tmppos-1,tmppos2-(tmppos-1)+1)); // have to include the two quotes, which is why +/-1 adjustment is introduced + segments_isquote.push_back(true); + + // update the position indicator and leftquote flag + tmppos = tmppos2+1; + leftquote = true; + } + } + + // sanity check: if leftquote = false after the loop, it means a left quote is found but not its associated rightquote + // in this case, crash the code + if (!leftquote) { + std::string message = "Problematic configuration line\n"; + message.append(newstring.c_str()); + throw std::invalid_argument(message); } - if (!selections.empty()) { - // read body of (sub)selection - auto & sel = selections.back(); - if (boost::algorithm::starts_with(newstring, ". ")) { - // source another (sub)selection here - auto subselName = newstring.substr(2); - auto subselIt = std::find_if(selections.rbegin(), selections.rend(), - [subselName](SelectionData const & sel){ return (subselName == sel.name); }); - if (subselIt == selections.rend()) - throw std::invalid_argument("ConfigurationSettings: unknown selection: " + subselName); - sel.cuts.insert(sel.cuts.end(), subselIt->cuts.begin(), subselIt->cuts.end()); + //run the original trim_all for each segment that is NOT a quote + for (uint i = 0; i < segments.size(); i++) { + std::string seg = segments.at(i); + if (seg.size() == 0) continue; + if (segments_isquote.at(i)) continue; + boost::algorithm::trim_all(seg); + + // if the segment has a space in the end and it's not the last segment, add the space back + if (i+1 != segments.size()) { + if (segments.at(i).at(segments.at(i).size()-1) == ' ') { + seg += " "; } - else { - sel.cuts.push_back(newstring); + } + // if the segment has a space in the head and it's not the first segment, add the space back + if (i != 0) { + if (segments.at(i).at(0) == ' ') { + seg = " " + seg; } - continue; + } + + // update the segment + segments.at(i) = seg; } - // parse key-value pair - std::istringstream liness(newstring); - std::string key; - std::string value; + // combine the segments back to newstring + newstring = ""; + for (uint i = 0; i < segments.size(); i++) { + newstring += segments.at(i); + } + } + + if (newstring.empty()) continue; + + // handle start of a (sub)selection (implies end of key-value section) + if (boost::algorithm::starts_with(newstring, "SELECTION ")) { + selections.push_back({newstring.substr(10), false, {}}); + continue; + } + if (boost::algorithm::starts_with(newstring, "SUB ")) { + selections.push_back({newstring.substr(4), true, {}}); + continue; + } + + if (!selections.empty()) { + // read body of (sub)selection + auto& sel = selections.back(); + if (boost::algorithm::starts_with(newstring, ". ")) { + // source another (sub)selection here + auto subselName = newstring.substr(2); + auto subselIt = std::find_if(selections.rbegin(), selections.rend(), + [subselName](SelectionData const& sel) { + return(subselName == sel.name); + }); + if (subselIt == selections.rend()) throw std::invalid_argument( + "ConfigurationSettings: unknown selection: " + subselName); + sel.cuts.insert(sel.cuts.end(), subselIt->cuts.begin(), subselIt->cuts.end()); + } else { + sel.cuts.push_back(newstring); + } + continue; + } + + // parse key-value pair + std::istringstream liness(newstring); + std::string key; + std::string value; + + std::getline(liness, key, ' '); //to the space + std::getline(liness, value); //to the end of the line + + auto its = strings_.find(key); + if (its != strings_.end()) { + its->second.m_data = value; + its->second.m_set = true; + } + + //// add dynamic keys + if ("DynamicKeys" == key) { + std::vector<std::string> listofkeys; + std::string separator = ","; + std::string::size_type start = 0, end = 0; + while ((end = value.find(separator, start)) != std::string::npos) { + std::string token = value.substr(start, end - start); + if (token.size()) listofkeys.push_back(token); + start = end + 1; + } - std::getline(liness, key, ' '); //to the space - std::getline(liness, value); //to the end of the line + std::string lasttoken = value.substr(start); + if (lasttoken.size()) listofkeys.push_back(lasttoken); - auto its = m_strings.find(key); - if (its != m_strings.end()) { - its->second.m_data = value; - its->second.m_set = true; + for (auto par : listofkeys) { + registerParameter(par, "Dynamic parameter", ""); } + } + } - //// add dynamic keys - if("DynamicKeys" == key) { - std::vector<std::string> listofkeys; - std::string separator = ","; - std::string::size_type start = 0, end = 0; - while ((end = value.find(separator, start)) != std::string::npos) { - std::string token = value.substr(start, end - start); - if(token.size()) listofkeys.push_back(token); - start = end + 1; - } - - std::string lasttoken = value.substr(start); - if(lasttoken.size()) listofkeys.push_back(lasttoken); - - for(auto par : listofkeys) { - registerParameter(par, "Dynamic parameter", ""); - } - } + for (auto& sel : selections) { + if (sel.isSub) continue; + m_selections.push_back({sel.name, sel.cuts}); } - for (auto & sel : selections) { - if (sel.isSub) - continue; - m_selections.push_back({sel.name, sel.cuts}); + { + auto const& it = strings_.find("KillExperimental"); + m_killedFeatures.clear(); + if (it != strings_.end() && it->second.m_set) { + std::string strValue(it->second.m_data); + boost::trim(strValue); + boost::split(m_killedFeatures, strValue, boost::is_any_of(" ")); + } } input.close(); m_configured = true; -} + } - void ConfigurationSettings::registerParameter(const std::string& name, const std::string& message, const std::string& default_val) { + void ConfigurationSettings::registerParameter(const std::string& name, const std::string& message, + const std::string& default_val) { StringData data; + data.m_data = default_val; data.m_human_explanation = message; data.m_set = (default_val.empty() ? false : true); - m_strings[name] = data; -} + strings_[name] = data; + } -const std::string& ConfigurationSettings::value(const std::string& key) const { + const std::string& ConfigurationSettings::value(const std::string& key) const { //This class never has loadFromFile called if (!m_configured) { - std::string message = "ConfigurationSettings: Not correctly configured\n"; - message.append("You need to call top::ConfigurationSettings::get()->loadFromFile(filename)\n"); - message.append("Early in your program\n"); - throw std::invalid_argument(message); + std::string message = "ConfigurationSettings: Not correctly configured\n"; + message.append("You need to call top::ConfigurationSettings::get()->loadFromFile(filename)\n"); + message.append("Early in your program\n"); + throw std::invalid_argument(message); } - std::map<std::string, StringData>::const_iterator its = m_strings.find(key); + std::map<std::string, StringData>::const_iterator its = strings_.find(key); //The string is not in the map - if (its == m_strings.end()) { - throw std::invalid_argument("ConfigurationSettings: The variable doesn't exist in the code " + key); + if (its == strings_.end()) { + throw std::invalid_argument("ConfigurationSettings: The variable doesn't exist in the code " + key); } //In the map, but never set to anything if (!its->second.m_set) { - throw std::invalid_argument("ConfigurationSettings: You never set a value for " + key); + throw std::invalid_argument("ConfigurationSettings: You never set a value for " + key); } return its->second.m_data; -} + } -bool ConfigurationSettings::configured() const { + bool ConfigurationSettings::configured() const { return m_configured; -} + } -const std::map<std::string, StringData>& ConfigurationSettings::stringData() const { - return m_strings; -} + const std::map<std::string, StringData>& ConfigurationSettings::stringData() const { + return strings_; + } -const std::vector<SelectionConfigurationData> ConfigurationSettings::selections() const { + const std::vector<SelectionConfigurationData> ConfigurationSettings::selections() const { return m_selections; -} + } -bool ConfigurationSettings::retrieve(std::string const & key, bool & value) const { + void ConfigurationSettings::retrieve(std::string const& key, bool& value) const { using boost::trim; using boost::equals; using boost::iequals; auto stringValue = ConfigurationSettings::get()->value(key); trim(stringValue); - if (equals(stringValue, "")) { - return false; - } - if (iequals(stringValue, "false") or iequals(stringValue, "0") or iequals(stringValue, "n") or iequals(stringValue, "no") or iequals(stringValue, "off")) { - value = false; - return true; + + if (iequals(stringValue, "false") or iequals(stringValue, "0") or iequals(stringValue, "n") or iequals(stringValue, + "no") or + iequals(stringValue, "off")) { + value = false; + return; } - if (iequals(stringValue, "true") or iequals(stringValue, "1") or iequals(stringValue, "y") or iequals(stringValue, "yes") or iequals(stringValue, "on")) { - value = true; - return true; + if (iequals(stringValue, "true") or iequals(stringValue, "1") or iequals(stringValue, "y") or iequals(stringValue, + "yes") or + iequals(stringValue, "on")) { + value = true; + return; } throw std::invalid_argument(std::string("expected boolean value for configuration setting ") + key); -} - -} - -std::ostream& operator<<(std::ostream& os, const top::SelectionConfigurationData& data) { + } + + bool ConfigurationSettings::retrieve(std::string const& key) const { + bool result=false; + retrieve(key,result); + return result; + } + + bool ConfigurationSettings::feature(std::string const& name) const { + /* We search a list of strings, not a particularly efficient implementation. + * If need be, we could abuse the aux registry and use integers instead of + * strings. Anyhow, in most cases, the list should be empty. */ + return(m_killedFeatures.empty() || + std::find(m_killedFeatures.begin(), m_killedFeatures.end(), name) == m_killedFeatures.end()); + } + + std::ostream& operator << (std::ostream& os, const SelectionConfigurationData& data) { os << " - " << data.m_name << "\n"; for (const auto& cutname : data.m_cutnames) - os << " " << cutname << "\n"; + os << " " << cutname << "\n"; return os; -} - -std::ostream& operator<<(std::ostream& os, const top::ConfigurationSettings& settings) { - for (std::map<std::string, top::StringData >::const_iterator its = settings.stringData().begin(); its != settings.stringData().end(); ++its) { - std::stringstream s; - s << "\"" << its->first << "\""; - - std::stringstream s2; - s2 << "\"" << its->second.m_data << "\""; - os << std::setw(40) << std::left << s.str() << " : " << std::setw(35) << s2.str() << " - " << std::right << its->second.m_human_explanation << "\n"; + } + + std::ostream& operator << (std::ostream& os, const ConfigurationSettings& settings) { + for (std::map<std::string, top::StringData >::const_iterator its = settings.stringData().begin(); + its != settings.stringData().end(); ++its) { + std::stringstream s; + s << "\"" << its->first << "\""; + + std::stringstream s2; + s2 << "\"" << its->second.m_data << "\""; + os << std::setw(40) << std::left << s.str() << " : " << std::setw(35) << s2.str() << " - " << std::right << + its->second.m_human_explanation << "\n"; } //for (const auto& selection : settings.selections()) // os << selection << "\n"; return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/JsonUtils.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/JsonUtils.cxx new file mode 100644 index 0000000000000000000000000000000000000000..0bde4b13d88f6bcb9f12946d2753dd01f24014c9 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/JsonUtils.cxx @@ -0,0 +1,97 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopConfiguration/JsonUtils.h" + +#include "AsgTools/TProperty.h" + +#include <stdexcept> + +namespace top { + std::string json_dump(std::string const& value) { + std::string out; + out.reserve(value.size() + value.size() / 8 + 8); + char const* hexalphabet = "0123456789abcdef"; + out.push_back('"'); + for (auto it = value.cbegin(); it != value.cend(); it++) { + char c = *it; + if (0x00 <= c && c < 0x20) { + out.push_back('\\'); + switch (c) { + case '\b': out.push_back('b'); + break; + + case '\f': out.push_back('f'); + break; + + case '\n': out.push_back('n'); + break; + + case '\r': out.push_back('r'); + break; + + case '\t': out.push_back('t'); + break; + + default: + out.push_back('x'); + out.push_back(hexalphabet[c >> 4]); + out.push_back(hexalphabet[c & 0xf]); + break; + } + } else { + if (c == '"' || c == '\\') out.push_back('\\'); + out.push_back(c); + } + } + out.push_back('"'); + return out; + } + + namespace { +/** + * @brief Convert values of TProperty<T> instances to JSON. + */ + template<typename T> + class TPropertyValueJsonDumper: public PropertyValueJsonDumper::ISpecializedDumper { + public: + TPropertyValueJsonDumper() : + m_convprop(createProperty(m_value)) { + } + + virtual std::string operator () (Property* prop) override { + if (m_convprop->setFrom(*prop) != 0) throw std::logic_error( + "TPropertyValueJsonDumper called with wrong type of argument"); + return json_dump(m_value); + } + + private: + T m_value; + std::unique_ptr<Property> m_convprop; + }; + } + + + PropertyValueJsonDumper::PropertyValueJsonDumper() { + m_dispatch.emplace_back(Property::BOOL, std::make_unique<TPropertyValueJsonDumper<bool> >()); + m_dispatch.emplace_back(Property::INT, std::make_unique<TPropertyValueJsonDumper<int> >()); + m_dispatch.emplace_back(Property::FLOAT, std::make_unique<TPropertyValueJsonDumper<float> >()); + m_dispatch.emplace_back(Property::DOUBLE, std::make_unique<TPropertyValueJsonDumper<double> >()); + m_dispatch.emplace_back(Property::STRING, std::make_unique<TPropertyValueJsonDumper<std::string> >()); + } + + PropertyValueJsonDumper::~PropertyValueJsonDumper() { + } + + boost::optional<std::string> PropertyValueJsonDumper::operator () (Property* prop) const { + Property::Type propType = prop->type(); + for (auto&& kv : m_dispatch) { + if (kv.first == propType) return (*kv.second)(prop); + } + return boost::none; + } + + PropertyValueJsonDumper::ISpecializedDumper::~ISpecializedDumper() { + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/LinkDef.h index 28d0ad31aa1c4f1593be2025ddc4aee2a7187156..9e5c4faac1437f4e3101771cc0f9a9001df34486 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/LinkDef.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopConfiguration/TopPersistentSettings.h" diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/MsgCategory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/MsgCategory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..61251b912f6ab9978c22df6335ae1e84e5dfc71a --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/MsgCategory.cxx @@ -0,0 +1,6 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#include "TopConfiguration/MsgCategory.h" + +ANA_MSG_SOURCE(TopConfiguration, "TopConfiguration") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopConfig.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopConfig.cxx index 1df5df61732988aa97dab033f9a4d6352329cbb7..7f645d967c33a12597f0b5198c5e307c9e2ad06b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopConfig.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopConfig.cxx @@ -1,22 +1,25 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyrightf (C) 2002-2020 CERN for the benefit of the ATLAS collaboration */ -// $Id: TopConfig.cxx 803103 2017-04-18 17:30:51Z tpelzer $ #include "TopConfiguration/TopConfig.h" #include "TopConfiguration/AodMetaDataAccess.h" #include "TopConfiguration/ConfigurationSettings.h" #include <algorithm> +#include <cassert> #include <iterator> #include <sstream> #include <stdexcept> #include <boost/algorithm/string.hpp> +#include <boost/algorithm/string/replace.hpp> #include "TopConfiguration/Tokenize.h" -namespace top{ +#include "TopConfiguration/MsgCategory.h" +using namespace TopConfiguration; +namespace top { TopConfig::TopConfig() : // Prevent any more configuration m_configFixed(false), @@ -25,7 +28,9 @@ namespace top{ // Use which objects m_usePhotons(false), m_useElectrons(false), + m_useFwdElectrons(false), m_useMuons(false), + m_useSoftMuons(false), m_useAntiMuons(false), m_useTaus(false), m_useJets(false), @@ -34,7 +39,7 @@ namespace top{ m_useRCJets(false), m_useVarRCJets(false), m_useJetGhostTrack(false), - + m_useTracks(false), m_useTruthParticles(false), m_useTruthElectrons(false), m_useTruthMuons(false), @@ -45,41 +50,58 @@ namespace top{ m_applyTTVACut(true), + m_demandPriVtx(true), + m_jetSubstructureName("None"), + m_recomputeCPvars(true), + // Do systematics? - this needs many more configuration options m_systematics("SetMe"), /// special syst config m_nominalSystName("Nominal"), m_allSystName("All"), - + m_DSID(-1), m_MapIndex(0), + m_showeringAlgo(SampleXsection::unknown), // Is MC m_isMC(false), // Is AFII m_isAFII(false), + // Generators + m_generators("SetMe"), + // AMITag + m_AMITag("SetMe"), // Is Primary xAOD m_isPrimaryxAOD(false), // Is Truth xAOD m_isTruthDxAOD(false), // Derivation name m_derivationStream("SetMe"), - // Do loose events - m_doLooseEvents(false), - // Do fakes MM weights calculation - m_doFakesMMWeights(false), - // Directory of efficiency files for MM fake estimate - m_FakesMMDir("$ROOTCOREBIN/data/TopFakes"), - // Directory of efficiency files for MM fake estimate - m_doFakesMMDebug(false), + // Do fakes MM weights calculation using FakeBkgTools from IFF + m_doFakesMMWeightsIFF(false), + // Configurations for MM fake estimate using FakeBkgTools from IFF + m_FakesMMConfigIFF("$ROOTCOREBIN/data/TopFakes/efficiencies.xml:1T:1F[T]"), + // Debug level for MM fake estimate using FakeBkgTools from IFF + m_doFakesMMIFFDebug(false), + //options to select if you want to use loose objects for MET rebuilding instead of the tight ones + m_useLooseObjectsInMETInLooseTree(false), + m_useLooseObjectsInMETInNominalTree(false), + //this will write a separate branch with the met built using loose objects + m_writeMETBuiltWithLooseObjects(false), // Apply overlap removal on loose lepton definitons - not the top recommendation, for studies only m_doOverlapRemovalOnLooseLeptonDef(false), // do overlap removal also with large-R jets // (using whatever procedure is used in the official tools) m_doLargeJetOverlapRemoval(false), - // Only dumps the *_Loose trees - also on MC - m_doLooseTreeOnly(false), + // Dumps the normal non-"*_Loose" trees + m_doTightEvents(true), + // Runs Loose selection and dumps the "*_Loose" trees + m_doLooseEvents(false), + // Runs systematics on the given selection + m_doTightSysts(true), + m_doLooseSysts(true), // In the *_Loose trees, lepton SFs are calculated considering // tight ID and isolation instead of loose // Only tight leptons are considered in the event SF calculation @@ -94,9 +116,15 @@ namespace top{ // Write MC generator weights m_doMCGeneratorWeights(false), m_doMCGeneratorWeightsInNominalTrees(false), + m_nominalWeightNames(), + m_nominalWeightName("SetMe"), + m_nominalWeightIndex(-1), + m_MCweightsSize(-1), + m_forceWeightIndex(false), // Top Parton History m_doTopPartonHistory(false), m_isTopPartonHistoryRegisteredInNtuple(false), + m_doTopPartonLevel(true), m_doTopParticleLevel(false), m_doParticleLevelOverlapRemovalMuJet(true), @@ -106,11 +134,13 @@ namespace top{ // KLFitter m_doKLFitter(false), m_KLFitterTransferFunctionsPath("SetMe"), + m_KLFitterOutput("SetMe"), m_KLFitterJetSelectionMode("SetMe"), m_KLFitterBTaggingMethod("SetMe"), m_KLFitterLH("SetMe"), m_KLFitterTopMassFixed(true), m_KLFitterSaveAllPermutations(false), + m_KLFitterFailOnLessThanXJets(false), // PseudoTop m_doPseudoTop(false), @@ -121,14 +151,17 @@ namespace top{ m_sgKeyPrimaryVertices("PrimaryVertices"), m_sgKeyPhotons("SetMe"), m_sgKeyElectrons("SetMe"), + m_sgKeyFwdElectrons("SetMe"), m_sgKeyMuons("SetMe"), + m_sgKeySoftMuons("SetMe"), m_sgKeyTaus("SetMe"), m_sgKeyJets("SetMe"), + m_sgKeyJetsType("SetMe"), m_sgKeyLargeRJets("SetMe"), m_sgKeyTrackJets("SetMe"), + m_sgKeyTrackJetsType("SetMe"), m_sgKeyMissingEt("MET"), m_sgKeyMissingEtLoose("LooseMET"), - m_sgKeyInDetTrackParticles("InDetTrackParticles"), m_sgKeyTruthEvent("TruthEvents"), m_sgKeyMCParticle("SetMe"), @@ -145,81 +178,165 @@ namespace top{ m_sgKeyTopSystematicEventsLoose("TopSystematicEventsLoose"), m_passEventSelectionDecoration("passEventSelection"), m_decoKeyJetGhostTrack("GhostTrack"), + m_sgKeyInDetTrackParticles("InDetTrackParticles"), + m_sgKeyTracks("SetMe"), + + + m_jetResponseMatchingDeltaR(-1), // special: allow to dump the systematics-shifted b-tagging SFs in the systematics trees m_dumpBtagSystsInSystTrees(false), + m_storePerJetBtagSFs(false), + // Electron configuration m_egammaSystematicModel("1NP_v1"), + m_electronEfficiencySystematicModel("TOTAL"), + m_electronEfficiencySystematicModelEtaBinning(""), + m_electronEfficiencySystematicModelEtBinning(""), m_electronID("SetMe"), m_electronIDLoose("SetMe"), m_electronVetoLArCrack(true), m_electronPtcut(25000.), m_electronIsolation("SetMe"), m_electronIsolationLoose("SetMe"), + m_electronIsolationSF("SetMe"), + m_electronIsolationSFLoose("SetMe"), m_electronIsoSFs(true), m_electronIDDecoration("SetMe"), m_electronIDLooseDecoration("SetMe"), + m_useElectronChargeIDSelection(false), + m_useEgammaLeakageCorrection(true), + m_enablePromptLeptonImprovedVetoStudies(false), + + // Fwd electron configuration + m_fwdElectronPtcut(25000.), + m_fwdElectronMinEtacut(2.5), + m_fwdElectronMaxEtacut(4.9), + m_fwdElectronID("SetMe"), + m_fwdElectronIDLoose("SetMe"), + m_fwdElectronBCIDCleaningMinRun(266904), + m_fwdElectronBCIDCleaningMaxRun(311481), // Muon configuration m_muonPtcut(25000.), m_muonEtacut(2.5), m_muonQuality("SetMe"), + m_muonUseMVALowPt(false), + m_muonUse2stationMuonsHighPt(true), m_muonQualityLoose("SetMe"), + m_muonUseMVALowPtLoose(false), + m_muonUse2stationMuonsHighPtLoose(true), m_muonIsolation("SetMe"), m_muonIsolationLoose("SetMe"), + m_muonIsolationSF("SetMe"), + m_muonIsolationSFLoose("SetMe"), + m_muonMuonDoSmearing2stationHighPt(true), + m_muonMuonDoExtraSmearingHighPt(false), + + // Soft Muon configuration + m_softmuonPtcut(4000.), + m_softmuonEtacut(2.5), + m_softmuonQuality("SetMe"), + m_softmuonUseMVALowPt(false), + m_softmuonDRJetcut(0.4), + m_softmuonDRJetcutUseRapidity(false), + m_softmuonAdditionalTruthInfo(false), + m_softmuonAdditionalTruthInfoCheckPartonOrigin(false), + m_softmuonAdditionalTruthInfoDoVerbose(false), // Jet configuration m_jetPtcut(25000.), m_jetEtacut(2.5), - m_fwdJetAndMET("Default"), - m_jetUncertainties_BunchSpacing("25ns"), + m_jetPtGhostTracks(30000.), + m_jetEtaGhostTracks(2.5), m_jetUncertainties_NPModel("AllNuisanceParameters"), + m_jetUncertainties_QGFracFile("None"), + m_jetUncertainties_QGHistPatterns(), m_doMultipleJES(false), m_jetJERSmearingModel("Simple"), m_jetCalibSequence("GSC"), + m_jetStoreTruthLabels("True"), m_doJVTInMETCalculation(true), + m_saveFailJVTJets(false), + m_JVTWP("Default"), + m_doForwardJVTInMETCalculation(false), + m_saveFailForwardJVTJets(false), + m_fJVTWP("None"), + + // MET configuration + m_METUncertaintiesConfigDir("SetMe"), + + // Ghost Track Configuration + m_ghostTrackspT(500.), + m_ghostTracksVertexAssociation("nominal"), + m_ghostTracksQuality("TightPrimary"), m_largeRJetPtcut(25000.), m_largeRJetEtacut(2.5), - m_largeRJESUncertaintyConfig("SetMe"), + m_largeRJetUncertainties_NPModel("CategoryReduction"), + m_largeRJetUncertaintiesConfigDir("SetMe"), m_largeRJESJMSConfig("SetMe"), m_trackJetPtcut(7000.0), m_trackJetEtacut(2.5), + + m_RCJetPtcut(100000.), + m_RCJetEtacut(2.0), + m_RCInputJetPtMin(0.), + m_RCInputJetEtaMax(999.), + m_RCJetTrimcut(0.05), + m_RCJetRadius(1.0), + m_useRCJetSubstructure(false), + m_useRCJetAdditionalSubstructure(false), + + m_VarRCJetPtcut(100000.), + m_VarRCJetEtacut(2.0), + m_VarRCJetTrimcut(0.05), + m_VarRCJetMaxRadius(1.0), + m_VarRCJetRho("2"), + m_VarRCJetMassScale("m_w,m_z,m_h,m_t"), + m_useVarRCJetSubstructure(false), + m_useVarRCJetAdditionalSubstructure(false), + + m_trackQuality("SetMe"), m_JSF(1.0), m_bJSF(1.0), - // Tau configuration + // Tau configuration /** - m_tauJetID("SetMe"), - m_tauJetIDBkg("SetMe"), - m_tauEVetoID("SetMe"), - m_tauVetoLArCrack(false), - m_tauPtcut(20000.), - **/ - // Applying new tau energy calibration - m_applyTauMVATES(false), + m_tauJetID("SetMe"), + m_tauJetIDBkg("SetMe"), + m_tauEVetoID("SetMe"), + m_tauVetoLArCrack(false), + m_tauPtcut(20000.), + **/ // [[[----------------------------------------------- // Particle Level / Truth Configuration - m_truth_electron{ 25000., 2.5, true, false }, - m_truth_muon{ 25000., 2.5, true, false }, - m_truth_photon{ 25000., 2.5, "SET_ME", "SET_ME" }, - m_truth_jet{ 25000., 2.5 }, + m_truth_electron{25000., 2.5, true, false}, + m_truth_muon{25000., 2.5, true, false}, + m_truth_softmuon{4000., 2.5}, + m_truth_photon{25000., 2.5, "SET_ME", "SET_ME"}, + m_truth_jet{25000., 2.5}, // -----------------------------------------------]]] // HL LHC studies m_HLLHC(false), + m_HLLHCFakes(false), // Selections m_allSelectionNames(nullptr), // Trigger - m_allTriggers(nullptr), - m_electronTriggers(nullptr), - m_muonTriggers(nullptr), - m_tauTriggers(nullptr), + m_allTriggers_Tight(nullptr), + m_electronTriggers_Tight(nullptr), + m_muonTriggers_Tight(nullptr), + m_tauTriggers_Tight(nullptr), + m_allTriggers_Loose(nullptr), + m_electronTriggers_Loose(nullptr), + m_muonTriggers_Loose(nullptr), + m_tauTriggers_Loose(nullptr), // Where the sum of event weights // before derivation framework is kept @@ -233,7 +350,9 @@ namespace top{ m_outputEvents("SetMe"), m_saveOnlySelectedEvents(true), m_outputFileSetAutoFlushZero(false), - + m_outputFileNEventAutoFlush(1000), // 1000 events + m_outputFileBasketSizePrimitive(4096), // 4kB + m_outputFileBasketSizeVector(40960), // 40kB // Number of events to run on (only for testing) m_numberOfEventsToRun(0), @@ -247,11 +366,14 @@ namespace top{ m_systHashPhotons(nullptr), m_systHashElectrons(nullptr), + m_systHashFwdElectrons(nullptr), m_systHashMuons(nullptr), + m_systHashSoftMuons(nullptr), m_systHashTaus(nullptr), m_systHashJets(nullptr), m_systHashLargeRJets(nullptr), m_systHashTrackJets(nullptr), + m_systHashTracks(nullptr), m_systHashMET(nullptr), m_systHashAll(nullptr), @@ -262,31 +384,40 @@ namespace top{ m_systMapPhotons(nullptr), m_systMapElectrons(nullptr), + m_systMapFwdElectrons(nullptr), m_systMapMuons(nullptr), + m_systMapSoftMuons(nullptr), m_systMapTaus(nullptr), m_systMapJets(nullptr), m_systMapLargeRJets(nullptr), m_systMapTrackJets(nullptr), + m_systMapTracks(nullptr), m_systMapMET(nullptr), m_systSgKeyMapPhotons(nullptr), m_systSgKeyMapElectrons(nullptr), + m_systSgKeyMapFwdElectrons(nullptr), m_systSgKeyMapMuons(nullptr), + m_systSgKeyMapSoftMuons(nullptr), m_systSgKeyMapTaus(nullptr), m_systSgKeyMapJets(nullptr), m_systSgKeyMapJets_electronInJetSubtraction(nullptr), m_systSgKeyMapJetsLoose_electronInJetSubtraction(nullptr), m_systSgKeyMapLargeRJets(nullptr), m_systSgKeyMapTrackJets(nullptr), + m_systSgKeyMapTracks(nullptr), m_systSgKeyMapMET(nullptr), m_systAllSgKeyMapPhotons(nullptr), m_systAllSgKeyMapElectrons(nullptr), + m_systAllSgKeyMapFwdElectrons(nullptr), m_systAllSgKeyMapMuons(nullptr), + m_systAllSgKeyMapSoftMuons(nullptr), m_systAllSgKeyMapTaus(nullptr), m_systAllSgKeyMapJets(nullptr), m_systAllSgKeyMapLargeRJets(nullptr), m_systAllSgKeyMapTrackJets(nullptr), + m_systAllSgKeyMapTracks(nullptr), m_systAllSgKeyMapElectrons_electronInJetSubtraction(nullptr), m_systAllSgKeyMapJets_electronInJetSubtraction(nullptr), m_systAllSgKeyMapJetsLoose_electronInJetSubtraction(nullptr), @@ -295,8 +426,12 @@ namespace top{ m_systAllSgKeyMapPhotonsTDSAux(nullptr), m_systAllSgKeyMapElectronsTDS(nullptr), m_systAllSgKeyMapElectronsTDSAux(nullptr), + m_systAllSgKeyMapFwdElectronsTDS(nullptr), + m_systAllSgKeyMapFwdElectronsTDSAux(nullptr), m_systAllSgKeyMapMuonsTDS(nullptr), m_systAllSgKeyMapMuonsTDSAux(nullptr), + m_systAllSgKeyMapSoftMuonsTDS(nullptr), + m_systAllSgKeyMapSoftMuonsTDSAux(nullptr), m_systAllSgKeyMapTausTDS(nullptr), m_systAllSgKeyMapTausTDSAux(nullptr), m_systAllSgKeyMapJetsTDS(nullptr), @@ -305,6 +440,8 @@ namespace top{ m_systAllSgKeyMapLargeRJetsTDSAux(nullptr), m_systAllSgKeyMapTrackJetsTDS(nullptr), m_systAllSgKeyMapTrackJetsTDSAux(nullptr), + m_systAllSgKeyMapTracksTDS(nullptr), + m_systAllSgKeyMapTracksTDSAux(nullptr), m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS(nullptr), m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux(nullptr), m_systAllSgKeyMapJets_electronInJetSubtractionTDS(nullptr), @@ -321,484 +458,1162 @@ namespace top{ m_sgKeyPseudoTop("PseudoTopResult"), m_systSgKeyMapPseudoTop(nullptr), + m_systSgKeyMapPseudoTopLoose(nullptr), m_systMapJetGhostTrack(nullptr), m_systDecoKeyMapJetGhostTrack(nullptr), m_systAllTTreeNames(nullptr), m_systPersistantAllTTreeNames(nullptr), m_systAllTTreeIndex(nullptr), - m_systAllTTreeLooseIndex(nullptr) - { - m_allSelectionNames = std::shared_ptr<std::vector<std::string>> ( new std::vector<std::string> ); - - m_systHashPhotons = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashElectrons = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashMuons = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashTaus = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashJets = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashLargeRJets = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashTrackJets = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_systHashMET = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - - m_systHashAll = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_list_systHashAll = std::shared_ptr<std::list<std::size_t>> ( new std::list<std::size_t> ); - m_systHash_electronInJetSubtraction = std::shared_ptr<std::unordered_set<std::size_t>> ( new std::unordered_set<std::size_t> ); - m_list_systHash_electronInJetSubtraction = std::shared_ptr<std::list<std::size_t>> ( new std::list<std::size_t> ); - - m_systMapPhotons = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapElectrons = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapMuons = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapTaus = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapJets = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapLargeRJets = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapTrackJets = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systMapMET = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - - m_systSgKeyMapPhotons = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapElectrons = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapMuons = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapTaus = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapJets = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapJets_electronInJetSubtraction = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapJetsLoose_electronInJetSubtraction = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapLargeRJets = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapTrackJets = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapMET = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - m_systAllSgKeyMapPhotons = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapElectrons = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapMuons = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapTaus = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJets = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapLargeRJets = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapTrackJets = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); + m_systAllTTreeLooseIndex(nullptr), + m_saveBootstrapWeights(false), + m_BootstrapReplicas(100), + m_useBadBatmanCleaning(true), + m_badBatmanCleaningMin(276262), + m_badBatmanCleaningMax(311481), + m_useEventLevelJetCleaningTool(false), + m_year("UNKNOWN") { + m_allSelectionNames = std::shared_ptr<std::vector<std::string> > (new std::vector<std::string> ); + + m_systHashPhotons = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashElectrons = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashFwdElectrons = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashMuons = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashSoftMuons = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashTaus = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashJets = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashLargeRJets = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashTrackJets = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashTracks = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_systHashMET = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + + m_systHashAll = std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_list_systHashAll = std::shared_ptr<std::list<std::size_t> > (new std::list<std::size_t> ); + m_systHash_electronInJetSubtraction = + std::shared_ptr<std::unordered_set<std::size_t> > (new std::unordered_set<std::size_t> ); + m_list_systHash_electronInJetSubtraction = std::shared_ptr<std::list<std::size_t> > (new std::list<std::size_t> ); + + m_systMapPhotons = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapElectrons = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapFwdElectrons = std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > ( + new std::unordered_map<std::size_t, CP::SystematicSet> ); + m_systMapMuons = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapSoftMuons = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapTaus = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapJets = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapLargeRJets = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapTrackJets = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + m_systMapTracks = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + + + + m_systMapMET = + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > (new std::unordered_map<std::size_t, + CP::SystematicSet> ); + + m_systSgKeyMapPhotons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapElectrons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapFwdElectrons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapMuons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapSoftMuons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapTaus = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapJets = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapJets_electronInJetSubtraction = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systSgKeyMapJetsLoose_electronInJetSubtraction = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systSgKeyMapLargeRJets = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapTrackJets = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + + m_systSgKeyMapTracks = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + + + m_systSgKeyMapMET = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + + m_systAllSgKeyMapPhotons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapElectrons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapFwdElectrons = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapMuons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapSoftMuons = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapTaus = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapJets = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapLargeRJets = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapTrackJets = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapTracks = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); m_systAllSgKeyMapElectrons_electronInJetSubtraction - = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); + = std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); m_systAllSgKeyMapJets_electronInJetSubtraction - = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); + = std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); m_systAllSgKeyMapJetsLoose_electronInJetSubtraction - = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - m_systAllSgKeyMapPhotonsTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapPhotonsTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapElectronsTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapElectronsTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapMuonsTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapMuonsTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapTausTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapTausTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJetsTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJetsTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapLargeRJetsTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapLargeRJetsTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapTrackJetsTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapTrackJetsTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJets_electronInJetSubtractionTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - - m_systSgKeyMapMissingET = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapMissingETLoose = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - m_systSgKeyMapKLFitter = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systSgKeyMapKLFitterLoose = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - m_systSgKeyMapPseudoTop = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - m_systMapJetGhostTrack = std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> ( new std::unordered_map<std::size_t,CP::SystematicSet> ); - m_systDecoKeyMapJetGhostTrack = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - - m_systAllTTreeNames = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systPersistantAllTTreeNames = std::shared_ptr<std::unordered_map<std::size_t,std::string>> ( new std::unordered_map<std::size_t,std::string> ); - m_systAllTTreeIndex = std::shared_ptr<std::unordered_map<std::size_t,unsigned int>> ( new std::unordered_map<std::size_t,unsigned int> ); - m_systAllTTreeLooseIndex = std::shared_ptr<std::unordered_map<std::size_t,unsigned int>> ( new std::unordered_map<std::size_t,unsigned int> ); + = std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + + m_systAllSgKeyMapPhotonsTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapPhotonsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapElectronsTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapElectronsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapFwdElectronsTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapFwdElectronsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapMuonsTDS = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapMuonsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapSoftMuonsTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapSoftMuonsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapTausTDS = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapTausTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapJetsTDS = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapJetsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapLargeRJetsTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapLargeRJetsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapTrackJetsTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapTrackJetsTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapTracksTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapTracksTDSAux = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + + m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapJets_electronInJetSubtractionTDS = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + + + m_systSgKeyMapMissingET = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapMissingETLoose = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + + m_systSgKeyMapKLFitter = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapKLFitterLoose = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + + m_systSgKeyMapPseudoTop = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systSgKeyMapPseudoTopLoose = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + + m_systMapJetGhostTrack = std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > ( + new std::unordered_map<std::size_t, CP::SystematicSet> ); + m_systDecoKeyMapJetGhostTrack = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + + + m_systAllTTreeNames = + std::shared_ptr<std::unordered_map<std::size_t, std::string> > (new std::unordered_map<std::size_t, + std::string> ); + m_systPersistantAllTTreeNames = std::shared_ptr<std::unordered_map<std::size_t, std::string> > ( + new std::unordered_map<std::size_t, std::string> ); + m_systAllTTreeIndex = + std::shared_ptr<std::unordered_map<std::size_t, unsigned int> > (new std::unordered_map<std::size_t, + unsigned int> ); + m_systAllTTreeLooseIndex = + std::shared_ptr<std::unordered_map<std::size_t, unsigned int> > (new std::unordered_map<std::size_t, + unsigned int> ); // Nominal has value CP::SystematicSet nominal; m_nominalHashValue = nominal.hash(); + + m_treeFilter = std::make_shared<TreeFilter>(); } - void TopConfig::setConfigSettings( top::ConfigurationSettings* const& settings ) - { + void TopConfig::setConfigSettings(top::ConfigurationSettings* const& settings) { // Selections const std::vector<top::SelectionConfigurationData> allSelections = settings->selections(); + for (auto sel : allSelections) { - m_allSelectionNames->push_back( sel.m_name ); + m_allSelectionNames->push_back(sel.m_name); } // set GRL file - this->setGrlDir( settings->value("GRLDir") ); - this->setGrlFile( settings->value("GRLFile") ); + this->setGrlDir(settings->value("GRLDir")); + this->setGrlFile(settings->value("GRLFile")); + + // Set TDP file name + this->setTDPPath(settings->value("TDPPath")); + + m_treeFilter->init(settings->value("FilterTrees")); + //we need storegate keys so people can pick different collections / met / jets etc. - this->sgKeyPhotons( settings->value("PhotonCollectionName") ); - this->sgKeyElectrons( settings->value("ElectronCollectionName") ); - this->sgKeyMuons( settings->value("MuonCollectionName") ); - this->sgKeyTaus( settings->value("TauCollectionName") ); - this->sgKeyJets( settings->value("JetCollectionName") ); - this->sgKeyLargeRJets( settings->value("LargeJetCollectionName") ); - this->sgKeyTrackJets( settings->value("TrackJetCollectionName") ); - this->jetSubstructureName( settings->value("LargeJetSubstructure") ); - this->decoKeyJetGhostTrack( settings->value("JetGhostTrackDecoName") ); - - if(settings->value("applyTTVACut") == "False") - this->m_applyTTVACut = false; + this->sgKeyPhotons(settings->value("PhotonCollectionName")); + this->sgKeyElectrons(settings->value("ElectronCollectionName")); + this->sgKeyFwdElectrons(settings->value("FwdElectronCollectionName")); + this->sgKeyMuons(settings->value("MuonCollectionName")); + //small trick for the soft muons + if (settings->value("UseSoftMuons") == "True") this->sgKeySoftMuons("Soft" + settings->value("MuonCollectionName")); + + else this->sgKeySoftMuons("None"); + this->sgKeyTaus(settings->value("TauCollectionName")); + this->sgKeyJets(settings->value("JetCollectionName")); + this->sgKeyLargeRJets(settings->value("LargeJetCollectionName")); + this->sgKeyTrackJets(settings->value("TrackJetCollectionName")); + this->sgKeyTracks(settings->value("TrackCollectionName")); + this->jetSubstructureName(settings->value("LargeJetSubstructure")); + this->decoKeyJetGhostTrack(settings->value("JetGhostTrackDecoName")); + + // check that jets use tagged collection name for new derivations + // this is due to b-tagging breaking changes in derivations + if (m_aodMetaData->valid()) { + try { + std::string deriv_rel_name = m_aodMetaData->get("/TagInfo", "AtlasRelease_AODtoDAOD"); + ATH_MSG_INFO("Checking jet collection name compatibility, reading (MetaData->TagInfo): " << deriv_rel_name); + size_t pos = deriv_rel_name.find('-'); + if (pos != std::string::npos) { + deriv_rel_name = deriv_rel_name.substr(pos + 1); + int deriv_rel; + std::sscanf(deriv_rel_name.c_str(), "21.2.%d", &deriv_rel); + // check for derivation version due to format breakage with calo jet b-tagging + if (deriv_rel >= 72) { // 21.2.72.0: release where we need tagged jet collection + if (this->sgKeyJets() == this->sgKeyJetsType()) { // jet collection is NOT tagged + throw std::runtime_error( + "TopConfig: You are using derivation with release 21.2.72.0 or newer and did not specify tagged small-R jet collection, e.g. \"AntiKt4EMPFlowJets_BTagging201903\". This is necessary for b-tagging to work!"); + } + } else { // release does NOT have tagged jet collection + if (this->sgKeyJets() != this->sgKeyJetsType()) { // jet collection is NOT tagged + throw std::runtime_error( + "TopConfig: You are using derivation with release older than 21.2.72.0 so you cannot use tagged jet containers as you specified: \"" + this->sgKeyJets() + "\". Use \"" + this->sgKeyJetsType() + + "\" instead."); + } + } + // check for derivation version due to format breakage with track jet b-tagging + if (this->useTrackJets()) { + if (deriv_rel >= 87) { // 21.2.87.0: release where we need tagged track jet collection + if (this->sgKeyTrackJets() == this->sgKeyTrackJetsType()) { // jet collection is NOT tagged + throw std::runtime_error( + "TopConfig: You are using derivation with release 21.2.87.0 or newer and did not specify tagged track jet collection, e.g. \"AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903\". This is necessary for b-tagging to work!"); + } + } else { // release does NOT have tagged jet collection + if (this->sgKeyTrackJets() != this->sgKeyTrackJetsType()) { // jet collection is NOT tagged + throw std::runtime_error( + "TopConfig: You are using derivation with release older than 21.2.87.0 so you cannot use tagged track jet containers as you specified: \"" + this->sgKeyTrackJets() + "\". Use \"" + this->sgKeyTrackJetsType() + + "\" instead."); + } + } + } + // check derivation version due to fJVT info needed at derivation level for PFlow + if (this->useParticleFlowJets() && (settings->retrieve("ForwardJVTinMETCalculation") || settings->value("ForwardJVTWP") != "None")){ //fJVT requested for PFlow + if (deriv_rel < 97) { //21.2.97.0 + throw std::runtime_error( + "TopConfig: You are using derivation with release 21.2.96.0 or older and requested fJVT for particle-flow jets. The necessary information for PFlow fjvt is only present from release 21.2.97.0 and newer, you will need to switch to newer derivations or turn off fJVT (ForwardJVTWP = \"None\" && ForwardJVTinMETCalculation = \"False\")"); + } + } + } else { + ATH_MSG_WARNING("Could not parse derivation release from the file metadata. We cannot check that correct jet and/or track jet collection is used for b-tagging, or that a new enough derivation is used for PFlow fJVT. You are on your own."); + } + // try to parse the derivation release, we need the release number + } catch (std::logic_error& e) { + ATH_MSG_WARNING(e.what()); + ATH_MSG_WARNING("Could not obtain derivation release from the file metadata. We cannot check that correct jet and/or track jet collection is used for b-tagging, or that a new enough derivation is used for PFlow fJVT. You are on your own."); + } + } + + // ROOTCORE/Analysis release series + this->setReleaseSeries(); + + if (settings->value("applyTTVACut") == "False") this->m_applyTTVACut = false; if (this->isMC()) { - this->sgKeyMCParticle( settings->value("TruthCollectionName") ); - this->sgKeyTruthElectrons( settings->value("TruthElectronCollectionName") ); - this->sgKeyTruthMuons( settings->value("TruthMuonCollectionName") ); - this->sgKeyTruthPhotons( settings->value("TruthPhotonCollectionName") ); - this->sgKeyTruthMET( settings->value("TruthMETCollectionName") ); - this->sgKeyTruthJets( settings->value("TruthJetCollectionName") ); - this->sgKeyTruthLargeRJets( settings->value("TruthLargeRJetCollectionName") ); + this->sgKeyMCParticle(settings->value("TruthCollectionName")); + this->sgKeyTruthElectrons(settings->value("TruthElectronCollectionName")); + this->sgKeyTruthMuons(settings->value("TruthMuonCollectionName")); + this->sgKeyTruthPhotons(settings->value("TruthPhotonCollectionName")); + this->sgKeyTruthMET(settings->value("TruthMETCollectionName")); + this->sgKeyTruthJets(settings->value("TruthJetCollectionName")); + this->sgKeyTruthLargeRJets(settings->value("TruthLargeRJetCollectionName")); + this->sgKeyTruthTaus(settings->value("TruthTauCollectionName")); // Dump truth block - if (settings->value("TruthBlockInfo") == "True") - this->setTruthBlockInfo(); + if (settings->value("TruthBlockInfo") == "True") this->setTruthBlockInfo(); // Save the Truth PDF information if (settings->value("PDFInfo") == "True") { - this->setTruthPDFInfo(); - } - else if (settings->value("PDFInfo") == "Nominal") { - // Save the Truth PDF information in the reco-level tree instead of the truth-level one - this->setTruthPDFInfo(); - this->setTruthPDFInfoInNominalTrees(); + this->setTruthPDFInfo(); + } else if (settings->value("PDFInfo") == "Nominal") { + // Save the Truth PDF information in the reco-level tree instead of the truth-level one + this->setTruthPDFInfo(); + this->setTruthPDFInfoInNominalTrees(); } // Save the MC generator weights if (settings->value("MCGeneratorWeights") == "True") { - this->setMCGeneratorWeights(); + this->setMCGeneratorWeights(); + } else if (settings->value("MCGeneratorWeights") == "Nominal") { + // Save the Truth PDF information in the reco-level tree instead of the truth-level one + this->setMCGeneratorWeights(); + this->setMCGeneratorWeightsInNominalTrees(); + } + + // load the nominal weight names that we should try to get the real nominal weight name + const std::string& tmp = settings->value("NominalWeightNames"); + + // Remove the whitespaces between the names but keep + // the whitespaces within quotation marks + std::string trimmedName = ""; + bool deleteSpaces = true; + bool start = false; + for(unsigned int i = 0; i < tmp.size(); ++i) { + if(tmp[i] == '\"') { + start ? start = false : start = true; + if(start) { + deleteSpaces = false; + } + } + if(!start) { + deleteSpaces = true; + } + if(deleteSpaces) { + if(tmp[i] != ' ') { + trimmedName += tmp[i]; + } + } else { + trimmedName += tmp[i]; + } } - else if (settings->value("MCGeneratorWeights") == "Nominal") { - // Save the Truth PDF information in the reco-level tree instead of the truth-level one - this->setMCGeneratorWeights(); - this->setMCGeneratorWeightsInNominalTrees(); + boost::split(m_nominalWeightNames, trimmedName, boost::is_any_of(",")); + // now remove all occurences of '"' + for (std::string& iname : m_nominalWeightNames) { + iname.erase(std::remove(iname.begin(), iname.end(), '"'), iname.end()); + // and check if we have newline characters (some weight have those...) + // and parse them properly + boost::replace_all(iname, "\\n", "\n"); } - // Save the Top Parton History - if (this->useTruthParticles() && settings->value("TopPartonHistory") != "False") - this->setTopPartonHistory(); + try { + m_nominalWeightIndex = std::stoi(settings->value("NominalWeightFallbackIndex")); + } catch (std::invalid_argument &e) { + std::cout << "Failed to parse NominalWeightFallbackIndex value: " << settings->value("NominalWeightFallbackIndex") << std::endl; + throw; + } + settings->retrieve("ForceNominalWeightFallbackIndex", m_forceWeightIndex); + + // Save the Top Parton History + if (settings->value("TopPartonHistory") != "False") this->setTopPartonHistory(); + + // Perform parton-level selection and save particle level objects + bool topPartonLevel=true; + settings->retrieve("TopPartonLevel",topPartonLevel); + this->setTopPartonLevel(topPartonLevel); + // Perform particle-level selection and save particle level objects - if ( settings->value("TopParticleLevel") == "True" ){ - this->setTopParticleLevel(); - } + bool topParticleLevel=true; + settings->retrieve("TopParticleLevel",topParticleLevel); + this->setTopParticleLevel(topParticleLevel); + // Particle-level OR - if (settings->value("DoParticleLevelOverlapRemoval") == "True"){ - // Value True -> Do all ORs - this->setParticleLevelOverlapRemovalElJet(true); - this->setParticleLevelOverlapRemovalMuJet(true); - this->setParticleLevelOverlapRemovalJetPhoton(true); - } else if (settings->value("DoParticleLevelOverlapRemoval") == "False"){ - // Value False -> Do not perform any OR. - this->setParticleLevelOverlapRemovalElJet(false); - this->setParticleLevelOverlapRemovalMuJet(false); - this->setParticleLevelOverlapRemovalJetPhoton(false); + if (settings->value("DoParticleLevelOverlapRemoval") == "True") { + // Value True -> Do all ORs + this->setParticleLevelOverlapRemovalElJet(true); + this->setParticleLevelOverlapRemovalMuJet(true); + this->setParticleLevelOverlapRemovalJetPhoton(true); + } else if (settings->value("DoParticleLevelOverlapRemoval") == "False") { + // Value False -> Do not perform any OR. + this->setParticleLevelOverlapRemovalElJet(false); + this->setParticleLevelOverlapRemovalMuJet(false); + this->setParticleLevelOverlapRemovalJetPhoton(false); } else { - // Explicitly specify the possible OR values. - std::vector<std::string> tokens; - tokenize(settings->value("DoParticleLevelOverlapRemoval"), tokens, ","); - while (tokens.size()){ - const auto & token = tokens.back(); - - if (token == "MuonJet"){ - this->setParticleLevelOverlapRemovalMuJet(true); - } else if (token == "ElectronJet"){ - this->setParticleLevelOverlapRemovalElJet(true); - } else if (token == "JetPhoton"){ - this->setParticleLevelOverlapRemovalJetPhoton(true); - } else { - throw std::runtime_error{"TopConfig: Option DoParticleLevelOverlapRemoval: Invalid Token"}; - } - - // Remove the last token in the container. - tokens.pop_back(); + // Explicitly specify the possible OR values. + std::vector<std::string> tokens; + tokenize(settings->value("DoParticleLevelOverlapRemoval"), tokens, ","); + while (tokens.size()) { + const auto& token = tokens.back(); + + if (token == "MuonJet") { + this->setParticleLevelOverlapRemovalMuJet(true); + } else if (token == "ElectronJet") { + this->setParticleLevelOverlapRemovalElJet(true); + } else if (token == "JetPhoton") { + this->setParticleLevelOverlapRemovalJetPhoton(true); + } else { + throw std::runtime_error { + "TopConfig: Option DoParticleLevelOverlapRemoval: Invalid Token" + }; } - } + // Remove the last token in the container. + tokens.pop_back(); + } + } // check if you are running over AFII samples // only check the configuration file if the AodMetaData is not instatiated - if(m_aodMetaData->valid()){ - try{ - auto simulatorName = m_aodMetaData->get("/Simulation/Parameters","Simulator"); - bool aodMetaDataIsAFII = m_aodMetaData->isAFII(); - std::cout << "AodMetaData :: Simulation Type " << simulatorName << " -> " << "Setting IsAFII to " << aodMetaDataIsAFII << std::endl; - this->setIsAFII(aodMetaDataIsAFII); - } - catch(std::logic_error aodMetaDataError){ - std::cout << "An error was encountered handling AodMetaData : " << aodMetaDataError.what() << std::endl; - std::cout << "We will attempt to read the IsAFII flag from your config." << std::endl; - this->ReadIsAFII(settings); - } - } - else{ - this->ReadIsAFII(settings); - } - // Special mode to run Loose events on MC for the purposes - // of determining the Fakes control regions - // Not for regular analysis users - // If you use this option, and are not part of the Fakes sub-group, you just joined! - // Please report your studies in the top-fakes meetings! - if (settings->value("FakesControlRegionDoLooseMC") == "True") - this->FakesControlRegionDetermination_setDoLooseEventsOnMC_notForRegularUsers(); - } - - if (!this->isMC()) { - m_doLooseEvents = true; - if (settings->value("FakesMMWeights") == "True") { - this->setFakesMMWeightsCalculation(); - std::string dir = settings->value("FakesMMDir"); - if (dir != "") - this->setFakesMMDir(dir); - if (settings->value("FakesMMDebug") == "True") - this->setFakesMMDebug(); + if (m_aodMetaData->valid()) { + try{ + auto simulatorName = m_aodMetaData->get("/Simulation/Parameters", "Simulator"); + bool aodMetaDataIsAFII = m_aodMetaData->isAFII(); + ATH_MSG_INFO("AodMetaData :: Simulation Type " << simulatorName << " -> " << "Setting IsAFII to " << + aodMetaDataIsAFII); + this->setIsAFII(aodMetaDataIsAFII); + auto generatorsName = m_aodMetaData->get("/TagInfo", "generators"); + ATH_MSG_INFO("AodMetaData :: Generators Type " << generatorsName); + this->setGenerators(generatorsName); + auto AMITagName = m_aodMetaData->get("/TagInfo", "AMITag"); + ATH_MSG_INFO("AodMetaData :: AMITag " << AMITagName); + this->setAMITag(AMITagName); + } + catch (const std::logic_error& aodMetaDataError) { + ATH_MSG_WARNING("An error was encountered handling AodMetaData : " << aodMetaDataError.what()); + ATH_MSG_WARNING("We will attempt to read the IsAFII flag from your config."); + this->ReadIsAFII(settings); + ATH_MSG_WARNING("Unfortunately, we can not read MC generators and AMITag without valid MetaData."); + this->setGenerators("unknown"); + this->setAMITag("unknown"); + } + } else { + this->ReadIsAFII(settings); + } + } + + // Get list of branches to be filtered + if (settings->value("FilterBranches") != " ") { + std::vector<std::string> branches; + tokenize(settings->value("FilterBranches"), branches, ","); + + if (branches.size() == 0) { + ATH_MSG_WARNING("You provided \"FilterBranches\" option but you did not provide any meaningful values. Ignoring"); + } + this->setFilterBranches(branches); + } + + // Get list of PartonLevel branches to be filtered + if (settings->value("FilterPartonLevelBranches") != " ") { + std::vector<std::string> branches; + tokenize(settings->value("FilterPartonLevelBranches"), branches, ","); + + if (branches.size() == 0) { + ATH_MSG_WARNING("You provided \"FilterPartonLevelBranches\" option but you did not provide any meaningful values. Ignoring"); + } + this->setFilterPartonLevelBranches(branches); + } + + // Get list of ParticleLevel branches to be filtered + if (settings->value("FilterParticleLevelBranches") != " ") { + std::vector<std::string> branches; + tokenize(settings->value("FilterParticleLevelBranches"), branches, ","); + + if (branches.size() == 0) { + ATH_MSG_WARNING("You provided \"FilterParticleLevelBranches\" option but you did not provide any meaningful values. Ignoring"); } + this->setFilterParticleLevelBranches(branches); + } + + // Get list of nominal_Loose branches to be filtered + if (settings->value("FilterNominalLooseBranches") != " ") { + std::vector<std::string> branches; + tokenize(settings->value("FilterNominalLooseBranches"), branches, ","); + + if (branches.size() == 0) { + ATH_MSG_WARNING("You provided \"FilterNominalLooseBranches\" option but you did not provide any meaningful values. Ignoring"); + } + this->setFilterNominalLooseBranches(branches); + } + + // Force recomputation of CP variables? + if (settings->value("RecomputeCPVariables") == "False") m_recomputeCPvars = false; + + // Bootstrapping weights (permitted in MC and Data) + if (settings->value("SaveBootstrapWeights") == "True") { + this->setSaveBootstrapWeights(true); + this->setNumberOfBootstrapReplicas(std::atoi(settings->value("NumberOfBootstrapReplicas").c_str())); + } + + settings->retrieve("UseLooseObjectsInMETInLooseTree", m_useLooseObjectsInMETInLooseTree); + settings->retrieve("UseLooseObjectsInMETInNominalTree", m_useLooseObjectsInMETInNominalTree); + settings->retrieve("WriteMETBuiltWithLooseObjects", m_writeMETBuiltWithLooseObjects); + + if (this->isMC()) { + m_doLooseEvents = (settings->value("DoLoose") == "MC" || settings->value("DoLoose") == "Both"); + m_doTightEvents = (settings->value("DoTight") == "MC" || settings->value("DoTight") == "Both"); + m_doLooseSysts = (settings->value("DoSysts") == "Loose" || settings->value("DoSysts") == "Both") && + m_doLooseEvents; + m_doTightSysts = (settings->value("DoSysts") == "Tight" || settings->value("DoSysts") == "Both") && + m_doTightEvents; + } else { + m_doLooseEvents = (settings->value("DoLoose") == "Data" || settings->value("DoLoose") == "Both"); + if (m_doLooseEvents) { + if (settings->value("FakesMMWeightsIFF") == "True") { + this->setFakesMMWeightsCalculationIFF(); + std::string configIFF = settings->value("FakesMMConfigIFF"); + if (configIFF != "") { + this->setFakesMMConfigIFF(configIFF); + } + if (settings->value("FakesMMIFFDebug") == "True") { + this->setFakesMMIFFDebug(); + } + } + } + m_doTightEvents = (settings->value("DoTight") == "Data" || settings->value("DoTight") == "Both"); + } + + // Switch to set event BadBatman cleaning + if (settings->value("UseBadBatmanCleaning") == "False") { + this->setUseBadBatmanCleaning(false); + } else if (settings->value("UseBadBatmanCleaning") == "True") { + this->setUseBadBatmanCleaning(true); + } else { + throw std::invalid_argument { + "TopConfig: Option UseBadBatmanCleaning unknown value, only True or False (default) is allowed" + }; + } + + // now check the ranges of the batman cleaning + { + std::vector<std::string> tokens; + tokenize(settings->value("BadBatmanCleaningRange"), tokens, ":"); + if (tokens.size() != 2) { + throw std::runtime_error { + "TopConfig: Option BadBatmanCleaningRange should be of the form \'RunNumber1:RunNumber2\'" + }; + } + unsigned int minRunNumber = 999999; + unsigned int maxRunNumber = 0; + try { // convert the values from string to unsigned int + minRunNumber = std::stoul(tokens.at(0)); + maxRunNumber = std::stoul(tokens.at(1)); + } catch (...) { + throw std::invalid_argument { + "TopConfig: Option BadBatmanCleaningRange cannot convert the RunNumbers into unsigned int" + }; + } + + // check if the first value is not larger than the second value + if (maxRunNumber < minRunNumber) { + throw std::invalid_argument { + "TopConfig: Option BadBatmanCleaningRange: the first RunNumber cannot be larger than the second!" + }; + } + + // check if there is an overlap with data 2017 as this option should not be used for this period + static const unsigned int data17_begin = 325713; + static const unsigned int data17_end = 348835; + + if (std::max(minRunNumber, data17_begin) <= std::min(maxRunNumber, data17_end)) { + throw std::invalid_argument { + "TopConfig: Option BadBatmanCleaningRange cannot include RunNumbers from 2017 data taking (325713-348835)" + }; + } + + this->setBadBatmanCleaningMin(minRunNumber); + this->setBadBatmanCleaningMax(maxRunNumber); + } + + // Switch to set event level jet cleaning tool [false by default] + if (settings->value("UseEventLevelJetCleaningTool") == "True") { + this->setUseEventLevelJetCleaningTool(true); } // Object Selection Name - this->objectSelectionName( settings->value("ObjectSelectionName") ); + this->objectSelectionName(settings->value("ObjectSelectionName")); // Output Format - this->outputFormat( settings->value("OutputFormat") ); + this->outputFormat(settings->value("OutputFormat")); // Output Events - this->outputEvents( settings->value("OutputEvents") ); + this->outputEvents(settings->value("OutputEvents")); // SetAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround m_outputFileSetAutoFlushZero = false; - if (settings->value( "OutputFileSetAutoFlushZero" ) == "True") - m_outputFileSetAutoFlushZero = true; + if (settings->value("OutputFileSetAutoFlushZero") != "False") { + ATH_MSG_WARNING("OutputFileSetAutoFlushZero is deprecated in favour of more custom memory options"); + } + // Configurable TTree options (ANALYSISTO-463) + if (settings->value("OutputFileNEventAutoFlush") != "") { + m_outputFileNEventAutoFlush = std::stoi(settings->value("OutputFileNEventAutoFlush")); + } + if (settings->value("OutputFileBasketSizePrimitive") != "") { + m_outputFileBasketSizePrimitive = std::stoi(settings->value("OutputFileBasketSizePrimitive")); + } + if (settings->value("OutputFileBasketSizeVector") != "") { + m_outputFileBasketSizeVector = std::stoi(settings->value("OutputFileBasketSizeVector")); + } // The systematics want much much more configuration options..... - this->systematics( settings->value("Systematics") ); + this->systematics(settings->value("Systematics")); // special: allow to dump the systematics-shifted b-tagging SFs in the systematics trees - if (settings->value( "DumpBtagSystsInSystTrees" ) == "True") - this->dumpBtagSystsInSystTrees(true); + if (settings->value("DumpBtagSystsInSystTrees") == "True") this->dumpBtagSystsInSystTrees(true); + + // special: store per-jet btag SFs + if (settings->value("StorePerJetBtagSFs") == "True") this->storePerJetBtagSFs(true); // Electron configuration - this->egammaSystematicModel( settings->value("EgammaSystematicModel") ); - this->electronID( settings->value("ElectronID") ); - this->electronIDLoose( settings->value("ElectronIDLoose") ); - this->electronIsolation( settings->value("ElectronIsolation") ); - this->electronIsolationLoose( settings->value("ElectronIsolationLoose") ); - this->electronPtcut( std::stof(settings->value("ElectronPt")) ); - if( settings->value("ElectronIsoSFs") == "False" ) - this->m_electronIsoSFs = false; + this->egammaSystematicModel(settings->value("EgammaSystematicModel")); + this->electronEfficiencySystematicModel(settings->value("ElectronEfficiencySystematicModel")); + this->electronEfficiencySystematicModelEtaBinning(settings->value("ElectronEfficiencySystematicModelEtaBinning")); + this->electronEfficiencySystematicModelEtBinning(settings->value("ElectronEfficiencySystematicModelEtBinning")); + this->electronID(settings->value("ElectronID")); + this->electronIDLoose(settings->value("ElectronIDLoose")); + { + std::string const& cut_wp = settings->value("ElectronIsolation"); + std::string const& sf_wp = settings->value("ElectronIsolationSF"); + this->electronIsolation(cut_wp); + this->electronIsolationSF(sf_wp == " " ? cut_wp : sf_wp); + } + { + std::string const& cut_wp = settings->value("ElectronIsolationLoose"); + std::string const& sf_wp = settings->value("ElectronIsolationSFLoose"); + this->electronIsolationLoose(cut_wp); + this->electronIsolationSFLoose(sf_wp == " " ? cut_wp : sf_wp); + } + this->useElectronChargeIDSelection(settings->value("UseElectronChargeIDSelection")); + this->useEgammaLeakageCorrection(settings->value("UseEgammaLeakageCorrection")); + this->electronPtcut(std::stof(settings->value("ElectronPt"))); + this->enablePromptLeptonImprovedVetoStudies(settings->value("EnablePromptLeptonImprovedVetoStudies")); + + m_electronIDDecoration = "AnalysisTop_" + m_electronID; m_electronIDLooseDecoration = "AnalysisTop_" + m_electronIDLoose; - // Photon configuration - this->photonPtcut( std::stof(settings->value("PhotonPt")) ); - this->photonEtacut( std::stof(settings->value("PhotonEta")) ); - this->photonIdentification( settings->value("PhotonID") ); - this->photonIdentificationLoose( settings->value("PhotonIDLoose") ); - this->photonIsolation( settings->value("PhotonIsolation") ); - this->photonIsolationLoose( settings->value("PhotonIsolationLoose") ); - if( settings->value("PhotonUseRadiativeZ") == "True" ) - this->m_photon_configuration.useRadiativeZ = true; + //Fwd electron configuration + this->fwdElectronID(settings->value("FwdElectronID")); + this->fwdElectronIDLoose(settings->value("FwdElectronIDLoose")); + double fwdElPtCut = 99999999.; + try{ + fwdElPtCut = std::stof(settings->value("FwdElectronPt")); + } + catch (...) { + throw std::invalid_argument { + "TopConfig: cannot convert Option FwdElectronPt into float" + }; + } + this->fwdElectronPtcut(fwdElPtCut); + double fwdElMinEtaCut = 2.5; + try{ + fwdElMinEtaCut = std::stof(settings->value("FwdElectronMinEta")); + } + catch (...) { + throw std::invalid_argument { + "TopConfig: cannot convert Option FwdElectronMinEta into float" + }; + } + this->fwdElectronMinEtacut(fwdElMinEtaCut); + double fwdElMaxEtaCut = 2.5; + try{ + fwdElMaxEtaCut = std::stof(settings->value("FwdElectronMaxEta")); + } + catch (...) { + throw std::invalid_argument { + "TopConfig: cannot convert Option FwdElectronMaxEta into float" + }; + } + this->fwdElectronMaxEtacut(fwdElMaxEtaCut); - // Muon configuration - this->muonPtcut( std::stof(settings->value("MuonPt")) ); - this->muonEtacut( std::stof(settings->value("MuonEta")) ); - this->muonQuality( settings->value("MuonQuality") ); - this->muonQualityLoose( settings->value("MuonQualityLoose") ); - this->muonIsolation( settings->value("MuonIsolation") ); - this->muonIsolationLoose( settings->value("MuonIsolationLoose") ); + int fwdElectronBCIDCleaningMinRun = 0; + int fwdElectronBCIDCleaningMaxRun = 0; + std::vector<std::string> fwd_bcid_tokens; + tokenize(settings->value("FwdElectronBCIDCleaningRunRange"), fwd_bcid_tokens, ":"); + if (fwd_bcid_tokens.size() != 2) { + throw std::invalid_argument( + "TopConfig: Option FwdElectronBCIDCleaningRunRange requires values in the form of \'XXX:YYY\'. The number of values needs to be exactly 2."); + } + try{ + fwdElectronBCIDCleaningMinRun = std::stoi(fwd_bcid_tokens[0]); + fwdElectronBCIDCleaningMaxRun = std::stoi(fwd_bcid_tokens[1]); + } + catch (...) { + throw std::invalid_argument( + "TopConfig: Cannot convert the strings into integers for the run numbers in Option FwdElectronBCIDCleaningRunRange"); + } - if (settings->value("UseAntiMuons") == "True") - this->m_useAntiMuons = true; + this->fwdElectronBCIDCleaningMinRun(fwdElectronBCIDCleaningMinRun); + this->fwdElectronBCIDCleaningMaxRun(fwdElectronBCIDCleaningMaxRun); + + // Photon configuration + this->photonPtcut(std::stof(settings->value("PhotonPt"))); + this->photonEtacut(std::stof(settings->value("PhotonEta"))); + this->photonIdentification(settings->value("PhotonID")); + this->photonIdentificationLoose(settings->value("PhotonIDLoose")); + this->photonIsolation(settings->value("PhotonIsolation")); + this->photonIsolationLoose(settings->value("PhotonIsolationLoose")); + // Muon configuration + this->muonPtcut(std::stof(settings->value("MuonPt"))); + this->muonEtacut(std::stof(settings->value("MuonEta"))); + this->muonQuality(settings->value("MuonQuality")); + this->muonQualityLoose(settings->value("MuonQualityLoose")); + { + std::string const& cut_wp = settings->value("MuonIsolation"); + std::string const& sf_wp = settings->value("MuonIsolationSF"); + this->muonIsolation(cut_wp); + this->muonIsolationSF(sf_wp == " " ? cut_wp : sf_wp); + } + bool muonUse2stationHighPt = true; + settings->retrieve("MuonUse2stationHighPt", muonUse2stationHighPt); + if (settings->value("MuonQuality") != "HighPt") muonUse2stationHighPt = false; + this->muonUse2stationMuonsHighPt(muonUse2stationHighPt); + bool muonUseMVALowPt = false; + settings->retrieve("MuonUseMVALowPt", muonUseMVALowPt); + if (settings->value("MuonQuality") != "LowPt" && muonUseMVALowPt) { + ATH_MSG_WARNING("Could not set MuonUseMVALowPt True without using the LowPt muon WP. MuonUseMVALowPt is now setted to the default value (False)"); + muonUseMVALowPt = false; + } + this->muonUseMVALowPt(muonUseMVALowPt); + bool muonUse2stationHighPtLoose = true; + settings->retrieve("MuonUse2stationHighPtLoose", muonUse2stationHighPtLoose); + if (settings->value("MuonQualityLoose") != "HighPt") muonUse2stationHighPtLoose = false; + this->muonUse2stationMuonsHighPtLoose(muonUse2stationHighPtLoose); + bool muonUseMVALowPtLoose = false; + settings->retrieve("MuonUseMVALowPtLoose", muonUseMVALowPtLoose); + if (settings->value("MuonQualityLoose") != "LowPt" && muonUseMVALowPtLoose) { + ATH_MSG_WARNING("Could not set MuonUseMVALowPtLoose True without using the LowPt muon WP. MuonUseMVALowPtLoose is now setted to the default value (False)"); + muonUseMVALowPtLoose = false; + } + this->muonUseMVALowPtLoose(muonUseMVALowPtLoose); + { + std::string const& cut_wp = settings->value("MuonIsolationLoose"); + std::string const& sf_wp = settings->value("MuonIsolationSFLoose"); + this->muonIsolationLoose(cut_wp); + this->muonIsolationSFLoose(sf_wp == " " ? cut_wp : sf_wp); + } + bool muonDoSmearing2stationHighPt = false; + settings->retrieve("MuonDoSmearing2stationHighPt", muonDoSmearing2stationHighPt); + if (settings->value("MuonQuality") != "HighPt" ) muonDoSmearing2stationHighPt = false; + else if ( !muonUse2stationHighPt && muonDoSmearing2stationHighPt ) { + ATH_MSG_WARNING("Could not set MuonDoSmearing2stationHighPt True without MuonUse2stationHighPt. MuonDoSmearing2stationHighPt is now setted to False"); + muonDoSmearing2stationHighPt = false; + } + this->muonMuonDoSmearing2stationHighPt(muonDoSmearing2stationHighPt); + bool muonDoExtraSmearingHighPt = false; + settings->retrieve("MuonDoExtraSmearingHighPt", muonDoExtraSmearingHighPt); + if ( settings->value("MuonQuality") != "HighPt" && muonDoExtraSmearingHighPt ) { + ATH_MSG_WARNING("Could not set MuonDoExtraSmearingHighPt True without using the HighPt muon WP. MuonDoExtraSmearingHighPt is now setted to the default value (False)"); + muonDoExtraSmearingHighPt = false; + } + this->muonMuonDoExtraSmearingHighPt( muonDoExtraSmearingHighPt ); + + if (settings->value("UseAntiMuons") == "True") this->m_useAntiMuons = true; + + // Soft Muon configuration + this->softmuonPtcut(readFloatOption(settings, "SoftMuonPt")); + this->softmuonEtacut(readFloatOption(settings, "SoftMuonEta")); + this->softmuonQuality(settings->value("SoftMuonQuality")); + bool softmuonUseMVALowPtSoftMuon = false; + settings->retrieve("SoftMuonUseMVALowPt", softmuonUseMVALowPtSoftMuon); + if (settings->value("SoftMuonQuality") != "LowPt" && softmuonUseMVALowPtSoftMuon) { + ATH_MSG_WARNING("Could not set SoftMuonUseMVALowPt True without using the LowPt softmuon WP. SoftMuonUseMVALowPt is now setted to the default value (False)"); + softmuonUseMVALowPtSoftMuon = false; + } + this->softmuonUseMVALowPt(softmuonUseMVALowPtSoftMuon); + this->softmuonDRJetcut(readFloatOption(settings, "SoftMuonDRJet")); + this->softmuonDRJetcutUseRapidity(settings->retrieve("SoftMuonDRJetUseRapidity")); + this->softmuonAdditionalTruthInfo(settings->retrieve("SoftMuonAdditionalTruthInfo")); + this->softmuonAdditionalTruthInfoCheckPartonOrigin(settings->retrieve("SoftMuonAdditionalTruthInfoCheckPartonOrigin")); + this->softmuonAdditionalTruthInfoDoVerbose(settings->retrieve("SoftMuonAdditionalTruthInfoDoVerbose") ); //tau configuration this->tauPtcut(std::stof(settings->value("TauPt"))); + this->tauEtaRegions(settings->value("TauEtaRegions")); this->tauJetIDWP(settings->value("TauJetIDWP")); this->tauJetIDWPLoose(settings->value("TauJetIDWPLoose")); this->tauEleBDTWP(settings->value("TauEleBDTWP")); this->tauEleBDTWPLoose(settings->value("TauEleBDTWPLoose")); this->tauEleOLR((settings->value("TauEleOLR") == "True")); this->tauEleOLRLoose((settings->value("TauEleOLRLoose") == "True")); + this->tauSFDoRNNID((settings->value("TauSFDoRNNID") == "True")); + this->tauSFDoBDTID((settings->value("TauSFDoBDTID") == "True")); this->tauJetConfigFile(settings->value("TauJetConfigFile")); this->tauJetConfigFileLoose(settings->value("TauJetConfigFileLoose")); - this->applyTauMVATES((settings->value("ApplyTauMVATES") == "True")); + if (settings->value("ApplyTauMVATES") != "True") throw std::runtime_error { + "TopConfig: ApplyTauMVATES must be True" + }; // Jet configuration - this->jetPtcut( std::stof(settings->value("JetPt")) ); - this->jetEtacut( std::stof(settings->value("JetEta")) ); - this->fwdJetAndMET( settings->value("FwdJetAndMET") ); - this->jetUncertainties_BunchSpacing( settings->value("JetUncertainties_BunchSpacing") ); - this->jetUncertainties_NPModel( settings->value("JetUncertainties_NPModel") ); - this->jetJERSmearingModel( settings->value("JetJERSmearingModel") ); - this->jetCalibSequence( settings->value("JetCalibSequence") ); - this->doJVTinMET( (settings->value("JVTinMETCalculation") == "True" ? true : false) ); - this->m_largeRSmallRCorrelations = settings->value("LargeRSmallRCorrelations") == "True" ? true : false; - - this->largeRJetPtcut( std::stof(settings->value("LargeRJetPt")) ); - this->largeRJetEtacut( std::stof(settings->value("LargeRJetEta")) ); - this->largeRJESUncertaintyConfig( settings->value("LargeRJESUncertaintyConfig") ); - this->largeRJESJMSConfig( settings->value("LargeRJESJMSConfig") ); - - this->trackJetPtcut( std::stof(settings->value("TrackJetPt")) ); - this->trackJetEtacut( std::stof(settings->value("TrackJetEta")) ); + this->jetPtcut(std::stof(settings->value("JetPt"))); + this->jetEtacut(std::stof(settings->value("JetEta"))); + this->jetPtGhostTracks(std::stof(settings->value("JetPtGhostTracks")),std::stof(settings->value("JetPt"))); + if ( m_jetPtcut <= std::stof(settings->value("JetPtGhostTracks"))+5000){ + ATH_MSG_WARNING("jetPtGhostTracks set to " << m_jetPtGhostTracks <<" to ensure that all the selected jets have the ghost tracks associated"); + } + this->jetEtaGhostTracks(std::stof(settings->value("JetEtaGhostTracks"))); + this->jetUncertainties_NPModel(settings->value("JetUncertainties_NPModel")); + this->jetUncertainties_QGFracFile(settings->value("JetUncertainties_QGFracFile")); + this->jetUncertainties_QGHistPatterns(settings->value("JetUncertainties_QGHistPatterns")); + this->jetJERSmearingModel(settings->value("JetJERSmearingModel")); + this->jetCalibSequence(settings->value("JetCalibSequence")); + this->doJVTinMET(settings->retrieve("JVTinMETCalculation")); + this->saveFailJVTJets(settings->retrieve("SaveFailJVTJets")); + this->setJVTWP(settings->value("JVTWP")); + this->doForwardJVTinMET(settings->retrieve("ForwardJVTinMETCalculation")); + this->saveFailForwardJVTJets(settings->retrieve("SaveFailForwardJVTJets")); + this->setfJVTWP(settings->value("ForwardJVTWP")); + if (settings->value("ForwardJVTWP") == "Medium" && settings->retrieve("ForwardJVTinMETCalculation")){ + ATH_MSG_WARNING("TopConfig::setConfigSettings: fJVT WP set to Medium and fJVT in MET requested, MET working point will be changed to Tenacious to maintain compatibility with fJVT!!!"); + } + + + this->largeRJetPtcut(std::stof(settings->value("LargeRJetPt"))); + this->largeRJetEtacut(std::stof(settings->value("LargeRJetEta"))); + + + // now get all substructure variables from the config file. + std::string strSubstructure = settings->value("LargeRJetSubstructureVariables"); + // Making vector of strings with "," used as separator + std::vector<std::string> helpvecStr; + tokenize(strSubstructure, helpvecStr, ","); + + std::vector<std::string> vecSubstructure; + // Removing empty spaces + for (const std::string& x : helpvecStr) { + std::istringstream istrSubstructure(x); + std::copy(std::istream_iterator<std::string>(istrSubstructure), + std::istream_iterator<std::string>(), std::back_inserter(vecSubstructure)); + } + // Making map + for (const std::string& key: vecSubstructure) { + std::vector<std::string> pairs; + tokenize(key,pairs,":"); + if(pairs.size() == 1) m_largeRJetSubstructureVariables[pairs[0]]=pairs[0]; + else if(pairs.size() == 2) m_largeRJetSubstructureVariables[pairs[0]]=pairs[1]; + else throw std::runtime_error { + "TopConfig: Options in LargeRJetSubstructureVariables should be of the form \'x:y\' or \'y\'." + }; + } + + this->largeRJetUncertainties_NPModel(settings->value("LargeRJetUncertainties_NPModel")); + this->largeRJetUncertaintiesConfigDir(settings->value("AdvancedUsage_LargeRJetUncertaintiesConfigDir")); + this->largeRJESJMSConfig(settings->value("LargeRJESJMSConfig")); + + this->trackJetPtcut(std::stof(settings->value("TrackJetPt"))); + this->trackJetEtacut(std::stof(settings->value("TrackJetEta"))); + + //Ghost track associated to jets quality + this->ghostTrackspT(std::stof(settings->value("GhostTrackspT"))); + this->ghostTracksVertexAssociation(settings->value("GhostTracksVertexAssociation")); + this->ghostTracksQuality(settings->value("GhostTracksQuality")); + + this->trackPtcut(std::stof(settings->value("TrackPt"))); + this->trackEtacut(std::stof(settings->value("TrackEta"))); + this->trackQuality(settings->value("TrackQuality")); // Jet configuration reclustered jets - this->RCJetPtcut(std::stof(settings->value("RCJetPt")) ); - this->RCJetEtacut(std::stof(settings->value("RCJetEta")) ); - this->RCJetTrimcut(std::stof(settings->value("RCJetTrim")) ); - this->RCJetRadius(std::stof(settings->value("RCJetRadius")) ); - if (settings->value("UseRCJets") == "True" || settings->value("UseRCJets") == "true") - this->m_useRCJets = true; - - this->VarRCJetPtcut(std::stof(settings->value("VarRCJetPt")) ); - this->VarRCJetEtacut(std::stof(settings->value("VarRCJetEta")) ); - this->VarRCJetTrimcut(std::stof(settings->value("VarRCJetTrim")) ); - this->VarRCJetMaxRadius(std::stof(settings->value("VarRCJetMaxRadius")) ); + this->RCJetPtcut(std::stof(settings->value("RCJetPt"))); + this->RCJetEtacut(std::stof(settings->value("RCJetEta"))); + this->RCInputJetPtMin(std::stof(settings->value("RCInputJetPtMin"))); + this->RCInputJetEtaMax(std::stof(settings->value("RCInputJetEtaMax"))); + this->RCJetTrimcut(std::stof(settings->value("RCJetTrim"))); + this->RCJetRadius(std::stof(settings->value("RCJetRadius"))); + if (settings->value("UseRCJets") == "True" || settings->value("UseRCJets") == "true") this->m_useRCJets = true; + if (settings->value("UseRCJetSubstructure") == "True" || + settings->value("UseRCJetSubstructure") == "true") this->m_useRCJetSubstructure = true; + else this->m_useRCJetSubstructure = false; + + if (settings->value("UseRCJetAdditionalSubstructure") == "True" || + settings->value("UseRCJetAdditionalSubstructure") == "true") this->m_useRCJetAdditionalSubstructure = true; + else this->m_useRCJetAdditionalSubstructure = false; + + this->VarRCJetPtcut(std::stof(settings->value("VarRCJetPt"))); + this->VarRCJetEtacut(std::stof(settings->value("VarRCJetEta"))); + this->VarRCJetTrimcut(std::stof(settings->value("VarRCJetTrim"))); + this->VarRCJetMaxRadius(std::stof(settings->value("VarRCJetMaxRadius"))); this->VarRCJetRho(settings->value("VarRCJetRho")); this->VarRCJetMassScale(settings->value("VarRCJetMassScale")); - if (settings->value("UseVarRCJets") == "True" || settings->value("UseVarRCJets") == "true") - this->m_useVarRCJets = true; + if (settings->value("UseVarRCJets") == "True" || + settings->value("UseVarRCJets") == "true") this->m_useVarRCJets = true; + if (settings->value("UseVarRCJetSubstructure") == "True" || + settings->value("UseVarRCJetSubstructure") == "true") this->m_useVarRCJetSubstructure = true; + else this->m_useVarRCJetSubstructure = false; + if (settings->value("UseVarRCJetAdditionalSubstructure") == "True" || + settings->value("UseVarRCJetAdditionalSubstructure") == + "true") this->m_useVarRCJetAdditionalSubstructure = true; + else this->m_useVarRCJetAdditionalSubstructure = false; + + if (settings->value("StoreJetTruthLabels") == "False") { + this->jetStoreTruthLabels(false); + } else if (settings->value("StoreJetTruthLabels") == "True") { + this->jetStoreTruthLabels(true); + } else { + ATH_MSG_WARNING("TopConfig::setConfigSettings: Unrecognized option for \"StoreJetTruthLabels\", assuming True"); + this->jetStoreTruthLabels(true); + } + + // MET Configuration + this->METUncertaintiesConfigDir(settings->value("AdvancedUsage_METUncertaintiesConfigDir")); // for top mass analysis, per default set to 1.0! - m_JSF = std::stof(settings->value("JSF")); + m_JSF = std::stof(settings->value("JSF")); m_bJSF = std::stof(settings->value("bJSF")); // If parameter exists remove electron crack veto - if (settings->value("ElectronVetoLArCrack") == "False") - this->removeElectronVetoLArCrack(); + if (settings->value("ElectronVetoLArCrack") == "False") this->removeElectronVetoLArCrack(); // By default the top group does overlap removal on the tight lepton definitions // If you use this you are going off piste and need to report // your findings to the top reconstruction meeting - if (settings->value("OverlapRemovalLeptonDef") == "Loose") - this->setOverlapRemovalOnLooseLeptonDef(); + if (settings->value("OverlapRemovalLeptonDef") == "Loose") this->setOverlapRemovalOnLooseLeptonDef(); m_overlap_removal_procedure = settings->value("OverlapRemovalProcedure"); // do overlap removal also with large-R jets // (using whatever procedure is used in the official tools) if (settings->value("LargeJetOverlapRemoval") == "True") { - this->setLargeJetOverlapRemoval();// only usefull in case of MC - } - - // Only dumps the *_Loose trees - also on MC - // Usefull if you want your tight selection to be a subset of loose - if (settings->value("DoLooseTreeOnly") == "True") { - this->setLooseTreeOnly(); - if (this->isMC())// in case of MC *_Loose trees have to be activated - this->FakesControlRegionDetermination_setDoLooseEventsOnMC_notForRegularUsers(); + this->setLargeJetOverlapRemoval();// only usefull in case of MC } // In the *_Loose trees, lepton SFs are calculated considering // tight ID and isolation instead of loose // Only tight leptons are considered in the event SF calculation - if (settings->value("ApplyTightSFsInLooseTree") == "True") { - if (this->isMC()) - this->setApplyTightSFsInLooseTree();// only usefull in case of MC - } + // only usefull in case of MC + if (settings->value("ApplyTightSFsInLooseTree") == "True" && this->isMC()) this->setApplyTightSFsInLooseTree(); // Apply Electron In Jet Subtraction - boosted analysis - if (settings->value("ApplyElectronInJetSubtraction") == "True") - this->setApplyElectronInJetSubtraction(); + if (settings->value("ApplyElectronInJetSubtraction") == "True") this->setApplyElectronInJetSubtraction(); // Set Number of events to run on (for testing) - this->numberOfEventsToRun( std::stoi(settings->value("NEvents")) ); + this->numberOfEventsToRun(std::stoi(settings->value("NEvents"))); // Set Number of the first Event to run skip (for testing) - this->numberOfEventsToSkip( std::stoi(settings->value("FirstEvent")) ); + this->numberOfEventsToSkip(std::stoi(settings->value("FirstEvent"))); // [[[----------------------------------------------- //; Particle Level / Truth Configuration - this->truth_electron_PtCut( std::stof( settings->value( "TruthElectronPt" ) ) ); - this->truth_electron_EtaCut( std::stof( settings->value( "TruthElectronEta" ) ) ); + this->truth_electron_PtCut(std::stof(settings->value("TruthElectronPt"))); + this->truth_electron_EtaCut(std::stof(settings->value("TruthElectronEta"))); - this->truth_muon_PtCut( std::stof( settings->value( "TruthMuonPt" ) ) ); - this->truth_muon_EtaCut( std::stof( settings->value( "TruthMuonEta" ) ) ); + this->truth_muon_PtCut(std::stof(settings->value("TruthMuonPt"))); + this->truth_muon_EtaCut(std::stof(settings->value("TruthMuonEta"))); + + float truth_softmu_ptcut=4000.; + try{ + truth_softmu_ptcut=std::stof(settings->value("TruthSoftMuonPt")); + } + catch (...) { + throw std::runtime_error { + "TopConfig: can't convert provided TruthSoftMuonPt into float" + }; + } + + float truth_softmu_etacut=2.5; + try{ + truth_softmu_etacut=std::stof(settings->value("TruthSoftMuonEta")); + } + catch (...) { + throw std::runtime_error { + "TopConfig: can't convert provided TruthSoftMuonEta into float" + }; + } + + this->truth_softmuon_PtCut(truth_softmu_ptcut); + this->truth_softmuon_EtaCut(truth_softmu_etacut); - this->truth_photon_PtCut( std::stof( settings->value( "TruthPhotonPt" ) ) ); - this->truth_photon_EtaCut( std::stof( settings->value( "TruthPhotonEta" ) ) ); + this->truth_photon_PtCut(std::stof(settings->value("TruthPhotonPt"))); + this->truth_photon_EtaCut(std::stof(settings->value("TruthPhotonEta"))); // The TruthPhoton Origin and Isolation parameters are validated inside the // TopParticleLevel Loader Class. - this->truth_photon_Origin( settings->value( "TruthPhotonOrigin" ) ); - this->truth_photon_Isolation( settings->value( "TruthPhotonIsolation" ) ); + this->truth_photon_Origin(settings->value("TruthPhotonOrigin")); + this->truth_photon_Isolation(settings->value("TruthPhotonIsolation")); + + this->truth_jet_PtCut(std::stof(settings->value("TruthJetPt"))); + this->truth_jet_EtaCut(std::stof(settings->value("TruthJetEta"))); - this->truth_jet_PtCut( std::stof( settings->value( "TruthJetPt" ) ) ); - this->truth_jet_EtaCut( std::stof( settings->value( "TruthJetEta" ) ) ); + this->truth_jet_largeR_PtCut(std::stof(settings->value("TruthLargeRJetPt"))); + this->truth_jet_largeR_EtaCut(std::stof(settings->value("TruthLargeRJetEta"))); - this->truth_jet_largeR_PtCut( std::stof( settings->value( "TruthLargeRJetPt" ) ) ); - this->truth_jet_largeR_EtaCut( std::stof( settings->value( "TruthLargeRJetEta" ) ) ); + this->truth_tau_PtCut(std::stof(settings->value("TruthTauPt"))); + this->truth_tau_EtaCut(std::stof(settings->value("TruthTauEta"))); // -----------------------------------------------]]] // Upgrade studies - if(settings->value("HLLHC")=="True") this->HLLHC( true ); + if (settings->value("HLLHC") == "True") { + this->HLLHC(true); + if (settings->value("TDPPath").compare("dev/AnalysisTop/TopDataPreparation/XSection-MC15-13TeV.data") == 0) { + ATH_MSG_WARNING("TopConfig::setConfigSettings HLLHC is set to True, but the TDPPath is set to default " << + settings->value("TDPPath") << ". Changing to dev/AnalysisTop/TopDataPreparation/XSection-MC15-14TeV.data"); + this->setTDPPath("dev/AnalysisTop/TopDataPreparation/XSection-MC15-14TeV.data"); + } + } + if (settings->value("HLLHCFakes") == "True") this->HLLHCFakes(true); // LHAPDF Reweighting configuration - std::istringstream lha_pdf_ss(settings->value( "LHAPDFSets" )); - std::copy( std::istream_iterator<std::string>(lha_pdf_ss), - std::istream_iterator<std::string>(), - std::back_inserter(m_lhapdf_options.pdf_set_names) ); + std::istringstream lha_pdf_ss(settings->value("LHAPDFSets")); + std::copy(std::istream_iterator<std::string>(lha_pdf_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_lhapdf_options.pdf_set_names)); // if provided, it will be used to recompute XF1,XF2 (if any is zero) const std::string LHAPDFBase = settings->value("LHAPDFBaseSet"); - if( LHAPDFBase.find_first_not_of(' ') != std::string::npos ) { + if (LHAPDFBase.find_first_not_of(' ') != std::string::npos) { // should only set one base PDF set - if( LHAPDFBase.find(' ') != std::string::npos ) - std::cout << "LHAPDFBaseSet: " << LHAPDFBase - << " <<<<< only one PDF set allowed for recomputing XF1,XF2 !!!" << std::endl; + if (LHAPDFBase.find(' ') != std::string::npos) + ATH_MSG_WARNING("LHAPDFBaseSet: " << LHAPDFBase << " -- only one PDF set allowed for recomputing XF1,XF2 !!!"); m_lhapdf_options.baseLHAPDF = LHAPDFBase; } // if not already present, add to the list of PDF sets - if( ! m_lhapdf_options.baseLHAPDF.empty() && - !(std::find(m_lhapdf_options.pdf_set_names.begin(), - m_lhapdf_options.pdf_set_names.end(), - m_lhapdf_options.baseLHAPDF) != m_lhapdf_options.pdf_set_names.end()) ) - m_lhapdf_options.pdf_set_names.push_back(m_lhapdf_options.baseLHAPDF); + if (!m_lhapdf_options.baseLHAPDF.empty() && + !(std::find(m_lhapdf_options.pdf_set_names.begin(), + m_lhapdf_options.pdf_set_names.end(), + m_lhapdf_options.baseLHAPDF) != + m_lhapdf_options.pdf_set_names.end())) m_lhapdf_options.pdf_set_names.push_back(m_lhapdf_options.baseLHAPDF); - if( m_lhapdf_options.pdf_set_names.size() && this->isMC() ) - m_lhapdf_options.doLHAPDF = true; + if (m_lhapdf_options.pdf_set_names.size() && this->isMC()) m_lhapdf_options.doLHAPDF = true; - if( m_lhapdf_options.pdf_set_names.size() && this->isMC() && settings->value("LHAPDFEventWeights") == "True" ) { + if (m_lhapdf_options.pdf_set_names.size() && this->isMC() && settings->value("LHAPDFEventWeights") == "True") { m_lhapdf_options.save_per_event = true; - } - else if( m_lhapdf_options.pdf_set_names.size() && this->isMC() && settings->value("LHAPDFEventWeights") == "Nominal" ) { + } else if (m_lhapdf_options.pdf_set_names.size() && this->isMC() && + settings->value("LHAPDFEventWeights") == "Nominal") { m_lhapdf_options.save_per_event = true; m_lhapdf_options.doLHAPDFInNominalTrees = true; } + // now get all Boosted jet taggers from the config file. + std::string str_boostedJetTagger = settings->value("BoostedJetTagging"); + std::vector<std::string> helpvec_str; + tokenize(str_boostedJetTagger, helpvec_str, ","); - // now get all Btagging WP from the config file, and store them properly in a map. - // Need function to compare the cut value with the WP and vice versa + std::vector<std::string> vec_boostedJetTaggers; - std::istringstream str_btagging_WP(settings->value( "BTaggingWP" )); + for (const std::string& x : helpvec_str) { + std::istringstream istr_boostedJetTaggers(x); + std::copy(std::istream_iterator<std::string>(istr_boostedJetTaggers), + std::istream_iterator<std::string>(), std::back_inserter(vec_boostedJetTaggers)); + } - std::vector<std::string> all_btagging_WP; - std::copy( std::istream_iterator<std::string>(str_btagging_WP), - std::istream_iterator<std::string>(), - std::back_inserter(all_btagging_WP) ); + for (const std::string& tagger : vec_boostedJetTaggers) { + std::vector<std::string> helpvec; + tokenize(tagger, helpvec, ":"); + if (helpvec.size() != 2) throw std::runtime_error { + "TopConfig: Options in BoostedJetTagging should be of the form \'x:y\' where x is tagging type and y is shortened tagger name." + }; + m_chosen_boostedJetTaggers.push_back(std::make_pair(helpvec[0], helpvec[1])); + } - // loop through all btagging WPs requested - for (auto tag : all_btagging_WP) { - std::cout << "TopConfig: ==================================================> " << tag << std::endl; - std::string formatedWP = FormatedWP(tag); - // take care that no WP is taken twice - if ( std::find(m_chosen_btaggingWP.begin(), m_chosen_btaggingWP.end(), formatedWP) == m_chosen_btaggingWP.end() ) { - m_chosen_btaggingWP.push_back(formatedWP); - std::cout << "chosen btagging WP ===============================================> " << m_chosen_btaggingWP.back() << std::endl; + m_btagging_cdi_path = settings->value("BTagCDIPath"); + + // now get all Btagging WP from the config file, and store them properly in a map. + // Need function to compare the cut value with the WP and vice versa + parse_bTagWPs(settings->value("BTaggingWP"), m_chosen_btaggingWP, m_sgKeyJets + ", " + m_sgKeyTrackJets); + parse_bTagWPs(settings->value("BTaggingCaloJetWP"), m_chosen_btaggingWP_caloJet, m_sgKeyJets); + parse_bTagWPs(settings->value("BTaggingTrackJetWP"), m_chosen_btaggingWP_trkJet, m_sgKeyTrackJets); + + // check whether user is using the deprecated BTaggingWP option + if (m_chosen_btaggingWP.size() > 0) { + ATH_MSG_WARNING("You specified b-tagging WPs via BTaggingWP which is obsolete. Please switch to options BTaggingCaloJetWP for specifying EMTopo/EMPFlow b-tagging, and BTaggingTrackJetWP for track-jet b-tagging."); + if (m_chosen_btaggingWP_caloJet.size() > 0 || m_chosen_btaggingWP_trkJet.size() > 0) { + ATH_MSG_ERROR("You specified b-tagging WPs both via BTaggingWP as well as BTaggingCaloJetWP or BTaggingTrackJetWP. The BTaggingWP option is deprecated and conflicts with the other two options!"); + throw std::runtime_error("TopConfig: Failed to determine what b-tagging WPs to configure."); } else { - std::cout << "WP " << formatedWP << " aldready choosen" << std::endl; + // if deprecated option used, assume both calo and track jet WPs are the same + m_chosen_btaggingWP_caloJet = m_chosen_btaggingWP; + m_chosen_btaggingWP_trkJet = m_chosen_btaggingWP; } } m_btagging_calibration_B = settings->value("BTaggingCalibrationB"); m_btagging_calibration_C = settings->value("BTaggingCalibrationC"); m_btagging_calibration_Light = settings->value("BTaggingCalibrationLight"); - m_bTagSystsExcludedFromEV = settings->value( "BTaggingSystExcludedFromEV" ); + m_bTagSystsExcludedFromEV = settings->value("BTaggingSystExcludedFromEV"); + + // Set translatio ndictionary for MCMC maps + if (settings->value("RedefineMCMCMap") != " ") { + std::vector<std::string> tmp; + tokenize(settings->value("RedefineMCMCMap"), tmp, ","); + for (const std::string& dictionaries : tmp) { + std::vector<std::string> dictionary; + tokenize(dictionaries, dictionary, ":"); + if (dictionary.size() != 2) { + throw std::invalid_argument{"Wrong input argument for RedefineMCMCMap. Expected format is: \"shower1:shower2,shower3:shower4\""}; + } + + m_showerMCMCtranslator.insert({dictionary.at(0), dictionary.at(1)}); + } + } /************************************************************ * @@ -809,62 +1624,214 @@ namespace top{ * ***********************************************************/ - std::istringstream pileup_config_ss(settings->value( "PRWConfigFiles" )); - std::copy( std::istream_iterator<std::string>(pileup_config_ss), - std::istream_iterator<std::string>(), - std::back_inserter(m_pileup_reweighting.config_files) ); + std::istringstream pileup_config_ss(settings->value("PRWConfigFiles")); + std::copy(std::istream_iterator<std::string>(pileup_config_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_pileup_reweighting.config_files)); + + std::istringstream pileup_lumi_ss(settings->value("PRWLumiCalcFiles")); + std::copy(std::istream_iterator<std::string>(pileup_lumi_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_pileup_reweighting.lumi_calc_files)); + + std::istringstream pileup_config_FS_ss(settings->value("PRWConfigFiles_FS")); + std::copy(std::istream_iterator<std::string>(pileup_config_FS_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_pileup_reweighting.config_files_FS)); + + std::istringstream pileup_config_AF_ss(settings->value("PRWConfigFiles_AF")); + std::copy(std::istream_iterator<std::string>(pileup_config_AF_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_pileup_reweighting.config_files_AF)); - std::istringstream pileup_lumi_ss(settings->value( "PRWLumiCalcFiles" )); - std::copy( std::istream_iterator<std::string>(pileup_lumi_ss), - std::istream_iterator<std::string>(), - std::back_inserter(m_pileup_reweighting.lumi_calc_files) ); + std::istringstream actual_mu_FS_ss(settings->value("PRWActualMu_FS")); + std::copy(std::istream_iterator<std::string>(actual_mu_FS_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_pileup_reweighting.actual_mu_FS)); + + std::istringstream actual_mu_AF_ss(settings->value("PRWActualMu_AF")); + std::copy(std::istream_iterator<std::string>(actual_mu_AF_ss), + std::istream_iterator<std::string>(), + std::back_inserter(m_pileup_reweighting.actual_mu_AF)); + + m_pileup_reweighting.unrepresented_data_tol = std::stof(settings->value("PRWUnrepresentedDataTolerance")); m_pileup_reweighting.mu_dependent = (settings->value("PRWMuDependent") == "True"); // now even if the user don't provide a PRWConfigFiles, PRW is done on MC, using the default calibration file - if ( m_pileup_reweighting.lumi_calc_files.size() > 0 ) { + if (m_pileup_reweighting.lumi_calc_files.size() > 0) { m_pileup_reweighting.apply = true; } - if ( m_pileup_reweighting.apply && m_grlFile.size() > 0 && settings->value("PRWUseGRLTool") == "True" ) - m_pileup_reweighting.use_grl_tool = true; + if (m_pileup_reweighting.apply && m_grlFile.size() > 0 && + settings->value("PRWUseGRLTool") == "True") m_pileup_reweighting.use_grl_tool = true; + + // if provided, using custom Data Scale-Factors for pile-up reweighting + // nominal:up:down + // also allowing to specify under this form: 1/1.2:1.0:1/1.4 + if (m_pileup_reweighting.apply && settings->value("PRWCustomScaleFactor") != " ") { + std::vector<std::string> SFs_tokens; + tokenize(settings->value("PRWCustomScaleFactor"), SFs_tokens, ":"); + if (SFs_tokens.size() != 3) throw std::runtime_error { + "TopConfig: Option PRWCustomScaleFactor should be of the form \'nominal:up:down\'" + }; + try { + std::vector<std::string> nomSF_tokens; + tokenize(SFs_tokens[0], nomSF_tokens, "/"); + if (nomSF_tokens.size() == 1) m_pileup_reweighting.custom_SF.push_back(std::stof(nomSF_tokens[0])); + else if (nomSF_tokens.size() == 2) m_pileup_reweighting.custom_SF.push_back(std::stof( + nomSF_tokens[0]) / + std::stof(nomSF_tokens[1])); + else throw std::runtime_error { + "TopConfig: issue in division" + }; + } catch (...) { + throw std::runtime_error { + "TopConfig: can't convert provided PRW nominal Data SF into float" + }; + } + try { + std::vector<std::string> upSF_tokens; + tokenize(SFs_tokens[1], upSF_tokens, "/"); + if (upSF_tokens.size() == 1) m_pileup_reweighting.custom_SF.push_back(std::stof(upSF_tokens[0])); + else if (upSF_tokens.size() == 2) m_pileup_reweighting.custom_SF.push_back(std::stof( + upSF_tokens[0]) / + std::stof(upSF_tokens[1])); + else throw std::runtime_error { + "TopConfig: issue in division" + }; + } catch (...) { + throw std::runtime_error { + "TopConfig: can't convert provided PRW up Data SF into float" + }; + } + try { + std::vector<std::string> downSF_tokens; + tokenize(SFs_tokens[2], downSF_tokens, "/"); + if (downSF_tokens.size() == 1) m_pileup_reweighting.custom_SF.push_back(std::stof(downSF_tokens[0])); + else if (downSF_tokens.size() == 2) m_pileup_reweighting.custom_SF.push_back(std::stof( + downSF_tokens[0]) / + std::stof(downSF_tokens[1])); + else throw std::runtime_error { + "TopConfig: issue in division" + }; + } catch (...) { + throw std::runtime_error { + "TopConfig: can't convert provided PRW down Data SF into float" + }; + } + ATH_MSG_INFO("Custom PRW scale-factors - nominal:" << SFs_tokens[0] << "=" << m_pileup_reweighting.custom_SF[0] << + " up:" << SFs_tokens[1] << "=" << m_pileup_reweighting.custom_SF[1] << " down:" << SFs_tokens[2] << "=" << + m_pileup_reweighting.custom_SF[2]); + } + + if (m_pileup_reweighting.apply && settings->value("PRWPeriodAssignments") != " ") { + std::vector<std::string> period_tokens; + tokenize(settings->value("PRWPeriodAssignments"), period_tokens, ":"); + if (period_tokens.size() % 3 != 0) { + throw std::invalid_argument( + "TopConfig: Option PRWPeriodAssignments requires values in the form of \'value:value:value\'. The number of values needs to be divisible by 3."); + } + try { + for (const std::string& per : period_tokens) { + m_pileup_reweighting.periodAssignments.emplace_back(std::stoi(per)); + } + } catch (...) { + throw std::invalid_argument( + "TopConfig: Cannot convert the strings into integers for the run numbers in Option PRWPeriodAssignments"); + } + } // TRUTH derivations do not contain pile-up weights - if(m_isTruthDxAOD) - m_pileup_reweighting.apply = false; + if (m_isTruthDxAOD) m_pileup_reweighting.apply = false; /************************************************************ - * - * Muon trigger SF configuration - * see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15#How_to_retrieve_the_SF - * for the various trigger strings allowed - * - ************************************************************/ + * + * Muon trigger SF configuration + * see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15#How_to_retrieve_the_SF + * for the various trigger strings allowed + * + ************************************************************/ + + m_muon_trigger_SF = settings->value("MuonTriggerSF"); - m_muon_trigger_SF = settings->value( "MuonTriggerSF" ); + if (settings->value("DemandPrimaryVertex") == "False") + m_demandPriVtx = false; ///-- KLFitter settings --/// - m_KLFitterTransferFunctionsPath = settings->value( "KLFitterTransferFunctionsPath" ); - m_KLFitterJetSelectionMode = settings->value( "KLFitterJetSelectionMode" ); - m_KLFitterBTaggingMethod = settings->value( "KLFitterBTaggingMethod" ); - m_KLFitterLH = settings->value( "KLFitterLH" ); - - if (settings->value( "KLFitterTopMassFixed" ) == "True") - m_KLFitterTopMassFixed = true; - if (settings->value( "KLFitterTopMassFixed" ) == "False") - m_KLFitterTopMassFixed = false; - if (settings->value( "KLFitterSaveAllPermutations" ) == "True") - m_KLFitterSaveAllPermutations = true; - if (settings->value( "KLFitterSaveAllPermutations" ) == "False") - m_KLFitterSaveAllPermutations = false; + m_KLFitterTransferFunctionsPath = settings->value("KLFitterTransferFunctionsPath"); + m_KLFitterOutput = settings->value("KLFitterOutput"); + m_KLFitterJetSelectionMode = settings->value("KLFitterJetSelectionMode"); + m_KLFitterBTaggingMethod = settings->value("KLFitterBTaggingMethod"); + m_KLFitterLH = settings->value("KLFitterLH"); + + if (settings->value("KLFitterTopMassFixed") == "True") m_KLFitterTopMassFixed = true; + if (settings->value("KLFitterTopMassFixed") == "False") m_KLFitterTopMassFixed = false; + if (settings->value("KLFitterSaveAllPermutations") == "True") m_KLFitterSaveAllPermutations = true; + if (settings->value("KLFitterSaveAllPermutations") == "False") m_KLFitterSaveAllPermutations = false; + if (settings->value("KLFitterFailOnLessThanXJets") == "True") m_KLFitterFailOnLessThanXJets = true; + if (settings->value("KLFitterFailOnLessThanXJets") == "False") m_KLFitterFailOnLessThanXJets = false; + + //--- Check for configuration on the global lepton triggers ---// + if (settings->value("UseGlobalLeptonTriggerSF") == "True") { + auto parseTriggerString = + [settings](std::unordered_map<std::string, std::vector<std::string> >& triggersByPeriod, + std::string const& key) { + /* parse a string of the form "2015@triggerfoo,triggerbar,... 2016@triggerfoo,triggerbaz,... ..." */ + std::unordered_map<std::string, std::vector<std::string> > result; + std::vector<std::string> pairs; + boost::split(pairs, settings->value(key), boost::is_any_of(" ")); + for (std::string const& pair : pairs) { + if (pair.empty() || pair == "None") continue; + auto i = pair.find('@'); + if (!(i != std::string::npos && + pair.find('@', i + 1) == std::string::npos)) throw std::invalid_argument( + std::string() + "Malformed trigger list in configuration item `" + key + "'"); + auto&& period = pair.substr(0, i), triggerstr = pair.substr(i + 1); + auto&& triggers = result[period]; + if (!triggers.empty()) throw std::invalid_argument( + std::string() + "Period `" + period + "' appears multiple times in configuration item `" + key + + "'"); + boost::split(triggers, triggerstr, boost::is_any_of(",")); + } + /* merge trigger map from this configuration line into triggersByPeriod */ + for (auto&& kv : result) { + auto&& src = kv.second; + auto&& dst = triggersByPeriod[kv.first]; + for (std::string const& trigger : src) { + if (std::find(dst.begin(), dst.end(), + trigger) != dst.end()) throw std::invalid_argument( + std::string() + "Trigger `" + trigger + "' was specified multiple times"); + dst.push_back(trigger); + } + } + }; + m_trigGlobalConfiguration.isActivated = true; + parseTriggerString(m_trigGlobalConfiguration.trigger, "ElectronTriggers"); + parseTriggerString(m_trigGlobalConfiguration.trigger_loose, "ElectronTriggersLoose"); + parseTriggerString(m_trigGlobalConfiguration.trigger, "MuonTriggers"); + parseTriggerString(m_trigGlobalConfiguration.trigger_loose, "MuonTriggersLoose"); + parseTriggerString(m_trigGlobalConfiguration.trigger, "GlobalTriggers"); + parseTriggerString(m_trigGlobalConfiguration.trigger_loose, "GlobalTriggersLoose"); + } + } - + float TopConfig::readFloatOption(top::ConfigurationSettings* const& settings, std::string instring) const { + float invalue = 99999999.; + try{ + invalue = std::stof(settings->value(instring)); + } + catch (...) { + throw std::invalid_argument { + "TopConfig: cannot convert Option " + instring + "into float" + }; + } + return invalue; } - void TopConfig::setGrlDir( const std::string& s ) - { + void TopConfig::setGrlDir(const std::string& s) { if (!m_configFixed) { m_grlDir = s; m_grlDir.erase(remove_if(m_grlDir.begin(), m_grlDir.end(), isspace), m_grlDir.end()); @@ -886,206 +1853,262 @@ namespace top{ } } - void TopConfig::jetUncertainties_NPModel( const std::string& s ) - { + void TopConfig::setTDPPath(const std::string& s) { + if (!m_configFixed) { + m_topDataPreparationPath = s; + } + } + + void TopConfig::jetUncertainties_NPModel(const std::string& s) { if (!m_configFixed) { m_jetUncertainties_NPModel = s; m_doMultipleJES = false; - if (m_jetUncertainties_NPModel == "3NP") { + if (m_jetUncertainties_NPModel == "StrongReduction") { m_doMultipleJES = true; } } } - void TopConfig::sgKeyMCParticle(const std::string& s) - { + void TopConfig::jetUncertainties_QGFracFile(const std::string& s) { if (!m_configFixed) { - m_useTruthParticles = false; - if (s != "None") - m_useTruthParticles = true; + m_jetUncertainties_QGFracFile = s; + } + } - m_sgKeyMCParticle = s; + void TopConfig::jetUncertainties_QGHistPatterns(const std::string& s) { + if (!m_configFixed) { + std::vector<std::string> outVector; + if (s.find(" ") != std::string::npos) { + throw std::runtime_error { + "TopConfig: jetUncertainties_QGHistPatterns string can't contain white spaces" + }; + } + if (s != "None") { + tokenize(s, outVector, ","); // list of DSIDs separated by commas + if (outVector.size() != 1) // if size is !=1, we need to check if these are DSIDs + for (auto s : outVector) { + int i = std::atoi(s.c_str()); + if (i < 300000 || i >= 1000000) throw std::runtime_error { + "TopConfig: jetUncertainties_QGHistPatterns string doesn't look like a list of DISDs! You can either specify a single string pattern or a list of DSIDs separated by commas." + }; + } } + m_jetUncertainties_QGHistPatterns = outVector; + } } - void TopConfig::sgKeyPhotons(const std::string& s) - { + void TopConfig::sgKeyMCParticle(const std::string& s) { if (!m_configFixed) { - m_usePhotons = false; - if (s != "None") - m_usePhotons = true; + m_useTruthParticles = false; + if (s != "None") m_useTruthParticles = true; - m_sgKeyPhotons = s; + m_sgKeyMCParticle = s; } } - void TopConfig::sgKeyElectrons(const std::string& s) - { - if (!m_configFixed){ - m_useElectrons = false; - if (s != "None") - m_useElectrons = true; + void TopConfig::sgKeyPhotons(const std::string& s) { + if (!m_configFixed) { + m_usePhotons = false; + if (s != "None") m_usePhotons = true; - m_sgKeyElectrons = s; - } + m_sgKeyPhotons = s; + } } + void TopConfig::sgKeyElectrons(const std::string& s) { + if (!m_configFixed) { + m_useElectrons = false; + if (s != "None") m_useElectrons = true; + + m_sgKeyElectrons = s; + } + } - void TopConfig::sgKeyMuons(const std::string& s) - { - if(!m_configFixed){ - m_useMuons = false; - if (s != "None") - m_useMuons = true; + void TopConfig::sgKeyFwdElectrons(const std::string& s) { + if (!m_configFixed) { + m_useFwdElectrons = false; + if (s != "None") m_useFwdElectrons = true; - m_sgKeyMuons = s; - } + m_sgKeyFwdElectrons = s; + } } - void TopConfig::sgKeyTaus(const std::string& s) - { - if(!m_configFixed){ - m_useTaus = false; - if (s != "None") - m_useTaus = true; + void TopConfig::sgKeyMuons(const std::string& s) { + if (!m_configFixed) { + m_useMuons = false; + if (s != "None") m_useMuons = true; - m_sgKeyTaus = s; - } + m_sgKeyMuons = s; + } } - void TopConfig::sgKeyJets(const std::string& s) - { - if (!m_configFixed){ - m_useJets = false; - if (s != "None") - m_useJets = true; + void TopConfig::sgKeySoftMuons(const std::string& s) { + if (!m_configFixed) { + m_useSoftMuons = false; + if (s != "None") m_useSoftMuons = true; + + m_sgKeySoftMuons = s; + } + } - // If anti-kt4 pflow jets then... - if (s == "AntiKt4EMPFlowJets" ) - m_useParticleFlowJets = true; + void TopConfig::sgKeyTaus(const std::string& s) { + if (!m_configFixed) { + m_useTaus = false; + if (s != "None") m_useTaus = true; - m_sgKeyJets = s; - } + m_sgKeyTaus = s; + } } - void TopConfig::sgKeyLargeRJets(const std::string& s) - { - if(!m_configFixed){ - m_useLargeRJets = false; - if (s != "None") - m_useLargeRJets = true; + void TopConfig::sgKeyJets(const std::string& s) { + if (!m_configFixed) { + m_useJets = false; + if (s != "None") m_useJets = true; - m_sgKeyLargeRJets = s; - } + size_t delim_pos = s.find('_'); + // for b-tagging shallow copies, e,g. + // AntiKt4EMPFlowJets_BTagging20181003 + // we want to have quick access to base collection name + m_sgKeyJetsType = s.substr(0, delim_pos); + + // If anti-kt4 pflow jets then... + if (m_sgKeyJetsType == "AntiKt4EMPFlowJets") m_useParticleFlowJets = true; + + m_sgKeyJets = s; + } } - void TopConfig::sgKeyTrackJets(const std::string& s) - { - if(!m_configFixed){ - m_useTrackJets = false; - if (s != "None") - m_useTrackJets = true; + void TopConfig::sgKeyLargeRJets(const std::string& s) { + if (!m_configFixed) { + m_useLargeRJets = false; + if (s != "None") m_useLargeRJets = true; - m_sgKeyTrackJets = s; - } + m_sgKeyLargeRJets = s; + } } - void TopConfig::sgKeyTruthElectrons(const std::string& s) - { - if(!m_configFixed){ - m_useTruthElectrons = false; - if (s != "None") - m_useTruthElectrons = true; + void TopConfig::sgKeyTrackJets(const std::string& s) { + if (!m_configFixed) { + m_useTrackJets = false; + if (s != "None") m_useTrackJets = true; - m_sgKeyTruthElectrons = s; - } + size_t delim_pos = s.find('_'); + // for time-stamped track jet collections due to b-tagging + // AntiKtVR30Rmax4Rmin02TrackJets_BTagging201903 + // we want to have quick access to base collection name + m_sgKeyTrackJetsType = s.substr(0, delim_pos); + + m_sgKeyTrackJets = s; + } } - void TopConfig::sgKeyTruthMuons(const std::string& s) - { - if(!m_configFixed){ - m_useTruthMuons = false; - if (s != "None") - m_useTruthMuons = true; + void TopConfig::sgKeyTracks(const std::string& s) { + + if (!m_configFixed) { + m_useTracks = false; + if (s != "None") m_useTracks = true; + m_sgKeyTracks = s; + } + } - m_sgKeyTruthMuons = s; - } + void TopConfig::sgKeyTruthElectrons(const std::string& s) { + if (!m_configFixed) { + m_useTruthElectrons = false; + if (s != "None") m_useTruthElectrons = true; + + m_sgKeyTruthElectrons = s; + } } - void TopConfig::sgKeyTruthPhotons(const std::string& s) - { - if(!m_configFixed){ - m_useTruthPhotons = false; - if (s != "None"){ - m_useTruthPhotons = true; - } + void TopConfig::sgKeyTruthMuons(const std::string& s) { + if (!m_configFixed) { + m_useTruthMuons = false; + if (s != "None") m_useTruthMuons = true; + + m_sgKeyTruthMuons = s; + } + } - m_sgKeyTruthPhotons = s; + void TopConfig::sgKeyTruthPhotons(const std::string& s) { + if (!m_configFixed) { + m_useTruthPhotons = false; + if (s != "None") { + m_useTruthPhotons = true; } + + m_sgKeyTruthPhotons = s; + } } - void TopConfig::sgKeyTruthMET(const std::string& s) - { - if(!m_configFixed){ - m_useTruthMET = false; - if (s != "None") - m_useTruthMET = true; + void TopConfig::sgKeyTruthMET(const std::string& s) { + if (!m_configFixed) { + m_useTruthMET = false; + if (s != "None") m_useTruthMET = true; - m_sgKeyTruthMET = s; - } + m_sgKeyTruthMET = s; + } } - void TopConfig::sgKeyTruthJets(const std::string& s) - { - if(!m_configFixed){ - m_useTruthJets = false; - if (s != "None") - m_useTruthJets = true; + void TopConfig::sgKeyTruthJets(const std::string& s) { + if (!m_configFixed) { + m_useTruthJets = false; + if (s != "None") m_useTruthJets = true; - m_sgKeyTruthJets = s; - } + m_sgKeyTruthJets = s; + } } - void TopConfig::sgKeyTruthLargeRJets(const std::string& s) - { - if(!m_configFixed){ - m_useTruthLargeRJets = false; - if (s != "None") - m_useTruthLargeRJets = true; + void TopConfig::sgKeyTruthLargeRJets(const std::string& s) { + if (!m_configFixed) { + m_useTruthLargeRJets = false; + if (s != "None") m_useTruthLargeRJets = true; - m_sgKeyTruthLargeRJets = s; - } + m_sgKeyTruthLargeRJets = s; + } } - void TopConfig::decoKeyJetGhostTrack(const std::string & key) - { - if (!m_configFixed) { - m_useJetGhostTrack = false; - if (key != "None") - m_useJetGhostTrack = true; + void TopConfig::sgKeyTruthTaus(const std::string& s) { + if (!m_configFixed) { + m_useTruthTaus = false; + if (s != "None") m_useTruthTaus = true; - m_decoKeyJetGhostTrack = key; - } + m_sgKeyTruthTaus = s; + } + } + + void TopConfig::decoKeyJetGhostTrack(const std::string& key) { + if (!m_configFixed) { + m_useJetGhostTrack = false; + if (key != "None") m_useJetGhostTrack = true; + + m_decoKeyJetGhostTrack = key; + } } // setting the run periods for ghost track // even if configuration is fixed - could be changed later - void TopConfig::runPeriodJetGhostTrack(const std::vector<std::uint32_t> & vect) - { - if (m_useJetGhostTrack == true) - m_jetGhostTrackRunPeriods = vect; + void TopConfig::runPeriodJetGhostTrack(const std::vector<std::uint32_t>& vect) { + if (m_useJetGhostTrack == true) m_jetGhostTrackRunPeriods = vect; } - void TopConfig::setBTaggingSFSysts( std::string WP, const std::set<std::string>& btagging_SF_names, bool isTrackJet ) - { - + // setting the run periods for tracks + // even if configuration is fixed - could be changed later + void TopConfig::runPeriodTrack(const std::vector<std::uint32_t>& vect) { + if (m_useTracks) m_trackRunPeriods = vect; + } + + + void TopConfig::setBTaggingSFSysts(std::string WP, const std::set<std::string>& btagging_SF_names, bool isTrackJet) { //this avoids code duplication - std::unordered_map<std::string,std::set<std::string>>& base_names = isTrackJet ? m_bTag_base_names_trkJet : m_bTag_base_names; - std::unordered_map<std::string,std::set<std::string>>& named_systs = isTrackJet ? m_bTag_named_systs_trkJet : m_bTag_named_systs; - std::unordered_map<std::string,unsigned int>& eigen_B = isTrackJet ? m_bTag_eigen_B_trkJet : m_bTag_eigen_B; - std::unordered_map<std::string,unsigned int>& eigen_C = isTrackJet ? m_bTag_eigen_C_trkJet : m_bTag_eigen_C; - std::unordered_map<std::string,unsigned int>& eigen_light = isTrackJet ? m_bTag_eigen_light_trkJet : m_bTag_eigen_light; - + std::unordered_map<std::string, + std::set<std::string> >& base_names = isTrackJet ? bTag_base_names_trkJet : bTag_base_names; + std::unordered_map<std::string, + std::set<std::string> >& named_systs = isTrackJet ? bTag_named_systs_trkJet : bTag_named_systs; + std::unordered_map<std::string, unsigned int>& eigen_B = isTrackJet ? bTag_eigen_B_trkJet : bTag_eigen_B; + std::unordered_map<std::string, unsigned int>& eigen_C = isTrackJet ? bTag_eigen_C_trkJet : bTag_eigen_C; + std::unordered_map<std::string, + unsigned int>& eigen_light = isTrackJet ? bTag_eigen_light_trkJet : bTag_eigen_light; + //names of all systematics base_names[WP] = btagging_SF_names; //initialise named systematics to empty set @@ -1095,52 +2118,115 @@ namespace top{ eigen_C[WP] = 0; eigen_light[WP] = 0; // loop on systematic names - for( const auto& SF_name : base_names.at(WP) ){ - if ( SF_name.find("_Eigen_B_") != std::string::npos ) - eigen_B.at(WP)++; - else if ( SF_name.find("_Eigen_C_") != std::string::npos ) - eigen_C.at(WP)++; - else if ( SF_name.find("_Eigen_Light_") != std::string::npos ) - eigen_light.at(WP)++; + for (const auto& SF_name : base_names.at(WP)) { + if (SF_name.find("_Eigen_B_") != std::string::npos) eigen_B.at(WP)++; + else if (SF_name.find("_Eigen_C_") != std::string::npos) eigen_C.at(WP)++; + else if (SF_name.find("_Eigen_Light_") != std::string::npos) eigen_light.at(WP)++; else named_systs[WP].insert(SF_name); } } + void TopConfig::setCalibBoostedJetTagger(const std::string& WP, const std::string& SFname) { + m_boostedTaggerSFnames[WP] = SFname; + } + std::string TopConfig::FormatedWP(std::string raw_WP) { // just to have some backward compatibility... - if (raw_WP=="60%") return "FixedCutBEff_60"; - else if (raw_WP=="70%") return "FixedCutBEff_70"; - else if (raw_WP=="77%") return "FixedCutBEff_77"; - else if (raw_WP=="85%") return "FixedCutBEff_85"; + if (raw_WP == "60%") return "FixedCutBEff_60"; + else if (raw_WP == "70%") return "FixedCutBEff_70"; + else if (raw_WP == "77%") return "FixedCutBEff_77"; + else if (raw_WP == "85%") return "FixedCutBEff_85"; else return raw_WP; } - - void TopConfig::setBTagWP_available( std::string btagging_WP ) { + + void TopConfig::parse_bTagWPs(const std::string& btagWPsettingString, + std::vector<std::pair<std::string, std::string>>& btagWPlist, + const std::string& jetCollectionName) { + std::istringstream str_btagging_WP(btagWPsettingString); + std::vector<std::string> all_btagging_WP; + std::copy(std::istream_iterator<std::string>(str_btagging_WP), + std::istream_iterator<std::string>(), + std::back_inserter(all_btagging_WP)); + // loop through all btagging WPs requested + for (const auto& AlgTag : all_btagging_WP) { + std::vector<std::string> btagAlg_btagWP; + tokenize(AlgTag, btagAlg_btagWP, ":"); + // DEFAULT algorithm - May remove in future + std::string alg = "MV2c10"; + std::string tag = ""; + // If no ':' delimiter, assume we want default algorithm, and take the WP from the option + if (btagAlg_btagWP.size() == 2) { + alg = btagAlg_btagWP.at(0); + tag = btagAlg_btagWP.at(1); + } else if (btagAlg_btagWP.size() == 1) { + tag = btagAlg_btagWP.at(0); + } else { + ATH_MSG_ERROR("Cannot parse b-tagging ALGORITHM_NAME:WP. Incorrect format."); + continue; + } + + ATH_MSG_INFO("BTagging algorithm: " << alg << "_" << tag << " for collection: " << jetCollectionName); + std::string formatedWP = FormatedWP(tag); + std::pair<std::string, std::string> alg_tag = std::make_pair(alg, tag); + // take care that no WP is taken twice + if (std::find(btagWPlist.begin(), btagWPlist.end(), alg_tag) == btagWPlist.end()) { + btagWPlist.push_back(alg_tag); + } else { + ATH_MSG_INFO("This b-tag algorithm was already added!"); + } + } + } + + void TopConfig::setBTagWP_available(std::string btagging_WP) { m_available_btaggingWP.push_back(btagging_WP); } - - void TopConfig::setBTagWP_available_trkJet( std::string btagging_WP ) { + + void TopConfig::setBTagWP_available_trkJet(std::string btagging_WP) { m_available_btaggingWP_trkJet.push_back(btagging_WP); } - - void TopConfig::setBTagWP_calibrated( std::string btagging_WP ) { + + void TopConfig::setBTagWP_calibrated(std::string btagging_WP) { m_calibrated_btaggingWP.push_back(btagging_WP); } - - void TopConfig::setBTagWP_calibrated_trkJet( std::string btagging_WP ) { + + void TopConfig::setBTagWP_calibrated_trkJet(std::string btagging_WP) { m_calibrated_btaggingWP_trkJet.push_back(btagging_WP); } + void TopConfig::setBTagAlgo_available(std::string algo, std::string toolName) { + if (algo.find("DL1") == std::string::npos) { + if (algo.find("MV2c10") != std::string::npos) + m_MV2c10_algo_used = true; + else + ATH_MSG_WARNING("Encountered b-tagging algorithm that is not considered in the EventSaver: " << algo); + } else { + auto is_inserted = m_available_btaggingAlgos.insert(algo); + if (is_inserted.second) { + m_algo_selTools[algo] = toolName; + } + } + } - void TopConfig::addLHAPDFResult( const std::string& pdf_name, - std::vector<float> sum_of_weights ){ + void TopConfig::setBTagAlgo_available_trkJet(std::string algo, std::string toolName) { + if (algo.find("DL1") == std::string::npos) { + if (algo.find("MV2c10") != std::string::npos) + m_MV2c10_algo_used_trkJet = true; + else + ATH_MSG_WARNING("Encountered track-jet b-tagging algorithm that is not considered in the EventSaver: " << algo); + } else { + auto is_inserted = m_available_btaggingAlgos_trkJet.insert(algo); + if (is_inserted.second) { + m_algo_selTools_trkJet[algo] = toolName; + } + } + } + void TopConfig::addLHAPDFResult(const std::string& pdf_name, + std::vector<float> sum_of_weights) { m_lhapdf_options.pdf_results[ pdf_name ] = sum_of_weights; - } - void TopConfig::outputEvents(const std::string& s) - { + void TopConfig::outputEvents(const std::string& s) { if (!m_configFixed) { m_outputEvents = s; if (m_outputEvents == "AllEvents") { @@ -1150,20 +2236,19 @@ namespace top{ } /// syst helper functions - bool TopConfig::isSystNominal(const std::string& syst) const{ + bool TopConfig::isSystNominal(const std::string& syst) const { return boost::iequals(syst, m_nominalSystName); } - bool TopConfig::isSystAll(const std::string& syst) const{ + bool TopConfig::isSystAll(const std::string& syst) const { return boost::iequals(syst, m_allSystName); } - bool TopConfig::getSystematicsList(const std::string& syststr, std::set<std::string>& systList) const{ - - if(isSystAll(syststr) || isSystNominal(syststr)) return true; + bool TopConfig::getSystematicsList(const std::string& syststr, std::set<std::string>& systList) const { + if (isSystAll(syststr) || isSystNominal(syststr)) return true; - if( syststr.find(" ") != std::string::npos ){ - std::cout << "ERROR getSystematicsList: systematic string can't contain white spaces" << std::endl; + if (syststr.find(" ") != std::string::npos) { + ATH_MSG_ERROR("getSystematicsList: systematic string can't contain white spaces"); return false; } @@ -1171,45 +2256,41 @@ namespace top{ std::string::size_type start = 0, end = 0; while ((end = syststr.find(separator, start)) != std::string::npos) { std::string token = syststr.substr(start, end - start); - if(token.size()) systList.insert(token); + if (token.size()) systList.insert(token); start = end + 1; } std::string lasttoken = syststr.substr(start); - if(lasttoken.size()) systList.insert(lasttoken); + if (lasttoken.size()) systList.insert(lasttoken); return true; - } - bool TopConfig::contains(const std::set<std::string>& systList, const std::string& name) const{ + bool TopConfig::contains(const std::set<std::string>& systList, const std::string& name) const { return systList.find(name) != systList.end(); } - // set systematics - void TopConfig::systematicsPhotons( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashPhotons->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_systMapPhotons->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapPhotons->insert( std::make_pair( s.hash() , m_sgKeyPhotons + "_" + s.name() ) ); + void TopConfig::systematicsPhotons(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashPhotons->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapPhotons->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapPhotons->insert(std::make_pair(s.hash(), m_sgKeyPhotons + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); } } - void TopConfig::systematicsElectrons( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashElectrons->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_list_systHash_electronInJetSubtraction->push_back( s.hash() ); - m_systMapElectrons->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapElectrons->insert( std::make_pair( s.hash() , m_sgKeyElectrons + "_" + s.name() ) ); + void TopConfig::systematicsElectrons(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashElectrons->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_list_systHash_electronInJetSubtraction->push_back(s.hash()); + m_systMapElectrons->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapElectrons->insert(std::make_pair(s.hash(), m_sgKeyElectrons + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); @@ -1218,43 +2299,66 @@ namespace top{ } } - void TopConfig::systematicsMuons( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashMuons->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_systMapMuons->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapMuons->insert( std::make_pair( s.hash() , m_sgKeyMuons + "_" + s.name() ) ); + void TopConfig::systematicsFwdElectrons(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (const auto& s : syst) { + m_systHashFwdElectrons->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapFwdElectrons->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapFwdElectrons->insert(std::make_pair(s.hash(), m_sgKeyFwdElectrons + "_" + s.name())); + } + m_list_systHashAll->sort(); + m_list_systHashAll->unique(); + } + } + + void TopConfig::systematicsMuons(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashMuons->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapMuons->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapMuons->insert(std::make_pair(s.hash(), m_sgKeyMuons + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); } } - void TopConfig::systematicsTaus( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashTaus->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_systMapTaus->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapTaus->insert( std::make_pair( s.hash() , m_sgKeyTaus + "_" + s.name() ) ); + void TopConfig::systematicsSoftMuons(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (const CP::SystematicSet& s : syst) { + m_systHashSoftMuons->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapSoftMuons->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapSoftMuons->insert(std::make_pair(s.hash(), m_sgKeySoftMuons + "_" + s.name())); + } + m_list_systHashAll->sort(); + m_list_systHashAll->unique(); + } + } + + void TopConfig::systematicsTaus(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashTaus->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapTaus->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapTaus->insert(std::make_pair(s.hash(), m_sgKeyTaus + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); } } - void TopConfig::systematicsJets( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashJets->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_list_systHash_electronInJetSubtraction->push_back( s.hash() ); - m_systMapJets->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapJets->insert( std::make_pair( s.hash() , m_sgKeyJets + "_" + s.name() ) ); + void TopConfig::systematicsJets(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashJets->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_list_systHash_electronInJetSubtraction->push_back(s.hash()); + m_systMapJets->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapJets->insert(std::make_pair(s.hash(), m_sgKeyJets + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); @@ -1263,79 +2367,94 @@ namespace top{ } } - void TopConfig::systematicsLargeRJets( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashLargeRJets->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_systMapLargeRJets->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapLargeRJets->insert( std::make_pair( s.hash() , m_sgKeyLargeRJets + "_" + s.name() ) ); + void TopConfig::systematicsLargeRJets(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashLargeRJets->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapLargeRJets->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapLargeRJets->insert(std::make_pair(s.hash(), m_sgKeyLargeRJets + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); } } - void TopConfig::systematicsTrackJets( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashTrackJets->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_systMapTrackJets->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapTrackJets->insert( std::make_pair( s.hash() , m_sgKeyTrackJets + "_" + s.name() ) ); + void TopConfig::systematicsTrackJets(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashTrackJets->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapTrackJets->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapTrackJets->insert(std::make_pair(s.hash(), m_sgKeyTrackJets + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); } } - void TopConfig::systematicsMET( const std::list<CP::SystematicSet>& syst) - { - if( !m_configFixed ){ - for( auto s : syst ){ - m_systHashMET->insert( s.hash() ); - m_list_systHashAll->push_back( s.hash() ); - m_systMapMET->insert( std::make_pair( s.hash() , s ) ); - m_systSgKeyMapMET->insert( std::make_pair( s.hash() , m_sgKeyLargeRJets + "_" + s.name() ) ); + void TopConfig::systematicsMET(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + for (auto s : syst) { + m_systHashMET->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapMET->insert(std::make_pair(s.hash(), s)); + m_systSgKeyMapMET->insert(std::make_pair(s.hash(), m_sgKeyLargeRJets + "_" + s.name())); } m_list_systHashAll->sort(); m_list_systHashAll->unique(); } } - void TopConfig::systematicsJetGhostTrack( const std::list<CP::SystematicSet>& syst) { - if( !m_configFixed ){ - // Add the nominal (for reporting purposes). - (* m_systMapJetGhostTrack)[m_nominalHashValue] = {}; - (* m_systDecoKeyMapJetGhostTrack)[m_nominalHashValue] = m_decoKeyJetGhostTrack; - m_jetGhostTrackSystematics.push_back(""); + void TopConfig::systematicsJetGhostTrack(const std::list<CP::SystematicSet>& syst) { + if (!m_configFixed) { + // Add the nominal (for reporting purposes). + (*m_systMapJetGhostTrack)[m_nominalHashValue] = {}; + (*m_systDecoKeyMapJetGhostTrack)[m_nominalHashValue] = m_decoKeyJetGhostTrack + "_"; + m_jetGhostTrackSystematics.push_back(""); + + for (auto s : syst) { + (*m_systMapJetGhostTrack)[s.hash()] = s; + (*m_systDecoKeyMapJetGhostTrack)[s.hash()] = m_decoKeyJetGhostTrack + "_" + s.name(); + m_list_systHashAll->push_back(s.hash()); + m_jetGhostTrackSystematics.push_back(s.name()); + } + + // Ensure that elements are unique. + std::sort(m_jetGhostTrackSystematics.begin(), + m_jetGhostTrackSystematics.end()); + auto last = std::unique(m_jetGhostTrackSystematics.begin(), + m_jetGhostTrackSystematics.end()); + m_jetGhostTrackSystematics.erase(last, + m_jetGhostTrackSystematics.end()); - for(auto s : syst){ - (* m_systMapJetGhostTrack)[s.hash()] = s; - (* m_systDecoKeyMapJetGhostTrack)[s.hash()] = m_decoKeyJetGhostTrack + "_" + s.name(); - m_jetGhostTrackSystematics.push_back(s.name()); - } + m_list_systHashAll->sort(); + m_list_systHashAll->unique(); + } + } + + void TopConfig::systematicsTracks(const std::list<CP::SystematicSet>& syst) { + + if (!m_configFixed) { + + for (auto s : syst) { + m_systHashTracks->insert(s.hash()); + m_list_systHashAll->push_back(s.hash()); + m_systMapTracks->insert(std::make_pair(s.hash(), s)); + + m_systSgKeyMapTracks->insert(std::make_pair(s.hash(), m_sgKeyTracks + "_" + s.name())); - // Ensure that elements are unique. - std::sort(m_jetGhostTrackSystematics.begin(), - m_jetGhostTrackSystematics.end()); - auto last = std::unique(m_jetGhostTrackSystematics.begin(), - m_jetGhostTrackSystematics.end()); - m_jetGhostTrackSystematics.erase(last, - m_jetGhostTrackSystematics.end()); } + + m_list_systHashAll->sort(); + m_list_systHashAll->unique(); + } + } - void TopConfig::fixConfiguration() - { - std::cout<<std::endl; - std::cout<<std::endl; - std::cout<<"TopConfig::fixConfiguration()"<<std::endl; - std::cout<<std::endl; - std::cout<<std::endl; + void TopConfig::fixConfiguration() { + ATH_MSG_INFO("TopConfig::fixConfiguration()"); // Prevent the user from changing anything // Yes, this is deliberate m_configFixed = true; @@ -1343,12 +2462,13 @@ namespace top{ // copy hash values in m_systHashAll_list // into m_systHashAll // The std::unordered_set is faster - for (std::list<std::size_t>::const_iterator i=m_list_systHashAll->begin();i!=m_list_systHashAll->end();++i) { - m_systHashAll->insert( (*i) ); + for (std::list<std::size_t>::const_iterator i = m_list_systHashAll->begin(); i != m_list_systHashAll->end(); ++i) { + m_systHashAll->insert((*i)); } // same for m_systHash_electronInJetSubtraction - for (std::list<std::size_t>::const_iterator i=m_list_systHash_electronInJetSubtraction->begin();i!=m_list_systHash_electronInJetSubtraction->end();++i) { - m_systHash_electronInJetSubtraction->insert( (*i) ); + for (std::list<std::size_t>::const_iterator i = m_list_systHash_electronInJetSubtraction->begin(); + i != m_list_systHash_electronInJetSubtraction->end(); ++i) { + m_systHash_electronInJetSubtraction->insert((*i)); } @@ -1356,108 +2476,155 @@ namespace top{ // Let's do ALL string manipulation here, never do it per event std::string nominalPhotons("SetMe"); std::string nominalElectrons("SetMe"); + std::string nominalFwdElectrons("SetMe"); std::string nominalMuons("SetMe"); + std::string nominalSoftMuons("SetMe"); std::string nominalTaus("SetMe"); std::string nominalJets("SetMe"); std::string nominalLargeRJets("SetMe"); std::string nominalTrackJets("SetMe"); + std::string nominalTracks("SetMe"); std::string nominal("nominal"); std::string tds("TDS"); std::string tdsAux("TDSAux."); // Figure out the nominal object collection names - std::unordered_map<std::size_t,std::string>::const_iterator ph = m_systSgKeyMapPhotons->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator ph = m_systSgKeyMapPhotons->find(m_nominalHashValue); if (ph != m_systSgKeyMapPhotons->end()) { nominalPhotons = (*ph).second; } - std::unordered_map<std::size_t,std::string>::const_iterator el = m_systSgKeyMapElectrons->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator el = m_systSgKeyMapElectrons->find(m_nominalHashValue); if (el != m_systSgKeyMapElectrons->end()) { nominalElectrons = (*el).second; } - std::unordered_map<std::size_t,std::string>::const_iterator mu = m_systSgKeyMapMuons->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator fwdel = m_systSgKeyMapFwdElectrons->find( + m_nominalHashValue); + if (fwdel != m_systSgKeyMapFwdElectrons->end()) { + nominalFwdElectrons = (*fwdel).second; + } + + std::unordered_map<std::size_t, std::string>::const_iterator mu = m_systSgKeyMapMuons->find(m_nominalHashValue); if (mu != m_systSgKeyMapMuons->end()) { nominalMuons = (*mu).second; } - std::unordered_map<std::size_t,std::string>::const_iterator tau = m_systSgKeyMapTaus->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator softmu = m_systSgKeyMapSoftMuons->find( + m_nominalHashValue); + if (softmu != m_systSgKeyMapSoftMuons->end()) { + nominalSoftMuons = (*softmu).second; + } + + std::unordered_map<std::size_t, std::string>::const_iterator tau = m_systSgKeyMapTaus->find(m_nominalHashValue); if (tau != m_systSgKeyMapTaus->end()) { nominalTaus = (*tau).second; } - std::unordered_map<std::size_t,std::string>::const_iterator jet = m_systSgKeyMapJets->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator jet = m_systSgKeyMapJets->find(m_nominalHashValue); if (jet != m_systSgKeyMapJets->end()) { nominalJets = (*jet).second; } - std::unordered_map<std::size_t,std::string>::const_iterator largeRJet = m_systSgKeyMapLargeRJets->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator largeRJet = m_systSgKeyMapLargeRJets->find( + m_nominalHashValue); if (largeRJet != m_systSgKeyMapLargeRJets->end()) { nominalLargeRJets = (*largeRJet).second; } - std::unordered_map<std::size_t,std::string>::const_iterator trackJet = m_systSgKeyMapTrackJets->find( m_nominalHashValue ); + std::unordered_map<std::size_t, std::string>::const_iterator trackJet = m_systSgKeyMapTrackJets->find( + m_nominalHashValue); if (trackJet != m_systSgKeyMapTrackJets->end()) { nominalTrackJets = (*trackJet).second; } + std::unordered_map<std::size_t, std::string>::const_iterator tracks = m_systSgKeyMapTracks->find(m_nominalHashValue); + if (tracks != m_systSgKeyMapTracks->end()) { + nominalTracks = (*tracks).second; + } - for (std::unordered_set<std::size_t>::const_iterator i=m_systHashAll->begin();i!=m_systHashAll->end();++i) { - std::unordered_map<std::size_t,std::string>::const_iterator ph = m_systSgKeyMapPhotons->find( *i ); + for (std::unordered_set<std::size_t>::const_iterator i = m_systHashAll->begin(); i != m_systHashAll->end(); ++i) { + std::unordered_map<std::size_t, std::string>::const_iterator ph = m_systSgKeyMapPhotons->find(*i); if (ph != m_systSgKeyMapPhotons->end()) { - m_systAllSgKeyMapPhotons->insert( std::make_pair( (*i) , (*ph).second ) ); + m_systAllSgKeyMapPhotons->insert(std::make_pair((*i), (*ph).second)); } if (ph == m_systSgKeyMapPhotons->end()) { - m_systAllSgKeyMapPhotons->insert( std::make_pair( (*i) , nominalPhotons ) ); + m_systAllSgKeyMapPhotons->insert(std::make_pair((*i), nominalPhotons)); } - std::unordered_map<std::size_t,std::string>::const_iterator el = m_systSgKeyMapElectrons->find( *i ); + std::unordered_map<std::size_t, std::string>::const_iterator el = m_systSgKeyMapElectrons->find(*i); if (el != m_systSgKeyMapElectrons->end()) { - m_systAllSgKeyMapElectrons->insert( std::make_pair( (*i) , (*el).second ) ); + m_systAllSgKeyMapElectrons->insert(std::make_pair((*i), (*el).second)); } if (el == m_systSgKeyMapElectrons->end()) { - m_systAllSgKeyMapElectrons->insert( std::make_pair( (*i) , nominalElectrons ) ); + m_systAllSgKeyMapElectrons->insert(std::make_pair((*i), nominalElectrons)); + } + + std::unordered_map<std::size_t, std::string>::const_iterator fwdel = m_systSgKeyMapFwdElectrons->find(*i); + if (fwdel != m_systSgKeyMapFwdElectrons->end()) { + m_systAllSgKeyMapFwdElectrons->insert(std::make_pair((*i), (*fwdel).second)); + } + if (fwdel == m_systSgKeyMapFwdElectrons->end()) { + m_systAllSgKeyMapFwdElectrons->insert(std::make_pair((*i), nominalFwdElectrons)); } - std::unordered_map<std::size_t,std::string>::const_iterator mu = m_systSgKeyMapMuons->find( *i ); + std::unordered_map<std::size_t, std::string>::const_iterator mu = m_systSgKeyMapMuons->find(*i); if (mu != m_systSgKeyMapMuons->end()) { - m_systAllSgKeyMapMuons->insert( std::make_pair( (*i) , (*mu).second ) ); + m_systAllSgKeyMapMuons->insert(std::make_pair((*i), (*mu).second)); } if (mu == m_systSgKeyMapMuons->end()) { - m_systAllSgKeyMapMuons->insert( std::make_pair( (*i) , nominalMuons ) ); + m_systAllSgKeyMapMuons->insert(std::make_pair((*i), nominalMuons)); } - std::unordered_map<std::size_t,std::string>::const_iterator tau = m_systSgKeyMapTaus->find( *i ); + std::unordered_map<std::size_t, std::string>::const_iterator softmu = m_systSgKeyMapSoftMuons->find(*i); + if (softmu != m_systSgKeyMapSoftMuons->end()) { + m_systAllSgKeyMapSoftMuons->insert(std::make_pair((*i), (*softmu).second)); + } + if (softmu == m_systSgKeyMapSoftMuons->end()) { + m_systAllSgKeyMapSoftMuons->insert(std::make_pair((*i), nominalSoftMuons)); + } + + std::unordered_map<std::size_t, std::string>::const_iterator tau = m_systSgKeyMapTaus->find(*i); if (tau != m_systSgKeyMapTaus->end()) { - m_systAllSgKeyMapTaus->insert( std::make_pair( (*i) , (*tau).second ) ); + m_systAllSgKeyMapTaus->insert(std::make_pair((*i), (*tau).second)); } if (tau == m_systSgKeyMapTaus->end()) { - m_systAllSgKeyMapTaus->insert( std::make_pair( (*i) , nominalTaus ) ); + m_systAllSgKeyMapTaus->insert(std::make_pair((*i), nominalTaus)); } - std::unordered_map<std::size_t,std::string>::const_iterator jet = m_systSgKeyMapJets->find( *i ); + std::unordered_map<std::size_t, std::string>::const_iterator jet = m_systSgKeyMapJets->find(*i); if (jet != m_systSgKeyMapJets->end()) { - m_systAllSgKeyMapJets->insert( std::make_pair( (*i) , (*jet).second ) ); + m_systAllSgKeyMapJets->insert(std::make_pair((*i), (*jet).second)); } if (jet == m_systSgKeyMapJets->end()) { - m_systAllSgKeyMapJets->insert( std::make_pair( (*i) , nominalJets ) ); + m_systAllSgKeyMapJets->insert(std::make_pair((*i), nominalJets)); } - std::unordered_map<std::size_t,std::string>::const_iterator largeRJet = m_systSgKeyMapLargeRJets->find( *i ); + std::unordered_map<std::size_t, std::string>::const_iterator largeRJet = m_systSgKeyMapLargeRJets->find(*i); if (largeRJet != m_systSgKeyMapLargeRJets->end()) { - m_systAllSgKeyMapLargeRJets->insert( std::make_pair( (*i) , (*largeRJet).second ) ); + m_systAllSgKeyMapLargeRJets->insert(std::make_pair((*i), (*largeRJet).second)); } if (largeRJet == m_systSgKeyMapLargeRJets->end()) { - m_systAllSgKeyMapLargeRJets->insert( std::make_pair( (*i) , nominalLargeRJets ) ); + m_systAllSgKeyMapLargeRJets->insert(std::make_pair((*i), nominalLargeRJets)); } - std::unordered_map<std::size_t,std::string>::const_iterator trackJet = m_systSgKeyMapTrackJets->find( *i ); + std::unordered_map<std::size_t, std::string>::const_iterator trackJet = m_systSgKeyMapTrackJets->find(*i); if (trackJet != m_systSgKeyMapTrackJets->end()) { - m_systAllSgKeyMapTrackJets->insert( std::make_pair( (*i) , (*trackJet).second ) ); + m_systAllSgKeyMapTrackJets->insert(std::make_pair((*i), (*trackJet).second)); } if (trackJet == m_systSgKeyMapTrackJets->end()) { - m_systAllSgKeyMapTrackJets->insert( std::make_pair( (*i) , nominalTrackJets ) ); + m_systAllSgKeyMapTrackJets->insert(std::make_pair((*i), nominalTrackJets)); + } + + std::unordered_map<std::size_t, std::string>::const_iterator tracks = m_systSgKeyMapTracks->find(*i); + if (tracks != m_systSgKeyMapTracks->end()) { + m_systAllSgKeyMapTracks->insert(std::make_pair((*i), (*tracks).second)); + } + if (tracks == m_systSgKeyMapTracks->end()) { + m_systAllSgKeyMapTracks->insert(std::make_pair((*i), nominalTracks)); } + + } // Loop over all systematic hash values @@ -1466,133 +2633,207 @@ namespace top{ std::string electronInJetSubtraction_Electrons("electronInJetSubtraction_Electrons_USING_"); std::string electronInJetSubtraction_Jets("electronInJetSubtraction_Jets_USING_"); std::string electronInJetSubtraction_JetsLoose("electronInJetSubtraction_JetsLoose_USING_"); - std::string electronInJetSubtraction_nominalElectrons = electronInJetSubtraction_Electrons+nominalElectrons+"_AND_"+nominalJets; - std::string electronInJetSubtraction_nominalJets = electronInJetSubtraction_Jets+nominalElectrons+"_AND_"+nominalJets; - std::string electronInJetSubtraction_nominalJetsLoose = electronInJetSubtraction_JetsLoose+nominalElectrons+"_AND_"+nominalJets; + std::string electronInJetSubtraction_nominalElectrons = electronInJetSubtraction_Electrons + nominalElectrons + + "_AND_" + nominalJets; + std::string electronInJetSubtraction_nominalJets = electronInJetSubtraction_Jets + nominalElectrons + "_AND_" + + nominalJets; + std::string electronInJetSubtraction_nominalJetsLoose = electronInJetSubtraction_JetsLoose + nominalElectrons + + "_AND_" + nominalJets; - for (std::unordered_set<std::size_t>::const_iterator i=m_systHashAll->begin();i!=m_systHashAll->end();++i) { - std::unordered_map<std::size_t,std::string>::const_iterator el = m_systSgKeyMapElectrons->find( *i ); - std::unordered_map<std::size_t,std::string>::const_iterator jet = m_systSgKeyMapJets->find( *i ); + for (std::unordered_set<std::size_t>::const_iterator i = m_systHashAll->begin(); i != m_systHashAll->end(); ++i) { + std::unordered_map<std::size_t, std::string>::const_iterator el = m_systSgKeyMapElectrons->find(*i); + std::unordered_map<std::size_t, std::string>::const_iterator jet = m_systSgKeyMapJets->find(*i); if (el != m_systSgKeyMapElectrons->end()) { - m_systAllSgKeyMapElectrons_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_Electrons+(*el).second+"_AND_"+nominalJets ) ); - m_systAllSgKeyMapJets_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_Jets+(*el).second+"_AND_"+nominalJets ) ); - m_systSgKeyMapJets_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_Jets+(*el).second+"_AND_"+nominalJets ) ); - - m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_JetsLoose+(*el).second+"_AND_"+nominalJets ) ); - m_systSgKeyMapJetsLoose_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_JetsLoose+(*el).second+"_AND_"+nominalJets ) ); + m_systAllSgKeyMapElectrons_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_Electrons + + (*el).second + "_AND_" + + nominalJets)); + m_systAllSgKeyMapJets_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_Jets + + (*el).second + "_AND_" + nominalJets)); + m_systSgKeyMapJets_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_Jets + + (*el).second + "_AND_" + nominalJets)); + + m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_JetsLoose + + (*el).second + "_AND_" + + nominalJets)); + m_systSgKeyMapJetsLoose_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_JetsLoose + + (*el).second + "_AND_" + + nominalJets)); } if (jet != m_systSgKeyMapJets->end()) { - m_systAllSgKeyMapElectrons_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_Electrons+nominalElectrons+"_AND_"+(*jet).second ) ); - m_systAllSgKeyMapJets_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_Jets+nominalElectrons+"_AND_"+(*jet).second ) ); - m_systSgKeyMapJets_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_Jets+nominalElectrons+"_AND_"+(*jet).second ) ); - - m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_JetsLoose+nominalElectrons+"_AND_"+(*jet).second ) ); - m_systSgKeyMapJetsLoose_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_JetsLoose+nominalElectrons+"_AND_"+(*jet).second ) ); + m_systAllSgKeyMapElectrons_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_Electrons + + nominalElectrons + "_AND_" + + (*jet).second)); + m_systAllSgKeyMapJets_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_Jets + + nominalElectrons + "_AND_" + + (*jet).second)); + m_systSgKeyMapJets_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_Jets + + nominalElectrons + "_AND_" + + (*jet).second)); + + m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_JetsLoose + + nominalElectrons + "_AND_" + + (*jet).second)); + m_systSgKeyMapJetsLoose_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_JetsLoose + + nominalElectrons + "_AND_" + + (*jet).second)); } if (el == m_systSgKeyMapElectrons->end() && jet == m_systSgKeyMapJets->end()) { - m_systAllSgKeyMapElectrons_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_nominalElectrons ) ); - m_systAllSgKeyMapJets_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_nominalJets ) ); - m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->insert( std::make_pair( (*i) , electronInJetSubtraction_nominalJetsLoose ) ); + m_systAllSgKeyMapElectrons_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_nominalElectrons)); + m_systAllSgKeyMapJets_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_nominalJets)); + m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->insert(std::make_pair((*i), + electronInJetSubtraction_nominalJetsLoose)); } } // Loop over all systematic hash values } // electron in jet Subtraction // Tempory data store names - typedef std::unordered_map<std::size_t,std::string>::const_iterator Itr2; - for (Itr2 i=m_systAllSgKeyMapPhotons->begin();i!=m_systAllSgKeyMapPhotons->end();++i) { - m_systAllSgKeyMapPhotonsTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapPhotonsTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + typedef std::unordered_map<std::size_t, std::string>::const_iterator Itr2; + for (Itr2 i = m_systAllSgKeyMapPhotons->begin(); i != m_systAllSgKeyMapPhotons->end(); ++i) { + m_systAllSgKeyMapPhotonsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapPhotonsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); + } + + for (Itr2 i = m_systAllSgKeyMapElectrons->begin(); i != m_systAllSgKeyMapElectrons->end(); ++i) { + m_systAllSgKeyMapElectronsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapElectronsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapElectrons->begin();i!=m_systAllSgKeyMapElectrons->end();++i) { - m_systAllSgKeyMapElectronsTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapElectronsTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (const auto& i : *(m_systAllSgKeyMapFwdElectrons)) { + m_systAllSgKeyMapFwdElectronsTDS->insert(std::make_pair(i.first, i.second + tds)); + m_systAllSgKeyMapFwdElectronsTDSAux->insert(std::make_pair(i.first, i.second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapMuons->begin();i!=m_systAllSgKeyMapMuons->end();++i) { - m_systAllSgKeyMapMuonsTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapMuonsTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapMuons->begin(); i != m_systAllSgKeyMapMuons->end(); ++i) { + m_systAllSgKeyMapMuonsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapMuonsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapTaus->begin();i!=m_systAllSgKeyMapTaus->end();++i) { - m_systAllSgKeyMapTausTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapTausTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapSoftMuons->begin(); i != m_systAllSgKeyMapSoftMuons->end(); ++i) { + m_systAllSgKeyMapSoftMuonsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapSoftMuonsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapJets->begin();i!=m_systAllSgKeyMapJets->end();++i) { - m_systAllSgKeyMapJetsTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapJetsTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapTaus->begin(); i != m_systAllSgKeyMapTaus->end(); ++i) { + m_systAllSgKeyMapTausTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapTausTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapLargeRJets->begin();i!=m_systAllSgKeyMapLargeRJets->end();++i) { - m_systAllSgKeyMapLargeRJetsTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapLargeRJetsTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapJets->begin(); i != m_systAllSgKeyMapJets->end(); ++i) { + m_systAllSgKeyMapJetsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapJetsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapElectrons_electronInJetSubtraction->begin();i!=m_systAllSgKeyMapElectrons_electronInJetSubtraction->end();++i) { - m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapLargeRJets->begin(); i != m_systAllSgKeyMapLargeRJets->end(); ++i) { + m_systAllSgKeyMapLargeRJetsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapLargeRJetsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapTrackJets->begin();i!=m_systAllSgKeyMapTrackJets->end();++i) { - m_systAllSgKeyMapTrackJetsTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapTrackJetsTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapElectrons_electronInJetSubtraction->begin(); + i != m_systAllSgKeyMapElectrons_electronInJetSubtraction->end(); ++i) { + m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux->insert(std::make_pair((*i).first, + (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapJets_electronInJetSubtraction->begin();i!=m_systAllSgKeyMapJets_electronInJetSubtraction->end();++i) { - m_systAllSgKeyMapJets_electronInJetSubtractionTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapTrackJets->begin(); i != m_systAllSgKeyMapTrackJets->end(); ++i) { + m_systAllSgKeyMapTrackJetsTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapTrackJetsTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); } - for (Itr2 i=m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->begin();i!=m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->end();++i) { - m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS->insert( std::make_pair( (*i).first , (*i).second + tds ) ); - m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux->insert( std::make_pair( (*i).first , (*i).second + tdsAux ) ); + for (Itr2 i = m_systAllSgKeyMapTracks->begin(); i != m_systAllSgKeyMapTracks->end(); ++i) { + m_systAllSgKeyMapTracksTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapTracksTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); + } + + for (Itr2 i = m_systAllSgKeyMapJets_electronInJetSubtraction->begin(); + i != m_systAllSgKeyMapJets_electronInJetSubtraction->end(); ++i) { + m_systAllSgKeyMapJets_electronInJetSubtractionTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux->insert(std::make_pair((*i).first, (*i).second + tdsAux)); + } + + for (Itr2 i = m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->begin(); + i != m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->end(); ++i) { + m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS->insert(std::make_pair((*i).first, (*i).second + tds)); + m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux->insert(std::make_pair((*i).first, + (*i).second + tdsAux)); } // TTree names - m_systAllTTreeNames->insert( std::make_pair( m_nominalHashValue , nominal ) ); - typedef std::unordered_map<std::size_t,CP::SystematicSet>::const_iterator Itr; + m_systAllTTreeNames->insert(std::make_pair(m_nominalHashValue, nominal)); + typedef std::unordered_map<std::size_t, CP::SystematicSet>::const_iterator Itr; if (m_usePhotons) { - for (Itr i=m_systMapPhotons->begin();i!=m_systMapPhotons->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapPhotons->begin(); i != m_systMapPhotons->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } if (m_useElectrons) { - for (Itr i=m_systMapElectrons->begin();i!=m_systMapElectrons->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapElectrons->begin(); i != m_systMapElectrons->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); + } + } + if (m_useFwdElectrons) { + for (Itr i = m_systMapFwdElectrons->begin(); i != m_systMapFwdElectrons->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } if (m_useMuons) { - for (Itr i=m_systMapMuons->begin();i!=m_systMapMuons->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapMuons->begin(); i != m_systMapMuons->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); + } + } + if (m_useSoftMuons) { + for (Itr i = m_systMapSoftMuons->begin(); i != m_systMapSoftMuons->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } if (m_useTaus) { - for (Itr i=m_systMapTaus->begin();i!=m_systMapTaus->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapTaus->begin(); i != m_systMapTaus->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } if (m_useJets) { - for (Itr i=m_systMapJets->begin();i!=m_systMapJets->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapJets->begin(); i != m_systMapJets->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } if (m_useLargeRJets) { - for (Itr i=m_systMapLargeRJets->begin();i!=m_systMapLargeRJets->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapLargeRJets->begin(); i != m_systMapLargeRJets->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } if (m_useTrackJets) { - for (Itr i=m_systMapTrackJets->begin();i!=m_systMapTrackJets->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + for (Itr i = m_systMapTrackJets->begin(); i != m_systMapTrackJets->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } } - for (Itr i=m_systMapMET->begin();i!=m_systMapMET->end();++i) { - m_systAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second.name() ) ); + if (m_useTracks) { + for (Itr i = m_systMapTracks->begin(); i != m_systMapTracks->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); + } + } + if (m_useJetGhostTrack) { + for (Itr i = m_systMapJetGhostTrack->begin(); i != m_systMapJetGhostTrack->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); + } + } + for (Itr i = m_systMapMET->begin(); i != m_systMapMET->end(); ++i) { + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second.name())); } @@ -1600,86 +2841,89 @@ namespace top{ // Missing ET from TTree names // KLFitter from TTree names - for (Itr2 i=m_systAllTTreeNames->begin();i!=m_systAllTTreeNames->end();++i) { - if (!m_doLooseTreeOnly) - m_systSgKeyMapMissingET->insert( std::make_pair( (*i).first , m_sgKeyMissingEt + "_" + (*i).second ) ); - if (m_doLooseEvents) - m_systSgKeyMapMissingETLoose->insert( std::make_pair( (*i).first , m_sgKeyMissingEt + "_Loose_" + (*i).second ) ); + for (Itr2 i = m_systAllTTreeNames->begin(); i != m_systAllTTreeNames->end(); ++i) { + if (m_doTightEvents) m_systSgKeyMapMissingET->insert(std::make_pair((*i).first, + m_sgKeyMissingEt + "_" + (*i).second)); + if (m_doLooseEvents) m_systSgKeyMapMissingETLoose->insert(std::make_pair((*i).first, + m_sgKeyMissingEt + "_Loose_" + + (*i).second)); - if (!m_doLooseTreeOnly) - m_systSgKeyMapKLFitter->insert( std::make_pair( (*i).first , m_sgKeyKLFitter + "_" + (*i).second ) ); - if (m_doLooseEvents) - m_systSgKeyMapKLFitterLoose->insert( std::make_pair( (*i).first , m_sgKeyKLFitter + "_Loose_" + (*i).second ) ); + if (m_doTightEvents) m_systSgKeyMapKLFitter->insert(std::make_pair((*i).first, + m_sgKeyKLFitter + "_" + (*i).second)); + if (m_doLooseEvents) m_systSgKeyMapKLFitterLoose->insert(std::make_pair((*i).first, + m_sgKeyKLFitter + "_Loose_" + + (*i).second)); - m_systSgKeyMapPseudoTop->insert( std::make_pair( (*i).first , m_sgKeyPseudoTop + "_" + (*i).second ) ); - + if (m_doTightEvents) m_systSgKeyMapPseudoTop->insert(std::make_pair((*i).first, + m_sgKeyPseudoTop + "_" + (*i).second)); + if (m_doLooseEvents) m_systSgKeyMapPseudoTopLoose->insert(std::make_pair((*i).first, + m_sgKeyPseudoTop + "_Loose_" + + (*i).second)); } // TTree index unsigned int TTreeIndex(0); - if (!m_doLooseTreeOnly) { - for (Itr2 i=m_systAllTTreeNames->begin();i!=m_systAllTTreeNames->end();++i) { - m_systAllTTreeIndex->insert( std::make_pair( (*i).first , TTreeIndex ) ); - ++TTreeIndex; + if (m_doTightEvents) { + for (Itr2 i = m_systAllTTreeNames->begin(); i != m_systAllTTreeNames->end(); ++i) { + if ((*i).second == "nominal" || m_doTightSysts) { + m_systAllTTreeIndex->insert(std::make_pair((*i).first, TTreeIndex)); + ++TTreeIndex; + } } } if (m_doLooseEvents) { - for (Itr2 i=m_systAllTTreeNames->begin();i!=m_systAllTTreeNames->end();++i) { - m_systAllTTreeLooseIndex->insert( std::make_pair( (*i).first , TTreeIndex ) ); - ++TTreeIndex; + for (Itr2 i = m_systAllTTreeNames->begin(); i != m_systAllTTreeNames->end(); ++i) { + if ((*i).second == "nominal" || m_doLooseSysts) { + m_systAllTTreeLooseIndex->insert(std::make_pair((*i).first, TTreeIndex)); + ++TTreeIndex; + } } } if (m_makeAllCPTools) { - for (Itr2 i=m_systAllTTreeNames->begin();i!=m_systAllTTreeNames->end();++i) { - m_systPersistantAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second) ); + for (Itr2 i = m_systAllTTreeNames->begin(); i != m_systAllTTreeNames->end(); ++i) { + m_systPersistantAllTTreeNames->insert(std::make_pair((*i).first, (*i).second)); } } - } - - - - const std::string& TopConfig::sgKeyPhotons( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapPhotons->find( hash ); + const std::string& TopConfig::sgKeyPhotons(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapPhotons->find(hash); if (key != m_systAllSgKeyMapPhotons->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyPhotonsTDS( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapPhotonsTDS->find( hash ); + const std::string& TopConfig::sgKeyPhotonsTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapPhotonsTDS->find(hash); if (key != m_systAllSgKeyMapPhotonsTDS->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyPhotonsTDSAux( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapPhotonsTDSAux->find( hash ); + const std::string& TopConfig::sgKeyPhotonsTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapPhotonsTDSAux->find(hash); if (key != m_systAllSgKeyMapPhotonsTDSAux->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyElectrons( const std::size_t hash ) const - { + const std::string& TopConfig::sgKeyElectrons(const std::size_t hash) const { if (!m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectrons->find( hash ); + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapElectrons->find(hash); if (key != m_systAllSgKeyMapElectrons->end()) { return (*key).second; } } if (m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectrons_electronInJetSubtraction->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = m_systAllSgKeyMapElectrons_electronInJetSubtraction->find( + hash); if (key != m_systAllSgKeyMapElectrons_electronInJetSubtraction->end()) { return (*key).second; } @@ -1688,17 +2932,18 @@ namespace top{ return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyElectronsTDS( const std::size_t hash ) const - { + const std::string& TopConfig::sgKeyElectronsTDS(const std::size_t hash) const { if (!m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectronsTDS->find( hash ); + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapElectronsTDS->find(hash); if (key != m_systAllSgKeyMapElectronsTDS->end()) { return (*key).second; } } if (m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = + m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS->find(hash); if (key != m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS->end()) { return (*key).second; } @@ -1707,17 +2952,18 @@ namespace top{ return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyElectronsTDSAux( const std::size_t hash ) const - { + const std::string& TopConfig::sgKeyElectronsTDSAux(const std::size_t hash) const { if (!m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectronsTDSAux->find( hash ); + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapElectronsTDSAux->find(hash); if (key != m_systAllSgKeyMapElectronsTDSAux->end()) { return (*key).second; } } if (m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = + m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux->find(hash); if (key != m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux->end()) { return (*key).second; } @@ -1726,74 +2972,124 @@ namespace top{ return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyElectronsStandAlone( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapElectrons->find( hash ); + const std::string& TopConfig::sgKeyElectronsStandAlone(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapElectrons->find(hash); if (key != m_systAllSgKeyMapElectrons->end()) { return (*key).second; } return m_sgKeyDummy; } + const std::string& TopConfig::sgKeyFwdElectrons(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapFwdElectrons->find(hash); + if (key != m_systAllSgKeyMapFwdElectrons->end()) { + return (*key).second; + } + + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeyFwdElectronsTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapFwdElectronsTDS->find(hash); + if (key != m_systAllSgKeyMapFwdElectronsTDS->end()) { + return (*key).second; + } + + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeyFwdElectronsTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapFwdElectronsTDSAux->find(hash); + if (key != m_systAllSgKeyMapFwdElectronsTDSAux->end()) { + return (*key).second; + } + + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeyFwdElectronsStandAlone(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapFwdElectrons->find(hash); + if (key != m_systAllSgKeyMapFwdElectrons->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } - const std::string& TopConfig::sgKeyMuons( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapMuons->find( hash ); + const std::string& TopConfig::sgKeyMuons(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapMuons->find(hash); if (key != m_systAllSgKeyMapMuons->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyMuonsTDS( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapMuonsTDS->find( hash ); + const std::string& TopConfig::sgKeyMuonsTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapMuonsTDS->find(hash); if (key != m_systAllSgKeyMapMuonsTDS->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyMuonsTDSAux( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapMuonsTDSAux->find( hash ); + const std::string& TopConfig::sgKeyMuonsTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapMuonsTDSAux->find(hash); if (key != m_systAllSgKeyMapMuonsTDSAux->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyTaus( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapTaus->find( hash ); + const std::string& TopConfig::sgKeySoftMuons(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapSoftMuons->find(hash); + if (key != m_systAllSgKeyMapSoftMuons->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeySoftMuonsTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapSoftMuonsTDS->find(hash); + if (key != m_systAllSgKeyMapSoftMuonsTDS->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeySoftMuonsTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapSoftMuonsTDSAux->find(hash); + if (key != m_systAllSgKeyMapSoftMuonsTDSAux->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeyTaus(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTaus->find(hash); if (key != m_systAllSgKeyMapTaus->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyTausTDS( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapTausTDS->find( hash ); + const std::string& TopConfig::sgKeyTausTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTausTDS->find(hash); if (key != m_systAllSgKeyMapTausTDS->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyTausTDSAux( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapTausTDSAux->find( hash ); + const std::string& TopConfig::sgKeyTausTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTausTDSAux->find(hash); if (key != m_systAllSgKeyMapTausTDSAux->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyJets( const std::size_t hash , const bool useLooseLeptonJets) const - { + const std::string& TopConfig::sgKeyJets(const std::size_t hash, const bool useLooseLeptonJets) const { if (!m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJets->find( hash ); + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapJets->find(hash); if (key != m_systAllSgKeyMapJets->end()) { return (*key).second; } @@ -1801,13 +3097,17 @@ namespace top{ if (m_applyElectronInJetSubtraction) { if (!useLooseLeptonJets) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJets_electronInJetSubtraction->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = + m_systAllSgKeyMapJets_electronInJetSubtraction->find(hash); if (key != m_systAllSgKeyMapJets_electronInJetSubtraction->end()) { return (*key).second; } } if (useLooseLeptonJets) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->find( + hash); if (key != m_systAllSgKeyMapJetsLoose_electronInJetSubtraction->end()) { return (*key).second; } @@ -1817,10 +3117,9 @@ namespace top{ return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyJetsTDS( const std::size_t hash , const bool useLooseLeptonJets) const - { + const std::string& TopConfig::sgKeyJetsTDS(const std::size_t hash, const bool useLooseLeptonJets) const { if (!m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJetsTDS->find( hash ); + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapJetsTDS->find(hash); if (key != m_systAllSgKeyMapJetsTDS->end()) { return (*key).second; } @@ -1828,13 +3127,17 @@ namespace top{ if (m_applyElectronInJetSubtraction) { if (!useLooseLeptonJets) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJets_electronInJetSubtractionTDS->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = m_systAllSgKeyMapJets_electronInJetSubtractionTDS->find( + hash); if (key != m_systAllSgKeyMapJets_electronInJetSubtractionTDS->end()) { return (*key).second; } } if (useLooseLeptonJets) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = + m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS->find(hash); if (key != m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS->end()) { return (*key).second; } @@ -1844,11 +3147,9 @@ namespace top{ return m_sgKeyDummy; } - - const std::string& TopConfig::sgKeyJetsTDSAux( const std::size_t hash , const bool useLooseLeptonJets) const - { + const std::string& TopConfig::sgKeyJetsTDSAux(const std::size_t hash, const bool useLooseLeptonJets) const { if (!m_applyElectronInJetSubtraction) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJetsTDSAux->find( hash ); + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapJetsTDSAux->find(hash); if (key != m_systAllSgKeyMapJetsTDSAux->end()) { return (*key).second; } @@ -1856,13 +3157,17 @@ namespace top{ if (m_applyElectronInJetSubtraction) { if (!useLooseLeptonJets) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = + m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux->find(hash); if (key != m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux->end()) { return (*key).second; } } if (useLooseLeptonJets) { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux->find( hash ); + std::unordered_map<std::size_t, + std::string>::const_iterator key = + m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux->find(hash); if (key != m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux->end()) { return (*key).second; } @@ -1872,138 +3177,159 @@ namespace top{ return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyJetsStandAlone( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapJets->find( hash ); + const std::string& TopConfig::sgKeyJetsStandAlone(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapJets->find(hash); if (key != m_systAllSgKeyMapJets->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyLargeRJets( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapLargeRJets->find( hash ); + const std::string& TopConfig::sgKeyLargeRJets(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapLargeRJets->find(hash); if (key != m_systAllSgKeyMapLargeRJets->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyLargeRJetsTDS( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapLargeRJetsTDS->find( hash ); + const std::string& TopConfig::sgKeyLargeRJetsTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapLargeRJetsTDS->find(hash); if (key != m_systAllSgKeyMapLargeRJetsTDS->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyLargeRJetsTDSAux( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapLargeRJetsTDSAux->find( hash ); + const std::string& TopConfig::sgKeyLargeRJetsTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapLargeRJetsTDSAux->find(hash); if (key != m_systAllSgKeyMapLargeRJetsTDSAux->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyTrackJets( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapTrackJets->find( hash ); + const std::string& TopConfig::sgKeyTrackJets(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTrackJets->find(hash); if (key != m_systAllSgKeyMapTrackJets->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyTrackJetsTDS( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapTrackJetsTDS->find( hash ); + const std::string& TopConfig::sgKeyTrackJetsTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTrackJetsTDS->find(hash); if (key != m_systAllSgKeyMapTrackJetsTDS->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyTrackJetsTDSAux( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systAllSgKeyMapTrackJetsTDSAux->find( hash ); + const std::string& TopConfig::sgKeyTrackJetsTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTrackJetsTDSAux->find(hash); if (key != m_systAllSgKeyMapTrackJetsTDSAux->end()) { return (*key).second; } return m_sgKeyDummy; } + const std::string& TopConfig::sgKeyTracks(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTracks->find(hash); + if (key != m_systAllSgKeyMapTracks->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeyTracksTDS(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTracksTDS->find(hash); + if (key != m_systAllSgKeyMapTracksTDS->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } + + const std::string& TopConfig::sgKeyTracksTDSAux(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systAllSgKeyMapTracksTDSAux->find(hash); + if (key != m_systAllSgKeyMapTracksTDSAux->end()) { + return (*key).second; + } + return m_sgKeyDummy; + } - const std::string& TopConfig::sgKeyMissingEt( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systSgKeyMapMissingET->find( hash ); + const std::string& TopConfig::sgKeyMissingEt(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systSgKeyMapMissingET->find(hash); if (key != m_systSgKeyMapMissingET->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyMissingEtLoose( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systSgKeyMapMissingETLoose->find( hash ); + const std::string& TopConfig::sgKeyMissingEtLoose(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systSgKeyMapMissingETLoose->find(hash); if (key != m_systSgKeyMapMissingETLoose->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyKLFitter( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systSgKeyMapKLFitter->find( hash ); + const std::string& TopConfig::sgKeyKLFitter(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systSgKeyMapKLFitter->find(hash); if (key != m_systSgKeyMapKLFitter->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyKLFitterLoose( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systSgKeyMapKLFitterLoose->find( hash ); + const std::string& TopConfig::sgKeyKLFitterLoose(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systSgKeyMapKLFitterLoose->find(hash); if (key != m_systSgKeyMapKLFitterLoose->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string& TopConfig::sgKeyPseudoTop( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systSgKeyMapPseudoTop->find( hash ); + const std::string& TopConfig::sgKeyPseudoTop(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systSgKeyMapPseudoTop->find(hash); if (key != m_systSgKeyMapPseudoTop->end()) { return (*key).second; } return m_sgKeyDummy; } - const std::string & TopConfig::decoKeyJetGhostTrack(const std::size_t hash) const { - // If it's in the map, use the mapped value, otherwise use the nominal. - auto it = m_systDecoKeyMapJetGhostTrack->find(hash); - if (it != m_systDecoKeyMapJetGhostTrack->end()){ - return it->second; - } else { - return m_decoKeyJetGhostTrack; - } + const std::string& TopConfig::sgKeyPseudoTopLoose(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systSgKeyMapPseudoTopLoose->find(hash); + if (key != m_systSgKeyMapPseudoTopLoose->end()) { + return (*key).second; + } + return m_sgKeyDummy; } + const std::string& TopConfig::decoKeyJetGhostTrack(const std::size_t hash) const { + // If it's in the map, use the mapped value, otherwise use the nominal. + auto it = m_systDecoKeyMapJetGhostTrack->find(hash); - const std::string& TopConfig::systematicName( const std::size_t hash ) const - { - std::unordered_map<std::size_t,std::string>::const_iterator key = m_systPersistantAllTTreeNames - ->find( hash ); + if (it != m_systDecoKeyMapJetGhostTrack->end()) { + return it->second; + } else { + it = m_systDecoKeyMapJetGhostTrack->find(m_nominalHashValue); + if (it == m_systDecoKeyMapJetGhostTrack->end()) throw std::runtime_error( + "TopConfig: Failed to retrieve decoKeyJetGhostTrack."); + return it->second; + } + } + + const std::string& TopConfig::systematicName(const std::size_t hash) const { + std::unordered_map<std::size_t, std::string>::const_iterator key = m_systPersistantAllTTreeNames + ->find(hash); if (key != m_systPersistantAllTTreeNames->end()) { return (*key).second; } return m_sgKeyDummy; } - std::shared_ptr<std::unordered_map<std::size_t,std::string>> TopConfig::systSgKeyMapJets(const bool useLooseLeptonJets) const - { + std::shared_ptr<std::unordered_map<std::size_t, std::string> > TopConfig::systSgKeyMapJets( + const bool useLooseLeptonJets) const { if (m_applyElectronInJetSubtraction) { if (useLooseLeptonJets) { return m_systSgKeyMapJetsLoose_electronInJetSubtraction; @@ -2014,73 +3340,107 @@ namespace top{ } // TTree index - unsigned int TopConfig::ttreeIndex( const std::size_t hash ) const - { + unsigned int TopConfig::ttreeIndex(const std::size_t hash) const { unsigned int index(99999); // This will crash the job if not set properly - std::unordered_map<std::size_t,unsigned int>::const_iterator Itr = m_systAllTTreeIndex->find( hash ); + + std::unordered_map<std::size_t, unsigned int>::const_iterator Itr = m_systAllTTreeIndex->find(hash); if (Itr != m_systAllTTreeIndex->end()) { index = (*Itr).second; } if (index == 99999) { - std::cout<<"ttreeIndex is crazy, something has gone wrong with the hash value = "<<hash<<std::endl; + ATH_MSG_WARNING("ttreeIndex is crazy, something has gone wrong with the hash value = " << hash); } return index; } - unsigned int TopConfig::ttreeIndexLoose( const std::size_t hash ) const - { + unsigned int TopConfig::ttreeIndexLoose(const std::size_t hash) const { unsigned int index(99999); // This will crash the job if not set properly - std::unordered_map<std::size_t,unsigned int>::const_iterator Itr = m_systAllTTreeLooseIndex->find( hash ); + + std::unordered_map<std::size_t, unsigned int>::const_iterator Itr = m_systAllTTreeLooseIndex->find(hash); if (Itr != m_systAllTTreeLooseIndex->end()) { index = (*Itr).second; } if (index == 99999) { - std::cout<<"ttreeIndex is crazy, something has gone wrong with the hash value = "<<hash<<std::endl; + ATH_MSG_WARNING("ttreeIndex is crazy, something has gone wrong with the hash value = " << hash); } return index; } - const std::vector<std::string>& TopConfig::allTriggers(const std::string& selection) const - { - std::unordered_map<std::string,std::vector<std::string>>::const_iterator key = m_allTriggers->find( selection ); - if (key != m_allTriggers->end()) { + const std::vector<std::string>& TopConfig::allTriggers_Tight(const std::string& selection) const { + std::unordered_map<std::string, + std::vector<std::string> >::const_iterator key = m_allTriggers_Tight->find(selection); + if (key != m_allTriggers_Tight->end()) { + return (*key).second; + } + return m_dummyTrigger; + } + + const std::vector<std::string>& TopConfig::electronTriggers_Tight(const std::string& selection) const { + std::unordered_map<std::string, std::vector<std::string> >::const_iterator key = m_electronTriggers_Tight->find( + selection); + if (key != m_electronTriggers_Tight->end()) { + return (*key).second; + } + return m_dummyTrigger; + } + + const std::vector<std::string>& TopConfig::muonTriggers_Tight(const std::string& selection) const { + std::unordered_map<std::string, std::vector<std::string> >::const_iterator key = m_muonTriggers_Tight->find( + selection); + if (key != m_muonTriggers_Tight->end()) { + return (*key).second; + } + return m_dummyTrigger; + } + + const std::vector<std::string>& TopConfig::tauTriggers_Tight(const std::string& selection) const { + std::unordered_map<std::string, + std::vector<std::string> >::const_iterator key = m_tauTriggers_Tight->find(selection); + if (key != m_tauTriggers_Tight->end()) { return (*key).second; } return m_dummyTrigger; } - const std::vector<std::string>& TopConfig::electronTriggers(const std::string& selection) const - { - std::unordered_map<std::string,std::vector<std::string>>::const_iterator key = m_electronTriggers->find( selection ); - if (key != m_electronTriggers->end()) { + const std::vector<std::string>& TopConfig::allTriggers_Loose(const std::string& selection) const { + std::unordered_map<std::string, + std::vector<std::string> >::const_iterator key = m_allTriggers_Loose->find(selection); + if (key != m_allTriggers_Loose->end()) { return (*key).second; } return m_dummyTrigger; } - const std::vector<std::string>& TopConfig::muonTriggers(const std::string& selection) const - { - std::unordered_map<std::string,std::vector<std::string>>::const_iterator key = m_muonTriggers->find( selection ); - if (key != m_muonTriggers->end()) { + const std::vector<std::string>& TopConfig::electronTriggers_Loose(const std::string& selection) const { + std::unordered_map<std::string, std::vector<std::string> >::const_iterator key = m_electronTriggers_Loose->find( + selection); + if (key != m_electronTriggers_Loose->end()) { return (*key).second; } return m_dummyTrigger; } - const std::vector<std::string>& TopConfig::tauTriggers(const std::string& selection) const - { - std::unordered_map<std::string,std::vector<std::string>>::const_iterator key = m_tauTriggers->find( selection ); - if (key != m_tauTriggers->end()) { + const std::vector<std::string>& TopConfig::muonTriggers_Loose(const std::string& selection) const { + std::unordered_map<std::string, std::vector<std::string> >::const_iterator key = m_muonTriggers_Loose->find( + selection); + if (key != m_muonTriggers_Loose->end()) { return (*key).second; } return m_dummyTrigger; } + const std::vector<std::string>& TopConfig::tauTriggers_Loose(const std::string& selection) const { + std::unordered_map<std::string, + std::vector<std::string> >::const_iterator key = m_tauTriggers_Loose->find(selection); + if (key != m_tauTriggers_Loose->end()) { + return (*key).second; + } + return m_dummyTrigger; + } - ///-- top::TopPersistentSettings allows us to take a snapshot of top::TopConfig --/// + ///-- top::TopPersistentSettings allows us to take a snapshot of top::TopConfig --/// ///-- and save it to a mini-xAOD. We can then re-create the top::TopConfig from file --/// - top::TopPersistentSettings* TopConfig::createPersistentSettings() - { + top::TopPersistentSettings* TopConfig::createPersistentSettings() { top::TopPersistentSettings* out = new top::TopPersistentSettings(); out->m_isMC = m_isMC; @@ -2097,11 +3457,14 @@ namespace top{ out->m_sgKeyPrimaryVertices = m_sgKeyPrimaryVertices; out->m_sgKeyPhotons = m_sgKeyPhotons; out->m_sgKeyElectrons = m_sgKeyElectrons; + out->m_sgKeyFwdElectrons = m_sgKeyFwdElectrons; out->m_sgKeyMuons = m_sgKeyMuons; + out->m_sgKeySoftMuons = m_sgKeySoftMuons; out->m_sgKeyTaus = m_sgKeyTaus; out->m_sgKeyJets = m_sgKeyJets; out->m_sgKeyLargeRJets = m_sgKeyLargeRJets; out->m_sgKeyTrackJets = m_sgKeyTrackJets; + out->m_sgKeyTracks = m_sgKeyTracks; out->m_sgKeyMissingEt = m_sgKeyMissingEt; out->m_sgKeyMissingEtLoose = m_sgKeyMissingEtLoose; @@ -2109,6 +3472,11 @@ namespace top{ out->m_electronIDLoose = m_electronIDLoose; out->m_electronIsolation = m_electronIsolation; out->m_electronIsolationLoose = m_electronIsolationLoose; + out->m_useElectronChargeIDSelection = m_useElectronChargeIDSelection; + out->m_useEgammaLeakageCorrection = m_useEgammaLeakageCorrection; + out->m_enablePromptLeptonImprovedVetoStudies = m_enablePromptLeptonImprovedVetoStudies; + + out->m_fwdElectronID = m_fwdElectronID; out->m_muon_trigger_SF = m_muon_trigger_SF; out->m_muonQuality = m_muonQuality; @@ -2116,85 +3484,118 @@ namespace top{ out->m_muonIsolation = m_muonIsolation; out->m_muonIsolationLoose = m_muonIsolationLoose; - typedef std::unordered_map<std::size_t,std::string>::const_iterator Itr; + out->m_softmuonQuality = m_softmuonQuality; + + out->m_trackQuality = m_trackQuality; + + typedef std::unordered_map<std::size_t, std::string>::const_iterator Itr; + + for (std::vector<std::pair<std::string, std::string> >::const_iterator i = m_chosen_btaggingWP.begin(); + i != m_chosen_btaggingWP.end(); ++i) + out->m_chosen_btaggingWP.push_back(*i); - for (std::vector<std::string>::const_iterator i=m_chosen_btaggingWP.begin();i!=m_chosen_btaggingWP.end();++i) - out->m_chosen_btaggingWP.push_back( *i ); + for (Itr i = m_systSgKeyMapPhotons->begin(); i != m_systSgKeyMapPhotons->end(); ++i) + out->m_systSgKeyMapPhotons.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapPhotons->begin();i!=m_systSgKeyMapPhotons->end();++i) - out->m_systSgKeyMapPhotons.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapElectrons->begin(); i != m_systSgKeyMapElectrons->end(); ++i) + out->m_systSgKeyMapElectrons.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapElectrons->begin();i!=m_systSgKeyMapElectrons->end();++i) - out->m_systSgKeyMapElectrons.insert( std::make_pair( (*i).first , (*i).second ) ); + for (const auto& i : *(m_systSgKeyMapFwdElectrons)) + out->m_systSgKeyMapFwdElectrons.insert(std::make_pair(i.first, i.second)); - for (Itr i=m_systSgKeyMapMuons->begin();i!=m_systSgKeyMapMuons->end();++i) - out->m_systSgKeyMapMuons.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapMuons->begin(); i != m_systSgKeyMapMuons->end(); ++i) + out->m_systSgKeyMapMuons.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapTaus->begin();i!=m_systSgKeyMapTaus->end();++i) - out->m_systSgKeyMapTaus.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapSoftMuons->begin(); i != m_systSgKeyMapSoftMuons->end(); ++i) + out->m_systSgKeyMapSoftMuons.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapJets->begin();i!=m_systSgKeyMapJets->end();++i) - out->m_systSgKeyMapJets.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapTaus->begin(); i != m_systSgKeyMapTaus->end(); ++i) + out->m_systSgKeyMapTaus.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapJets_electronInJetSubtraction->begin();i!=m_systSgKeyMapJets_electronInJetSubtraction->end();++i) - out->m_systSgKeyMapJets_electronInJetSubtraction.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapJets->begin(); i != m_systSgKeyMapJets->end(); ++i) + out->m_systSgKeyMapJets.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapJetsLoose_electronInJetSubtraction->begin();i!=m_systSgKeyMapJetsLoose_electronInJetSubtraction->end();++i) - out->m_systSgKeyMapJetsLoose_electronInJetSubtraction.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapJets_electronInJetSubtraction->begin(); + i != m_systSgKeyMapJets_electronInJetSubtraction->end(); ++i) + out->m_systSgKeyMapJets_electronInJetSubtraction.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapLargeRJets->begin();i!=m_systSgKeyMapLargeRJets->end();++i) - out->m_systSgKeyMapLargeRJets.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapJetsLoose_electronInJetSubtraction->begin(); + i != m_systSgKeyMapJetsLoose_electronInJetSubtraction->end(); ++i) + out->m_systSgKeyMapJetsLoose_electronInJetSubtraction.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapTrackJets->begin();i!=m_systSgKeyMapTrackJets->end();++i) - out->m_systSgKeyMapTrackJets.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapLargeRJets->begin(); i != m_systSgKeyMapLargeRJets->end(); ++i) + out->m_systSgKeyMapLargeRJets.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapMissingET->begin();i!=m_systSgKeyMapMissingET->end();++i) - out->m_systSgKeyMapMissingET.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapTrackJets->begin(); i != m_systSgKeyMapTrackJets->end(); ++i) + out->m_systSgKeyMapTrackJets.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapMissingETLoose->begin();i!=m_systSgKeyMapMissingETLoose->end();++i) - out->m_systSgKeyMapMissingETLoose.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapTracks->begin(); i != m_systSgKeyMapTracks->end(); ++i) + out->m_systSgKeyMapTracks.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapKLFitter->begin();i!=m_systSgKeyMapKLFitter->end();++i) - out->m_systSgKeyMapKLFitter.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapMissingET->begin(); i != m_systSgKeyMapMissingET->end(); ++i) + out->m_systSgKeyMapMissingET.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapKLFitterLoose->begin();i!=m_systSgKeyMapKLFitterLoose->end();++i) - out->m_systSgKeyMapKLFitterLoose.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapMissingETLoose->begin(); i != m_systSgKeyMapMissingETLoose->end(); ++i) + out->m_systSgKeyMapMissingETLoose.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systSgKeyMapPseudoTop->begin();i!=m_systSgKeyMapPseudoTop->end();++i) - out->m_systSgKeyMapPseudoTop.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapKLFitter->begin(); i != m_systSgKeyMapKLFitter->end(); ++i) + out->m_systSgKeyMapKLFitter.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systDecoKeyMapJetGhostTrack->begin();i!=m_systDecoKeyMapJetGhostTrack->end();++i) - out->m_systDecoKeyMapJetGhostTrack.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapKLFitterLoose->begin(); i != m_systSgKeyMapKLFitterLoose->end(); ++i) + out->m_systSgKeyMapKLFitterLoose.insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=m_systPersistantAllTTreeNames->begin();i!=m_systPersistantAllTTreeNames->end();++i) - out->m_systPersistantAllTTreeNames.insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = m_systSgKeyMapPseudoTop->begin(); i != m_systSgKeyMapPseudoTop->end(); ++i) + out->m_systSgKeyMapPseudoTop.insert(std::make_pair((*i).first, (*i).second)); - for (std::list<std::size_t>::const_iterator i=m_list_systHashAll->begin();i!=m_list_systHashAll->end();++i) - out->m_list_systHashAll.push_back( *i ); + for (Itr i = m_systSgKeyMapPseudoTopLoose->begin(); i != m_systSgKeyMapPseudoTopLoose->end(); ++i) + out->m_systSgKeyMapPseudoTopLoose.insert(std::make_pair((*i).first, (*i).second)); - for (std::list<std::size_t>::const_iterator i=m_list_systHash_electronInJetSubtraction->begin();i!=m_list_systHash_electronInJetSubtraction->end();++i) - out->m_list_systHash_electronInJetSubtraction.push_back( *i ); + for (Itr i = m_systDecoKeyMapJetGhostTrack->begin(); i != m_systDecoKeyMapJetGhostTrack->end(); ++i) + out->m_systDecoKeyMapJetGhostTrack.insert(std::make_pair((*i).first, (*i).second)); - for (std::vector<std::string>::const_iterator i=m_allSelectionNames->begin();i!=m_allSelectionNames->end();++i) - out->m_allSelectionNames.push_back( *i ); + for (Itr i = m_systPersistantAllTTreeNames->begin(); i != m_systPersistantAllTTreeNames->end(); ++i) + out->m_systPersistantAllTTreeNames.insert(std::make_pair((*i).first, (*i).second)); - for (auto i : *m_allTriggers) { - out->m_allTriggers.insert(i); + for (std::list<std::size_t>::const_iterator i = m_list_systHashAll->begin(); i != m_list_systHashAll->end(); ++i) + out->m_list_systHashAll.push_back(*i); + + for (std::list<std::size_t>::const_iterator i = m_list_systHash_electronInJetSubtraction->begin(); + i != m_list_systHash_electronInJetSubtraction->end(); ++i) + out->m_list_systHash_electronInJetSubtraction.push_back(*i); + + for (std::vector<std::string>::const_iterator i = m_allSelectionNames->begin(); i != m_allSelectionNames->end(); + ++i) + out->m_allSelectionNames.push_back(*i); + + for (auto i : *m_allTriggers_Tight) { + out->m_allTriggers_Tight.insert(i); + } + for (auto i : *m_electronTriggers_Tight) { + out->m_electronTriggers_Tight.insert(i); + } + for (auto i : *m_muonTriggers_Tight) { + out->m_tauTriggers_Tight.insert(i); + } + + for (auto i : *m_allTriggers_Loose) { + out->m_allTriggers_Loose.insert(i); + } + for (auto i : *m_electronTriggers_Loose) { + out->m_electronTriggers_Loose.insert(i); } - for (auto i : *m_electronTriggers) { - out->m_electronTriggers.insert(i); + for (auto i : *m_muonTriggers_Loose) { + out->m_muonTriggers_Loose.insert(i); } - for (auto i : *m_muonTriggers) { - out->m_muonTriggers.insert(i); + for (auto i : *m_tauTriggers_Loose) { + out->m_tauTriggers_Loose.insert(i); } return out; } -TopConfig::TopConfig( const top::TopPersistentSettings* settings ) : + TopConfig::TopConfig(const top::TopPersistentSettings* settings) : // delegate to the default ctor - this is a nice C++11 feature, John likes this a lot - TopConfig() - { + TopConfig() { m_makeAllCPTools = false; m_isMC = settings->m_isMC; m_isAFII = settings->m_isAFII; @@ -2208,13 +3609,16 @@ TopConfig::TopConfig( const top::TopPersistentSettings* settings ) : m_sgKeyEventInfo = settings->m_sgKeyEventInfo; m_sgKeyPrimaryVertices = settings->m_sgKeyPrimaryVertices; - sgKeyPhotons( settings->m_sgKeyPhotons ); - sgKeyElectrons( settings->m_sgKeyElectrons ); - sgKeyMuons( settings->m_sgKeyMuons ); - sgKeyTaus( settings->m_sgKeyTaus ); - sgKeyJets( settings->m_sgKeyJets ); - sgKeyLargeRJets( settings->m_sgKeyLargeRJets ); - sgKeyTrackJets( settings->m_sgKeyTrackJets ); + sgKeyPhotons(settings->m_sgKeyPhotons); + sgKeyElectrons(settings->m_sgKeyElectrons); + sgKeyFwdElectrons(settings->m_sgKeyFwdElectrons); + sgKeyMuons(settings->m_sgKeyMuons); + sgKeySoftMuons(settings->m_sgKeySoftMuons); + sgKeyTaus(settings->m_sgKeyTaus); + sgKeyJets(settings->m_sgKeyJets); + sgKeyLargeRJets(settings->m_sgKeyLargeRJets); + sgKeyTrackJets(settings->m_sgKeyTrackJets); + sgKeyTracks(settings->m_sgKeyTracks); m_sgKeyMissingEt = settings->m_sgKeyMissingEt; m_sgKeyMissingEtLoose = settings->m_sgKeyMissingEtLoose; @@ -2222,170 +3626,336 @@ TopConfig::TopConfig( const top::TopPersistentSettings* settings ) : m_electronIDLoose = settings->m_electronIDLoose; m_electronIsolation = settings->m_electronIsolation; m_electronIsolationLoose = settings->m_electronIsolationLoose; + m_useElectronChargeIDSelection = settings->m_useElectronChargeIDSelection; + m_useEgammaLeakageCorrection = settings->m_useEgammaLeakageCorrection; + m_enablePromptLeptonImprovedVetoStudies = settings->m_enablePromptLeptonImprovedVetoStudies; + + m_fwdElectronID = settings->m_fwdElectronID; m_muon_trigger_SF = settings->m_muon_trigger_SF; m_muonQuality = settings->m_muonQuality; m_muonQualityLoose = settings->m_muonQualityLoose; m_muonIsolation = settings->m_muonIsolation; m_muonIsolationLoose = settings->m_muonIsolationLoose; - - for (std::vector<std::string>::const_iterator i=settings->m_chosen_btaggingWP.begin();i!=settings->m_chosen_btaggingWP.end();++i) - m_chosen_btaggingWP.push_back( *i ); - typedef std::map<std::size_t,std::string>::const_iterator Itr; + m_softmuonQuality = settings->m_softmuonQuality; + + for (std::vector<std::pair<std::string, std::string> >::const_iterator i = settings->m_chosen_btaggingWP.begin(); + i != settings->m_chosen_btaggingWP.end(); ++i) + m_chosen_btaggingWP.push_back(*i); + + typedef std::map<std::size_t, std::string>::const_iterator Itr; + + for (Itr i = settings->m_systSgKeyMapPhotons.begin(); i != settings->m_systSgKeyMapPhotons.end(); ++i) + m_systSgKeyMapPhotons->insert(std::make_pair((*i).first, (*i).second)); + + for (Itr i = settings->m_systSgKeyMapElectrons.begin(); i != settings->m_systSgKeyMapElectrons.end(); ++i) + m_systSgKeyMapElectrons->insert(std::make_pair((*i).first, (*i).second)); + + for (Itr i = settings->m_systSgKeyMapFwdElectrons.begin(); i != settings->m_systSgKeyMapFwdElectrons.end(); ++i) + m_systSgKeyMapFwdElectrons->insert(std::make_pair((*i).first, (*i).second)); + + for (Itr i = settings->m_systSgKeyMapMuons.begin(); i != settings->m_systSgKeyMapMuons.end(); ++i) + m_systSgKeyMapMuons->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapPhotons.begin();i!=settings->m_systSgKeyMapPhotons.end();++i) - m_systSgKeyMapPhotons->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapSoftMuons.begin(); i != settings->m_systSgKeyMapSoftMuons.end(); ++i) + m_systSgKeyMapSoftMuons->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapElectrons.begin();i!=settings->m_systSgKeyMapElectrons.end();++i) - m_systSgKeyMapElectrons->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapTaus.begin(); i != settings->m_systSgKeyMapTaus.end(); ++i) + m_systSgKeyMapTaus->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapMuons.begin();i!=settings->m_systSgKeyMapMuons.end();++i) - m_systSgKeyMapMuons->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapJets.begin(); i != settings->m_systSgKeyMapJets.end(); ++i) + m_systSgKeyMapJets->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapTaus.begin();i!=settings->m_systSgKeyMapTaus.end();++i) - m_systSgKeyMapTaus->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapJets_electronInJetSubtraction.begin(); + i != settings->m_systSgKeyMapJets_electronInJetSubtraction.end(); ++i) + m_systSgKeyMapJets_electronInJetSubtraction->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapJets.begin();i!=settings->m_systSgKeyMapJets.end();++i) - m_systSgKeyMapJets->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapJetsLoose_electronInJetSubtraction.begin(); + i != settings->m_systSgKeyMapJetsLoose_electronInJetSubtraction.end(); ++i) + m_systSgKeyMapJetsLoose_electronInJetSubtraction->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapJets_electronInJetSubtraction.begin();i!=settings->m_systSgKeyMapJets_electronInJetSubtraction.end();++i) - m_systSgKeyMapJets_electronInJetSubtraction->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapLargeRJets.begin(); i != settings->m_systSgKeyMapLargeRJets.end(); ++i) + m_systSgKeyMapLargeRJets->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapJetsLoose_electronInJetSubtraction.begin();i!=settings->m_systSgKeyMapJetsLoose_electronInJetSubtraction.end();++i) - m_systSgKeyMapJetsLoose_electronInJetSubtraction->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapTrackJets.begin(); i != settings->m_systSgKeyMapTrackJets.end(); ++i) + m_systSgKeyMapTrackJets->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapLargeRJets.begin();i!=settings->m_systSgKeyMapLargeRJets.end();++i) - m_systSgKeyMapLargeRJets->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapTracks.begin(); i != settings->m_systSgKeyMapTracks.end(); ++i) + m_systSgKeyMapTracks->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapTrackJets.begin();i!=settings->m_systSgKeyMapTrackJets.end();++i) - m_systSgKeyMapTrackJets->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapMissingET.begin(); i != settings->m_systSgKeyMapMissingET.end(); ++i) + m_systSgKeyMapMissingET->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapMissingET.begin();i!=settings->m_systSgKeyMapMissingET.end();++i) - m_systSgKeyMapMissingET->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapMissingETLoose.begin(); i != settings->m_systSgKeyMapMissingETLoose.end(); ++i) + m_systSgKeyMapMissingETLoose->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapMissingETLoose.begin();i!=settings->m_systSgKeyMapMissingETLoose.end();++i) - m_systSgKeyMapMissingETLoose->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapKLFitter.begin(); i != settings->m_systSgKeyMapKLFitter.end(); ++i) + m_systSgKeyMapKLFitter->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapKLFitter.begin();i!=settings->m_systSgKeyMapKLFitter.end();++i) - m_systSgKeyMapKLFitter->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapKLFitterLoose.begin(); i != settings->m_systSgKeyMapKLFitterLoose.end(); ++i) + m_systSgKeyMapKLFitterLoose->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapKLFitterLoose.begin();i!=settings->m_systSgKeyMapKLFitterLoose.end();++i) - m_systSgKeyMapKLFitterLoose->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapPseudoTop.begin(); i != settings->m_systSgKeyMapPseudoTop.end(); ++i) + m_systSgKeyMapPseudoTop->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systSgKeyMapPseudoTop.begin();i!=settings->m_systSgKeyMapPseudoTop.end();++i) - m_systSgKeyMapPseudoTop->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systSgKeyMapPseudoTopLoose.begin(); i != settings->m_systSgKeyMapPseudoTopLoose.end(); ++i) + m_systSgKeyMapPseudoTopLoose->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systDecoKeyMapJetGhostTrack.begin();i!=settings->m_systDecoKeyMapJetGhostTrack.end();++i) - m_systDecoKeyMapJetGhostTrack->insert( std::make_pair( (*i).first , (*i).second ) ); + for (Itr i = settings->m_systDecoKeyMapJetGhostTrack.begin(); i != settings->m_systDecoKeyMapJetGhostTrack.end(); + ++i) + m_systDecoKeyMapJetGhostTrack->insert(std::make_pair((*i).first, (*i).second)); - for (Itr i=settings->m_systPersistantAllTTreeNames.begin();i!=settings->m_systPersistantAllTTreeNames.end();++i) { - m_systPersistantAllTTreeNames->insert( std::make_pair( (*i).first , (*i).second ) ); - m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second)); + for (Itr i = settings->m_systPersistantAllTTreeNames.begin(); i != settings->m_systPersistantAllTTreeNames.end(); + ++i) { + m_systPersistantAllTTreeNames->insert(std::make_pair((*i).first, (*i).second)); + m_systAllTTreeNames->insert(std::make_pair((*i).first, (*i).second)); } - - for (std::vector<std::size_t>::const_iterator i=settings->m_list_systHashAll.begin();i!=settings->m_list_systHashAll.end();++i) - m_list_systHashAll->push_back( *i ); - for (std::vector<std::size_t>::const_iterator i=settings->m_list_systHash_electronInJetSubtraction.begin();i!=settings->m_list_systHash_electronInJetSubtraction.end();++i) - m_list_systHash_electronInJetSubtraction->push_back( *i ); + for (std::vector<std::size_t>::const_iterator i = settings->m_list_systHashAll.begin(); + i != settings->m_list_systHashAll.end(); ++i) + m_list_systHashAll->push_back(*i); - for (std::vector<std::string>::const_iterator i=settings->m_allSelectionNames.begin();i!=settings->m_allSelectionNames.end();++i) - m_allSelectionNames->push_back( *i ); + for (std::vector<std::size_t>::const_iterator i = settings->m_list_systHash_electronInJetSubtraction.begin(); + i != settings->m_list_systHash_electronInJetSubtraction.end(); ++i) + m_list_systHash_electronInJetSubtraction->push_back(*i); - m_allTriggers = std::make_shared<std::unordered_map<std::string, std::vector<std::string> >>(); - m_electronTriggers = std::make_shared<std::unordered_map<std::string, std::vector<std::string> >>(); - m_muonTriggers = std::make_shared<std::unordered_map<std::string, std::vector<std::string> >>(); - - for (auto i : settings->m_allTriggers) { - m_allTriggers->insert(i); + for (std::vector<std::string>::const_iterator i = settings->m_allSelectionNames.begin(); + i != settings->m_allSelectionNames.end(); ++i) + m_allSelectionNames->push_back(*i); + + m_allTriggers_Tight = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + m_electronTriggers_Tight = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + m_muonTriggers_Tight = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + m_tauTriggers_Tight = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + + m_allTriggers_Loose = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + m_electronTriggers_Loose = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + m_muonTriggers_Loose = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + m_tauTriggers_Loose = std::make_shared<std::unordered_map<std::string, std::vector<std::string> > >(); + + for (auto i : settings->m_allTriggers_Tight) { + m_allTriggers_Tight->insert(i); + } + for (auto i : settings->m_electronTriggers_Tight) { + m_electronTriggers_Tight->insert(i); + } + for (auto i : settings->m_muonTriggers_Tight) { + m_muonTriggers_Tight->insert(i); + } + for (auto i : settings->m_tauTriggers_Tight) { + m_tauTriggers_Tight->insert(i); } - for (auto i : settings->m_electronTriggers) { - m_electronTriggers->insert(i); + + for (auto i : settings->m_allTriggers_Loose) { + m_allTriggers_Loose->insert(i); + } + for (auto i : settings->m_electronTriggers_Loose) { + m_electronTriggers_Loose->insert(i); } - for (auto i : settings->m_muonTriggers) { - m_muonTriggers->insert(i); + for (auto i : settings->m_muonTriggers_Loose) { + m_muonTriggers_Loose->insert(i); + } + for (auto i : settings->m_tauTriggers_Loose) { + m_tauTriggers_Loose->insert(i); } fixConfiguration(); } - - AodMetaDataAccess & TopConfig::aodMetaData() { + AodMetaDataAccess& TopConfig::aodMetaData() { return *m_aodMetaData; } // Place into a private function to allow use without replication of code - void TopConfig::ReadIsAFII(top::ConfigurationSettings* const& settings){ - if (settings->value("IsAFII") == "True") - this->setIsAFII(true); - else if (settings->value("IsAFII") == "False") - this->setIsAFII(false); - else if (settings->value("IsAFII") != " ") - throw std::runtime_error("TopConfig: option IsAFII must be either True or False"); - else if (this->isMC()) - throw std::runtime_error("TopConfig: option IsAFII not set"); + void TopConfig::ReadIsAFII(top::ConfigurationSettings* const& settings) { + if (settings->value("IsAFII") == "True") this->setIsAFII(true); + else if (settings->value("IsAFII") == "False") this->setIsAFII(false); + else if (settings->value("IsAFII") != " ") throw std::runtime_error( + "TopConfig: option IsAFII must be either True or False"); + else if (this->isMC()) throw std::runtime_error("TopConfig: option IsAFII not set"); } -} - -std::ostream& operator<<(std::ostream& os, const top::TopConfig& config) -{ - typedef std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> map_t; - typedef std::unordered_map<std::size_t,CP::SystematicSet>::const_iterator Itr; + // Function to set the release series (this method may change so refactor) + void TopConfig::setReleaseSeries() { + // Method taken from TopCPTools + std::string release_series = ""; + const char* rel_temp = std::getenv("ROOTCORE_RELEASE_SERIES"); + if (rel_temp) { + release_series = std::string(rel_temp); + } else { + release_series = ""; + } - if( config.useJetGhostTrack() ){ - for (const auto & item : config.systematicsJetGhostTrack()){ - os << " Jet Ghost Track Systematic\t\t :: " << item << " \n"; - } + if (release_series == "23") { + m_release_series = 23; // 2.3 + } else if (release_series == "24") { + m_release_series = 24; // 2.4 R20.7 + } else if (release_series == "25") { + m_release_series = 25; // 2.6 R21 + } else { + // Default to R21 because this build has moved away from ROOTCORE + m_release_series = 25; + } + return; } - os << "\n"; - os << "top::TopConfig will evaluate the following systematics (saved as TTrees in your ntuple) \n"; - os << "A blank systematic means \"Nominal\" in xAOD. All Nominal calibrations go into the Nominal TTree. \n"; - os << "\n"; - if( config.usePhotons() ){ - map_t syst = config.systMapPhotons(); - for(Itr i=syst->begin();i!=syst->end();++i){ - os << " Photon systematic\t :: " << (*i).second.name() <<" \n"; + void TopConfig::setAmiTag(std::string const& amiTag) { + assert(!m_configFixed); + if (m_amiTagSet == 0) { + m_amiTag = amiTag; + m_amiTagSet = 1; + } else if (m_amiTagSet > 0 && m_amiTag != amiTag) { + m_amiTag.clear(); + m_amiTagSet = -1; } } - if( config.useElectrons() ){ - map_t syst = config.systMapElectrons(); - for(Itr i=syst->begin();i!=syst->end();++i){ - os << " Electron systematic\t :: " << (*i).second.name() <<" \n"; - } + std::string const& TopConfig::getAmiTag() const { + assert(m_configFixed); + return m_amiTag; } - if( config.useMuons() ){ - map_t syst = config.systMapMuons(); - for(Itr i=syst->begin();i!=syst->end();++i){ - os << " Muon systematic\t :: " << (*i).second.name() <<" \n"; + // Function to return the year of data taking based on either run number (data) or random run number (MC) + std::string TopConfig::getYear(unsigned int runnumber, const bool isMC) { + + if (isMC) { + // mc16a - returning only 2015 but is really a mix of 15 + 16 + if (runnumber == 284500) return "2015"; + + // mc16d + if (runnumber == 300000) return "2017"; + + // mc16e + if (runnumber == 310000) return "2018"; + + return "UNKNOWN"; } + + // Set of runNumbers for data + // 2015 : 266904 - 284484 + if (runnumber >= 266904 && runnumber <= 284484) return "2015"; + + // 2016 : 296939 - 311481 + if (runnumber >= 296939 && runnumber <= 311481) return "2016"; + + // 2017 : 324320 - 348835 + if (runnumber >= 324320 && runnumber <= 348835) return "2017"; + + // 2018 : > 348835 + if (runnumber > 348835 && runnumber < 999999) return "2018"; + + return "UNKNOWN"; } - if( config.useTaus() ){ - map_t syst = config.systMapTaus(); - for(Itr i=syst->begin();i!=syst->end();++i){ - os << " Tau systematic\t :: " << (*i).second.name() <<" \n"; - } + void TopConfig::SetTriggersToYear(const bool isMC) { + if (m_year == "UNKNOWN") return; + + std::string year2(""); + if (isMC && m_year == "2015") year2 = "2016"; + if (isMC && m_year == "2016") year2 = "2015"; + + auto removeYears = [](std::unordered_map<std::string,std::vector<std::string> >& trig, const std::string& year1, const std::string& year2) { + auto itr = trig.begin(); + while (itr != trig.end()) { + if ((*itr).first != year1 && (*itr).first != year2) { + itr = trig.erase(itr); + } else { + itr++; + } + } + }; + + removeYears(m_trigGlobalConfiguration.trigger, m_year, year2); + removeYears(m_trigGlobalConfiguration.trigger_loose, m_year, year2); } - if( config.useJets() ){ - map_t syst = config.systMapJets(); - for(Itr i=syst->begin();i!=syst->end();++i){ - os << " Jet systematic\t\t :: " << (*i).second.name() <<" \n"; - } + void TopConfig::setGlobalTriggerConfiguration(std::vector<std::string> electron_trigger_systematics, + std::vector<std::string> muon_trigger_systematics, + std::vector<std::string> electron_tool_names, + std::vector<std::string> muon_tool_names) { + m_trigGlobalConfiguration.electron_trigger_systematics = electron_trigger_systematics; + m_trigGlobalConfiguration.muon_trigger_systematics = muon_trigger_systematics; + m_trigGlobalConfiguration.electron_trigger_tool_names = electron_tool_names; + m_trigGlobalConfiguration.muon_trigger_tool_names = muon_tool_names; + m_trigGlobalConfiguration.isConfigured = true; + return; } - if( config.useLargeRJets() ){ - map_t syst = config.systMapLargeRJets(); - for(Itr i=syst->begin();i!=syst->end();++i){ - os << " Large-R Jet systematic\t\t :: " << (*i).second.name() <<" \n"; + + + std::ostream& operator << (std::ostream& os, const TopConfig& config) { + typedef std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > map_t; + typedef std::unordered_map<std::size_t, CP::SystematicSet>::const_iterator Itr; + + if (config.useJetGhostTrack()) { + for (const auto& item : config.systematicsJetGhostTrack()) { + os << " Jet Ghost Track Systematic\t\t :: " << item << " \n"; + } + } + + os << "\n"; + os << "top::TopConfig has identified the following analysis release series : " << config.getReleaseSeries() << "\n"; + os << "top::TopConfig will evaluate the following systematics (saved as TTrees in your ntuple) \n"; + os << "A blank systematic means \"Nominal\" in xAOD. All Nominal calibrations go into the Nominal TTree. \n"; + os << "\n"; + if (config.usePhotons()) { + map_t syst = config.systMapPhotons(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Photon systematic\t :: " << (*i).second.name() << " \n"; + } + } + + if (config.useElectrons()) { + map_t syst = config.systMapElectrons(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Electron systematic\t :: " << (*i).second.name() << " \n"; + } + } + + if (config.useFwdElectrons()) { + map_t syst = config.systMapFwdElectrons(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Fwd Electron systematic\t :: " << (*i).second.name() << " \n"; + } } - } - os << "\n"; - return os; + if (config.useMuons()) { + map_t syst = config.systMapMuons(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Muon systematic\t :: " << (*i).second.name() << " \n"; + } + } + + if (config.useSoftMuons()) { + map_t syst = config.systMapSoftMuons(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Soft Muon systematic\t :: " << (*i).second.name() << " \n"; + } + } + + if (config.useTaus()) { + map_t syst = config.systMapTaus(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Tau systematic\t :: " << (*i).second.name() << " \n"; + } + } + + if (config.useJets()) { + map_t syst = config.systMapJets(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Jet systematic\t\t :: " << (*i).second.name() << " \n"; + } + } + + if (config.useLargeRJets()) { + map_t syst = config.systMapLargeRJets(); + for (Itr i = syst->begin(); i != syst->end(); ++i) { + os << " Large-R Jet systematic\t\t :: " << (*i).second.name() << " \n"; + } + } + + os << "\n"; + return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopPersistentSettings.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopPersistentSettings.cxx index 4b75df76123276f3a14e78e101fdbe6be63f1729..47a4bdf30d04f205d38c02d9fdfbc5d55f2c18e8 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopPersistentSettings.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TopPersistentSettings.cxx @@ -1,10 +1,10 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopConfiguration/TopPersistentSettings.h" -namespace top{ +namespace top { TopPersistentSettings::TopPersistentSettings() : m_isMC(false), m_isAFII(false), @@ -19,11 +19,14 @@ namespace top{ m_sgKeyPrimaryVertices("SetMe"), m_sgKeyPhotons("SetMe"), m_sgKeyElectrons("SetMe"), + m_sgKeyFwdElectrons("SetMe"), m_sgKeyMuons("SetMe"), + m_sgKeySoftMuons("SetMe"), m_sgKeyTaus("SetMe"), m_sgKeyJets("SetMe"), m_sgKeyLargeRJets("SetMe"), m_sgKeyTrackJets("SetMe"), + m_sgKeyTracks("SetMe"), m_sgKeyMissingEt("SetMe"), m_sgKeyMissingEtLoose("SetMe"), @@ -31,6 +34,11 @@ namespace top{ m_electronIDLoose("SetMe"), m_electronIsolation("SetMe"), m_electronIsolationLoose("SetMe"), + m_useElectronChargeIDSelection(false), + m_useEgammaLeakageCorrection(true), + m_enablePromptLeptonImprovedVetoStudies(false), + + m_fwdElectronID("SetMe"), m_muon_trigger_SF("SetMe"), m_muonQuality("SetMe"), @@ -38,11 +46,17 @@ namespace top{ m_muonIsolation("SetMe"), m_muonIsolationLoose("SetMe"), + m_softmuonQuality("SetMe"), + + m_trackQuality("SetMe"), + m_chosen_btaggingWP(), m_systSgKeyMapPhotons(), m_systSgKeyMapElectrons(), + m_systSgKeyMapFwdElectrons(), m_systSgKeyMapMuons(), + m_systSgKeyMapSoftMuons(), m_systSgKeyMapTaus(), m_systSgKeyMapJets(), m_systSgKeyMapJets_electronInJetSubtraction(), @@ -54,16 +68,22 @@ namespace top{ m_systSgKeyMapKLFitter(), m_systSgKeyMapKLFitterLoose(), m_systSgKeyMapPseudoTop(), + m_systSgKeyMapPseudoTopLoose(), m_systPersistantAllTTreeNames(), m_systDecoKeyMapJetGhostTrack(), + m_systSgKeyMapTracks(), m_list_systHashAll(), m_list_systHash_electronInJetSubtraction(), - m_allSelectionNames(), - m_allTriggers(), - m_electronTriggers(), - m_muonTriggers(), - m_tauTriggers() + m_allTriggers_Tight(), + m_electronTriggers_Tight(), + m_muonTriggers_Tight(), + m_tauTriggers_Tight(), + + m_allTriggers_Loose(), + m_electronTriggers_Loose(), + m_muonTriggers_Loose(), + m_tauTriggers_Loose() {} } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TreeFilter.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TreeFilter.cxx new file mode 100644 index 0000000000000000000000000000000000000000..3e08b7bd0739878d3f705c99b0738cdcc2706a67 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/Root/TreeFilter.cxx @@ -0,0 +1,53 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopConfiguration/TreeFilter.h" +#include "TopConfiguration/Tokenize.h" + +#include <iostream> +#include <regex> +#include <sstream> + +namespace top { + + TreeFilter::TreeFilter(){} + + TreeFilter::TreeFilter(const std::string& longstring){ + init(longstring); + } + + void TreeFilter::init(const std::string& longstring){ + std::vector<std::string> helpvec_str; + tokenize(longstring, helpvec_str, ","); + + m_vecFilters.clear(); + for (const std::string& x : helpvec_str) { + std::istringstream isstr(x); + std::copy(std::istream_iterator<std::string>(isstr), + std::istream_iterator<std::string>(), std::back_inserter(m_vecFilters)); + } + + for (std::string& filter : m_vecFilters) { + // replace "*" with ".*" + filter = regex_replace(filter, std::regex("\\*"), ".*"); + } + + + } + + bool TreeFilter::filterTree(const std::string& treename) const{ + + for (const std::string& filter : m_vecFilters) { + // check for a match + std::smatch match; + std::regex_search(treename, match, std::regex("^"+filter)); + if (!match.empty()) return false; + } + + + return true; + } + + +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/AodMetaDataAccess.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/AodMetaDataAccess.h index d1607a65b30d560dbc6aba206abcbe408ecf3ce2..ac3e4a52ba93811bd4266a61b6a6dd7b9d193380 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/AodMetaDataAccess.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/AodMetaDataAccess.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPCONFIGURATION_AODMETADATAACCESS_H #define TOPCONFIGURATION_AODMETADATAACCESS_H @@ -9,63 +9,62 @@ #include <string> namespace top { - -class AodMetaDataAccess { - -public: - - AodMetaDataAccess(); - virtual ~AodMetaDataAccess(); - virtual void loadWithFilesFrom(std::string const & fileListPath); - - /** - * @brief retrieve an AOD meta-data value - * - * @param folderName the folder name, e.g. "/TagInfo" - * @param keyName the key name, e.g. "project_name" - * - * @return the meta-data value as a string - */ - std::string get(std::string const & folderName, std::string const & keyName) const; - - /** - * @brief retrieve an AOD meta-data value - * - * @param folderName the folder name, e.g. "/TagInfo" - * @param keyName the key name, e.g. "project_name" - * - * @return the meta-data value as a string, or @p defaultValue if the meta-data entry does not exist - */ - std::string get(std::string const & folderName, std::string const & keyName, std::string const & defaultValue) const; - - /** - * @brief check whether AOD meta-data has been loaded - * - * @return whether the AOD meta-data has been loaded - */ - bool valid() const; - - /** - * @brief check whether the data are simulated or real - * - * @return true for MC, false for real data - */ - bool isSimulation() const; - - /** - * @brief check whether this sample is simulation, and then check if it was simulated with ATLFASTII - * - * @return true for AFII, false otherwise (FS or Data) - */ - bool isAFII() const; - - -private: - - std::map<std::string, std::map< std::string, std::string > > * m_data; - -}; - + class AodMetaDataAccess { + public: + AodMetaDataAccess(); + virtual ~AodMetaDataAccess(); + virtual void loadWithFilesFrom(std::string const& fileListPath); + + /** + * @brief retrieve an AOD meta-data value + * + * @param folderName the folder name, e.g. "/TagInfo" + * @param keyName the key name, e.g. "project_name" + * + * @return the meta-data value as a string + */ + std::string get(std::string const& folderName, std::string const& keyName) const; + + /** + * @brief retrieve an AOD meta-data value + * + * @param folderName the folder name, e.g. "/TagInfo" + * @param keyName the key name, e.g. "project_name" + * + * @return the meta-data value as a string, or @p defaultValue if the meta-data entry does not exist + */ + std::string get(std::string const& folderName, std::string const& keyName, std::string const& defaultValue) const; + + /** + * @brief check whether AOD meta-data has been loaded + * + * @return whether the AOD meta-data has been loaded + */ + bool valid() const; + + /** + * @brief check whether the data are simulated or real + * + * @return true for MC, false for real data + */ + bool isSimulation() const; + + /** + * @brief check whether the sample is MCoverlay or not + * + * @return true if it is overlay + */ + bool IsEventOverlayInputSim() const; + + /** + * @brief check whether this sample is simulation, and then check if it was simulated with ATLFASTII + * + * @return true for AFII, false otherwise (FS or Data) + */ + bool isAFII() const; + private: + std::map<std::string, std::map< std::string, std::string > >* m_data; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/ConfigurationSettings.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/ConfigurationSettings.h index 26422ee55983cbc3970b5deb34d9ea14da50634b..354cb5874935de41e4c5ee63773ef988044dacd4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/ConfigurationSettings.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/ConfigurationSettings.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef CONFIGURATIONSETTINGS_H_ #define CONFIGURATIONSETTINGS_H_ @@ -13,14 +13,13 @@ #include "StringData.h" namespace top { - /** * @brief Hold the configuration information for the whole run. A singleton, * so only one of these exists. It needs populating with a call to loadFromFile * early on. Otherwise it'll be full of rubbish and will refuse to run properly */ -class ConfigurationSettings { -public: + class ConfigurationSettings { + public: /** * @brief Design patterns 101. A singleton getter function. */ @@ -41,11 +40,14 @@ public: * @param key The string key used to identify this variable. * @param value On success, the setting for the given key (output). * - * @return Indicates success (i.e. the value was not empty). - * * Note: an attempt to retrieve a key with a non-boolean values raises an exception. */ - bool retrieve(std::string const & key, bool & value) const; + void retrieve(std::string const& key, bool& value) const; + + /** + * same as above, but directly returning the boolean + */ + bool retrieve(std::string const& key) const; /** * @brief Have the configuration settings been read from a file? @@ -81,9 +83,15 @@ public: * @param name The key used to refer to this variable. * @param message A human readable explanation */ - void registerParameter(const std::string& name, const std::string& message, const std::string& default_val=""); + void registerParameter(const std::string& name, const std::string& message, const std::string& default_val = ""); -private: + /** + * @brief test whether an (experimental) feature should be enabled + * + * Note: It's not a particularly cheap operation, so avoid it in loops. + */ + bool feature(std::string const& name) const; + private: ///True if the class has read the settings from a file or something bool m_configured; @@ -91,11 +99,14 @@ private: static ConfigurationSettings* m_instance; ///Hold the configuration data - std::map<std::string, StringData> m_strings; + std::map<std::string, StringData> strings_; ///Data used when configuring the selections std::vector<SelectionConfigurationData> m_selections; + ///Kill-switch for experimental features + std::vector<std::string> m_killedFeatures; + ///private constructor ConfigurationSettings(); @@ -103,14 +114,12 @@ private: ConfigurationSettings(const ConfigurationSettings&); ///Here but not implemented, resulting in a happy compile error if you try and use them - ConfigurationSettings operator=(const ConfigurationSettings&); - -}; + ConfigurationSettings operator = (const ConfigurationSettings&); + }; + std::ostream& operator << (std::ostream& os, const ConfigurationSettings& settings); + std::ostream& operator << (std::ostream& os, const SelectionConfigurationData& data); } -std::ostream& operator<<(std::ostream& os, const top::ConfigurationSettings& settings); -std::ostream& operator<<(std::ostream& os, const top::SelectionConfigurationData& data); - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/JsonUtils.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/JsonUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..35b83cae193cf48c5e4329d8e40609a1b01ae7da --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/JsonUtils.h @@ -0,0 +1,85 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef _TOPCONFIGURATION_JSONUTILS_H_ +#define _TOPCONFIGURATION_JSONUTILS_H_ + +#include "AsgTools/Property.h" + +#include <boost/optional.hpp> + +#include <cmath> +#include <ios> +#include <memory> +#include <sstream> +#include <string> +#include <type_traits> +#include <utility> +#include <vector> + +class Property; + +namespace top { +/** @brief Convert boolean to JSON format. */ + template<typename T, typename std::enable_if< + std::is_same<typename std::remove_cv<T>::type, bool>::value + >::type* = nullptr> + std::string json_dump(T value) { + return(value ? "true" : "false"); + } + +/** @brief Convert number to JSON format. */ + template<typename T, typename std::enable_if< + std::is_integral<T>::value&& !std::is_same<typename std::remove_cv<T>::type, bool>::value + >::type* = nullptr> + std::string json_dump(T value) { + std::stringstream out; + out << value; + return out.str(); + } + +/** @brief Convert number to JSON format. */ + template<typename T, typename std::enable_if< + std::is_floating_point<T>::value + >::type* = nullptr> + std::string json_dump(T value) { + if (std::isfinite(value)) { + std::stringstream out; + out << value; + return out.str(); + } + return(std::isinf(value) ? (std::signbit(value) ? "-Infinity" : "Infinity") : "NaN"); + } + +/** @brief Escape string for use in JSON format. */ + std::string json_dump(std::string const& value); + + +/** + * @brief Convert values of Property instances to JSON. + */ + class PropertyValueJsonDumper { + public: + PropertyValueJsonDumper(); + ~PropertyValueJsonDumper(); + + /** + * @brief Convert the value of a property to JSON. + * + * @return The JSON representation of the value, or boost::none if no conversion is available. + */ + boost::optional<std::string> operator () (Property* prop) const; + + class ISpecializedDumper { + public: + virtual ~ISpecializedDumper(); + virtual std::string operator () (Property* prop) = 0; + }; + protected: + std::vector<std::pair<Property::Type, std::unique_ptr<ISpecializedDumper> > > m_dispatch; + }; +} + + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/MsgCategory.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/MsgCategory.h new file mode 100644 index 0000000000000000000000000000000000000000..f69ad0e9863367245ec024dafc9f5a6c4b02e283 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/MsgCategory.h @@ -0,0 +1,11 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#ifndef _TOPCONFIGURATION_MSG_CATEGORY_H_ +#define _TOPCONFIGURATION_MSG_CATEGORY_H_ + +#include <AsgMessaging/MessageCheck.h> + +ANA_MSG_HEADER(TopConfiguration) + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/SelectionConfigurationData.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/SelectionConfigurationData.h index 93ab53bf74e0c83e528615e9dbaa616991422f18..62dfb1a26132cb7f7daa570cea3b09626fac9477 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/SelectionConfigurationData.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/SelectionConfigurationData.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SELECTIONCONFIGURATIONDATA_H_ #define SELECTIONCONFIGURATIONDATA_H_ @@ -9,21 +9,19 @@ #include <vector> namespace top { - /** * @brief Some configuration data to setup the selections. * * My understanding is that we'll only have a single stream of data next year, * so you might want to run ee, mumu and emu in the same job (i.e. selections). */ -struct SelectionConfigurationData { + struct SelectionConfigurationData { ///The name of the selection, e.g. ee std::string m_name; ///The cuts for this particular selection stored as strings, as read from the text file std::vector<std::string> m_cutnames; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/StringData.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/StringData.h index 117bbd9d525dff0d336ada085e5f48f068f1a6bd..16752f14cc1e66da509cb6c31565aab4cca4a331 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/StringData.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/StringData.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef STRINGDATA_H_ #define STRINGDATA_H_ @@ -8,12 +8,11 @@ #include <string> namespace top { - /** * @brief A little helper to hold the data, a little information that's useful * to humans and a flag (true) if the settings has been set. */ -struct StringData { + struct StringData { ///The data set by the user std::string m_data; @@ -22,8 +21,7 @@ struct StringData { ///A flag that lets us know if the user has set something or not. bool m_set; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/Tokenize.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/Tokenize.h index 5561b0d1d620838815d2e757f8fd3624de244c4b..9a98b74df09d34d0a35f0a274426ac4973350b9f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/Tokenize.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/Tokenize.h @@ -1,58 +1,49 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: Tokenize.h -// Description: -// Author: Fabian Wilk -// Created: Tue Aug 11 10:12:30 2015 -// -// (c) by The ATLAS Collaboration -// (c) by Fabian Wilk <mail@fabianwilk.de> -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef _UTILS_TOKENIZE_H_ #define _UTILS_TOKENIZE_H_ #include <string> -namespace top{ - /*! - * @brief Tokenize an input string using a set of delimiters. - * @tparam Container The type of the output container. - * @param input The input string which is to be tokenized. - * @param output The container onto which the tokens are to be appended. Must - * support an emplace_back function which takes as pointer to const char (the - * string data) and a std::size_t (the string length). - * - * For maximum performance use a non-allocating string in the out container, - * e.g. use `Container = std::vector<std::string_view>` in c++14. - */ - template <typename Container> - void tokenize(const std::string & input, Container & output, - const std::string & delimiters = " ", bool trim_empty = false) { - const auto size = input.size(); - std::string::size_type pos{0}; - std::string::size_type last_pos{0}; - - while (last_pos < size + 1) { - pos = input.find_first_of(delimiters, last_pos); - if (pos == std::string::npos) { - pos = size; - } - - if (pos != last_pos || not trim_empty){ - output.emplace_back(input.data() + last_pos, pos - last_pos); - } - - last_pos = pos + 1; - } +namespace top { + /*! + * @brief Tokenize an input string using a set of delimiters. + * @tparam Container The type of the output container. + * @param input The input string which is to be tokenized. + * @param output The container onto which the tokens are to be appended. Must + * support an emplace_back function which takes as pointer to const char (the + * string data) and a std::size_t (the string length). + * + * For maximum performance use a non-allocating string in the out container, + * e.g. use `Container = std::vector<std::string_view>` in c++14. + */ + template <typename Container> + void tokenize(const std::string& input, Container& output, + const std::string& delimiters = " ", bool trim_empty = false) { + const auto size = input.size(); + + std::string::size_type pos { + 0 + }; + std::string::size_type last_pos { + 0 + }; + + while (last_pos < size + 1) { + pos = input.find_first_of(delimiters, last_pos); + if (pos == std::string::npos) { + pos = size; + } + + if (pos != last_pos || not trim_empty) { + output.emplace_back(input.data() + last_pos, pos - last_pos); + } + + last_pos = pos + 1; } + } } #endif /* _UTILS_TOKENIZE_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopConfig.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopConfig.h index 10cdeaa9efac96583204a2ae4d71136a4693d2bf..e9eedb97962ac98056a25fb8c0b4e660e30ea587 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopConfig.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopConfig.h @@ -1,8 +1,7 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ -// $Id: TopConfig.h 803103 2017-04-18 17:30:51Z tpelzer $ #ifndef ANALYSISTOP_TOPCONFIGURATION_TOPCONFIG_H #define ANALYSISTOP_TOPCONFIGURATION_TOPCONFIG_H @@ -12,10 +11,6 @@ * @brief TopConfig * A simple configuration that is NOT a singleton * - * $Revision: 803103 $ - * $Date: 2017-04-18 19:30:51 +0200 (Tue, 18 Apr 2017) $ - * - * **/ // System include(s): @@ -27,1343 +22,2744 @@ #include <unordered_map> #include <unordered_set> #include <iostream> +#include <utility> // Systematic include(s): #include "PATInterfaces/SystematicSet.h" // Persistent settings #include "TopConfiguration/TopPersistentSettings.h" +// Tree Filter +#include "TopConfiguration/TreeFilter.h" + +#include "TopDataPreparation/SampleXsection.h" + +namespace top { + class AodMetaDataAccess; + class ConfigurationSettings; + + class TopConfig final { + public: + TopConfig(); + explicit TopConfig(const top::TopPersistentSettings* settings); + virtual ~TopConfig() {} + + // Delete Standard constructors + TopConfig(const TopConfig& rhs) = delete; + TopConfig(TopConfig&& rhs) = delete; + TopConfig& operator = (const TopConfig& rhs) = delete; + + // create settings to persist to mini-xAOD + top::TopPersistentSettings* createPersistentSettings(); + + void setConfigSettings(top::ConfigurationSettings* const& settings); + + // Prevent any more configuration + void fixConfiguration(); + + // Make all CP Tools? + inline bool makeAllCPTools() const {return m_makeAllCPTools;} + + // GRL file + void setGrlDir(const std::string& s); + inline const std::string& grlDir() const {return m_grlDir;} + void setGrlFile(const std::string& s); + inline const std::vector<std::string> grlFile() const {return m_grlFile;} + + // TDP path + void setTDPPath(const std::string& s); + inline const std::string& getTDPPath() const {return m_topDataPreparationPath;} + + //showering algorithm + void setShoweringAlgorithm(SampleXsection::showering in) { m_showeringAlgo=in; } + SampleXsection::showering getShoweringAlgorithm() const {return m_showeringAlgo;} + + inline bool recomputeCPvars() const {return m_recomputeCPvars;} + + // What objects are we using + inline bool usePhotons() const {return m_usePhotons;} + inline bool useElectrons() const {return m_useElectrons;} + inline bool useFwdElectrons() const {return m_useFwdElectrons;} + inline bool useMuons() const {return m_useMuons;} + inline bool useSoftMuons() const {return m_useSoftMuons;} + inline bool useTaus() const {return m_useTaus;} + inline bool useJets() const {return m_useJets;} + inline bool useLargeRJets() const {return m_useLargeRJets;} + inline bool useTrackJets() const {return m_useTrackJets;} + inline bool useTracks() const {return m_useTracks;} + inline bool useJetGhostTrack() const {return m_useJetGhostTrack;} + inline bool useRCJets() const {return m_useRCJets;} + inline bool useVarRCJets() const {return m_useVarRCJets;} + + inline bool useParticleFlowJets() const {return m_useParticleFlowJets;} + + inline bool useTruthParticles() const {return m_useTruthParticles;} + inline bool useTruthElectrons() const {return m_useTruthElectrons;} + inline bool useTruthMuons() const {return m_useTruthMuons;} + inline bool useTruthPhotons() const {return m_useTruthPhotons;} + inline bool useTruthJets() const {return m_useTruthJets;} + inline bool useTruthLargeRJets() const {return m_useTruthLargeRJets;} + inline bool useTruthTaus() const {return m_useTruthTaus;} + inline bool useTruthMET() const {return m_useTruthMET;} + + inline bool applyTTVACut() const {return m_applyTTVACut;} + + inline bool useAntiMuons() const {return m_useAntiMuons;}; + + // MC or not MC - this should be set by metadata + inline bool isMC() const {return m_isMC;} + inline void setIsMC(const bool value) { + if (!m_configFixed) { + m_isMC = value; + } + } -namespace top{ - -class AodMetaDataAccess; -class ConfigurationSettings; - -class TopConfig final { - public: - TopConfig(); - explicit TopConfig( const top::TopPersistentSettings* settings ); - virtual ~TopConfig(){} - - // Delete Standard constructors - TopConfig( const TopConfig& rhs ) = delete; - TopConfig( TopConfig&& rhs ) = delete; - TopConfig& operator=( const TopConfig& rhs ) = delete; - - // create settings to persist to mini-xAOD - top::TopPersistentSettings* createPersistentSettings(); - - void setConfigSettings( top::ConfigurationSettings* const& settings ); - - // Prevent any more configuration - void fixConfiguration(); - - // Make all CP Tools? - inline bool makeAllCPTools() const {return m_makeAllCPTools;} - - // GRL file - void setGrlDir( const std::string& s ); - inline const std::string& grlDir() const {return m_grlDir;} - void setGrlFile( const std::string& s ); - inline const std::vector<std::string> grlFile() const {return m_grlFile;} - - // What objects are we using - inline bool usePhotons() const {return m_usePhotons; } - inline bool useElectrons() const {return m_useElectrons; } - inline bool useMuons() const {return m_useMuons; } - inline bool useTaus() const {return m_useTaus; } - inline bool useJets() const {return m_useJets; } - inline bool useLargeRJets() const {return m_useLargeRJets;} - inline bool useTrackJets() const {return m_useTrackJets; } - inline bool useJetGhostTrack() const {return m_useJetGhostTrack; } - inline bool useRCJets() const {return m_useRCJets;} - inline bool useVarRCJets() const {return m_useVarRCJets;} - - inline bool useParticleFlowJets() const {return m_useParticleFlowJets;} - - inline bool useTruthParticles() const {return m_useTruthParticles;} - inline bool useTruthElectrons() const {return m_useTruthElectrons; } - inline bool useTruthMuons() const {return m_useTruthMuons; } - inline bool useTruthPhotons() const {return m_useTruthPhotons; } - inline bool useTruthJets() const {return m_useTruthJets; } - inline bool useTruthLargeRJets() const {return m_useTruthLargeRJets; } - inline bool useTruthMET() const {return m_useTruthMET; } - - inline bool applyTTVACut() const {return m_applyTTVACut; } - - inline bool useAntiMuons() const {return m_useAntiMuons; }; - - // MC or not MC - this should be set by metadata - inline bool isMC() const {return m_isMC;} - inline void setIsMC(const bool value) {if(!m_configFixed){m_isMC = value;}} - - // AFII? - inline bool isAFII() const {return m_isAFII;} - inline void setIsAFII(const bool value) {if(!m_configFixed){m_isAFII = value;}} - - // Is this a Primary xAOD? - inline bool isPrimaryxAOD() const {return m_isPrimaryxAOD;} - inline void setIsPrimaryxAOD(const bool value) {if(!m_configFixed){m_isPrimaryxAOD = value;}} - - // Is this a Truth DxAOD? - inline bool isTruthDxAOD() const {return m_isTruthDxAOD;} - inline void setIsTruthDxAOD(const bool value) {if(!m_configFixed){m_isTruthDxAOD = value;}} - - // What derivation type is it? - inline std::string getDerivationStream() const { return m_derivationStream;} - inline void setDerivationStream(const std::string value) {if(!m_configFixed){m_derivationStream = value;}} - - inline unsigned int getDSID() const {return m_DSID;} - inline void setDSID(unsigned int value) { - // Check here if this is a sherpa 2.2 V+jets sample - // (see below to set DSIDs) - setIsSherpa22Vjets(value); - m_DSID = value; - } - - // Is this Sherpa 2.2 V+jets? - // (if so then we need to reweight based on num truth jets) - inline bool isSherpa22Vjets() const {return m_is_sherpa_22_vjets;} - inline void setIsSherpa22Vjets(unsigned int dsid) { - // m_is_sherpa_22_vjets = false by default - // Sherpa 2.2 W+jets (from TopDataPrep) - if (dsid >= 363331 && dsid <= 363354) - m_is_sherpa_22_vjets = true; - if (dsid >= 363436 && dsid <= 363483) - m_is_sherpa_22_vjets = true; - // Sherpa 2.2 Z+jets (from TopDataPrep) - if (dsid >= 363102 && dsid <= 363122) - m_is_sherpa_22_vjets = true; - if (dsid >= 363361 && dsid <= 363435) - m_is_sherpa_22_vjets = true; - } - - // map index for MC/MC b-tagging scale factors - inline unsigned int getMapIndex() const {return m_MapIndex;} - inline void setMapIndex(unsigned int value) {m_MapIndex = value;} - - // Do Loose analysis for fakes - // For analysis this should only be run on data, not for MC - // By default you will get a Loose TTree for data and not for MC - inline bool doLooseEvents() const {return m_doLooseEvents;} - - // Do fakes MM weight calculation - inline bool doFakesMMWeights() const {return m_doFakesMMWeights;} - - // Directory of efficiency files for MM fake estimate - inline std::string FakesMMDir() const {return m_FakesMMDir;} - - // DDebug mode for MM fake estimate - inline bool FakesMMDebug() const {return m_doFakesMMDebug;} - - // Special mode to run Loose events on MC for the purposes - // of determining the Fakes control regions - // This is not for regular users, it is for the Fakes sub-group - // or for determining your own control regions - // - // If you are determining your own control regions, you have just joined - // the fakes sub-group, please report your finding in the Fakes meetings - // - // The function name is long and convoluted on purpose, I hope you don't call it by mistake - inline void FakesControlRegionDetermination_setDoLooseEventsOnMC_notForRegularUsers() - {if(!m_configFixed){m_doLooseEvents = true;}} - - // enables calculation of MM weights - // only possible for data loose - // doing it on MC loose is explicitly forbidden - inline void setFakesMMWeightsCalculation() - {m_doFakesMMWeights = true;} - inline void setFakesMMDir(const std::string dir) - {m_FakesMMDir = dir;} - inline void setFakesMMDebug() - {m_doFakesMMDebug = true;} - - // By default the top group does overlap removal on the tight lepton definitions - // If you use this you are going off piste and need to report - // your findings to the top reconstruction meeting - inline void setOverlapRemovalOnLooseLeptonDef() - {if(!m_configFixed){m_doOverlapRemovalOnLooseLeptonDef = true;}} - inline bool doOverlapRemovalOnLooseLeptonDef() const {return m_doOverlapRemovalOnLooseLeptonDef;} - - inline std::string overlapRemovalProcedure() const - {return m_overlap_removal_procedure;} - - // do overlap removal also with large-R jets - // (using whatever procedure is used in the official tools) - inline void setLargeJetOverlapRemoval() - {if(!m_configFixed){m_doLargeJetOverlapRemoval = true;}} - inline bool doLargeJetOverlapRemoval() const {return m_doLargeJetOverlapRemoval;} - - // Only dumps the *_Loose trees - also on MC - // Usefull if you want your tight selection to be a subset of loose - inline void setLooseTreeOnly() - {if(!m_configFixed){m_doLooseTreeOnly = true;}} - inline bool doLooseTreeOnly() const {return m_doLooseTreeOnly;} - - // In the *_Loose trees, lepton SFs are calculated considering - // tight ID and isolation instead of loose - // Only tight leptons are considered in the event SF calculation - inline void setApplyTightSFsInLooseTree() - {if(!m_configFixed){m_applyTightSFsInLooseTree = true;}} - inline bool applyTightSFsInLooseTree() const {return m_applyTightSFsInLooseTree;} - - // Apply Electron In Jet subtraction - // For boosted analysis - inline bool applyElectronInJetSubtraction() const {return m_applyElectronInJetSubtraction;} - inline void setApplyElectronInJetSubtraction() - {if(!m_configFixed){m_applyElectronInJetSubtraction = true;}} - - // Dump truth block info - inline bool doTruthBlockInfo() const {return m_doTruthBlockInfo;} - inline void setTruthBlockInfo() - {if(!m_configFixed){m_doTruthBlockInfo = true;}} - - // Write truth PDF info - inline bool doTruthPDFInfo() const {return m_doTruthPDFInfo;} - inline void setTruthPDFInfo() - {if(!m_configFixed){m_doTruthPDFInfo = true;}} - // Write truth PDF info in reco tree - inline bool doTruthPDFInfoInNominalTrees() const {return m_doTruthPDFInfoInNominalTrees;} - inline void setTruthPDFInfoInNominalTrees() - {if(!m_configFixed){m_doTruthPDFInfoInNominalTrees = true;}} - - // Write MC generator weights - inline bool doMCGeneratorWeights() const {return m_doMCGeneratorWeights;} - inline void setMCGeneratorWeights() - {if(!m_configFixed){m_doMCGeneratorWeights = true;}} - // Write truth PDF info in reco tree - inline bool doMCGeneratorWeightsInNominalTrees() const {return m_doMCGeneratorWeightsInNominalTrees;} - inline void setMCGeneratorWeightsInNominalTrees() - {if(!m_configFixed){m_doMCGeneratorWeightsInNominalTrees = true;}} - - // Top Parton History - inline bool doTopPartonHistory() const {return m_doTopPartonHistory;} - inline void setTopPartonHistory() - {if(!m_configFixed){m_doTopPartonHistory = true;}} - - // Register Top Parton History in flat ntuple - // This doesn't use m_configFixed - this is bad :( - // This is a simple implementation of saving xAOD objects to ntuples - // John has more advanced ideas on how to do this - // This is just a quick fix for now to get the concept working - inline bool isTopPartonHistoryRegisteredInNtuple() const {return m_isTopPartonHistoryRegisteredInNtuple;} - inline void setTopPartonHistoryRegisteredInNtuple() - {m_isTopPartonHistoryRegisteredInNtuple = true;} - - // TopParticleLevel - inline bool doTopParticleLevel() const { return m_doTopParticleLevel; } - inline void setTopParticleLevel() { if ( ! m_configFixed ){ m_doTopParticleLevel = true; } } - - inline bool doParticleLevelOverlapRemovalMuJet() const { return m_doParticleLevelOverlapRemovalMuJet; } - inline bool doParticleLevelOverlapRemovalElJet() const { return m_doParticleLevelOverlapRemovalElJet; } - inline bool doParticleLevelOverlapRemovalJetPhoton() const { return m_doParticleLevelOverlapRemovalJetPhoton; } - inline void setParticleLevelOverlapRemovalMuJet( bool value ) { if ( ! m_configFixed ){ m_doParticleLevelOverlapRemovalMuJet = value; } } - inline void setParticleLevelOverlapRemovalElJet( bool value ) { if ( ! m_configFixed ){ m_doParticleLevelOverlapRemovalElJet = value; } } - inline void setParticleLevelOverlapRemovalJetPhoton( bool value ) { if ( ! m_configFixed ){ m_doParticleLevelOverlapRemovalJetPhoton = value; } } - - // KLFitter - inline bool doKLFitter() const {return m_doKLFitter;} - inline void setKLFitter(){if(!m_configFixed){m_doKLFitter = true;}} - inline const std::string& KLFitterTransferFunctionsPath() const {return m_KLFitterTransferFunctionsPath;} - inline const std::string& KLFitterJetSelectionMode() const {return m_KLFitterJetSelectionMode;} - inline const std::string& KLFitterBTaggingMethod() const {return m_KLFitterBTaggingMethod;} - inline const std::string& KLFitterLH() const {return m_KLFitterLH;} - - inline bool KLFitterTopMassFixed() const {return m_KLFitterTopMassFixed;} - inline bool KLFitterSaveAllPermutations() const {return m_KLFitterSaveAllPermutations;} - - // PseudoTop - inline bool doPseudoTop() const {return m_doPseudoTop;} - inline void setPseudoTop(){if(!m_configFixed){m_doPseudoTop = true;}} - - // Triggers - inline virtual void allTriggers(std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> triggers) - {if(!m_configFixed){m_allTriggers = triggers;}} - - inline virtual void electronTriggers(std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> triggers) - {if(!m_configFixed){m_electronTriggers = triggers;}} - - inline virtual void muonTriggers(std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> triggers) - {if(!m_configFixed){m_muonTriggers = triggers;}} - - inline virtual void tauTriggers(std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> triggers) - {if(!m_configFixed){m_tauTriggers = triggers;}} - - inline std::shared_ptr<std::vector<std::string>> allSelectionNames() const {return m_allSelectionNames;} - virtual const std::vector<std::string>& allTriggers(const std::string& selection) const; - virtual const std::vector<std::string>& electronTriggers(const std::string& selection) const; - virtual const std::vector<std::string>& muonTriggers(const std::string& selection) const; - virtual const std::vector<std::string>& tauTriggers(const std::string& selection) const; - - // StoreGate Keys - virtual void sgKeyMCParticle ( const std::string& s ); - virtual void sgKeyPhotons ( const std::string& s ); - virtual void sgKeyElectrons ( const std::string& s ); - virtual void sgKeyMuons ( const std::string& s ); - virtual void sgKeyTaus ( const std::string& s ); - virtual void sgKeyJets ( const std::string& s ); - virtual void sgKeyLargeRJets ( const std::string& s ); - virtual void sgKeyTrackJets ( const std::string& s ); - - virtual void sgKeyTruthElectrons ( const std::string& s ); - virtual void sgKeyTruthMuons ( const std::string& s ); - virtual void sgKeyTruthPhotons ( const std::string& s ); - virtual void sgKeyTruthMET ( const std::string& s ); - virtual void sgKeyTruthJets ( const std::string& s ); - virtual void sgKeyTruthLargeRJets ( const std::string& s ); - - inline virtual void sgKeyMissingEt ( const std::string& s ){if(!m_configFixed){m_sgKeyMissingEt = s; }} - inline virtual void sgKeyMissingEtLoose ( const std::string& s ){if(!m_configFixed){m_sgKeyMissingEtLoose = s; }} - - inline const std::string& sgKeyEventInfo() const {return m_sgKeyEventInfo; } - inline const std::string& sgKeyPrimaryVertices() const {return m_sgKeyPrimaryVertices;} - inline virtual const std::string& sgKeyPhotons() const {return m_sgKeyPhotons; } - inline virtual const std::string& sgKeyElectrons() const {return m_sgKeyElectrons; } - inline virtual const std::string& sgKeyMuons() const {return m_sgKeyMuons; } - inline virtual const std::string& sgKeyTaus() const {return m_sgKeyTaus; } - inline virtual const std::string& sgKeyJets() const {return m_sgKeyJets; } - inline virtual const std::string& sgKeyLargeRJets() const {return m_sgKeyLargeRJets;} - inline virtual const std::string& sgKeyTrackJets() const {return m_sgKeyTrackJets; } - inline virtual const std::string& sgKeyMissingEt() const {return m_sgKeyMissingEt; } - inline virtual const std::string& sgKeyMissingEtLoose() const {return m_sgKeyMissingEtLoose; } - inline const std::string& sgKeyInDetTrackParticles() const {return m_sgKeyInDetTrackParticles;} - - inline const std::string& sgKeyTruthEvent() const {return m_sgKeyTruthEvent;} - inline virtual const std::string& sgKeyMCParticle() const {return m_sgKeyMCParticle;} - inline const std::string& sgKeyTruthPhotons() const {return m_sgKeyTruthPhotons;} - inline const std::string& sgKeyTruthElectrons() const {return m_sgKeyTruthElectrons;} - inline const std::string& sgKeyTruthMuons() const {return m_sgKeyTruthMuons;} - inline const std::string& sgKeyTruthTaus() const {return m_sgKeyTruthTaus;} - inline virtual const std::string& sgKeyTruthJets() const {return m_sgKeyTruthJets;} - inline virtual const std::string& sgKeyTruthLargeRJets() const {return m_sgKeyTruthLargeRJets;} - inline const std::string& sgKeyTruthMET() const {return m_sgKeyTruthMET;} - inline const std::string& sgKeyTopPartonHistory() const {return m_sgKeyTopPartonHistory;} - - inline const std::string& sgKeyTopSystematicEvents() const {return m_sgKeyTopSystematicEvents;} - inline const std::string& sgKeyTopSystematicEventsLoose() const {return m_sgKeyTopSystematicEventsLoose;} - inline const std::string& passEventSelectionDecoration() const {return m_passEventSelectionDecoration;} - virtual void decoKeyJetGhostTrack(const std::string & key); - inline virtual const std::string & decoKeyJetGhostTrack() const {return m_decoKeyJetGhostTrack;} - virtual void runPeriodJetGhostTrack(const std::vector<std::uint32_t> & vect); - - virtual const std::string& sgKeyPhotons ( const std::size_t hash ) const; - virtual const std::string& sgKeyElectrons ( const std::size_t hash ) const; - virtual const std::string& sgKeyElectronsStandAlone ( const std::size_t hash ) const; - virtual const std::string& sgKeyMuons ( const std::size_t hash ) const; - virtual const std::string& sgKeyTaus - ( const std::size_t hash ) const; - virtual const std::string& sgKeyJets ( const std::size_t hash , const bool useLooseLeptonJets ) const; - virtual const std::string& sgKeyJetsStandAlone ( const std::size_t hash ) const; - virtual const std::string& sgKeyLargeRJets( const std::size_t hash ) const; - virtual const std::string& sgKeyTrackJets ( const std::size_t hash ) const; - virtual const std::string& sgKeyMissingEt ( const std::size_t hash ) const; - virtual const std::string& sgKeyMissingEtLoose ( const std::size_t hash ) const; - - // For top::TopEventMaker - const std::string& sgKeyPhotonsTDS( const std::size_t hash ) const; - const std::string& sgKeyPhotonsTDSAux( const std::size_t hash ) const; - const std::string& sgKeyElectronsTDS( const std::size_t hash ) const; - const std::string& sgKeyElectronsTDSAux( const std::size_t hash ) const; - const std::string& sgKeyMuonsTDS( const std::size_t hash ) const; - const std::string& sgKeyMuonsTDSAux( const std::size_t hash ) const; - const std::string& sgKeyTausTDS( const std::size_t hash ) const; - const std::string& sgKeyTausTDSAux( const std::size_t hash ) const; - const std::string& sgKeyJetsTDS( const std::size_t hash , const bool useLooseLeptonJets ) const; - const std::string& sgKeyJetsTDSAux( const std::size_t hash , const bool useLooseLeptonJets ) const; - const std::string& sgKeyLargeRJetsTDS( const std::size_t hash ) const; - const std::string& sgKeyLargeRJetsTDSAux( const std::size_t hash ) const; - const std::string& sgKeyTrackJetsTDS( const std::size_t hash ) const; - const std::string& sgKeyTrackJetsTDSAux( const std::size_t hash ) const; - - // KLFitter - const std::string& sgKeyKLFitter( const std::size_t hash ) const; - const std::string& sgKeyKLFitterLoose( const std::size_t hash ) const; - - // PseudoTop - const std::string& sgKeyPseudoTop( const std::size_t hash ) const; - const std::string& sgKeyPseudoTop( const std::string ) const; - - // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv - // Jet Ghost-Track Systematics - - // The jet decoration name for a given systematic (nominal also possible). - const std::string & decoKeyJetGhostTrack(const std::size_t hash) const; - - // Retrieve names of all (registered) systematics that affect ghost tracks. - const std::vector<std::string> & systematicsJetGhostTrack() const {return m_jetGhostTrackSystematics;} - - // Retrieve run periods for ghost tracks. - const std::vector<std::uint32_t> & runPeriodsJetGhostTrack() const {return m_jetGhostTrackRunPeriods;} - - // Retrieve mapping from systematic hash to CP::SystematicSet. - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapJetGhostTrack() const {return m_systMapJetGhostTrack; } - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - - - // special: allow to dump the systematics-shifted b-tagging SFs in the systematics trees - inline virtual void dumpBtagSystsInSystTrees( const bool& b ){if(!m_configFixed){m_dumpBtagSystsInSystTrees = b;}} - inline virtual const bool& dumpBtagSystsInSystTrees(){return m_dumpBtagSystsInSystTrees;} - - // Electron configuration - inline virtual void egammaSystematicModel( const std::string& s ){if(!m_configFixed){m_egammaSystematicModel = s;}} - inline virtual void electronID( const std::string& s ){if(!m_configFixed){m_electronID = s;}} - inline virtual void electronIDLoose( const std::string& s ){if(!m_configFixed){m_electronIDLoose = s;}} - inline void removeElectronVetoLArCrack() {if(!m_configFixed){m_electronVetoLArCrack = false;}} - inline virtual void electronVetoLArCrack( const bool b ){if(!m_configFixed){m_electronVetoLArCrack = b;}} - inline virtual void electronPtcut(const float pt) {if(!m_configFixed){m_electronPtcut = pt;}} - inline virtual void electronIsolation(const std::string& iso) {if(!m_configFixed){m_electronIsolation = iso;}} - inline virtual void electronIsolationLoose(const std::string& iso) {if(!m_configFixed){m_electronIsolationLoose = iso;}} - inline virtual void electronIsoSFs(const bool b){if(!m_configFixed){m_electronIsoSFs = b;}} - - inline virtual const std::string& egammaSystematicModel(){return m_egammaSystematicModel;} - inline virtual const std::string& electronID() const {return m_electronID; } - inline virtual const std::string& electronIDLoose() const {return m_electronIDLoose;} - inline virtual bool electronVetoLArCrack() const {return m_electronVetoLArCrack;} - inline virtual float electronPtcut() const {return m_electronPtcut;} - inline virtual const std::string& electronIsolation() const {return m_electronIsolation;} - inline virtual const std::string& electronIsolationLoose() const {return m_electronIsolationLoose;} - inline virtual bool electronIsoSFs() const {return m_electronIsoSFs;} - inline const std::string& electronIDDecoration() const {return m_electronIDDecoration;} - inline const std::string& electronIDLooseDecoration() const {return m_electronIDLooseDecoration;} - - // Photon configuration - inline virtual void photonPtcut(const float pt) {if(!m_configFixed){m_photon_configuration.pt = pt;}} - inline virtual void photonEtacut(const float eta) {if(!m_configFixed){m_photon_configuration.eta = eta;}} - inline virtual void photonIdentification(const std::string& quality) {if(!m_configFixed){m_photon_configuration.identification = quality;}} - inline virtual void photonIdentificationLoose(const std::string& quality) {if(!m_configFixed){m_photon_configuration_loose.identification = quality;}} - inline virtual void photonIsolation(const std::string& quality) {if(!m_configFixed){m_photon_configuration.isolation = quality;}} - inline virtual void photonIsolationLoose(const std::string& quality) {if(!m_configFixed){m_photon_configuration_loose.isolation = quality;}} - inline virtual void photonUseRadiativeZ(const bool b) {if(!m_configFixed){m_photon_configuration.useRadiativeZ = b;}} - - // Muon configuration - inline virtual void muonPtcut(const float pt) {if(!m_configFixed){m_muonPtcut = pt;}} - inline virtual void muonEtacut(const float eta) {if(!m_configFixed){m_muonEtacut = eta;}} - inline virtual void muonQuality(const std::string& quality) {if(!m_configFixed){m_muonQuality = quality;}} - inline virtual void muonQualityLoose(const std::string& quality) {if(!m_configFixed){m_muonQualityLoose = quality;}} - inline virtual void muonIsolation(const std::string& iso) {if(!m_configFixed){m_muonIsolation = iso;}} - inline virtual void muonIsolationLoose(const std::string& iso) {if(!m_configFixed){m_muonIsolationLoose = iso;}} - - inline virtual float muonPtcut() const {return m_muonPtcut;} - inline virtual float muonEtacut() const {return m_muonEtacut;} - inline virtual const std::string& muonQuality() const {return m_muonQuality;} - inline virtual const std::string& muonQualityLoose() const {return m_muonQualityLoose;} - inline virtual const std::string& muonIsolation() const {return m_muonIsolation;} - inline virtual const std::string& muonIsolationLoose() const {return m_muonIsolationLoose;} - - // Jet configuration - inline virtual void jetPtcut(const float pt) {if(!m_configFixed){m_jetPtcut = pt;}} - inline virtual void jetEtacut(const float eta) {if(!m_configFixed){m_jetEtacut = eta;}} - inline virtual void fwdJetAndMET(const std::string& fwd) {if(!m_configFixed){m_fwdJetAndMET = fwd;}} - - inline virtual float jetPtcut() const {return m_jetPtcut;} - inline virtual float jetEtacut() const {return m_jetEtacut;} - inline virtual const std::string& fwdJetAndMET() const {return m_fwdJetAndMET;} - - inline virtual void largeRJetPtcut(const float pt) {if(!m_configFixed){m_largeRJetPtcut = pt;}} - inline virtual void largeRJetEtacut(const float eta) {if(!m_configFixed){m_largeRJetEtacut = eta;}} - inline virtual void largeRJESUncertaintyConfig(const std::string& largeR_config) {if(!m_configFixed){m_largeRJESUncertaintyConfig = largeR_config;}} - inline virtual void largeRJESJMSConfig(const std::string& largeR_config) {if(!m_configFixed){m_largeRJESJMSConfig = largeR_config;}} - inline virtual float largeRJetPtcut() const {return m_largeRJetPtcut;} - inline virtual float largeRJetEtacut() const {return m_largeRJetEtacut;} - inline virtual const std::string& largeRJESUncertaintyConfig() const {return m_largeRJESUncertaintyConfig;} - inline virtual const std::string& largeRJESJMSConfig() const {return m_largeRJESJMSConfig;} - - inline virtual void trackJetPtcut(const float pt) {if(!m_configFixed){m_trackJetPtcut = pt;}} - inline virtual void trackJetEtacut(const float eta) {if(!m_configFixed){m_trackJetEtacut = eta;}} - inline virtual float trackJetPtcut() const {return m_trackJetPtcut;} - inline virtual float trackJetEtacut() const {return m_trackJetEtacut;} - - inline virtual float RCJetPtcut() const {return m_RCJetPtcut;} - inline virtual float RCJetEtacut() const {return m_RCJetEtacut;} - inline virtual float RCJetTrimcut() const {return m_RCJetTrimcut;} - inline virtual float RCJetRadius() const {return m_RCJetRadius;} - - inline virtual void RCJetPtcut(const float pt) {if(!m_configFixed){m_RCJetPtcut = pt;}} - inline virtual void RCJetEtacut(const float eta) {if(!m_configFixed){m_RCJetEtacut = eta;}} - inline virtual void RCJetTrimcut(const float trim) {if(!m_configFixed){m_RCJetTrimcut = trim;}} - inline virtual void RCJetRadius(const float radius) {if(!m_configFixed){m_RCJetRadius = radius;}} - - inline virtual float VarRCJetPtcut() const{return m_VarRCJetPtcut;} - inline virtual float VarRCJetEtacut() const {return m_VarRCJetEtacut;} - inline virtual float VarRCJetTrimcut() const {return m_VarRCJetTrimcut;} - inline virtual float VarRCJetMaxRadius() const {return m_VarRCJetMaxRadius;} - inline virtual const std::string& VarRCJetRho() const {return m_VarRCJetRho;} - inline virtual const std::string& VarRCJetMassScale() const {return m_VarRCJetMassScale;} - - inline virtual void VarRCJetPtcut(const float pt) {if(!m_configFixed){m_VarRCJetPtcut = pt;}} - inline virtual void VarRCJetEtacut(const float eta) {if(!m_configFixed){m_VarRCJetEtacut = eta;}} - inline virtual void VarRCJetTrimcut(const float trim) {if(!m_configFixed){m_VarRCJetTrimcut = trim;}} - inline virtual void VarRCJetMaxRadius(const float radius) {if(!m_configFixed){m_VarRCJetMaxRadius = radius;}} - inline virtual void VarRCJetRho(const std::string& rho) {if(!m_configFixed){m_VarRCJetRho = rho;}} - inline virtual void VarRCJetMassScale(const std::string& mass_scale) {if(!m_configFixed){m_VarRCJetMassScale = mass_scale;}} - - inline virtual void jetUncertainties_BunchSpacing( const std::string& s ){if(!m_configFixed){m_jetUncertainties_BunchSpacing = s;}} - inline virtual const std::string& jetUncertainties_BunchSpacing() const {return m_jetUncertainties_BunchSpacing;} - - virtual void jetUncertainties_NPModel( const std::string& s ); - inline bool doMultipleJES() const {return m_doMultipleJES;} - inline bool doLargeRSmallRCorrelations() const {return m_largeRSmallRCorrelations;} - inline virtual const std::string& jetUncertainties_NPModel() const {return m_jetUncertainties_NPModel;} - - inline virtual void jetJERSmearingModel( const std::string& s ){if(!m_configFixed){m_jetJERSmearingModel = s;}} - inline virtual const std::string& jetJERSmearingModel() const {return m_jetJERSmearingModel;} - - inline virtual void jetCalibSequence( const std::string& s ){if(!m_configFixed){m_jetCalibSequence = s;}} - inline virtual const std::string& jetCalibSequence() const {return m_jetCalibSequence;} - - inline virtual void doJVTinMET( const bool& doJVT ){if(!m_configFixed){m_doJVTInMETCalculation = doJVT;}} - inline virtual bool doJVTinMET() const {return m_doJVTInMETCalculation;} - - inline virtual float JSF() const{return m_JSF;} - inline virtual float bJSF() const{return m_bJSF;} - - // Tau configuration setters - inline virtual void tauPtcut(const float pt) { - if(!m_configFixed) { - m_tau_configuration.pt = pt; - m_tau_configuration_loose.pt = pt; - } - } - inline virtual void tauJetIDWP(const std::string& s) { - if(!m_configFixed) - m_tau_configuration.jetIDWP = s; - } - inline virtual void tauJetIDWPLoose(const std::string& s) { - if(!m_configFixed) - m_tau_configuration_loose.jetIDWP = s; - } - inline virtual void tauEleBDTWP(const std::string& s) { - if(!m_configFixed) - m_tau_configuration.eleBDTWP = s; - } - inline virtual void tauEleBDTWPLoose(const std::string& s) { - if(!m_configFixed) - m_tau_configuration_loose.eleBDTWP = s; - } - inline virtual void tauEleOLR(bool do_tau_ele_olr) { - if(!m_configFixed) - m_tau_configuration.eleOLR = do_tau_ele_olr; - } - inline virtual void tauEleOLRLoose(bool do_tau_ele_olr) { - if(!m_configFixed) - m_tau_configuration_loose.eleOLR = do_tau_ele_olr; - } - inline virtual void tauJetConfigFile(const std::string& s) { - if(!m_configFixed) - m_tau_configuration.fileName = s; - } - inline virtual void tauJetConfigFileLoose(const std::string& s) { - if(!m_configFixed) - m_tau_configuration_loose.fileName = s; - } - // Applying new tau energy calibration - inline virtual void applyTauMVATES(bool apply) { - m_applyTauMVATES = apply; - } - - // Tau configuration getters - inline virtual float tauPtcut() const { - return m_tau_configuration.pt; - } - inline const std::string& tauJetIDWP() const { - return m_tau_configuration.jetIDWP; - } - inline const std::string& tauJetIDWPLoose() const { - return m_tau_configuration_loose.jetIDWP; - } - inline const std::string& tauEleBDTWP() const { - return m_tau_configuration.eleBDTWP; - } - inline const std::string& tauEleBDTWPLoose() const { - return m_tau_configuration_loose.eleBDTWP; - } - inline virtual bool tauEleOLR() { - return m_tau_configuration.eleOLR; - } - inline virtual bool tauEleOLRLoose() { - return m_tau_configuration_loose.eleOLR; - } - inline const std::string& tauJetConfigFile() { - return m_tau_configuration.fileName; - } - inline const std::string& tauJetConfigFileLoose() { - return m_tau_configuration_loose.fileName; - } - // Applying new tau energy calibration - inline bool applyTauMVATES() { - return m_applyTauMVATES; - } - - // photon getters - inline virtual float photonPtcut() const { - return m_photon_configuration.pt; - } - inline virtual float photonEtacut() const { - return m_photon_configuration.eta; - } - inline const std::string& photonIdentification() { - return m_photon_configuration.identification; - } - inline const std::string& photonIdentificationLoose() { - return m_photon_configuration_loose.identification; - } - inline const std::string& photonIsolation() { - return m_photon_configuration.isolation; - } - inline const std::string& photonIsolationLoose() { - return m_photon_configuration_loose.isolation; - } - inline const bool& photonUseRadiativeZ() { - return m_photon_configuration.useRadiativeZ; - } - - // inline const std::string& tauJetID() const {return m_tauJetID;} - // inline const std::string& tauJetIDBkg() const {return m_tauJetIDBkg;} - // inline const std::string& tauEVetoID() const {return m_tauEVetoID;} - // inline virtual bool tauVetoLArCrack() const {return m_tauVetoLArCrack;} - // inline virtual float tauPtcut() const {return m_tauPtcut;} - - // [[[----------------------------------------------- - // Particle Level (Truth) configuration - - // electrons - inline virtual void truth_electron_PtCut( const float pt ) { if ( ! m_configFixed ){ m_truth_electron.PtCut = pt; } } - inline virtual void truth_electron_EtaCut( const float eta ) { if ( ! m_configFixed ){ m_truth_electron.EtaCut = eta; } } - - inline virtual float truth_electron_PtCut() const { return m_truth_electron.PtCut; } - inline virtual float truth_electron_EtaCut() const { return m_truth_electron.EtaCut; } - inline virtual bool truth_electron_NotFromHadron() const { return m_truth_electron.NotFromHadron; } - inline virtual bool truth_electron_TauIsHadron() const { return m_truth_electron.TauIsHadron; } - - // muons - inline virtual void truth_muon_PtCut( const float pt ) { if ( ! m_configFixed ){ m_truth_muon.PtCut = pt; } } - inline virtual void truth_muon_EtaCut( const float eta ) { if ( ! m_configFixed ){ m_truth_muon.EtaCut = eta; } } - - inline virtual float truth_muon_PtCut() const { return m_truth_muon.PtCut; } - inline virtual float truth_muon_EtaCut() const { return m_truth_muon.EtaCut; } - inline virtual bool truth_muon_NotFromHadron() const { return m_truth_muon.NotFromHadron; } - inline virtual bool truth_muon_TauIsHadron() const { return m_truth_muon.TauIsHadron; } - - // photons - inline virtual void truth_photon_PtCut( const float pt ) { if ( ! m_configFixed ){ m_truth_photon.PtCut = pt; } } - inline virtual void truth_photon_EtaCut( const float eta ) { if ( ! m_configFixed ){ m_truth_photon.EtaCut = eta; } } - inline virtual void truth_photon_Origin(const std::string & value) { if ( ! m_configFixed ){ m_truth_photon.Origin = value; } } - inline virtual void truth_photon_Isolation(const std::string & value) { if ( ! m_configFixed ){ m_truth_photon.Isolation = value; } } - - inline virtual float truth_photon_PtCut() const { return m_truth_photon.PtCut; } - inline virtual float truth_photon_EtaCut() const { return m_truth_photon.EtaCut; } - inline virtual const std::string & truth_photon_Origin() const { return m_truth_photon.Origin; } - inline virtual const std::string & truth_photon_Isolation() const { return m_truth_photon.Isolation; } - - // jets - inline virtual void truth_jet_PtCut( const float pt ) { if ( ! m_configFixed ){ m_truth_jet.PtCut = pt; } } - inline virtual void truth_jet_EtaCut( const float eta ) { if ( ! m_configFixed ){ m_truth_jet.EtaCut = eta; } } - - inline virtual float truth_jet_PtCut() const { return m_truth_jet.PtCut; } - inline virtual float truth_jet_EtaCut() const { return m_truth_jet.EtaCut; } - - // large R jets - inline virtual void truth_jet_largeR_PtCut( const float pt ) { if ( ! m_configFixed ){ m_truth_largeRJet.PtCut = pt; } } - inline virtual void truth_jet_largeR_EtaCut( const float eta ) { if ( ! m_configFixed ){ m_truth_largeRJet.EtaCut = eta; } } - - inline virtual float truth_jet_largeR_PtCut() const { return m_truth_largeRJet.PtCut; } - inline virtual float truth_jet_largeR_EtaCut() const { return m_truth_largeRJet.EtaCut; } - - // -----------------------------------------------]]] - - /// HL LHC studies - inline virtual void HLLHC(const bool s) { if(!m_configFixed){m_HLLHC=s;} } - inline virtual bool HLLHC() const {return m_HLLHC;} - - void setBTaggingSFSysts( std::string WP, const std::set<std::string>& btagging_SFs, bool isTrackJet=false ); - - inline virtual std::set<std::string> btagging_namedSysts(std::string WP) const { return m_bTag_named_systs.at(WP); } - inline virtual unsigned int btagging_num_B_eigenvars(std::string WP) const { return m_bTag_eigen_B.at(WP); } - inline virtual unsigned int btagging_num_C_eigenvars(std::string WP) const { return m_bTag_eigen_C.at(WP); } - inline virtual unsigned int btagging_num_Light_eigenvars(std::string WP) const { return m_bTag_eigen_light.at(WP); } - - inline virtual std::set<std::string> trkjet_btagging_namedSysts(std::string WP) const { return m_bTag_named_systs_trkJet.at(WP); } - inline virtual unsigned int trkjet_btagging_num_B_eigenvars(std::string WP) const { return m_bTag_eigen_B_trkJet.at(WP); } - inline virtual unsigned int trkjet_btagging_num_C_eigenvars(std::string WP) const { return m_bTag_eigen_C_trkJet.at(WP); } - inline virtual unsigned int trkjet_btagging_num_Light_eigenvars(std::string WP) const { return m_bTag_eigen_light_trkJet.at(WP); } - - // B-tagging WPs requested by user - const std::vector<std::string> bTagWP() const { return m_chosen_btaggingWP;} - // B-tagging systematics requested by user to be excluded from EV treatment, separated by semi-colons - const std::string bTagSystsExcludedFromEV() const { return m_bTagSystsExcludedFromEV;} - - // B-tagging WPs actually available, according to CDI file - // will be set in TopCPTools - void setBTagWP_available( std::string btagging_WP ); - void setBTagWP_available_trkJet( std::string btagging_WP ); - const std::vector<std::string>& bTagWP_available() const { return m_available_btaggingWP;} - const std::vector<std::string>& bTagWP_available_trkJet() const { return m_available_btaggingWP_trkJet;} - // B-tagging WPs actually calibrated, according to CDI file - // will be set in TopCPTools - void setBTagWP_calibrated( std::string btagging_WP ); - void setBTagWP_calibrated_trkJet( std::string btagging_WP ); - const std::vector<std::string>& bTagWP_calibrated() const { return m_calibrated_btaggingWP;} - const std::vector<std::string>& bTagWP_calibrated_trkJet() const { return m_calibrated_btaggingWP_trkJet;} - - std::string FormatedWP(std::string raw_WP); - - const std::string& bTaggingCalibration_B() const - {return m_btagging_calibration_B;}; - const std::string& bTaggingCalibration_C() const - {return m_btagging_calibration_C;}; - const std::string& bTaggingCalibration_Light() const - {return m_btagging_calibration_Light;}; - - // LHAPDF settings - - inline virtual std::vector<std::string> LHAPDFSets(){ return m_lhapdf_options.pdf_set_names; } - inline virtual bool doLHAPDF(){ return m_lhapdf_options.doLHAPDF; } - inline virtual std::string baseLHAPDF() { return m_lhapdf_options.baseLHAPDF; } - inline virtual bool doLHAPDFInNominalTrees(){ return m_lhapdf_options.doLHAPDFInNominalTrees; } - inline virtual bool saveLHAPDFEvent(){ return m_lhapdf_options.save_per_event; } - void addLHAPDFResult( const std::string& pdf_name, - std::vector<float> sum_of_weights ); - - std::unordered_map<std::string, std::vector<float> >& getLHAPDFResults() { return m_lhapdf_options.pdf_results; }; - - - // Pileup Reweighting Settings - bool doPileupReweighting(){ return m_pileup_reweighting.apply;}; - bool PileupUseGRLTool(){ return m_pileup_reweighting.use_grl_tool;}; - - const std::vector<std::string>& PileupConfig(){ return m_pileup_reweighting.config_files; }; - const std::vector<std::string>& PileupLumiCalc(){ return m_pileup_reweighting.lumi_calc_files; }; - - bool PileupMuDependent(){return m_pileup_reweighting.mu_dependent;}; - - inline const std::string& muonTriggerSF() const {return m_muon_trigger_SF;} - - // Where the sum of event weights - // before derivation framework is kept - inline const std::string& sumOfEventWeightsMetaData() const {return m_sumOfEventWeightsMetaData; } - - // Object Selector Name - inline virtual void objectSelectionName(const std::string& s){if(!m_configFixed){m_objectSelectionName = s;}} - inline virtual const std::string& objectSelectionName() const {return m_objectSelectionName;} - // Output Format - inline virtual void outputFormat(const std::string& s){if(!m_configFixed){m_outputFormat = s;}} - inline virtual const std::string& outputFormat() const {return m_outputFormat;} - // Output Events - virtual void outputEvents(const std::string& s); - inline virtual const std::string& outputEvents() const {return m_outputEvents;} - inline bool saveOnlySelectedEvents() const {return m_saveOnlySelectedEvents;} - - // SetAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround - inline bool outputFileSetAutoFlushZero() const {return m_outputFileSetAutoFlushZero;} - - // Number of events to run on (only for testing) - inline virtual unsigned int numberOfEventsToRun() const { return m_numberOfEventsToRun;} - inline virtual void numberOfEventsToRun(const unsigned int& n_events) {if(!m_configFixed){m_numberOfEventsToRun = n_events;}} - - // Number of events to skip (only for testing) - inline virtual unsigned int numberOfEventsToSkip() const { return m_numberOfEventsToSkip;} - inline virtual void numberOfEventsToSkip(const unsigned int& n_events) {if(!m_configFixed){m_numberOfEventsToSkip = n_events;}} - - // systematics - inline virtual void systematics(const std::string& s) {if(!m_configFixed){m_systematics = s;}} - inline virtual const std::string& systematics() const {return m_systematics;} - - /// syst helper functions - bool isSystNominal(const std::string& syst) const; - bool isSystAll(const std::string& syst) const; - bool getSystematicsList(const std::string& syst, std::set<std::string>& systList) const; - bool contains(const std::set<std::string>& systList, const std::string& name) const; - - virtual void systematicsPhotons ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsElectrons ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsMuons ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsTaus ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsJets ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsLargeRJets ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsTrackJets ( const std::list<CP::SystematicSet>& syst ); - virtual void systematicsMET ( const std::list<CP::SystematicSet>& syst ); - - virtual void systematicsJetGhostTrack ( const std::list<CP::SystematicSet>& syst ); - - inline virtual void jetSubstructureName(const std::string &s) {if(!m_configFixed){ m_jetSubstructureName = s;} } - inline virtual const std::string& jetSubstructureName() const {return m_jetSubstructureName;} - - // Systematic hash values - inline std::size_t nominalHashValue() const {return m_nominalHashValue;} - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashPhotons() const {return m_systHashPhotons; } - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashElectrons() const {return m_systHashElectrons;} - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashMuons() const {return m_systHashMuons; } - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashTaus() const {return m_systHashTaus; } - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashJets() const {return m_systHashJets; } - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashAll() const {return m_systHashAll; } - inline std::shared_ptr<std::unordered_set<std::size_t>> systHashElectronInJetSubtraction() const {return m_systHash_electronInJetSubtraction;} - - // Systematic Maps - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapPhotons() const {return m_systMapPhotons; } - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapElectrons() const {return m_systMapElectrons;} - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapMuons() const {return m_systMapMuons; } - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapTaus() const {return m_systMapTaus; } - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapJets() const {return m_systMapJets; } - inline std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> systMapLargeRJets() const {return m_systMapLargeRJets; } - - // Systematic StoreGate key Maps - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapPhotons() const {return m_systSgKeyMapPhotons; } - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapElectrons() const {return m_systSgKeyMapElectrons; } - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapMuons() const {return m_systSgKeyMapMuons; } - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapTaus() const {return m_systSgKeyMapTaus; } - std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapJets(const bool useLooseLeptonJets) const; - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapLargeRJets() const {return m_systSgKeyMapLargeRJets;} - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systSgKeyMapTrackJets() const {return m_systSgKeyMapTrackJets;} - - // TTree names - inline std::shared_ptr<std::unordered_map<std::size_t,std::string>> systAllTTreeNames() const {return m_systAllTTreeNames;} - const std::string& systematicName( const std::size_t hash ) const; - // TTree index - unsigned int ttreeIndex( const std::size_t hash ) const; - unsigned int ttreeIndexLoose( const std::size_t hash ) const; - - AodMetaDataAccess & aodMetaData(); - AodMetaDataAccess const & aodMetaData() const { return *m_aodMetaData; } - - private: - // Prevent any more configuration - bool m_configFixed; - - // Make all CP Tools, or just the SF - bool m_makeAllCPTools; - - // GRL file - std::string m_grlDir; - std::vector<std::string> m_grlFile = {}; - - // Use which objects - bool m_usePhotons; - bool m_useElectrons; - bool m_useMuons; - bool m_useAntiMuons; - bool m_useTaus; - bool m_useJets; - bool m_useLargeRJets; - bool m_useTrackJets; - bool m_useRCJets; - bool m_useVarRCJets; - - // Ghost Tracks on jets can not really be disabled because they are always - // available. However, we want the systematics to be executed automatically - // whenever the user has "configured" ghost tracks. - bool m_useJetGhostTrack; - - // Are we using particle flow jets - // Need this as some things aren't supported at the moment - // C++11 so nice inline initialization (we should make this consistent) - bool m_useParticleFlowJets = false; - - bool m_useTruthParticles; - bool m_useTruthElectrons; - bool m_useTruthMuons; - bool m_useTruthPhotons; - bool m_useTruthJets; - bool m_useTruthLargeRJets; - bool m_useTruthMET; - - // define if d0/z0 cut should be used at all - bool m_applyTTVACut; - - std::string m_jetSubstructureName; - - // Do systematics? - this needs many more configuration options - std::string m_systematics; - std::string m_nominalSystName; - std::string m_allSystName; - - unsigned int m_DSID; - unsigned int m_MapIndex; - bool m_is_sherpa_22_vjets = false; - - bool m_isMC; - bool m_isAFII; - bool m_isPrimaryxAOD; - bool m_isTruthDxAOD = false; - std::string m_derivationStream; - - // Do loose events? - default for data, MC is special case - bool m_doLooseEvents; - - // Do fakes MM weights calculation? - only for data loose - bool m_doFakesMMWeights; - // Directory of efficiency files for MM fake estimate - std::string m_FakesMMDir; - // Debug mode? - bool m_doFakesMMDebug; - - // By default the top group does overlap removal on - // the tight lepton definitions. - // If you turn this to true you are going off piste and need to report - // your findings to the top reconstruction meeting. - bool m_doOverlapRemovalOnLooseLeptonDef; - - // String to describe which overlap removal procedure is used - // Current options are whether to use the ASG recommended - // overlap removal (recommended) - // procedure, or the one developed by the harmonization - // task force and use throughout 2015 (harmonized) - std::string m_overlap_removal_procedure = "recommended"; - - // do overlap removal also with large-R jets - // (using whatever procedure is used in the official tools) - bool m_doLargeJetOverlapRemoval; - - // Only dumps the *_Loose trees - also on MC - // Usefull if you want your tight selection to be a subset of loose - bool m_doLooseTreeOnly; - - // In the *_Loose trees, lepton SFs are calculated considering - // tight ID and isolation instead of loose - // Only tight leptons are considered in the event SF calculation - bool m_applyTightSFsInLooseTree; - - // Apply Electron In Jet subtraction - // For boosted analysis - bool m_applyElectronInJetSubtraction; - - // Write Truth block info - bool m_doTruthBlockInfo; - - // Write Truth PDF info - bool m_doTruthPDFInfo; - bool m_doTruthPDFInfoInNominalTrees; - - // Write MC generator weights - bool m_doMCGeneratorWeights; - bool m_doMCGeneratorWeightsInNominalTrees; - - // Top Parton History - bool m_doTopPartonHistory; - bool m_isTopPartonHistoryRegisteredInNtuple; - - // Top Particle Level - bool m_doTopParticleLevel; - bool m_doParticleLevelOverlapRemovalMuJet; - bool m_doParticleLevelOverlapRemovalElJet; - bool m_doParticleLevelOverlapRemovalJetPhoton; - - // KLFitter - bool m_doKLFitter; - std::string m_KLFitterTransferFunctionsPath; - std::string m_KLFitterJetSelectionMode; - std::string m_KLFitterBTaggingMethod; - std::string m_KLFitterLH; - bool m_KLFitterTopMassFixed; - bool m_KLFitterSaveAllPermutations; - - // PseudoTop - bool m_doPseudoTop; - - // StoreGate / TStore keys - std::string m_sgKeyDummy; - std::string m_sgKeyEventInfo; - std::string m_sgKeyPrimaryVertices; - std::string m_sgKeyPhotons; - std::string m_sgKeyElectrons; - std::string m_sgKeyMuons; - std::string m_sgKeyTaus; - std::string m_sgKeyJets; - std::string m_sgKeyLargeRJets; - std::string m_sgKeyTrackJets; - std::string m_sgKeyMissingEt; - std::string m_sgKeyMissingEtLoose; - std::string m_sgKeyInDetTrackParticles; - - std::string m_sgKeyTruthEvent; - std::string m_sgKeyMCParticle; - std::string m_sgKeyTruthPhotons; - std::string m_sgKeyTruthElectrons; - std::string m_sgKeyTruthMuons; - std::string m_sgKeyTruthTaus; - std::string m_sgKeyTruthJets; - std::string m_sgKeyTruthLargeRJets; - std::string m_sgKeyTruthMET; - std::string m_sgKeyTopPartonHistory; - - std::string m_sgKeyTopSystematicEvents; - std::string m_sgKeyTopSystematicEventsLoose; - std::string m_passEventSelectionDecoration; - - std::string m_decoKeyJetGhostTrack; - std::vector<std::string> m_jetGhostTrackSystematics; - std::vector<std::uint32_t> m_jetGhostTrackRunPeriods; - - // special: allow to dump the systematics-shifted b-tagging SFs in the systematics trees - bool m_dumpBtagSystsInSystTrees; - - // Electron configuration - std::string m_egammaSystematicModel; - std::string m_electronID; - std::string m_electronIDLoose; - bool m_electronVetoLArCrack; - float m_electronPtcut; - std::string m_electronIsolation; - std::string m_electronIsolationLoose; - bool m_electronIsoSFs; - int m_electron_d0SigCut; - float m_electron_delta_z0; - - std::string m_electronIDDecoration; - std::string m_electronIDLooseDecoration; - - // Muon configuration - float m_muonPtcut; // muon object selection pT cut - float m_muonEtacut; // muon object selection (abs) eta cut - std::string m_muonQuality; // muon quality used in object selection - std::string m_muonQualityLoose; // loose muon quality used in object selection - std::string m_muonIsolation; - std::string m_muonIsolationLoose; - int m_muon_d0SigCut; - float m_muon_delta_z0; - - - // Jet configuration - float m_jetPtcut; // jet object selection pT cut - float m_jetEtacut; // jet object selection (abs) eta cut - std::string m_fwdJetAndMET; // type of treatment of forward jets, including for MET calculation - std::string m_jetUncertainties_BunchSpacing; // 25ns or 50ns - std::string m_jetUncertainties_NPModel; // AllNuisanceParameters, 19NP or 3NP - bool m_doMultipleJES; - bool m_largeRSmallRCorrelations = false; // Add correlations of large/small R jets - std::string m_jetJERSmearingModel; // Full or Simple - std::string m_jetCalibSequence; // GCC or JMS - bool m_doJVTInMETCalculation; - - // Large R jet configuration - float m_largeRJetPtcut; // large R jet object selection pT cut - float m_largeRJetEtacut; // large R jet object selection (abs) eta cut - std::string m_largeRJESUncertaintyConfig; // large R jet JES uncertainty configuration file - // see: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/JetUncertainties2015PrerecLargeR - std::string m_largeRJESJMSConfig; // large R jet JES/JMS calibration choice - see ANALYSISTO-210 - - // Track jet configuration - float m_trackJetPtcut; // track jet object selection pT cut - float m_trackJetEtacut; // track jet object selection (abs) eta cut - - // Jet configuration for reclustered jets - float m_RCJetPtcut; - float m_RCJetEtacut; - float m_RCJetTrimcut; - float m_RCJetRadius; - - // Jet configuration for variable large-R jets - float m_VarRCJetPtcut; - float m_VarRCJetEtacut; - float m_VarRCJetTrimcut; - float m_VarRCJetMaxRadius; - std::string m_VarRCJetRho; - std::string m_VarRCJetMassScale; - - // these are needed for the top mass analysis, per default should be 1.0 - float m_JSF; - float m_bJSF; - - // Tau configuration - struct { - // filename to load tau configuration from. - // If this is an empty string then take the 'default' - std::string fileName = "Default"; - // The jetIDWP in CamelCase - // see https://svnweb.cern.ch/trac/atlasoff/browser/PhysicsAnalysis/TauID/TauAnalysisTools/trunk/doc/README-TauSelectionTool.rst - // for supported WPs - std::string jetIDWP = "Medium"; - // the electron BDTWP - std::string eleBDTWP = "Medium"; - // Whether to perform electron overlap removal - bool eleOLR = false; - // pT cut on taus - float pt = 20000; - } m_tau_configuration, m_tau_configuration_loose; - - // Applying new tau energy calibration - bool m_applyTauMVATES = false; - - // photon configuration - struct { - // pT cut on photons - float pt = 25000; - float eta = 2.5; - std::string isolation = "None"; - std::string identification = "None"; - bool useRadiativeZ = false; - } m_photon_configuration, m_photon_configuration_loose; - - // [[[----------------------------------------------- - // Particle Level (truth) configuration - - // electrons - struct { - float PtCut; // [ParticleLevel / Truth] Electron Object - // Selection minimum pT Cut (Standard ATLAS - // units, [MeV]). - float EtaCut; // [ParticleLevel / Truth] Electron Object - // Selection maximum absolute eta Cut. - bool NotFromHadron; // [ParticleLevel / Truth] Whether to apply the - // 'NotFromHadron' requirement onto the objects. - bool TauIsHadron; // [ParticleLevel / Truth] Whether a tauon is a - // hadron during the 'NotFromHadron' check - } m_truth_electron; - - // muons - struct { - float PtCut; // [ParticleLevel / Truth] Muon Object - // Selection minimum pT Cut (Standard ATLAS - // units, [MeV]). - float EtaCut; // [ParticleLevel / Truth] Muon Object - // Selection maximum absolute eta Cut. - bool NotFromHadron; // [ParticleLevel / Truth] Whether to apply the - // 'NotFromHadron' requirement onto the objects. - bool TauIsHadron; // [ParticleLevel / Truth] Whether a tauon is a - // hadron during the 'NotFromHadron' check - } m_truth_muon; - - // photons - struct { - float PtCut; // [ParticleLevel / Truth] Photon Object - // Selection minimum pT Cut (Standard ATLAS - // units, [MeV]). - float EtaCut; // [ParticleLevel / Truth] Photon Object - // Selection maximum absolute eta Cut. - std::string Origin; // [ParticleLevel / Truth] Photon Object - // Selection truth origin configuration. - std::string Isolation; // [ParticleLevel / Truth] Photon Object - // Selection truth isolation configuration. - } m_truth_photon; - - // normal / large R jets - struct { - float PtCut; // [ParticleLevel / Truth] Jet Object - // Selection minimum pT Cut (Standard ATLAS - // units, [MeV]). - float EtaCut; // [ParticleLevel / Truth] Jet Object - // Selection maximum absolute eta Cut. - } m_truth_jet, m_truth_largeRJet; - - - // -----------------------------------------------]]] - - // Options for upgrade studies - bool m_HLLHC; - - // B-tagging WPs requested by the user - std::vector< std::string > m_chosen_btaggingWP = { }; - // B-tagging systematics requested by user to be excluded from EV treatment, separated by semi-colons - std::string m_bTagSystsExcludedFromEV = ""; - - // list of B-tagging WP actualy available - std::vector<std::string> m_available_btaggingWP; - std::vector<std::string> m_available_btaggingWP_trkJet; - // list of B-tagging WP actualy calibrated - std::vector<std::string> m_calibrated_btaggingWP; - std::vector<std::string> m_calibrated_btaggingWP_trkJet; - - // B-tagging calibration to be used - std::string m_btagging_calibration_B = "default"; - std::string m_btagging_calibration_C = "default"; - std::string m_btagging_calibration_Light = "default"; - - // b-tag SF helpers - one of each per WP - // will be set in the BTagScaleFactorCalculator - // These are the base names of the SF systematics (without __up/__down) - std::unordered_map<std::string,std::set<std::string>> m_bTag_base_names; - std::unordered_map<std::string,std::set<std::string>> m_bTag_base_names_trkJet; - // and those of them which are not eigenvectors - std::unordered_map<std::string,std::set<std::string>> m_bTag_named_systs; - std::unordered_map<std::string,std::set<std::string>> m_bTag_named_systs_trkJet; - // how many B eigen-variations do we have? - std::unordered_map<std::string,unsigned int> m_bTag_eigen_B; - std::unordered_map<std::string,unsigned int> m_bTag_eigen_B_trkJet; - // how many C eigen-variations do we have? - std::unordered_map<std::string,unsigned int> m_bTag_eigen_C; - std::unordered_map<std::string,unsigned int> m_bTag_eigen_C_trkJet; - // how many Light eigen-variations do we have? - std::unordered_map<std::string,unsigned int> m_bTag_eigen_light; - std::unordered_map<std::string,unsigned int> m_bTag_eigen_light_trkJet; - - // LHAPDF options - struct { - - std::vector<std::string> pdf_set_names = {}; - std::string baseLHAPDF = ""; // used only if XF1*XF2==0 - - // options - bool doLHAPDF = false; - bool doLHAPDFInNominalTrees = false; - - bool save_per_event = false; - - // we pass the results back to config in PDFScaleFactor::finalize - std::unordered_map< std::string, std::vector<float> > pdf_results; - - - } m_lhapdf_options; - - // Pile-up reweighting - struct { - - std::vector<std::string> lumi_calc_files = {}; - - std::vector<std::string> config_files = {}; - - bool apply = false; - - bool use_grl_tool = false; - - // Whether or not to perform mu dependent - // pile-up reweighting. Optional because can - // result in a possible loss of statistics - // that are crucial for things like MVA training. - bool mu_dependent = true; - - } m_pileup_reweighting; - - // Muon Trigger SF configuration - std::string m_muon_trigger_SF; - - - // Selections - std::shared_ptr<std::vector<std::string>> m_allSelectionNames; - // Trigger configuration - // First string is the selection name, second string is the trigger - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> m_allTriggers; - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> m_electronTriggers; - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> m_muonTriggers; - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> m_tauTriggers; - std::vector<std::string> m_dummyTrigger; - - // Where the sum of event weights - // before derivation framework is kept - std::string m_sumOfEventWeightsMetaData; - - // Object Selector name - std::string m_objectSelectionName; - // Output Format - std::string m_outputFormat; - // Output Events - std::string m_outputEvents; - bool m_saveOnlySelectedEvents; - // SetAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround - bool m_outputFileSetAutoFlushZero; - - // Number of events to run on (for testing) - unsigned int m_numberOfEventsToRun; - - // Number of events to skip (for testing) - unsigned int m_numberOfEventsToSkip; - - // AOD meta-data access service - AodMetaDataAccess * m_aodMetaData; - - // Systematics - std::size_t m_nominalHashValue; - - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashPhotons; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashElectrons; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashMuons; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashTaus; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashJets; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashLargeRJets; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashTrackJets; - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashMET; - - std::shared_ptr<std::unordered_set<std::size_t>> m_systHashAll; - std::shared_ptr<std::list<std::size_t>> m_list_systHashAll; - - std::shared_ptr<std::unordered_set<std::size_t>> m_systHash_electronInJetSubtraction; - std::shared_ptr<std::list<std::size_t>> m_list_systHash_electronInJetSubtraction; - - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapPhotons; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapElectrons; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapMuons; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapTaus; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapJets; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapLargeRJets; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapTrackJets; - std::shared_ptr<std::unordered_map<std::size_t,CP::SystematicSet>> m_systMapMET; - - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapPhotons; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapElectrons; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapMuons; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapTaus; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapJets; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapJets_electronInJetSubtraction; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapJetsLoose_electronInJetSubtraction; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapLargeRJets; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapTrackJets; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapMET; - - // For TopEvent/SingleSystEvent - will return the nominal key if not under variation - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapPhotons; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapElectrons; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapMuons; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapTaus; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJets; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapLargeRJets; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapTrackJets; - // The boosted case is a bit more complex, we need additional collections - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapElectrons_electronInJetSubtraction; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJets_electronInJetSubtraction; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJetsLoose_electronInJetSubtraction; - - // For top::TopEventMaker - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapPhotonsTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapPhotonsTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapElectronsTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapElectronsTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapMuonsTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapMuonsTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapTausTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapTausTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJetsTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJetsTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapLargeRJetsTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapLargeRJetsTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapTrackJetsTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapTrackJetsTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJets_electronInJetSubtractionTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux; - - // Missing ET - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapMissingET; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapMissingETLoose; - - // KLFitter - std::string m_sgKeyKLFitter; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapKLFitter; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapKLFitterLoose; - - // PseudoTop - std::string m_sgKeyPseudoTop; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systSgKeyMapPseudoTop; - - // Map from systematic hash to CP::SystematicSet - std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapJetGhostTrack; - // Map from systematic hash to decoration key. - std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systDecoKeyMapJetGhostTrack; - - // Output TTree names - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systAllTTreeNames; - std::shared_ptr<std::unordered_map<std::size_t,std::string>> m_systPersistantAllTTreeNames; - // Output TTree index - std::shared_ptr<std::unordered_map<std::size_t,unsigned int>> m_systAllTTreeIndex; - std::shared_ptr<std::unordered_map<std::size_t,unsigned int>> m_systAllTTreeLooseIndex; - - // Private function only to simplify the setting of AFII values - void ReadIsAFII(top::ConfigurationSettings* const& settings); - - -}; -} // namespace top + // AFII? + inline bool isAFII() const {return m_isAFII;} + inline void setIsAFII(const bool value) { + if (!m_configFixed) { + m_isAFII = value; + } + } + + // List of branches to be removed + inline std::vector<std::string> filterBranches() const {return m_filterBranches;} + inline void setFilterBranches(const std::vector<std::string>& value) { + if (!m_configFixed) { + m_filterBranches = value; + } + } + + // List of PartonLevel branches to be removed + inline std::vector<std::string> filterPartonLevelBranches() const {return m_filterPartonLevelBranches;} + inline void setFilterPartonLevelBranches(const std::vector<std::string>& value) { + if (!m_configFixed) { + m_filterPartonLevelBranches = value; + } + } + + // List of ParticleLevel branches to be removed + inline std::vector<std::string> filterParticleLevelBranches() const {return m_filterParticleLevelBranches;} + inline void setFilterParticleLevelBranches(const std::vector<std::string>& value) { + if (!m_configFixed) { + m_filterParticleLevelBranches = value; + } + } + + // List of NominalLoose branches to be removed + inline std::vector<std::string> filterNominalLooseBranches() const {return m_filterNominalLooseBranches;} + inline void setFilterNominalLooseBranches(const std::vector<std::string>& value) { + if (!m_configFixed) { + m_filterNominalLooseBranches = value; + } + } + + // Generators name + inline std::string getGenerators() const {return m_generators;} + inline void setGenerators(const std::string value) { + if (!m_configFixed) { + m_generators = value; + } + } + + // AMITag + inline std::string getAMITag() const {return m_AMITag;} + inline void setAMITag(const std::string value) { + if (!m_configFixed) { + m_AMITag = value; + } + } + + // Is this a Primary xAOD? + inline bool isPrimaryxAOD() const {return m_isPrimaryxAOD;} + inline void setIsPrimaryxAOD(const bool value) { + if (!m_configFixed) { + m_isPrimaryxAOD = value; + } + } + + // Is this a Truth DxAOD? + inline bool isTruthDxAOD() const {return m_isTruthDxAOD;} + inline void setIsTruthDxAOD(const bool value) { + if (!m_configFixed) { + m_isTruthDxAOD = value; + } + } + + // What derivation type is it? + inline std::string getDerivationStream() const {return m_derivationStream;} + inline void setDerivationStream(const std::string value) { + if (!m_configFixed) { + m_derivationStream = value; + } + } + + // AMI tag from metadata + std::string const& getAmiTag() const; + void setAmiTag(std::string const& amiTag); + + inline unsigned int getDSID() const {return m_DSID;} + inline void setDSID(unsigned int value) { + // Check here if this is a sherpa 2.2 V+jets sample + // (see below to set DSIDs) + setIsSherpa22Vjets(value); + m_DSID = value; + } + + // Is this Sherpa 2.2 V+jets? + // (if so then we need to reweight based on num truth jets) + inline bool isSherpa22Vjets() const {return m_is_sherpa_22_vjets;} + inline void setIsSherpa22Vjets(unsigned int dsid) { + // m_is_sherpa_22_vjets = false by default + // Sherpa 2.2 W+jets (from TopDataPrep) + if (dsid >= 363331 && dsid <= 363354) m_is_sherpa_22_vjets = true; + if (dsid >= 363436 && dsid <= 363483) m_is_sherpa_22_vjets = true; + // Sherpa 2.2 Z+jets (from TopDataPrep) + if (dsid >= 363102 && dsid <= 363122) m_is_sherpa_22_vjets = true; + if (dsid >= 363361 && dsid <= 363435) m_is_sherpa_22_vjets = true; + } + + // map index for MC/MC b-tagging scale factors + inline unsigned int getMapIndex() const {return m_MapIndex;} + inline void setMapIndex(unsigned int value) {m_MapIndex = value;} + + // Run normal (Tight) selection and dumps the non-Loose trees + // Default is true for both Data and MC + inline bool doTightEvents() const {return m_doTightEvents;} + // Run Loose selection and dumps the Loose trees + // Default is true for Data and false for MC + inline bool doLooseEvents() const {return m_doLooseEvents;} + + // Run systematics on Loose selection + // Default is true + inline bool doTightSysts() const {return m_doTightSysts;} + // Run systematics on Loose selection + // Default is true + inline bool doLooseSysts() const {return m_doLooseSysts;} + + // Do fakes MM weight calculation using FakeBkgTools from IFF + inline bool doFakesMMWeightsIFF() const {return m_doFakesMMWeightsIFF;} + + // Configurations for MM fake estimate using FakeBkgTools from IFF + inline std::string FakesMMConfigIFF() const {return m_FakesMMConfigIFF;} + + // Debug mode for MM fake estimate using FakeBkgTools from IFF + inline bool FakesMMIFFDebug() const {return m_doFakesMMIFFDebug;} + + // enables calculation of MM weights using FakeBkgTools from IFF + // only possible for data loose + // doing it on MC loose is explicitly forbidden + inline void setFakesMMWeightsCalculationIFF() + {m_doFakesMMWeightsIFF = true;} + inline void setFakesMMConfigIFF(const std::string& configIFF) + {m_FakesMMConfigIFF = configIFF;} + inline void setFakesMMIFFDebug() + {m_doFakesMMIFFDebug = true;} + + //by default AT uses always tight objects in MET re-building; these options allow for using loose objects instead in the loose analysis and/or in the nominal analysis + inline void setUseLooseObjectsInMETInLooseTree() {if (!m_configFixed) m_useLooseObjectsInMETInLooseTree = true;} + inline bool useLooseObjectsInMETInLooseTree() const {return m_useLooseObjectsInMETInLooseTree;} + inline void setUseLooseObjectsInMETInNominalTree() {if (!m_configFixed) m_useLooseObjectsInMETInNominalTree = true;} + inline bool useLooseObjectsInMETInNominalTree() const {return m_useLooseObjectsInMETInNominalTree;} + //this will write a separate branch with the met built using loose objects + inline void setWriteMETBuiltWithLooseObjects() {if (!m_configFixed) m_writeMETBuiltWithLooseObjects=true;} + inline bool writeMETBuiltWithLooseObjects() {return m_writeMETBuiltWithLooseObjects;} + + // By default the top group does overlap removal on the tight lepton definitions + // If you use this you are going off piste and need to report + // your findings to the top reconstruction meeting + inline void setOverlapRemovalOnLooseLeptonDef() { + if (!m_configFixed) { + m_doOverlapRemovalOnLooseLeptonDef = true; + } + } + + inline bool doOverlapRemovalOnLooseLeptonDef() const {return m_doOverlapRemovalOnLooseLeptonDef;} + + inline std::string overlapRemovalProcedure() const + {return m_overlap_removal_procedure;} + + inline float overlapRemovalSlidingInnerDRel() const + {return m_overlapRemovalSlidingInnerDRel;} + + inline float overlapRemovalSlidingInnerDRmu() const + {return m_overlapRemovalSlidingInnerDRmu;} + + // do overlap removal also with large-R jets + // (using whatever procedure is used in the official tools) + inline void setLargeJetOverlapRemoval() { + if (!m_configFixed) { + m_doLargeJetOverlapRemoval = true; + } + } + + inline bool doLargeJetOverlapRemoval() const {return m_doLargeJetOverlapRemoval;} + + // In the *_Loose trees, lepton SFs are calculated considering + // tight ID and isolation instead of loose + // Only tight leptons are considered in the event SF calculation + inline void setApplyTightSFsInLooseTree() { + if (!m_configFixed) { + m_applyTightSFsInLooseTree = true; + } + } + + inline bool applyTightSFsInLooseTree() const {return m_applyTightSFsInLooseTree;} + + // Apply Electron In Jet subtraction + // For boosted analysis + inline bool applyElectronInJetSubtraction() const {return m_applyElectronInJetSubtraction;} + inline void setApplyElectronInJetSubtraction() { + if (!m_configFixed) { + m_applyElectronInJetSubtraction = true; + } + } + + // Dump truth block info + inline bool doTruthBlockInfo() const {return m_doTruthBlockInfo;} + inline void setTruthBlockInfo() { + if (!m_configFixed) { + m_doTruthBlockInfo = true; + } + } + + // Write truth PDF info + inline bool doTruthPDFInfo() const {return m_doTruthPDFInfo;} + inline void setTruthPDFInfo() { + if (!m_configFixed) { + m_doTruthPDFInfo = true; + } + } + + // Write truth PDF info in reco tree + inline bool doTruthPDFInfoInNominalTrees() const {return m_doTruthPDFInfoInNominalTrees;} + inline void setTruthPDFInfoInNominalTrees() { + if (!m_configFixed) { + m_doTruthPDFInfoInNominalTrees = true; + } + } + + // Write MC generator weights + inline bool doMCGeneratorWeights() const {return m_doMCGeneratorWeights;} + inline void setMCGeneratorWeights() { + if (!m_configFixed) { + m_doMCGeneratorWeights = true; + } + } + + // Write truth PDF info in reco tree + inline bool doMCGeneratorWeightsInNominalTrees() const {return m_doMCGeneratorWeightsInNominalTrees;} + inline void setMCGeneratorWeightsInNominalTrees() { + if (!m_configFixed) { + m_doMCGeneratorWeightsInNominalTrees = true; + } + } + + inline const std::vector<std::string>& nominalWeightNames() const {return m_nominalWeightNames;} + inline void setNominalWeightName(const std::string& name) { + m_nominalWeightName = name; + } + inline void setNominalWeightIndex(size_t index) { + m_nominalWeightIndex = index; + } + inline std::string nominalWeightName() const {return m_nominalWeightName;} + inline size_t nominalWeightIndex() const {return m_nominalWeightIndex;} + inline bool forceNominalWeightFallbackIndex() const {return m_forceWeightIndex;} + + inline void setMCweightsVectorSize(size_t weights_size) { + m_MCweightsSize = weights_size; + } + + inline size_t MCweightsVectorSize() const {return m_MCweightsSize;} + + // Top Parton History + inline bool doTopPartonHistory() const {return m_doTopPartonHistory;} + inline void setTopPartonHistory() { + if (!m_configFixed) { + m_doTopPartonHistory = true; + } + } + + // Register Top Parton History in flat ntuple + // This doesn't use m_configFixed - this is bad :( + // This is a simple implementation of saving xAOD objects to ntuples + // John has more advanced ideas on how to do this + // This is just a quick fix for now to get the concept working + inline bool isTopPartonHistoryRegisteredInNtuple() const {return m_isTopPartonHistoryRegisteredInNtuple;} + inline void setTopPartonHistoryRegisteredInNtuple() + {m_isTopPartonHistoryRegisteredInNtuple = true;} + + inline bool doTopPartonLevel() const {return m_doTopPartonLevel;} + inline void setTopPartonLevel(bool in) { + if (!m_configFixed) { + m_doTopPartonLevel = in; + } + } + + // TopParticleLevel + inline bool doTopParticleLevel() const {return m_doTopParticleLevel;} + inline void setTopParticleLevel(bool in) { + if (!m_configFixed) { + m_doTopParticleLevel = in; + } + } + + inline bool doParticleLevelOverlapRemovalMuJet() const {return m_doParticleLevelOverlapRemovalMuJet;} + inline bool doParticleLevelOverlapRemovalElJet() const {return m_doParticleLevelOverlapRemovalElJet;} + inline bool doParticleLevelOverlapRemovalJetPhoton() const {return m_doParticleLevelOverlapRemovalJetPhoton;} + inline void setParticleLevelOverlapRemovalMuJet(bool value) { + if (!m_configFixed) { + m_doParticleLevelOverlapRemovalMuJet = value; + } + } + + inline void setParticleLevelOverlapRemovalElJet(bool value) { + if (!m_configFixed) { + m_doParticleLevelOverlapRemovalElJet = value; + } + } + + inline void setParticleLevelOverlapRemovalJetPhoton(bool value) { + if (!m_configFixed) { + m_doParticleLevelOverlapRemovalJetPhoton = value; + } + } + + // KLFitter + inline bool doKLFitter() const {return m_doKLFitter;} + inline void setKLFitter() { + if (!m_configFixed) { + m_doKLFitter = true; + } + } + + inline const std::string& KLFitterTransferFunctionsPath() const {return m_KLFitterTransferFunctionsPath;} + inline const std::string& KLFitterOutput() const {return m_KLFitterOutput;} + inline const std::string& KLFitterJetSelectionMode() const {return m_KLFitterJetSelectionMode;} + inline const std::string& KLFitterBTaggingMethod() const {return m_KLFitterBTaggingMethod;} + inline const std::string& KLFitterLH() const {return m_KLFitterLH;} + + inline bool KLFitterTopMassFixed() const {return m_KLFitterTopMassFixed;} + inline bool KLFitterSaveAllPermutations() const {return m_KLFitterSaveAllPermutations;} + + inline bool KLFitterFailOnLessThanXJets() const {return m_KLFitterFailOnLessThanXJets;} + // PseudoTop + inline bool doPseudoTop() const {return m_doPseudoTop;} + inline void setPseudoTop() { + if (!m_configFixed) { + m_doPseudoTop = true; + } + } + + // Triggers + inline virtual void allTriggers_Tight(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_allTriggers_Tight = triggers; + } + } + + inline virtual void electronTriggers_Tight(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_electronTriggers_Tight = triggers; + } + } + + inline virtual void muonTriggers_Tight(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_muonTriggers_Tight = triggers; + } + } + + inline virtual void tauTriggers_Tight(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_tauTriggers_Tight = triggers; + } + } + + inline virtual void allTriggers_Loose(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_allTriggers_Loose = triggers; + } + } + + inline virtual void electronTriggers_Loose(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_electronTriggers_Loose = triggers; + } + } + + inline virtual void muonTriggers_Loose(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_muonTriggers_Loose = triggers; + } + } + + inline virtual void tauTriggers_Loose(std::shared_ptr<std::unordered_map<std::string, + std::vector<std::string> > > triggers) { + if (!m_configFixed) { + m_tauTriggers_Loose = triggers; + } + } + + inline std::shared_ptr<std::vector<std::string> > allSelectionNames() const {return m_allSelectionNames;} + virtual const std::vector<std::string>& allTriggers_Tight(const std::string& selection) const; + virtual const std::vector<std::string>& electronTriggers_Tight(const std::string& selection) const; + virtual const std::vector<std::string>& muonTriggers_Tight(const std::string& selection) const; + virtual const std::vector<std::string>& tauTriggers_Tight(const std::string& selection) const; + + virtual const std::vector<std::string>& allTriggers_Loose(const std::string& selection) const; + virtual const std::vector<std::string>& electronTriggers_Loose(const std::string& selection) const; + virtual const std::vector<std::string>& muonTriggers_Loose(const std::string& selection) const; + virtual const std::vector<std::string>& tauTriggers_Loose(const std::string& selection) const; + + // StoreGate Keys + virtual void sgKeyMCParticle(const std::string& s); + virtual void sgKeyPhotons(const std::string& s); + virtual void sgKeyElectrons(const std::string& s); + virtual void sgKeyFwdElectrons(const std::string& s); + virtual void sgKeyMuons(const std::string& s); + virtual void sgKeySoftMuons(const std::string& s); + virtual void sgKeyTaus(const std::string& s); + virtual void sgKeyJets(const std::string& s); + virtual void sgKeyLargeRJets(const std::string& s); + virtual void sgKeyTrackJets(const std::string& s); + virtual void sgKeyTracks(const std::string& s); + + virtual void sgKeyTruthElectrons(const std::string& s); + virtual void sgKeyTruthMuons(const std::string& s); + virtual void sgKeyTruthPhotons(const std::string& s); + virtual void sgKeyTruthMET(const std::string& s); + virtual void sgKeyTruthJets(const std::string& s); + virtual void sgKeyTruthLargeRJets(const std::string& s); + virtual void sgKeyTruthTaus(const std::string& s); + + inline virtual void sgKeyMissingEt(const std::string& s) { + if (!m_configFixed) { + m_sgKeyMissingEt = s; + } + } + + inline virtual void sgKeyMissingEtLoose(const std::string& s) { + if (!m_configFixed) { + m_sgKeyMissingEtLoose = s; + } + } + + inline float jetResponseMatchingDeltaR() const {return m_jetResponseMatchingDeltaR;} + inline void setJetResponseMatchingDeltaR(const float value) {m_jetResponseMatchingDeltaR = value;} + + inline const std::string& sgKeyEventInfo() const {return m_sgKeyEventInfo;} + inline const std::string& sgKeyPrimaryVertices() const {return m_sgKeyPrimaryVertices;} + inline virtual const std::string& sgKeyPhotons() const {return m_sgKeyPhotons;} + inline virtual const std::string& sgKeyElectrons() const {return m_sgKeyElectrons;} + inline virtual const std::string& sgKeyFwdElectrons() const {return m_sgKeyFwdElectrons;} + inline virtual const std::string& sgKeyMuons() const {return m_sgKeyMuons;} + inline virtual const std::string& sgKeySoftMuons() const {return m_sgKeySoftMuons;} + inline virtual const std::string& sgKeyTaus() const {return m_sgKeyTaus;} + inline virtual const std::string& sgKeyJets() const {return m_sgKeyJets;} + inline virtual const std::string& sgKeyJetsType() const {return m_sgKeyJetsType;} + inline virtual const std::string& sgKeyLargeRJets() const {return m_sgKeyLargeRJets;} + inline virtual const std::string& sgKeyTrackJets() const {return m_sgKeyTrackJets;} + inline virtual const std::string& sgKeyTracks() const {return m_sgKeyTracks;} + inline virtual const std::string& sgKeyTrackJetsType() const {return m_sgKeyTrackJetsType;} + inline virtual const std::string& sgKeyMissingEt() const {return m_sgKeyMissingEt;} + inline virtual const std::string& sgKeyMissingEtLoose() const {return m_sgKeyMissingEtLoose;} + inline const std::string& sgKeyInDetTrackParticles() const {return m_sgKeyInDetTrackParticles;} + + inline const std::string& sgKeyTruthEvent() const {return m_sgKeyTruthEvent;} + inline virtual const std::string& sgKeyMCParticle() const {return m_sgKeyMCParticle;} + inline const std::string& sgKeyTruthPhotons() const {return m_sgKeyTruthPhotons;} + inline const std::string& sgKeyTruthElectrons() const {return m_sgKeyTruthElectrons;} + inline const std::string& sgKeyTruthMuons() const {return m_sgKeyTruthMuons;} + inline const std::string& sgKeyTruthTaus() const {return m_sgKeyTruthTaus;} + inline virtual const std::string& sgKeyTruthJets() const {return m_sgKeyTruthJets;} + inline virtual const std::string& sgKeyTruthLargeRJets() const {return m_sgKeyTruthLargeRJets;} + inline const std::string& sgKeyTruthMET() const {return m_sgKeyTruthMET;} + inline const std::string& sgKeyTopPartonHistory() const {return m_sgKeyTopPartonHistory;} + + inline const std::string& sgKeyTopSystematicEvents() const {return m_sgKeyTopSystematicEvents;} + inline const std::string& sgKeyTopSystematicEventsLoose() const {return m_sgKeyTopSystematicEventsLoose;} + inline const std::string& passEventSelectionDecoration() const {return m_passEventSelectionDecoration;} + virtual void decoKeyJetGhostTrack(const std::string& key); + inline virtual const std::string& decoKeyJetGhostTrack() const {return m_decoKeyJetGhostTrack;} + virtual void runPeriodJetGhostTrack(const std::vector<std::uint32_t>& vect); + virtual void runPeriodTrack(const std::vector<std::uint32_t>& vect); + + virtual const std::string& sgKeyPhotons(const std::size_t hash) const; + virtual const std::string& sgKeyElectrons(const std::size_t hash) const; + virtual const std::string& sgKeyFwdElectrons(const std::size_t hash) const; + virtual const std::string& sgKeyElectronsStandAlone(const std::size_t hash) const; + virtual const std::string& sgKeyFwdElectronsStandAlone(const std::size_t hash) const; + virtual const std::string& sgKeyMuons(const std::size_t hash) const; + virtual const std::string& sgKeySoftMuons(const std::size_t hash) const; + virtual const std::string& sgKeyTaus + (const std::size_t hash) const; + virtual const std::string& sgKeyJets(const std::size_t hash, const bool useLooseLeptonJets) const; + virtual const std::string& sgKeyJetsStandAlone(const std::size_t hash) const; + virtual const std::string& sgKeyLargeRJets(const std::size_t hash) const; + virtual const std::string& sgKeyTrackJets(const std::size_t hash) const; + virtual const std::string& sgKeyTracks(const std::size_t hash) const; + virtual const std::string& sgKeyMissingEt(const std::size_t hash) const; + virtual const std::string& sgKeyMissingEtLoose(const std::size_t hash) const; + + // For top::TopEventMaker + const std::string& sgKeyPhotonsTDS(const std::size_t hash) const; + const std::string& sgKeyPhotonsTDSAux(const std::size_t hash) const; + const std::string& sgKeyElectronsTDS(const std::size_t hash) const; + const std::string& sgKeyElectronsTDSAux(const std::size_t hash) const; + const std::string& sgKeyFwdElectronsTDS(const std::size_t hash) const; + const std::string& sgKeyFwdElectronsTDSAux(const std::size_t hash) const; + const std::string& sgKeyMuonsTDS(const std::size_t hash) const; + const std::string& sgKeyMuonsTDSAux(const std::size_t hash) const; + const std::string& sgKeySoftMuonsTDS(const std::size_t hash) const; + const std::string& sgKeySoftMuonsTDSAux(const std::size_t hash) const; + const std::string& sgKeyTausTDS(const std::size_t hash) const; + const std::string& sgKeyTausTDSAux(const std::size_t hash) const; + const std::string& sgKeyJetsTDS(const std::size_t hash, const bool useLooseLeptonJets) const; + const std::string& sgKeyJetsTDSAux(const std::size_t hash, const bool useLooseLeptonJets) const; + const std::string& sgKeyLargeRJetsTDS(const std::size_t hash) const; + const std::string& sgKeyLargeRJetsTDSAux(const std::size_t hash) const; + const std::string& sgKeyTrackJetsTDS(const std::size_t hash) const; + const std::string& sgKeyTrackJetsTDSAux(const std::size_t hash) const; + const std::string& sgKeyTracksTDS(const std::size_t hash) const; + const std::string& sgKeyTracksTDSAux(const std::size_t hash) const; + + // KLFitter + const std::string& sgKeyKLFitter(const std::size_t hash) const; + const std::string& sgKeyKLFitterLoose(const std::size_t hash) const; + + // PseudoTop + const std::string& sgKeyPseudoTop(const std::size_t hash) const; + const std::string& sgKeyPseudoTop(const std::string) const; + const std::string& sgKeyPseudoTopLoose(const std::size_t hash) const; + const std::string& sgKeyPseudoTopLoose(const std::string) const; + + // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv + // Jet Ghost-Track Systematics and selection + + // The jet decoration name for a given systematic (nominal also possible). + const std::string& decoKeyJetGhostTrack(const std::size_t hash) const; + + // Retrieve names of all (registered) systematics that affect ghost tracks. + const std::vector<std::string>& systematicsJetGhostTrack() const {return m_jetGhostTrackSystematics;} + + // Retrieve run periods for ghost tracks. + const std::vector<std::uint32_t>& runPeriodsJetGhostTrack() const {return m_jetGhostTrackRunPeriods;} + + // Retrieve run periods for tracks. + const std::vector<std::uint32_t>& runPeriodsTrack() const {return m_trackRunPeriods;} + + // Retrieve mapping from systematic hash to CP::SystematicSet. + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapJetGhostTrack() const { + return m_systMapJetGhostTrack; + } + + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + + // special: allow to dump the systematics-shifted b-tagging SFs in the systematics trees + inline virtual void dumpBtagSystsInSystTrees(const bool& b) { + if (!m_configFixed) { + m_dumpBtagSystsInSystTrees = b; + } + } + + inline virtual const bool& dumpBtagSystsInSystTrees() {return m_dumpBtagSystsInSystTrees;} + + // special: store per-jet btag SGs + inline virtual void storePerJetBtagSFs(const bool& b) { + if (!m_configFixed) { + m_storePerJetBtagSFs = b; + } + } + + inline virtual const bool& storePerJetBtagSFs() {return m_storePerJetBtagSFs;} + + // Electron configuration + inline virtual void egammaSystematicModel(const std::string& s) { + if (!m_configFixed) { + m_egammaSystematicModel = s; + } + } + + inline virtual void electronEfficiencySystematicModel(const std::string& s) { + if (!m_configFixed) { + m_electronEfficiencySystematicModel = s; + } + } + + inline virtual void electronEfficiencySystematicModelEtaBinning(const std::string& s) { + if (!m_configFixed) { + m_electronEfficiencySystematicModelEtaBinning = s; + } + } + + inline virtual void electronEfficiencySystematicModelEtBinning(const std::string& s) { + if (!m_configFixed) { + m_electronEfficiencySystematicModelEtBinning = s; + } + } + + inline virtual void electronID(const std::string& s) { + if (!m_configFixed) { + m_electronID = s; + } + } + + inline virtual void electronIDLoose(const std::string& s) { + if (!m_configFixed) { + m_electronIDLoose = s; + } + } + + inline void removeElectronVetoLArCrack() { + if (!m_configFixed) { + m_electronVetoLArCrack = false; + } + } + + inline virtual void electronVetoLArCrack(const bool b) { + if (!m_configFixed) { + m_electronVetoLArCrack = b; + } + } + + inline virtual void electronPtcut(const float pt) { + if (!m_configFixed) { + m_electronPtcut = pt; + } + } + + inline virtual void electronIsolation(const std::string& iso) { + if (!m_configFixed) { + m_electronIsolation = iso; + } + } + + inline virtual void electronIsolationLoose(const std::string& iso) { + if (!m_configFixed) { + m_electronIsolationLoose = iso; + } + } + + void electronIsolationSF(std::string const& iso) { + if (!m_configFixed) { + m_electronIsolationSF = iso; + } + } + + void electronIsolationSFLoose(std::string const& iso) { + if (!m_configFixed) { + m_electronIsolationSFLoose = iso; + } + } + + inline virtual void useElectronChargeIDSelection(const std::string& s) { + if (!m_configFixed) { + m_useElectronChargeIDSelection = (s == "True" || s == "true"); + } + } + + inline virtual void useEgammaLeakageCorrection(const std::string& s) { + if (!m_configFixed) { + m_useEgammaLeakageCorrection = (s == "True" || s == "true"); + } + } + + inline virtual void enablePromptLeptonImprovedVetoStudies(const std::string& s) { + if (!m_configFixed) { + m_enablePromptLeptonImprovedVetoStudies = (s == "True" || s == "true"); + } + } + + inline virtual const std::string& egammaSystematicModel() {return m_egammaSystematicModel;} + inline virtual const std::string& electronEfficiencySystematicModel() {return m_electronEfficiencySystematicModel;} + inline virtual const std::string& electronEfficiencySystematicModelEtaBinning() { + return m_electronEfficiencySystematicModelEtaBinning; + } + inline virtual const std::string& electronEfficiencySystematicModelEtBinning() { + return m_electronEfficiencySystematicModelEtBinning; + } + inline virtual const std::string& electronID() const {return m_electronID;} + inline virtual const std::string& electronIDLoose() const {return m_electronIDLoose;} + inline virtual bool electronVetoLArCrack() const {return m_electronVetoLArCrack;} + inline virtual float electronPtcut() const {return m_electronPtcut;} + inline virtual const std::string& electronIsolation() const {return m_electronIsolation;} + inline virtual const std::string& electronIsolationLoose() const {return m_electronIsolationLoose;} + std::string const& electronIsolationSF() const {return m_electronIsolationSF;} + std::string const& electronIsolationSFLoose() const {return m_electronIsolationSFLoose;} + inline virtual bool electronIsoSFs() const {return m_electronIsoSFs;} + inline const std::string& electronIDDecoration() const {return m_electronIDDecoration;} + inline const std::string& electronIDLooseDecoration() const {return m_electronIDLooseDecoration;} + inline bool useElectronChargeIDSelection() const {return m_useElectronChargeIDSelection;} + inline bool useEgammaLeakageCorrection() const {return m_useEgammaLeakageCorrection;} + inline bool enablePromptLeptonImprovedVetoStudies() const {return m_enablePromptLeptonImprovedVetoStudies;} + + // Fwd electron + inline virtual void fwdElectronID(const std::string& s) { + if (!m_configFixed) { + m_fwdElectronID = s; + } + } + + inline virtual void fwdElectronIDLoose(const std::string& s) { + if (!m_configFixed) { + m_fwdElectronIDLoose = s; + } + } + + inline virtual void fwdElectronPtcut(const float pt) { + if (!m_configFixed) { + m_fwdElectronPtcut = pt; + } + } + + inline virtual void fwdElectronMinEtacut(const float eta) { + if (!m_configFixed) { + m_fwdElectronMinEtacut = eta; + } + } + + inline virtual void fwdElectronMaxEtacut(const float eta) { + if (!m_configFixed) { + m_fwdElectronMaxEtacut = eta; + } + } + + inline virtual void fwdElectronBCIDCleaningMinRun(const int fwdElectronBCIDCleaningMinRun) { + if (!m_configFixed) { + m_fwdElectronBCIDCleaningMinRun = fwdElectronBCIDCleaningMinRun; + } + } + + inline virtual void fwdElectronBCIDCleaningMaxRun(const int fwdElectronBCIDCleaningMaxRun) { + if (!m_configFixed) { + m_fwdElectronBCIDCleaningMaxRun = fwdElectronBCIDCleaningMaxRun; + } + } + + inline virtual const std::string& fwdElectronID() const {return m_fwdElectronID;} + inline virtual const std::string& fwdElectronIDLoose() const {return m_fwdElectronIDLoose;} + inline virtual float fwdElectronPtcut() const {return m_fwdElectronPtcut;} + inline virtual float fwdElectronMinEtacut() const {return m_fwdElectronMinEtacut;} + inline virtual float fwdElectronMaxEtacut() const {return m_fwdElectronMaxEtacut;} + inline virtual int fwdElectronBCIDCleaningMinRun() const {return m_fwdElectronBCIDCleaningMinRun;} + inline virtual int fwdElectronBCIDCleaningMaxRun() const {return m_fwdElectronBCIDCleaningMaxRun;} + + // Photon configuration + inline virtual void photonPtcut(const float pt) { + if (!m_configFixed) { + m_photon_configuration.pt = pt; + } + } + + inline virtual void photonEtacut(const float eta) { + if (!m_configFixed) { + m_photon_configuration.eta = eta; + } + } + + inline virtual void photonIdentification(const std::string& quality) { + if (!m_configFixed) { + m_photon_configuration.identification = quality; + } + } + + inline virtual void photonIdentificationLoose(const std::string& quality) { + if (!m_configFixed) { + m_photon_configuration_loose.identification = quality; + } + } + + inline virtual void photonIsolation(const std::string& quality) { + if (!m_configFixed) { + m_photon_configuration.isolation = quality; + } + } + + inline virtual void photonIsolationLoose(const std::string& quality) { + if (!m_configFixed) { + m_photon_configuration_loose.isolation = quality; + } + } + + // Muon configuration + inline virtual void muonPtcut(const float pt) { + if (!m_configFixed) { + m_muonPtcut = pt; + } + } + + inline virtual void muonEtacut(const float eta) { + if (!m_configFixed) { + m_muonEtacut = eta; + } + } + + inline virtual void muonQuality(const std::string& quality) { + if (!m_configFixed) { + m_muonQuality = quality; + } + } + + void muonUseMVALowPt(const bool& UseMVALowPt) { + if (!m_configFixed) { + m_muonUseMVALowPt = UseMVALowPt; + } + } + + void muonUse2stationMuonsHighPt(const bool& Use2stationMuonsHighPt) { + if (!m_configFixed) { + m_muonUse2stationMuonsHighPt = Use2stationMuonsHighPt; + } + } + + void muonUseMVALowPtLoose(const bool& UseMVALowPtLoose) { + if (!m_configFixed) { + m_muonUseMVALowPtLoose = UseMVALowPtLoose; + } + } + + void muonUse2stationMuonsHighPtLoose(const bool& Use2stationMuonsHighPtLoose) { + if (!m_configFixed) { + m_muonUse2stationMuonsHighPtLoose = Use2stationMuonsHighPtLoose; + } + } + + inline virtual void muonQualityLoose(const std::string& quality) { + if (!m_configFixed) { + m_muonQualityLoose = quality; + } + } + + inline virtual void muonIsolation(const std::string& iso) { + if (!m_configFixed) { + m_muonIsolation = iso; + } + } + + inline virtual void muonIsolationLoose(const std::string& iso) { + if (!m_configFixed) { + m_muonIsolationLoose = iso; + } + } + + void muonIsolationSF(std::string const& iso) { + if (!m_configFixed) { + m_muonIsolationSF = iso; + } + } + + void muonIsolationSFLoose(std::string const& iso) { + if (!m_configFixed) { + m_muonIsolationSFLoose = iso; + } + } + + void muonMuonDoSmearing2stationHighPt(const bool& MuonDoSmearing2stationHighPt) { + if (!m_configFixed) { + m_muonMuonDoSmearing2stationHighPt = MuonDoSmearing2stationHighPt; + } + } + + void muonMuonDoExtraSmearingHighPt(const bool& MuonDoExtraSmearingHighPt) { + if (!m_configFixed) { + m_muonMuonDoExtraSmearingHighPt = MuonDoExtraSmearingHighPt; + } + } + + inline virtual float muonPtcut() const {return m_muonPtcut;} + inline virtual float muonEtacut() const {return m_muonEtacut;} + inline virtual const std::string& muonQuality() const {return m_muonQuality;} + inline virtual const std::string& muonQualityLoose() const {return m_muonQualityLoose;} + inline virtual bool muonUseMVALowPt() const {return m_muonUseMVALowPt;} + inline virtual bool muonUse2stationMuonsHighPt() const {return m_muonUse2stationMuonsHighPt;} + inline virtual bool muonUseMVALowPtLoose() const {return m_muonUseMVALowPtLoose;} + inline virtual bool muonUse2stationMuonsHighPtLoose() const {return m_muonUse2stationMuonsHighPtLoose;} + inline virtual const std::string& muonIsolation() const {return m_muonIsolation;} + inline virtual const std::string& muonIsolationLoose() const {return m_muonIsolationLoose;} + std::string const& muonIsolationSF() const {return m_muonIsolationSF;} + std::string const& muonIsolationSFLoose() const {return m_muonIsolationSFLoose;} + inline virtual bool muonMuonDoSmearing2stationHighPt() const {return m_muonMuonDoSmearing2stationHighPt;} + inline virtual bool muonMuonDoExtraSmearingHighPt() const {return m_muonMuonDoExtraSmearingHighPt;} + + // Soft Muon configuration + inline virtual void softmuonPtcut(const float pt) { + if (!m_configFixed) { + m_softmuonPtcut = pt; + } + } + + inline virtual void softmuonEtacut(const float eta) { + if (!m_configFixed) { + m_softmuonEtacut = eta; + } + } + + inline virtual void softmuonQuality(const std::string& quality) { + if (!m_configFixed) { + m_softmuonQuality = quality; + } + } + + void softmuonUseMVALowPt(const bool UseMVALowPtSoftMuon) { + if (!m_configFixed) { + m_softmuonUseMVALowPt = UseMVALowPtSoftMuon; + } + } + + inline virtual void softmuonDRJetcut(const float DRJet) { + if (!m_configFixed) { + m_softmuonDRJetcut = DRJet; + } + } + + inline virtual void softmuonDRJetcutUseRapidity(const bool in) { + if (!m_configFixed) { + m_softmuonDRJetcutUseRapidity = in; + } + } + + inline virtual void softmuonAdditionalTruthInfo(bool in) { + if (!m_configFixed) { + m_softmuonAdditionalTruthInfo=in; + } + } + + inline virtual void softmuonAdditionalTruthInfoCheckPartonOrigin(bool in) { + if (!m_configFixed) { + m_softmuonAdditionalTruthInfoCheckPartonOrigin=in; + } + } + + inline virtual void softmuonAdditionalTruthInfoDoVerbose(bool in) { + if (!m_configFixed) { + m_softmuonAdditionalTruthInfoDoVerbose=in; + } + } + + inline virtual float softmuonPtcut() const {return m_softmuonPtcut;} + inline virtual float softmuonEtacut() const {return m_softmuonEtacut;} + inline virtual const std::string& softmuonQuality() const {return m_softmuonQuality;} + inline virtual bool softmuonUseMVALowPt() const {return m_softmuonUseMVALowPt;} + inline virtual float softmuonDRJetcut() const {return m_softmuonDRJetcut;} + inline virtual bool softmuonDRJetcutUseRapidity() const {return m_softmuonDRJetcutUseRapidity;} + inline virtual bool softmuonAdditionalTruthInfo() const { return m_softmuonAdditionalTruthInfo;} + inline virtual bool softmuonAdditionalTruthInfoCheckPartonOrigin() const { return m_softmuonAdditionalTruthInfoCheckPartonOrigin;} + inline virtual bool softmuonAdditionalTruthInfoDoVerbose() const { return m_softmuonAdditionalTruthInfoDoVerbose;} + + // Jet configuration + inline virtual void jetPtcut(const float pt) { + if (!m_configFixed) { + m_jetPtcut = pt; + } + } + + inline virtual void jetEtacut(const float eta) { + if (!m_configFixed) { + m_jetEtacut = eta; + } + } + + inline virtual void jetPtGhostTracks(const float pt, const float small_jet_pt) { + if (!m_configFixed) { + if ( small_jet_pt >= pt+4999){ + m_jetPtGhostTracks = pt; + } + else { + m_jetPtGhostTracks = (small_jet_pt - 5000) > 20000 ? (small_jet_pt - 5000) : 20000; + } + } + } + + inline virtual void jetEtaGhostTracks(const float eta) { + if (!m_configFixed) { + m_jetEtaGhostTracks = eta; + } + } + + inline virtual void ghostTrackspT(const float pt) { + if (!m_configFixed) { + m_ghostTrackspT = pt; + } + } + + inline virtual void ghostTracksVertexAssociation(const std::string& vertexassociation) { + if (!m_configFixed) { + m_ghostTracksVertexAssociation = vertexassociation; + } + } + + inline virtual void ghostTracksQuality(const std::string& ghostTracksQuality) { + if (!m_configFixed) { + m_ghostTracksQuality = ghostTracksQuality; + } + } + + inline virtual float jetPtcut() const {return m_jetPtcut;} + inline virtual float jetEtacut() const {return m_jetEtacut;} + + inline virtual float ghostTrackspT() const {return m_ghostTrackspT;} + inline virtual const std::string& ghostTracksVertexAssociation() const {return m_ghostTracksVertexAssociation;} + inline virtual const std::string& ghostTracksQuality() const {return m_ghostTracksQuality;} + + inline virtual float jetPtGhostTracks() const {return m_jetPtGhostTracks;} + inline virtual float jetEtaGhostTracks() const {return m_jetEtaGhostTracks;} + + + inline virtual void largeRJetPtcut(const float pt) { + if (!m_configFixed) { + m_largeRJetPtcut = pt; + } + } + + inline virtual void largeRJetEtacut(const float eta) { + if (!m_configFixed) { + m_largeRJetEtacut = eta; + } + } + + inline virtual void largeRJetUncertainties_NPModel(const std::string& largeR_config) { + if (!m_configFixed) { + m_largeRJetUncertainties_NPModel = largeR_config; + } + } + + inline virtual void largeRJetUncertaintiesConfigDir(const std::string& largeRConfigDir) { + if (!m_configFixed) { + m_largeRJetUncertaintiesConfigDir = largeRConfigDir; + } + } + + inline virtual void largeRJESJMSConfig(const std::string& largeR_config) { + if (!m_configFixed) { + m_largeRJESJMSConfig = largeR_config; + } + } + + inline virtual float largeRJetPtcut() const {return m_largeRJetPtcut;} + inline virtual float largeRJetEtacut() const {return m_largeRJetEtacut;} + inline virtual const std::map<std::string,std::string> largeRJetSubstructureVariables() const {return m_largeRJetSubstructureVariables;} + inline virtual const std::string& largeRJetUncertainties_NPModel() const {return m_largeRJetUncertainties_NPModel;} + inline virtual const std::string& largeRJetUncertaintiesConfigDir() const {return m_largeRJetUncertaintiesConfigDir;} + inline virtual const std::string& largeRJESJMSConfig() const {return m_largeRJESJMSConfig;} + + inline virtual void trackJetPtcut(const float pt) { + if (!m_configFixed) { + m_trackJetPtcut = pt; + } + } + + inline virtual void trackJetEtacut(const float eta) { + if (!m_configFixed) { + m_trackJetEtacut = eta; + } + } + + inline virtual float trackJetPtcut() const {return m_trackJetPtcut;} + inline virtual float trackJetEtacut() const {return m_trackJetEtacut;} + + + inline virtual void trackPtcut(const float pt) { + if (!m_configFixed) { + m_trackPtcut = pt; + } + } + + inline virtual void trackEtacut(const float eta) { + if (!m_configFixed) { + m_trackEtacut = eta; + } + } + + inline virtual void trackQuality(const std::string& quality) { + if (!m_configFixed) { + m_trackQuality = quality; + } + } + + + inline virtual const std::string& trackQuality() const {return m_trackQuality;} + inline virtual float trackPtcut() const {return m_trackPtcut;} + inline virtual float trackEtacut() const {return m_trackEtacut;} + + + + + inline virtual float RCJetPtcut() const {return m_RCJetPtcut;} + inline virtual float RCJetEtacut() const {return m_RCJetEtacut;} + inline virtual float RCInputJetPtMin() const {return m_RCInputJetPtMin;} + inline virtual float RCInputJetEtaMax() const {return m_RCInputJetEtaMax;} + inline virtual float RCJetTrimcut() const {return m_RCJetTrimcut;} + inline virtual float RCJetRadius() const {return m_RCJetRadius;} + inline virtual bool useRCJetSubstructure() const {return m_useRCJetSubstructure;} + inline virtual bool useRCJetAdditionalSubstructure() const {return m_useRCJetAdditionalSubstructure;} + + inline virtual void RCJetPtcut(const float pt) { + if (!m_configFixed) { + m_RCJetPtcut = pt; + } + } + + inline virtual void RCJetEtacut(const float eta) { + if (!m_configFixed) { + m_RCJetEtacut = eta; + } + } + + inline virtual void RCInputJetPtMin(const float pt) { + if (!m_configFixed) { + m_RCInputJetPtMin = pt; + } + } + + inline virtual void RCInputJetEtaMax(const float eta) { + if (!m_configFixed) { + m_RCInputJetEtaMax = eta; + } + } + + inline virtual void RCJetTrimcut(const float trim) { + if (!m_configFixed) { + m_RCJetTrimcut = trim; + } + } + + inline virtual void RCJetRadius(const float radius) { + if (!m_configFixed) { + m_RCJetRadius = radius; + } + } + + inline virtual void useRCJetSubstructure(const bool use) { + if (!m_configFixed) { + m_useRCJetSubstructure = use; + } + } + + inline virtual void useRCJetAdditionalSubstructure(const bool use) { + if (!m_configFixed) { + m_useRCJetAdditionalSubstructure = use; + } + } + + inline virtual float VarRCJetPtcut() const {return m_VarRCJetPtcut;} + inline virtual float VarRCJetEtacut() const {return m_VarRCJetEtacut;} + inline virtual float VarRCJetTrimcut() const {return m_VarRCJetTrimcut;} + inline virtual float VarRCJetMaxRadius() const {return m_VarRCJetMaxRadius;} + inline virtual const std::string& VarRCJetRho() const {return m_VarRCJetRho;} + inline virtual const std::string& VarRCJetMassScale() const {return m_VarRCJetMassScale;} + inline virtual bool useVarRCJetSubstructure() const {return m_useVarRCJetSubstructure;} + inline virtual bool useVarRCJetAdditionalSubstructure() const {return m_useVarRCJetAdditionalSubstructure;} + + inline virtual void VarRCJetPtcut(const float pt) { + if (!m_configFixed) { + m_VarRCJetPtcut = pt; + } + } + + inline virtual void VarRCJetEtacut(const float eta) { + if (!m_configFixed) { + m_VarRCJetEtacut = eta; + } + } + + inline virtual void VarRCJetTrimcut(const float trim) { + if (!m_configFixed) { + m_VarRCJetTrimcut = trim; + } + } + + inline virtual void VarRCJetMaxRadius(const float radius) { + if (!m_configFixed) { + m_VarRCJetMaxRadius = radius; + } + } + + inline virtual void VarRCJetRho(const std::string& rho) { + if (!m_configFixed) { + m_VarRCJetRho = rho; + } + } + + inline virtual void VarRCJetMassScale(const std::string& mass_scale) { + if (!m_configFixed) { + m_VarRCJetMassScale = mass_scale; + } + } + + inline virtual void useVarRCJetSubstructure(const bool use) { + if (!m_configFixed) { + m_useVarRCJetSubstructure = use; + } + } + + inline virtual void useVarRCJetAdditionalSubstructure(const bool use) { + if (!m_configFixed) { + m_useVarRCJetAdditionalSubstructure = use; + } + } + + + virtual void jetUncertainties_NPModel(const std::string& s); + virtual void jetUncertainties_QGFracFile(const std::string& s); + virtual void jetUncertainties_QGHistPatterns(const std::string& s); + inline bool doMultipleJES() const {return m_doMultipleJES;} + inline virtual const std::string& jetUncertainties_NPModel() const {return m_jetUncertainties_NPModel;} + inline virtual const std::string& jetUncertainties_QGFracFile() const {return m_jetUncertainties_QGFracFile;} + inline virtual const std::vector<std::string>& jetUncertainties_QGHistPatterns() const { + return m_jetUncertainties_QGHistPatterns; + } + + inline virtual void jetJERSmearingModel(const std::string& s) { + if (!m_configFixed) { + m_jetJERSmearingModel = s; + } + } + + inline virtual const std::string& jetJERSmearingModel() const {return m_jetJERSmearingModel;} + + inline virtual void jetCalibSequence(const std::string& s) { + if (!m_configFixed) { + m_jetCalibSequence = s; + } + } + + inline virtual const std::string& jetCalibSequence() const {return m_jetCalibSequence;} + + inline virtual void jetStoreTruthLabels(bool b) { + if (!m_configFixed) { + m_jetStoreTruthLabels = b; + } + } + + inline virtual bool jetStoreTruthLabels() const {return m_jetStoreTruthLabels;} + + inline virtual void doJVTinMET(const bool& doJVT) { + if (!m_configFixed) { + m_doJVTInMETCalculation = doJVT; + } + } + + inline virtual bool doJVTinMET() const {return m_doJVTInMETCalculation;} + inline virtual void saveFailJVTJets(const bool& doJVT) { + if (!m_configFixed) { + m_saveFailJVTJets = doJVT; + } + } + + inline virtual bool saveFailJVTJets() const {return m_saveFailJVTJets;} + + inline const std::string& getJVTWP() const {return m_JVTWP;} + inline void setJVTWP(const std::string& value) {m_JVTWP = value;} + + inline virtual void doForwardJVTinMET(const bool& dofJVT) { + if (!m_configFixed) { + m_doForwardJVTInMETCalculation = dofJVT; + } + } + + inline virtual bool doForwardJVTinMET() const {return m_doForwardJVTInMETCalculation;} + inline virtual void saveFailForwardJVTJets(const bool& dofJVT) { + if (!m_configFixed) { + m_saveFailForwardJVTJets = dofJVT; + } + } + + inline virtual bool saveFailForwardJVTJets() const {return m_saveFailForwardJVTJets;} + + inline const std::string& getfJVTWP() const {return m_fJVTWP;} + inline void setfJVTWP(const std::string& value) {m_fJVTWP = value;} + + inline virtual float JSF() const {return m_JSF;} + inline virtual float bJSF() const {return m_bJSF;} + + // MET Configuration + inline virtual void METUncertaintiesConfigDir(const std::string& METConfigDir) { + if (!m_configFixed) { + m_METUncertaintiesConfigDir = METConfigDir; + } + } + inline virtual const std::string& METUncertaintiesConfigDir() const {return m_METUncertaintiesConfigDir;} + + // Tau configuration setters + inline virtual void tauPtcut(const float pt) { + if (!m_configFixed) { + m_tau_configuration.pt = pt; + m_tau_configuration_loose.pt = pt; + } + } + + inline virtual void tauEtaRegions(const std::string& etaRegions) { + if (!m_configFixed) { + m_tau_configuration.etaRegions = etaRegions; + m_tau_configuration_loose.etaRegions = etaRegions; + } + } + + inline virtual void tauJetIDWP(const std::string& s) { + if (!m_configFixed) m_tau_configuration.jetIDWP = s; + } + + inline virtual void tauJetIDWPLoose(const std::string& s) { + if (!m_configFixed) m_tau_configuration_loose.jetIDWP = s; + } + + inline virtual void tauEleBDTWP(const std::string& s) { + if (!m_configFixed) m_tau_configuration.eleBDTWP = s; + } + + inline virtual void tauEleBDTWPLoose(const std::string& s) { + if (!m_configFixed) m_tau_configuration_loose.eleBDTWP = s; + } + + inline virtual void tauEleOLR(bool do_tau_ele_olr) { + if (!m_configFixed) m_tau_configuration.eleOLR = do_tau_ele_olr; + } + + inline virtual void tauEleOLRLoose(bool do_tau_ele_olr) { + if (!m_configFixed) m_tau_configuration_loose.eleOLR = do_tau_ele_olr; + } + + inline virtual void tauSFDoRNNID(bool do_tau_rnn_id) { + if (!m_configFixed) m_tau_configuration.doRNNID = do_tau_rnn_id; + } + + inline virtual void tauSFDoBDTID(bool do_tau_bdt_id) { + if (!m_configFixed) m_tau_configuration.doBDTID = do_tau_bdt_id; + } + + inline virtual void tauJetConfigFile(const std::string& s) { + if (!m_configFixed) m_tau_configuration.fileName = s; + } -std::ostream& operator<<(std::ostream& os, const top::TopConfig& config); + inline virtual void tauJetConfigFileLoose(const std::string& s) { + if (!m_configFixed) m_tau_configuration_loose.fileName = s; + } + + inline virtual void tauSubstructureSF(bool do_tau_substructure_sf) { + if (!m_configFixed) m_tau_configuration.substructureSF = do_tau_substructure_sf; + } + + inline virtual void tauSubstructureSFLoose(bool do_tau_substructure_sf) { + if (!m_configFixed) m_tau_configuration_loose.substructureSF = do_tau_substructure_sf; + } + + // Tau configuration getters + inline virtual float tauPtcut() const { + return m_tau_configuration.pt; + } + + inline const std::string& tauEtaRegions() const { + return m_tau_configuration.etaRegions; + } + + inline const std::string& tauJetIDWP() const { + return m_tau_configuration.jetIDWP; + } + + inline const std::string& tauJetIDWPLoose() const { + return m_tau_configuration_loose.jetIDWP; + } + + inline const std::string& tauEleBDTWP() const { + return m_tau_configuration.eleBDTWP; + } + + inline const std::string& tauEleBDTWPLoose() const { + return m_tau_configuration_loose.eleBDTWP; + } + + inline virtual bool tauEleOLR() { + return m_tau_configuration.eleOLR; + } + + inline virtual bool tauEleOLRLoose() { + return m_tau_configuration_loose.eleOLR; + } + + inline const std::string& tauJetConfigFile() { + return m_tau_configuration.fileName; + } + + inline const std::string& tauJetConfigFileLoose() { + return m_tau_configuration_loose.fileName; + } + + inline virtual bool tauSubstructureSF() { + return m_tau_configuration.substructureSF; + } + + inline virtual bool tauSubstructureSFLoose() { + return m_tau_configuration_loose.substructureSF; + } + + // Applying new tau energy calibration + inline bool applyTauMVATES() { + return true; + } + + inline bool tauSFDoRNNID() const { + return m_tau_configuration.doRNNID; + } + + inline bool tauSFDoBDTID() const { + return m_tau_configuration.doBDTID; + } + + // photon getters + inline virtual float photonPtcut() const { + return m_photon_configuration.pt; + } + + inline virtual float photonEtacut() const { + return m_photon_configuration.eta; + } + + inline const std::string& photonIdentification() { + return m_photon_configuration.identification; + } + + inline const std::string& photonIdentificationLoose() { + return m_photon_configuration_loose.identification; + } + + inline const std::string& photonIsolation() { + return m_photon_configuration.isolation; + } + + inline const std::string& photonIsolationLoose() { + return m_photon_configuration_loose.isolation; + } + + // inline const std::string& tauJetID() const {return m_tauJetID;} + // inline const std::string& tauJetIDBkg() const {return m_tauJetIDBkg;} + // inline const std::string& tauEVetoID() const {return m_tauEVetoID;} + // inline virtual bool tauVetoLArCrack() const {return m_tauVetoLArCrack;} + // inline virtual float tauPtcut() const {return m_tauPtcut;} + + // [[[----------------------------------------------- + // Particle Level (Truth) configuration + + // electrons + inline virtual void truth_electron_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_electron.PtCut = pt; + } + } + + inline virtual void truth_electron_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_electron.EtaCut = eta; + } + } + + inline virtual float truth_electron_PtCut() const {return m_truth_electron.PtCut;} + inline virtual float truth_electron_EtaCut() const {return m_truth_electron.EtaCut;} + inline virtual bool truth_electron_NotFromHadron() const {return m_truth_electron.NotFromHadron;} + inline virtual bool truth_electron_TauIsHadron() const {return m_truth_electron.TauIsHadron;} + + // muons + inline virtual void truth_muon_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_muon.PtCut = pt; + } + } + + inline virtual void truth_muon_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_muon.EtaCut = eta; + } + } + + inline virtual float truth_muon_PtCut() const {return m_truth_muon.PtCut;} + inline virtual float truth_muon_EtaCut() const {return m_truth_muon.EtaCut;} + inline virtual bool truth_muon_NotFromHadron() const {return m_truth_muon.NotFromHadron;} + inline virtual bool truth_muon_TauIsHadron() const {return m_truth_muon.TauIsHadron;} + + // soft muons + inline virtual void truth_softmuon_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_softmuon.PtCut = pt; + } + } + + inline virtual void truth_softmuon_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_softmuon.EtaCut = eta; + } + } + + inline virtual float truth_softmuon_PtCut() const {return m_truth_softmuon.PtCut;} + inline virtual float truth_softmuon_EtaCut() const {return m_truth_softmuon.EtaCut;} + + // photons + inline virtual void truth_photon_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_photon.PtCut = pt; + } + } + + inline virtual void truth_photon_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_photon.EtaCut = eta; + } + } + + inline virtual void truth_photon_Origin(const std::string& value) { + if (!m_configFixed) { + m_truth_photon.Origin = value; + } + } + + inline virtual void truth_photon_Isolation(const std::string& value) { + if (!m_configFixed) { + m_truth_photon.Isolation = value; + } + } + + inline virtual float truth_photon_PtCut() const {return m_truth_photon.PtCut;} + inline virtual float truth_photon_EtaCut() const {return m_truth_photon.EtaCut;} + inline virtual const std::string& truth_photon_Origin() const {return m_truth_photon.Origin;} + inline virtual const std::string& truth_photon_Isolation() const {return m_truth_photon.Isolation;} + + // jets + inline virtual void truth_jet_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_jet.PtCut = pt; + } + } + + inline virtual void truth_jet_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_jet.EtaCut = eta; + } + } + + inline virtual float truth_jet_PtCut() const {return m_truth_jet.PtCut;} + inline virtual float truth_jet_EtaCut() const {return m_truth_jet.EtaCut;} + + // large R jets + inline virtual void truth_jet_largeR_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_largeRJet.PtCut = pt; + } + } + + inline virtual void truth_jet_largeR_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_largeRJet.EtaCut = eta; + } + } + + inline virtual float truth_jet_largeR_PtCut() const {return m_truth_largeRJet.PtCut;} + inline virtual float truth_jet_largeR_EtaCut() const {return m_truth_largeRJet.EtaCut;} + + inline virtual void truth_tau_PtCut(const float pt) { + if (!m_configFixed) { + m_truth_tau.PtCut = pt; + } + } + + inline virtual void truth_tau_EtaCut(const float eta) { + if (!m_configFixed) { + m_truth_tau.EtaCut = eta; + } + } + + inline virtual float truth_tau_PtCut() const {return m_truth_tau.PtCut;} + inline virtual float truth_tau_EtaCut() const {return m_truth_tau.EtaCut;} + + // -----------------------------------------------]]] + + /// HL LHC studies + inline virtual void HLLHC(const bool s) { + if (!m_configFixed) { + m_HLLHC = s; + } + } + + inline virtual bool HLLHC() const {return m_HLLHC;} + inline virtual void HLLHCFakes(const bool s) { + if (!m_configFixed) { + m_HLLHCFakes = s; + } + } + + inline virtual bool HLLHCFakes() const {return m_HLLHCFakes;} + + void setBTaggingSFSysts(std::string WP, const std::set<std::string>& btagging_SFs, bool isTrackJet = false); + + inline virtual std::set<std::string> btagging_namedSysts(std::string WP) const {return bTag_named_systs.at(WP);} + inline virtual unsigned int btagging_num_B_eigenvars(std::string WP) const {return bTag_eigen_B.at(WP);} + inline virtual unsigned int btagging_num_C_eigenvars(std::string WP) const {return bTag_eigen_C.at(WP);} + inline virtual unsigned int btagging_num_Light_eigenvars(std::string WP) const {return bTag_eigen_light.at(WP);} + + inline virtual std::set<std::string> trkjet_btagging_namedSysts(std::string WP) const {return bTag_named_systs_trkJet.at(WP);} + inline virtual unsigned int trkjet_btagging_num_B_eigenvars(std::string WP) const {return bTag_eigen_B_trkJet.at(WP);} + inline virtual unsigned int trkjet_btagging_num_C_eigenvars(std::string WP) const {return bTag_eigen_C_trkJet.at(WP);} + inline virtual unsigned int trkjet_btagging_num_Light_eigenvars(std::string WP) const {return bTag_eigen_light_trkJet.at(WP);} + + + const std::vector<std::pair<std::string, std::string> > boostedJetTaggers() const {return m_chosen_boostedJetTaggers;} + const std::unordered_map<std::string, std::string> boostedTaggerSFnames() const {return m_boostedTaggerSFnames;} + void setCalibBoostedJetTagger(const std::string& WP, const std::string& SFname); + // B-tagging WPs requested by user (updated to pair of strings to hold algorithm and WP) + const std::vector<std::pair<std::string, std::string> > bTagWP() const {return m_chosen_btaggingWP_caloJet;} + const std::vector<std::pair<std::string, std::string> > bTagWP_trkJet() const {return m_chosen_btaggingWP_trkJet;} + // parse b-tagging configuration from config file into a vector of pair <algorithm, WP> + void parse_bTagWPs(const std::string& btagWPsettingString, + std::vector<std::pair<std::string, std::string>>& btagWPlist, + const std::string& jetCollectionName); + // B-tagging systematics requested by user to be excluded from EV treatment, separated by semi-colons + const std::string bTagSystsExcludedFromEV() const {return m_bTagSystsExcludedFromEV;} + + // B-tagging WPs actually available, according to CDI file + // will be set in TopCPTools + void setBTagWP_available(std::string btagging_WP); + void setBTagWP_available_trkJet(std::string btagging_WP); + const std::vector<std::string>& bTagWP_available() const {return m_available_btaggingWP;} + const std::vector<std::string>& bTagWP_available_trkJet() const {return m_available_btaggingWP_trkJet;} + // B-tagging WPs actually calibrated, according to CDI file + // will be set in TopCPTools + void setBTagWP_calibrated(std::string btagging_WP); + void setBTagWP_calibrated_trkJet(std::string btagging_WP); + const std::vector<std::string>& bTagWP_calibrated() const {return m_calibrated_btaggingWP;} + const std::vector<std::string>& bTagWP_calibrated_trkJet() const {return m_calibrated_btaggingWP_trkJet;} + // B-tagging algorithms, e.g. DL1, DL1r, DL1rmu + // which of them can be initialized for the given CDI file + // used for e.g. storing algorithm discriminant in the event saver + void setBTagAlgo_available(std::string algo, std::string toolName); + void setBTagAlgo_available_trkJet(std::string algo, std::string toolName); + const std::set<std::string>& bTagAlgo_available() const {return m_available_btaggingAlgos;} + const std::set<std::string>& bTagAlgo_available_trkJet() const {return m_available_btaggingAlgos_trkJet;} + // since MV2c10 is the only non-DL1 b-tagger, we just expose a bool to check if MV2c10 is used or not + bool bTagAlgo_MV2c10_used() const {return m_MV2c10_algo_used;} + bool bTagAlgo_MV2c10_used_trkJet() const {return m_MV2c10_algo_used_trkJet;} + + const std::unordered_map<std::string, std::string>& bTagAlgo_selToolNames() const {return m_algo_selTools;} + const std::unordered_map<std::string, std::string>& bTagAlgo_selToolNames_trkJet() const {return m_algo_selTools_trkJet;} + + std::string FormatedWP(std::string raw_WP); + + bool printCDIpathWarning() const + {return m_cdi_path_warning;} + void setPrintCDIpathWarning(bool flag) + {m_cdi_path_warning = flag;} + const std::string bTaggingCDIPath() const + {return m_btagging_cdi_path;} + const std::string& bTaggingCalibration_B() const + {return m_btagging_calibration_B;}; + const std::string& bTaggingCalibration_C() const + {return m_btagging_calibration_C;}; + const std::string& bTaggingCalibration_Light() const + {return m_btagging_calibration_Light;}; + + // LHAPDF settings + + inline virtual std::vector<std::string> LHAPDFSets() {return m_lhapdf_options.pdf_set_names;} + inline virtual bool doLHAPDF() {return m_lhapdf_options.doLHAPDF;} + inline virtual std::string baseLHAPDF() {return m_lhapdf_options.baseLHAPDF;} + inline virtual bool doLHAPDFInNominalTrees() {return m_lhapdf_options.doLHAPDFInNominalTrees;} + inline virtual bool saveLHAPDFEvent() {return m_lhapdf_options.save_per_event;} + void addLHAPDFResult(const std::string& pdf_name, + std::vector<float> sum_of_weights); + + std::unordered_map<std::string, std::vector<float> >& getLHAPDFResults() {return m_lhapdf_options.pdf_results;}; + + + // Pileup Reweighting Settings + bool doPileupReweighting() {return m_pileup_reweighting.apply;}; + bool PileupUseGRLTool() {return m_pileup_reweighting.use_grl_tool;}; + + const std::vector<std::string>& PileupConfig() {return m_pileup_reweighting.config_files;}; + const std::vector<std::string>& PileupLumiCalc() {return m_pileup_reweighting.lumi_calc_files;}; + + bool PileupMuDependent() {return m_pileup_reweighting.mu_dependent;}; + + // Update for R21 + const std::vector<std::string>& PileupConfig_FS() {return m_pileup_reweighting.config_files_FS;}; + const std::vector<std::string>& PileupConfig_AF() {return m_pileup_reweighting.config_files_AF;}; + const std::vector<std::string>& PileupActualMu_FS() {return m_pileup_reweighting.actual_mu_FS;}; + const std::vector<std::string>& PileupActualMu_AF() {return m_pileup_reweighting.actual_mu_AF;}; + inline virtual float PileupDataTolerance() const {return m_pileup_reweighting.unrepresented_data_tol;}; + const std::vector<int>& PileupPeriodAssignments() const {return m_pileup_reweighting.periodAssignments;}; + + const std::vector<double>& PileUpCustomScaleFactors() {return m_pileup_reweighting.custom_SF;}; + + inline const std::string& muonTriggerSF() const {return m_muon_trigger_SF;} + + inline bool demandPriVtx() const {return m_demandPriVtx;} + + // Where the sum of event weights + // before derivation framework is kept + inline const std::string& sumOfEventWeightsMetaData() const {return m_sumOfEventWeightsMetaData;} + + // Object Selector Name + inline virtual void objectSelectionName(const std::string& s) { + if (!m_configFixed) { + m_objectSelectionName = s; + } + } + + inline virtual const std::string& objectSelectionName() const {return m_objectSelectionName;} + // Output Format + inline virtual void outputFormat(const std::string& s) { + if (!m_configFixed) { + m_outputFormat = s; + } + } + + inline virtual const std::string& outputFormat() const {return m_outputFormat;} + // Output Events + virtual void outputEvents(const std::string& s); + inline virtual const std::string& outputEvents() const {return m_outputEvents;} + inline bool saveOnlySelectedEvents() const {return m_saveOnlySelectedEvents;} + + // SetAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround + inline bool outputFileSetAutoFlushZero() const {return m_outputFileSetAutoFlushZero;} + // Better configurable settings for TTree memory optimisation (ANALYSISTO-44, ANALYSISTO-463) + inline int outputFileNEventAutoFlush() const {return m_outputFileNEventAutoFlush;} + inline int outputFileBasketSizePrimitive() const {return m_outputFileBasketSizePrimitive;} + inline int outputFileBasketSizeVector() const {return m_outputFileBasketSizeVector;} + + // Number of events to run on (only for testing) + inline virtual unsigned int numberOfEventsToRun() const {return m_numberOfEventsToRun;} + inline virtual void numberOfEventsToRun(const unsigned int& n_events) { + if (!m_configFixed) { + m_numberOfEventsToRun = n_events; + } + } + + // Number of events to skip (only for testing) + inline virtual unsigned int numberOfEventsToSkip() const {return m_numberOfEventsToSkip;} + inline virtual void numberOfEventsToSkip(const unsigned int& n_events) { + if (!m_configFixed) { + m_numberOfEventsToSkip = n_events; + } + } + + // systematics + inline virtual void systematics(const std::string& s) { + if (!m_configFixed) { + m_systematics = s; + } + } + + inline virtual const std::string& systematics() const {return m_systematics;} + + /// syst helper functions + bool isSystNominal(const std::string& syst) const; + bool isSystAll(const std::string& syst) const; + bool getSystematicsList(const std::string& syst, std::set<std::string>& systList) const; + bool contains(const std::set<std::string>& systList, const std::string& name) const; + + virtual void systematicsPhotons(const std::list<CP::SystematicSet>& syst); + virtual void systematicsElectrons(const std::list<CP::SystematicSet>& syst); + virtual void systematicsFwdElectrons(const std::list<CP::SystematicSet>& syst); + virtual void systematicsMuons(const std::list<CP::SystematicSet>& syst); + virtual void systematicsSoftMuons(const std::list<CP::SystematicSet>& syst); + virtual void systematicsTaus(const std::list<CP::SystematicSet>& syst); + virtual void systematicsJets(const std::list<CP::SystematicSet>& syst); + virtual void systematicsLargeRJets(const std::list<CP::SystematicSet>& syst); + virtual void systematicsTrackJets(const std::list<CP::SystematicSet>& syst); + virtual void systematicsTracks(const std::list<CP::SystematicSet>& syst); + virtual void systematicsMET(const std::list<CP::SystematicSet>& syst); + + virtual void systematicsJetGhostTrack(const std::list<CP::SystematicSet>& syst); + + inline virtual void jetSubstructureName(const std::string& s) { + if (!m_configFixed) { + m_jetSubstructureName = s; + } + } + + inline virtual const std::string& jetSubstructureName() const {return m_jetSubstructureName;} + + // Systematic hash values + inline std::size_t nominalHashValue() const {return m_nominalHashValue;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashPhotons() const {return m_systHashPhotons;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashElectrons() const {return m_systHashElectrons;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashFwdElectrons() const {return m_systHashFwdElectrons;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashMuons() const {return m_systHashMuons;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashSoftMuons() const {return m_systHashSoftMuons;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashTaus() const {return m_systHashTaus;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashJets() const {return m_systHashJets;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashAll() const {return m_systHashAll;} + inline std::shared_ptr<std::unordered_set<std::size_t> > systHashElectronInJetSubtraction() const {return m_systHash_electronInJetSubtraction;} + + // Systematic Maps + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapPhotons() const {return m_systMapPhotons;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapElectrons() const {return m_systMapElectrons;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapFwdElectrons() const {return m_systMapFwdElectrons;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapMuons() const {return m_systMapMuons;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapSoftMuons() const {return m_systMapSoftMuons;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapTaus() const {return m_systMapTaus;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapJets() const {return m_systMapJets;} + inline std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > systMapLargeRJets() const {return m_systMapLargeRJets;} + + // Systematic StoreGate key Maps + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapPhotons() const {return m_systSgKeyMapPhotons;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapElectrons() const {return m_systSgKeyMapElectrons;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapFwdElectrons() const {return m_systSgKeyMapFwdElectrons;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapMuons() const {return m_systSgKeyMapMuons;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapSoftMuons() const {return m_systSgKeyMapSoftMuons;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapTaus() const {return m_systSgKeyMapTaus;} + std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapJets(const bool useLooseLeptonJets) const; + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapLargeRJets() const {return m_systSgKeyMapLargeRJets;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapTrackJets() const {return m_systSgKeyMapTrackJets;} + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systSgKeyMapTracks() const {return m_systSgKeyMapTracks;} + + // TTree names + inline std::shared_ptr<std::unordered_map<std::size_t, std::string> > systAllTTreeNames() const {return m_systAllTTreeNames;} + const std::string& systematicName(const std::size_t hash) const; + // TTree index + unsigned int ttreeIndex(const std::size_t hash) const; + unsigned int ttreeIndexLoose(const std::size_t hash) const; + + AodMetaDataAccess& aodMetaData(); + AodMetaDataAccess const& aodMetaData() const {return *m_aodMetaData;} + + // Function to handle release series such that it can be cleaner to update in the future + void setReleaseSeries(); + inline int getReleaseSeries() const {return m_release_series;} + + // Create bootstrapping weights + inline bool saveBootstrapWeights() const {return m_saveBootstrapWeights;} + inline void setSaveBootstrapWeights(const bool value) {m_saveBootstrapWeights = value;} + inline int getNumberOfBootstrapReplicas() const {return m_BootstrapReplicas;} + inline void setNumberOfBootstrapReplicas(const int value) {m_BootstrapReplicas = value;} + + // Switch to use BadBatmanCleaning + inline bool useBadBatmanCleaning() const {return m_useBadBatmanCleaning;} + inline void setUseBadBatmanCleaning(const bool value) {m_useBadBatmanCleaning = value;} + inline unsigned int badBatmanCleaningMin() const {return m_badBatmanCleaningMin;} + inline void setBadBatmanCleaningMin(const unsigned int value) {m_badBatmanCleaningMin = value;} + inline unsigned int badBatmanCleaningMax() const {return m_badBatmanCleaningMax;} + inline void setBadBatmanCleaningMax(const unsigned int value) {m_badBatmanCleaningMax = value;} + + // Switch to use event-level jet cleaning tool for studies + inline bool useEventLevelJetCleaningTool() const {return m_useEventLevelJetCleaningTool;} + inline void setUseEventLevelJetCleaningTool(const bool value) {m_useEventLevelJetCleaningTool = value;} + + // Just a function that might need to be used in multiple places - return the running year (2015, 2016, 2017) + std::string getYear(unsigned int runnumber, const bool isMC); + + const std::string& getYear(){return m_year;} + void SetYear(const std::string& year){m_year = year;} + + void SetTriggersToYear(const bool isMC); + + // Setter and getter functions for recording whether we have configured the nominal objects + inline virtual void setNominalAvailable(const bool s) {m_isNominalAvailable = s;} + inline bool isNominalAvailable() const {return m_isNominalAvailable;} + + // Function to set the options for global trigger tool + void setGlobalTriggerConfiguration(std::vector<std::string>, std::vector<std::string>, std::vector<std::string>, std::vector<std::string>); + inline bool useGlobalTrigger() const {return m_trigGlobalConfiguration.isActivated;} // Was this requested by the + // user + inline auto const& getGlobalTriggers() const {return m_trigGlobalConfiguration.trigger;} + inline auto const& getGlobalTriggersLoose() const {return m_trigGlobalConfiguration.trigger_loose;} + inline bool useGlobalTriggerConfiguration() const {return m_trigGlobalConfiguration.isConfigured;} // Was this + // subsequently + // configured + inline std::vector<std::string> getGlobalTriggerElectronSystematics() const {return m_trigGlobalConfiguration.electron_trigger_systematics;} + inline std::vector<std::string> getGlobalTriggerMuonSystematics() const {return m_trigGlobalConfiguration.muon_trigger_systematics;} + inline std::vector<std::string> getGlobalTriggerElectronTools() const {return m_trigGlobalConfiguration.electron_trigger_tool_names;} + inline std::vector<std::string> getGlobalTriggerMuonTools() const {return m_trigGlobalConfiguration.muon_trigger_tool_names;} + + inline const TreeFilter* getTreeFilter() const { return m_treeFilter.get();} + + inline const std::unordered_map<std::string, std::string>& GetMCMCTranslator() const {return m_showerMCMCtranslator;} + + private: + // Prevent any more configuration + bool m_configFixed; + + // Make all CP Tools, or just the SF + bool m_makeAllCPTools; + + // GRL file + std::string m_grlDir; + std::vector<std::string> m_grlFile = {}; + + // TDP + std::string m_topDataPreparationPath; + + // Use which objects + bool m_usePhotons; + bool m_useElectrons; + bool m_useFwdElectrons; + bool m_useMuons; + bool m_useSoftMuons; + bool m_useAntiMuons; + bool m_useTaus; + bool m_useJets; + bool m_useLargeRJets; + bool m_useTrackJets; + bool m_useRCJets; + bool m_useVarRCJets; + + // Ghost Tracks on jets can not really be disabled because they are always + // available. However, we want the systematics to be executed automatically + // whenever the user has "configured" ghost tracks. + bool m_useJetGhostTrack; + + bool m_useTracks; + + // Are we using particle flow jets + // Need this as some things aren't supported at the moment + // C++11 so nice inline initialization (we should make this consistent) + bool m_useParticleFlowJets = false; + + bool m_useTruthParticles; + bool m_useTruthElectrons; + bool m_useTruthMuons; + bool m_useTruthPhotons; + bool m_useTruthJets; + bool m_useTruthLargeRJets; + bool m_useTruthTaus; + bool m_useTruthMET; + + // define if d0/z0 cut should be used at all + bool m_applyTTVACut; + + bool m_demandPriVtx; // whether at leas one primary vertex is required for each event + + std::string m_jetSubstructureName; + + // recompute CP vars? + bool m_recomputeCPvars; + + // Store in config a boolean which lets us know if we called the nominal object setup + bool m_isNominalAvailable; + + // Do systematics? - this needs many more configuration options + std::string m_systematics; + std::string m_nominalSystName; + std::string m_allSystName; + + unsigned int m_DSID; + unsigned int m_MapIndex; + SampleXsection::showering m_showeringAlgo; + bool m_is_sherpa_22_vjets = false; + + bool m_isMC; + bool m_isAFII; + std::vector<std::string> m_filterBranches, m_filterPartonLevelBranches, m_filterParticleLevelBranches, m_filterNominalLooseBranches; + std::string m_generators; + std::string m_AMITag; + bool m_isPrimaryxAOD; + bool m_isTruthDxAOD = false; + std::string m_derivationStream; + std::string m_amiTag; + int m_amiTagSet = 0; + + // Do fakes MM weights calculation? - only for data loose + bool m_doFakesMMWeightsIFF; + // Configurations for MM fake estimate + std::string m_FakesMMConfigIFF; + // Debug mode? + bool m_doFakesMMIFFDebug; + + //options to select if you want to use loose objects for MET rebuilding instead of the tight ones + bool m_useLooseObjectsInMETInLooseTree; + bool m_useLooseObjectsInMETInNominalTree; + //this will write a separate branch with the met built using loose objects + bool m_writeMETBuiltWithLooseObjects; + + // By default the top group does overlap removal on + // the tight lepton definitions. + // If you turn this to true you are going off piste and need to report + // your findings to the top reconstruction meeting. + bool m_doOverlapRemovalOnLooseLeptonDef; + + // String to describe which overlap removal procedure is used + // Current options are whether to use the ASG recommended + // overlap removal (recommended) + // procedure, or the one developed by the harmonization + // task force and use throughout 2015 (harmonized) + std::string m_overlap_removal_procedure = "recommended"; + + float m_overlapRemovalSlidingInnerDRel = 0.2; + float m_overlapRemovalSlidingInnerDRmu = 0.2; + + // do overlap removal also with large-R jets + // (using whatever procedure is used in the official tools) + bool m_doLargeJetOverlapRemoval; + + // Dumps the normal, non-"*_Loose" trees (on demand) + bool m_doTightEvents; + // Dumps the "*_Loose trees (on demand) + bool m_doLooseEvents; + + // Run systematics on the given selection + bool m_doTightSysts; + bool m_doLooseSysts; + + // In the *_Loose trees, lepton SFs are calculated considering + // tight ID and isolation instead of loose + // Only tight leptons are considered in the event SF calculation + bool m_applyTightSFsInLooseTree; + + // Apply Electron In Jet subtraction + // For boosted analysis + bool m_applyElectronInJetSubtraction; + + // Write Truth block info + bool m_doTruthBlockInfo; + + // Write Truth PDF info + bool m_doTruthPDFInfo; + bool m_doTruthPDFInfoInNominalTrees; + + // Write MC generator weights + bool m_doMCGeneratorWeights; + bool m_doMCGeneratorWeightsInNominalTrees; + + // list of names of nominal weight + // attempts to find nominal weight in the order as specified here + std::vector<std::string> m_nominalWeightNames; + std::string m_nominalWeightName; + size_t m_nominalWeightIndex; + size_t m_MCweightsSize; + bool m_forceWeightIndex; // to force useage of index instead of metadata + + // Top Parton History + bool m_doTopPartonHistory; + bool m_isTopPartonHistoryRegisteredInNtuple; + bool m_doTopPartonLevel; + + // Top Particle Level + bool m_doTopParticleLevel; + bool m_doParticleLevelOverlapRemovalMuJet; + bool m_doParticleLevelOverlapRemovalElJet; + bool m_doParticleLevelOverlapRemovalJetPhoton; + + // KLFitter + bool m_doKLFitter; + std::string m_KLFitterTransferFunctionsPath; + std::string m_KLFitterOutput; + std::string m_KLFitterJetSelectionMode; + std::string m_KLFitterBTaggingMethod; + std::string m_KLFitterLH; + bool m_KLFitterTopMassFixed; + bool m_KLFitterSaveAllPermutations; + bool m_KLFitterFailOnLessThanXJets; + + // PseudoTop + bool m_doPseudoTop; + + // StoreGate / TStore keys + std::string m_sgKeyDummy; + std::string m_sgKeyEventInfo; + std::string m_sgKeyPrimaryVertices; + std::string m_sgKeyPhotons; + std::string m_sgKeyElectrons; + std::string m_sgKeyFwdElectrons; + std::string m_sgKeyMuons; + std::string m_sgKeySoftMuons; + std::string m_sgKeyTaus; + std::string m_sgKeyJets; + std::string m_sgKeyJetsType; + std::string m_sgKeyLargeRJets; + std::string m_sgKeyTrackJets; + std::string m_sgKeyTrackJetsType; + + std::string m_sgKeyMissingEt; + std::string m_sgKeyMissingEtLoose; + + std::string m_sgKeyTruthEvent; + std::string m_sgKeyMCParticle; + std::string m_sgKeyTruthPhotons; + std::string m_sgKeyTruthElectrons; + std::string m_sgKeyTruthMuons; + std::string m_sgKeyTruthTaus; + std::string m_sgKeyTruthJets; + std::string m_sgKeyTruthLargeRJets; + std::string m_sgKeyTruthMET; + std::string m_sgKeyTopPartonHistory; + + std::string m_sgKeyTopSystematicEvents; + std::string m_sgKeyTopSystematicEventsLoose; + std::string m_passEventSelectionDecoration; + + std::string m_decoKeyJetGhostTrack; + std::vector<std::string> m_jetGhostTrackSystematics; + std::vector<std::uint32_t> m_jetGhostTrackRunPeriods; + + std::string m_sgKeyInDetTrackParticles; + std::string m_sgKeyTracks; + std::string m_sgKeyTracksType; + std::vector<std::uint32_t> m_trackRunPeriods; + + + + float m_jetResponseMatchingDeltaR; + + // special: allow to dump the systematics-shifted b-tagging SFs in the systematics trees + bool m_dumpBtagSystsInSystTrees; + + bool m_storePerJetBtagSFs; + + // Electron configuration + std::string m_egammaSystematicModel; + std::string m_electronEfficiencySystematicModel; + std::string m_electronEfficiencySystematicModelEtaBinning; + std::string m_electronEfficiencySystematicModelEtBinning; + std::string m_electronID; + std::string m_electronIDLoose; + bool m_electronVetoLArCrack; + float m_electronPtcut; + std::string m_electronIsolation; + std::string m_electronIsolationLoose; + std::string m_electronIsolationSF; + std::string m_electronIsolationSFLoose; + bool const m_electronIsoSFs; // no longer supported, always true (use m_electronIsolationSF instead) + int m_electron_d0SigCut; + float m_electron_delta_z0; + + std::string m_electronIDDecoration; + std::string m_electronIDLooseDecoration; + bool m_useElectronChargeIDSelection; + bool m_useEgammaLeakageCorrection; + bool m_enablePromptLeptonImprovedVetoStudies; + + //Fwd electron configuration + float m_fwdElectronPtcut; + float m_fwdElectronMinEtacut; + float m_fwdElectronMaxEtacut; + std::string m_fwdElectronID; + std::string m_fwdElectronIDLoose; + int m_fwdElectronBCIDCleaningMinRun; + int m_fwdElectronBCIDCleaningMaxRun; + + // Muon configuration + float m_muonPtcut; // muon object selection pT cut + float m_muonEtacut; // muon object selection (abs) eta cut + std::string m_muonQuality; // muon quality used in object selection + bool m_muonUseMVALowPt; //to turn on MVA for low-pT muons + bool m_muonUse2stationMuonsHighPt; //to allow muon reco with 2-station + std::string m_muonQualityLoose; // loose muon quality used in object selection + bool m_muonUseMVALowPtLoose; //to turn on MVA for low-pT muons (loose tree) + bool m_muonUse2stationMuonsHighPtLoose; //to allow muon reco with 2-station (loose tree) + std::string m_muonIsolation; + std::string m_muonIsolationLoose; + std::string m_muonIsolationSF; + std::string m_muonIsolationSFLoose; + int m_muon_d0SigCut; + float m_muon_delta_z0; + bool m_muonMuonDoSmearing2stationHighPt; //to turn on/off special correction for the reco with 2-station muons with missing inner MS station allowed for abs(eta)<1.3, only HighPt WP + bool m_muonMuonDoExtraSmearingHighPt; //to turn on/off a special correction for the muon with high momenta. + + //Soft muon configuration + float m_softmuonPtcut; // soft muon object selection pT cut + float m_softmuonEtacut; // soft muon object selection (abs) eta cut + std::string m_softmuonQuality; // soft muon quality used in object selection + bool m_softmuonUseMVALowPt; //to turn on MVA for low-pT muons + float m_softmuonDRJetcut; // soft muon object selection DR wrt jets cut + bool m_softmuonDRJetcutUseRapidity; // true -> use rapidity for DR(jet,mu) matching; false -> use pseudorapidity + bool m_softmuonAdditionalTruthInfo; //additional info on the particle-level origin of the muon, see TopParticleLevel/TruthTools.h + bool m_softmuonAdditionalTruthInfoCheckPartonOrigin; //additional info on the parton-level origin of the muon, see TopParticleLevel/TruthTools.h + bool m_softmuonAdditionalTruthInfoDoVerbose; //to help debugging the above options + + // Jet configuration + float m_jetPtcut; // jet object selection pT cut + float m_jetEtacut; // jet object selection (abs) eta cut + float m_jetPtGhostTracks; // jet pt threshold for ghost track systematic variations calculation + float m_jetEtaGhostTracks; // jet eta threshold for ghost track systematic variations calculation + std::string m_jetUncertainties_NPModel; // AllNuisanceParameters, 19NP or 3NP + std::string m_jetUncertainties_QGFracFile; // to improve Flavour composition and response + std::vector<std::string> m_jetUncertainties_QGHistPatterns; // to improve Flavour composition and response, with + // more flexibility + bool m_doMultipleJES; + std::string m_jetJERSmearingModel; // Full or Simple + std::string m_jetCalibSequence; // GCC or JMS + bool m_jetStoreTruthLabels; // True or False + bool m_doJVTInMETCalculation; + bool m_saveFailJVTJets; + std::string m_JVTWP; + bool m_doForwardJVTInMETCalculation; + bool m_saveFailForwardJVTJets; + std::string m_fJVTWP; + + // MET configuration + std::string m_METUncertaintiesConfigDir; //Path prefix for directory with MET calibration configs + + //Ghost tracks quality + float m_ghostTrackspT; + std::string m_ghostTracksVertexAssociation; + std::string m_ghostTracksQuality; + + // Large R jet configuration + float m_largeRJetPtcut; // large R jet object selection pT cut + float m_largeRJetEtacut; // large R jet object selection (abs) eta cut + std::map<std::string,std::string> m_largeRJetSubstructureVariables; + std::string m_largeRJetUncertainties_NPModel; //large R JES/(plus old JMS, JMR, JER) uncertainties configuration + std::string m_largeRJetUncertaintiesConfigDir; //Relative path to directory with large R JES config + // file + //See https://twiki.cern.ch/twiki/bin/view/AtlasProtected/JetUncertaintiesRel21Summer2019LargeR + std::string m_largeRJESJMSConfig; // large R jet JES/JMS calibration choice - see ANALYSISTO-210 + + // Track jet configuration + float m_trackJetPtcut; // track jet object selection pT cut + float m_trackJetEtacut; // track jet object selection (abs) eta cut + + // Tracks + float m_trackPtcut; // track object selection pT cut + float m_trackEtacut; // track object selection (abs) eta cut + + // Jet configuration for reclustered jets + float m_RCJetPtcut; + float m_RCJetEtacut; + float m_RCInputJetPtMin; + float m_RCInputJetEtaMax; + float m_RCJetTrimcut; + float m_RCJetRadius; + bool m_useRCJetSubstructure; + bool m_useRCJetAdditionalSubstructure; + + // Jet configuration for variable large-R jets + float m_VarRCJetPtcut; + float m_VarRCJetEtacut; + float m_VarRCJetTrimcut; + float m_VarRCJetMaxRadius; + std::string m_VarRCJetRho; + std::string m_VarRCJetMassScale; + bool m_useVarRCJetSubstructure; + bool m_useVarRCJetAdditionalSubstructure; + + std::string m_trackQuality; // track quality to be used in track selection + + // these are needed for the top mass analysis, per default should be 1.0 + float m_JSF; + float m_bJSF; + + // Tau configuration + struct { + // filename to load tau configuration from. + // If this is an empty string then take the 'default' + std::string fileName = "Default"; + // The jetIDWP in CamelCase + // see + // https://svnweb.cern.ch/trac/atlasoff/browser/PhysicsAnalysis/TauID/TauAnalysisTools/trunk/doc/README-TauSelectionTool.rst + // for supported WPs + std::string jetIDWP = "RNNMedium"; + bool doRNNID = true; + bool doBDTID = false; + // the electron BDTWP + std::string eleBDTWP = "Medium"; + bool substructureSF = false; + // Whether to perform electron overlap removal + bool eleOLR = false; + // pT cut on taus + float pt = 20000; + std::string etaRegions="[0., 1.37, 1.52, 2.5]"; + } m_tau_configuration, m_tau_configuration_loose; + + // photon configuration + struct { + // pT cut on photons + float pt = 25000; + float eta = 2.5; + std::string isolation = "None"; + std::string identification = "None"; + } m_photon_configuration, m_photon_configuration_loose; + + // [[[----------------------------------------------- + // Particle Level (truth) configuration + + // electrons + struct { + float PtCut; // [ParticleLevel / Truth] Electron Object + // Selection minimum pT Cut (Standard ATLAS + // units, [MeV]). + float EtaCut; // [ParticleLevel / Truth] Electron Object + // Selection maximum absolute eta Cut. + bool NotFromHadron; // [ParticleLevel / Truth] Whether to apply the + // 'NotFromHadron' requirement onto the objects. + bool TauIsHadron; // [ParticleLevel / Truth] Whether a tauon is a + // hadron during the 'NotFromHadron' check + } m_truth_electron; + + // muons + struct { + float PtCut; // [ParticleLevel / Truth] Muon Object + // Selection minimum pT Cut (Standard ATLAS + // units, [MeV]). + float EtaCut; // [ParticleLevel / Truth] Muon Object + // Selection maximum absolute eta Cut. + bool NotFromHadron; // [ParticleLevel / Truth] Whether to apply the + // 'NotFromHadron' requirement onto the objects. + bool TauIsHadron; // [ParticleLevel / Truth] Whether a tauon is a + // hadron during the 'NotFromHadron' check + } m_truth_muon; + + // soft muons + struct { + float PtCut; // [ParticleLevel / Truth] Muon Object + // Selection minimum pT Cut (Standard ATLAS + // units, [MeV]). + float EtaCut; // [ParticleLevel / Truth] Muon Object + // Selection maximum absolute eta Cut. + } m_truth_softmuon; + + // photons + struct { + float PtCut; // [ParticleLevel / Truth] Photon Object + // Selection minimum pT Cut (Standard ATLAS + // units, [MeV]). + float EtaCut; // [ParticleLevel / Truth] Photon Object + // Selection maximum absolute eta Cut. + std::string Origin; // [ParticleLevel / Truth] Photon Object + // Selection truth origin configuration. + std::string Isolation; // [ParticleLevel / Truth] Photon Object + // Selection truth isolation configuration. + } m_truth_photon; + + // taus + struct { + float PtCut; // [ParticleLevel / Truth] Tau Object + // Selection minimum pT Cut (Standard ATLAS + // units, [MeV]). + float EtaCut; // [ParticleLevel / Truth] Tau Object + // Selection maximum absolute eta Cut. + } m_truth_tau; + + // normal / large R jets + struct { + float PtCut; // [ParticleLevel / Truth] Jet Object + // Selection minimum pT Cut (Standard ATLAS + // units, [MeV]). + float EtaCut; // [ParticleLevel / Truth] Jet Object + // Selection maximum absolute eta Cut. + } m_truth_jet, m_truth_largeRJet; + + + // -----------------------------------------------]]] + + // Options for upgrade studies + bool m_HLLHC; + bool m_HLLHCFakes; + + // Boosted jet taggers requested by user + std::vector<std::pair<std::string, std::string> > m_chosen_boostedJetTaggers; + std::unordered_map<std::string, std::string> m_boostedTaggerSFnames; + + // B-tagging WPs requested by the user (updated to pair of string to hold algorithm and WP) + std::vector<std::pair<std::string, std::string> > m_chosen_btaggingWP; + std::vector<std::pair<std::string, std::string> > m_chosen_btaggingWP_caloJet; + std::vector<std::pair<std::string, std::string> > m_chosen_btaggingWP_trkJet; + // B-tagging systematics requested by user to be excluded from EV treatment, separated by semi-colons + std::string m_bTagSystsExcludedFromEV = ""; + + // list of B-tagging WP actualy available + std::vector<std::string> m_available_btaggingWP; + std::vector<std::string> m_available_btaggingWP_trkJet; + // list of B-tagging WP actualy calibrated + std::vector<std::string> m_calibrated_btaggingWP; + std::vector<std::string> m_calibrated_btaggingWP_trkJet; + // list of B-tagging algorithms requested + std::set<std::string> m_available_btaggingAlgos; + std::set<std::string> m_available_btaggingAlgos_trkJet; + bool m_MV2c10_algo_used = false; + bool m_MV2c10_algo_used_trkJet = false; + + std::unordered_map<std::string, std::string> m_algo_selTools; + std::unordered_map<std::string, std::string> m_algo_selTools_trkJet; + + // B-tagging calibration to be used + bool m_cdi_path_warning = false; + std::string m_btagging_cdi_path = "Default"; + std::string m_btagging_calibration_B = "default"; + std::string m_btagging_calibration_C = "default"; + std::string m_btagging_calibration_Light = "default"; + + // b-tag SF helpers - one of each per WP + // will be set in the BTagScaleFactorCalculator + // These are the base names of the SF systematics (without __up/__down) + std::unordered_map<std::string, std::set<std::string> > bTag_base_names; + std::unordered_map<std::string, std::set<std::string> > bTag_base_names_trkJet; + // and those of them which are not eigenvectors + std::unordered_map<std::string, std::set<std::string> > bTag_named_systs; + std::unordered_map<std::string, std::set<std::string> > bTag_named_systs_trkJet; + // how many B eigen-variations do we have? + std::unordered_map<std::string, unsigned int> bTag_eigen_B; + std::unordered_map<std::string, unsigned int> bTag_eigen_B_trkJet; + // how many C eigen-variations do we have? + std::unordered_map<std::string, unsigned int> bTag_eigen_C; + std::unordered_map<std::string, unsigned int> bTag_eigen_C_trkJet; + // how many Light eigen-variations do we have? + std::unordered_map<std::string, unsigned int> bTag_eigen_light; + std::unordered_map<std::string, unsigned int> bTag_eigen_light_trkJet; + + // LHAPDF options + struct { + std::vector<std::string> pdf_set_names = {}; + std::string baseLHAPDF = ""; // used only if XF1*XF2==0 + + // options + bool doLHAPDF = false; + bool doLHAPDFInNominalTrees = false; + + bool save_per_event = false; + + // we pass the results back to config in PDFScaleFactor::finalize + std::unordered_map< std::string, std::vector<float> > pdf_results; + } m_lhapdf_options; + + // Pile-up reweighting + struct { + std::vector<std::string> lumi_calc_files = {}; + + std::vector<std::string> config_files = {}; + + // R21 - Need to allow configuration for FS and AF2 + std::vector<std::string> config_files_FS = {}; + std::vector<std::string> config_files_AF = {}; + std::vector<std::string> actual_mu_FS = {}; + std::vector<std::string> actual_mu_AF = {}; + float unrepresented_data_tol = 0.05; + + bool apply = false; + + bool use_grl_tool = false; + + // Whether or not to perform mu dependent + // pile-up reweighting. Optional because can + // result in a possible loss of statistics + // that are crucial for things like MVA training. + bool mu_dependent = true; + + std::vector<double> custom_SF = {}; + + std::vector<int> periodAssignments = {}; + } m_pileup_reweighting; + + // Struct for holding TrigGlobalEfficiencyCorrectionTool settings in order to + // manage systematic variations through this tool + + struct { + typedef std::unordered_map<std::string, std::vector<std::string> > triggermap_t; + // -- Set from cutfile --// + // Boolean to be set to true if the user activates a flag + bool isActivated = false; + // Maps of periods -> list of triggers + triggermap_t trigger; + triggermap_t trigger_loose; + + // -- Set from TopCPTools --// + // Boolean to be set to true if we set this information + bool isConfigured = false; + // Names of CP::SystematicSet from electron trigger tools + std::vector<std::string> electron_trigger_systematics; + // Names of CP::SystematicSet from muon trigger tools + std::vector<std::string> muon_trigger_systematics; + // Name of the underlying electron tools, to be accessed and passes CP::SystematicSet + std::vector<std::string> electron_trigger_tool_names; + // Name of the underlying muon tools, to be accessed and passes CP::SystematicSet + std::vector<std::string> muon_trigger_tool_names; + } m_trigGlobalConfiguration; + + // Muon Trigger SF configuration + std::string m_muon_trigger_SF; + + + // Selections + std::shared_ptr<std::vector<std::string> > m_allSelectionNames; + // Trigger configuration + // First string is the selection name, second string is the trigger + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_allTriggers_Tight; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_electronTriggers_Tight; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_muonTriggers_Tight; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_tauTriggers_Tight; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_allTriggers_Loose; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_electronTriggers_Loose; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_muonTriggers_Loose; + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > m_tauTriggers_Loose; + std::vector<std::string> m_dummyTrigger; + + // Where the sum of event weights + // before derivation framework is kept + std::string m_sumOfEventWeightsMetaData; + + // Object Selector name + std::string m_objectSelectionName; + // Output Format + std::string m_outputFormat; + // Output Events + std::string m_outputEvents; + bool m_saveOnlySelectedEvents; + // SetAutoFlush(0) on EventSaverFlatNtuple for ANALYSISTO-44 workaround + bool m_outputFileSetAutoFlushZero; + // Better configurable settings for TTree memory optimisation (ANALYSISTO-44, ANALYSISTO-463) + int m_outputFileNEventAutoFlush; + int m_outputFileBasketSizePrimitive; + int m_outputFileBasketSizeVector; + // Number of events to run on (for testing) + unsigned int m_numberOfEventsToRun; + + // Number of events to skip (for testing) + unsigned int m_numberOfEventsToSkip; + + // AOD meta-data access service + AodMetaDataAccess* m_aodMetaData; + + // Systematics + std::size_t m_nominalHashValue; + + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashPhotons; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashElectrons; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashFwdElectrons; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashMuons; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashSoftMuons; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashTaus; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashJets; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashLargeRJets; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashTrackJets; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashTracks; + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashMET; + + std::shared_ptr<std::unordered_set<std::size_t> > m_systHashAll; + std::shared_ptr<std::list<std::size_t> > m_list_systHashAll; + + std::shared_ptr<std::unordered_set<std::size_t> > m_systHash_electronInJetSubtraction; + std::shared_ptr<std::list<std::size_t> > m_list_systHash_electronInJetSubtraction; + + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapPhotons; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapElectrons; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapFwdElectrons; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapMuons; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapSoftMuons; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapTaus; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapJets; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapLargeRJets; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapTrackJets; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapTracks; + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapMET; + + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapPhotons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapElectrons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapFwdElectrons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapMuons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapSoftMuons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapTaus; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapJets; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapJets_electronInJetSubtraction; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapJetsLoose_electronInJetSubtraction; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapLargeRJets; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapTrackJets; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapTracks; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapMET; + + // For TopEvent/SingleSystEvent - will return the nominal key if not under variation + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapPhotons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapElectrons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapFwdElectrons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapMuons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapSoftMuons; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTaus; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJets; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapLargeRJets; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTrackJets; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTracks; + + // The boosted case is a bit more complex, we need additional collections + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapElectrons_electronInJetSubtraction; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJets_electronInJetSubtraction; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJetsLoose_electronInJetSubtraction; + + // For top::TopEventMaker + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapPhotonsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapPhotonsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapElectronsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapElectronsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapFwdElectronsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapFwdElectronsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapMuonsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapMuonsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapSoftMuonsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapSoftMuonsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTausTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTausTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJetsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJetsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapLargeRJetsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapLargeRJetsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTrackJetsTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTrackJetsTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTracksTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapTracksTDSAux; + + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapElectrons_electronInJetSubtractionTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapElectrons_electronInJetSubtractionTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJets_electronInJetSubtractionTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJets_electronInJetSubtractionTDSAux; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDS; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllSgKeyMapJetsLoose_electronInJetSubtractionTDSAux; + + // Missing ET + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapMissingET; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapMissingETLoose; + + // KLFitter + std::string m_sgKeyKLFitter; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapKLFitter; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapKLFitterLoose; + + // PseudoTop + std::string m_sgKeyPseudoTop; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapPseudoTop; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systSgKeyMapPseudoTopLoose; + + // Map from systematic hash to CP::SystematicSet + std::shared_ptr<std::unordered_map<std::size_t, CP::SystematicSet> > m_systMapJetGhostTrack; + // Map from systematic hash to decoration key. + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systDecoKeyMapJetGhostTrack; + + // Output TTree names + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systAllTTreeNames; + std::shared_ptr<std::unordered_map<std::size_t, std::string> > m_systPersistantAllTTreeNames; + // Output TTree index + std::shared_ptr<std::unordered_map<std::size_t, unsigned int> > m_systAllTTreeIndex; + std::shared_ptr<std::unordered_map<std::size_t, unsigned int> > m_systAllTTreeLooseIndex; + + // Private function only to simplify the setting of AFII values + void ReadIsAFII(top::ConfigurationSettings* const& settings); + + // Int holding the release series value + int m_release_series; + + // Bool to hold whether we generate and store poisson bootstrap weights + bool m_saveBootstrapWeights; + int m_BootstrapReplicas; + + // Switch to use BadBatmanCleaning + bool m_useBadBatmanCleaning; + unsigned int m_badBatmanCleaningMin; + unsigned int m_badBatmanCleaningMax; + + // Switch to use event-level jet cleaning tool for testing + bool m_useEventLevelJetCleaningTool; + + std::shared_ptr<TreeFilter> m_treeFilter; + + std::unordered_map<std::string, std::string> m_showerMCMCtranslator; + + std::string m_year; + + //ReadFloatOption + float readFloatOption(top::ConfigurationSettings* const& settings, std::string in) const; + }; + + std::ostream& operator << (std::ostream& os, const TopConfig& config); +} // namespace top #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopPersistentSettings.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopPersistentSettings.h index 20d1f3d03d5a9601785ab8216fb1f24053291bd6..ed72fa8a0d4f54e7ce514948ce217870da953f6a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopPersistentSettings.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TopPersistentSettings.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPCONFIGURATION_TOPPERSISTENTSETTINGS_H #define ANALYSISTOP_TOPCONFIGURATION_TOPPERSISTENTSETTINGS_H @@ -9,11 +9,11 @@ * @author John Morris <john.morris@cern.ch> * * @brief TopPersistentSettings - * We presist this information into the mini-xAOD + * We presist this information into the mini-xAOD * It allows us to reconstruct the state of the top-xaod code * - * $Revision: 790409 $ - * $Date: 2016-12-19 01:46:29 +0100 (Mon, 19 Dec 2016) $ + * $Revision: 809568 $ + * $Date: 2017-08-18 14:09:22 +0100 (Fri, 18 Aug 2017) $ * * **/ @@ -23,78 +23,99 @@ #include <vector> #include <map> #include <unordered_map> +#include <utility> -namespace top{ - class TopPersistentSettings{ - public: - TopPersistentSettings(); - virtual ~TopPersistentSettings(){} - - bool m_isMC; - bool m_isAFII; - bool m_applyElectronInJetSubtraction; - bool m_doOverlapRemovalOnLooseLeptonDef; - bool m_doKLFitter; - bool m_doPseudoTop; - - std::string m_sgKeyTopSystematicEvents; - std::string m_sgKeyTopSystematicEventsLoose; - - std::string m_sgKeyEventInfo; - std::string m_sgKeyPrimaryVertices; - std::string m_sgKeyPhotons; - std::string m_sgKeyElectrons; - std::string m_sgKeyMuons; - std::string m_sgKeyTaus; - std::string m_sgKeyJets; - std::string m_sgKeyLargeRJets; - std::string m_sgKeyTrackJets; - std::string m_sgKeyMissingEt; - std::string m_sgKeyMissingEtLoose; - - std::string m_electronID; - std::string m_electronIDLoose; - std::string m_electronIsolation; - std::string m_electronIsolationLoose; - - std::string m_muon_trigger_SF; - std::string m_muonQuality; - std::string m_muonQualityLoose; - std::string m_muonIsolation; - std::string m_muonIsolationLoose; - - std::vector<std::string> m_chosen_btaggingWP; - - std::map<std::size_t,std::string> m_systSgKeyMapPhotons; - std::map<std::size_t,std::string> m_systSgKeyMapElectrons; - std::map<std::size_t,std::string> m_systSgKeyMapMuons; - std::map<std::size_t,std::string> m_systSgKeyMapTaus; - std::map<std::size_t,std::string> m_systSgKeyMapJets; - std::map<std::size_t,std::string> m_systSgKeyMapJets_electronInJetSubtraction; - std::map<std::size_t,std::string> m_systSgKeyMapJetsLoose_electronInJetSubtraction; - std::map<std::size_t,std::string> m_systSgKeyMapLargeRJets; - std::map<std::size_t,std::string> m_systSgKeyMapTrackJets; - std::map<std::size_t,std::string> m_systSgKeyMapMissingET; - std::map<std::size_t,std::string> m_systSgKeyMapMissingETLoose; - std::map<std::size_t,std::string> m_systSgKeyMapKLFitter; - std::map<std::size_t,std::string> m_systSgKeyMapKLFitterLoose; - std::map<std::size_t,std::string> m_systSgKeyMapPseudoTop; - std::map<std::size_t,std::string> m_systPersistantAllTTreeNames; - - std::map<std::size_t,std::string> m_systDecoKeyMapJetGhostTrack; - - std::vector<std::size_t> m_list_systHashAll; - std::vector<std::size_t> m_list_systHash_electronInJetSubtraction; - - std::vector<std::string> m_allSelectionNames; - - std::unordered_map<std::string, std::vector<std::string> > m_allTriggers; - std::unordered_map<std::string, std::vector<std::string> > m_electronTriggers; - std::unordered_map<std::string, std::vector<std::string> > m_muonTriggers; - std::unordered_map<std::string, std::vector<std::string> > m_tauTriggers; +namespace top { + class TopPersistentSettings { + public: + TopPersistentSettings(); + virtual ~TopPersistentSettings() {} + + bool m_isMC; + bool m_isAFII; + bool m_applyElectronInJetSubtraction; + bool m_doOverlapRemovalOnLooseLeptonDef; + bool m_doKLFitter; + bool m_doPseudoTop; + + std::string m_sgKeyTopSystematicEvents; + std::string m_sgKeyTopSystematicEventsLoose; + + std::string m_sgKeyEventInfo; + std::string m_sgKeyPrimaryVertices; + std::string m_sgKeyPhotons; + std::string m_sgKeyElectrons; + std::string m_sgKeyFwdElectrons; + std::string m_sgKeyMuons; + std::string m_sgKeySoftMuons; + std::string m_sgKeyTaus; + std::string m_sgKeyJets; + std::string m_sgKeyLargeRJets; + std::string m_sgKeyTrackJets; + std::string m_sgKeyTracks; + std::string m_sgKeyMissingEt; + std::string m_sgKeyMissingEtLoose; + + std::string m_electronID; + std::string m_electronIDLoose; + std::string m_electronIsolation; + std::string m_electronIsolationLoose; + bool m_useElectronChargeIDSelection; + bool m_useEgammaLeakageCorrection; + bool m_enablePromptLeptonImprovedVetoStudies; + + std::string m_fwdElectronID; + + std::string m_muon_trigger_SF; + std::string m_muonQuality; + std::string m_muonQualityLoose; + std::string m_muonIsolation; + std::string m_muonIsolationLoose; + + std::string m_softmuonQuality; + + std::string m_trackQuality; + + std::vector<std::pair<std::string, std::string> > m_chosen_btaggingWP; + + std::map<std::size_t, std::string> m_systSgKeyMapPhotons; + std::map<std::size_t, std::string> m_systSgKeyMapElectrons; + std::map<std::size_t, std::string> m_systSgKeyMapFwdElectrons; + std::map<std::size_t, std::string> m_systSgKeyMapMuons; + std::map<std::size_t, std::string> m_systSgKeyMapSoftMuons; + std::map<std::size_t, std::string> m_systSgKeyMapTaus; + std::map<std::size_t, std::string> m_systSgKeyMapJets; + std::map<std::size_t, std::string> m_systSgKeyMapJets_electronInJetSubtraction; + std::map<std::size_t, std::string> m_systSgKeyMapJetsLoose_electronInJetSubtraction; + std::map<std::size_t, std::string> m_systSgKeyMapLargeRJets; + std::map<std::size_t, std::string> m_systSgKeyMapTrackJets; + std::map<std::size_t, std::string> m_systSgKeyMapMissingET; + std::map<std::size_t, std::string> m_systSgKeyMapMissingETLoose; + std::map<std::size_t, std::string> m_systSgKeyMapKLFitter; + std::map<std::size_t, std::string> m_systSgKeyMapKLFitterLoose; + std::map<std::size_t, std::string> m_systSgKeyMapPseudoTop; + std::map<std::size_t, std::string> m_systSgKeyMapPseudoTopLoose; + std::map<std::size_t, std::string> m_systPersistantAllTTreeNames; + + std::map<std::size_t, std::string> m_systDecoKeyMapJetGhostTrack; + std::map<std::size_t, std::string> m_systSgKeyMapTracks; + + std::vector<std::size_t> m_list_systHashAll; + std::vector<std::size_t> m_list_systHash_electronInJetSubtraction; + + std::vector<std::string> m_allSelectionNames; + + std::unordered_map<std::string, std::vector<std::string> > m_allTriggers_Tight; + std::unordered_map<std::string, std::vector<std::string> > m_electronTriggers_Tight; + std::unordered_map<std::string, std::vector<std::string> > m_muonTriggers_Tight; + std::unordered_map<std::string, std::vector<std::string> > m_tauTriggers_Tight; + + std::unordered_map<std::string, std::vector<std::string> > m_allTriggers_Loose; + std::unordered_map<std::string, std::vector<std::string> > m_electronTriggers_Loose; + std::unordered_map<std::string, std::vector<std::string> > m_muonTriggers_Loose; + std::unordered_map<std::string, std::vector<std::string> > m_tauTriggers_Loose; }; } // Dictonaries -CLASS_DEF( top::TopPersistentSettings , 117063636 , 1 ) +CLASS_DEF(top::TopPersistentSettings, 117063636, 1) #endif - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TreeFilter.h b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TreeFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..cfd3e0607ccdfef79ba6163312d68e3f28e9f158 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopConfiguration/TopConfiguration/TreeFilter.h @@ -0,0 +1,28 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPCONFIGURATION_TREEFILTER_H +#define ANALYSISTOP_TOPCONFIGURATION_TREEFILTER_H + +#include <string> +#include <vector> + +namespace top { + + class TreeFilter { + private: + std::vector<std::string> m_vecFilters; + + public: + TreeFilter(); + TreeFilter(const std::string& longstring); + void init(const std::string& longstring); + bool filterTree(const std::string& treename) const; + + }; + +} + + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/CMakeLists.txt index db669697fa291a4e9a5b043e90d55fc88da8a18b..9b933124d83e407b7a7a27f2c48fdf6b60c53218 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/CMakeLists.txt @@ -1,7 +1,5 @@ -# Auto-generated on: 2017-03-08 14:47:35.652165 - # Declare the name of this package: -atlas_subdir( TopCorrections None ) +atlas_subdir( TopCorrections ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC @@ -10,37 +8,47 @@ atlas_depends_on_subdirs( PUBLIC TopEvent PileupReweighting ElectronEfficiencyCorrection - MuonEfficiencyCorrections - xAODBTaggingEfficiency TauAnalysisTools JetJvtEfficiency PhotonEfficiencyCorrection - PMGTools ) + PMGTools + PATInterfaces + FTagAnalysisInterfaces + MuonAnalysisInterfaces + TriggerAnalysisInterfaces + PMGAnalysisInterfaces + EgammaAnalysisInterfaces) # This package uses LHAPDF: find_package( Lhapdf ) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) -# Custom definitions needed for this package: -add_definitions( -g -std=c++14 ) +# Add a ROOT dictionary +atlas_add_root_dictionary( TopCorrections _cintDictSource + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopCorrections Root/*.cxx Root/*.h Root/*.icc TopCorrections/*.h TopCorrections/*.icc TopCorrections/*/*.h - TopCorrections/*/*.icc + TopCorrections/*/*.icc ${_cintDictSource} PUBLIC_HEADERS TopCorrections LINK_LIBRARIES xAODEgamma xAODMuon TopEvent PileupReweightingLib ElectronEfficiencyCorrectionLib - MuonEfficiencyCorrectionsLib - xAODBTaggingEfficiencyLib TauAnalysisToolsLib JetJvtEfficiencyLib PhotonEfficiencyCorrectionLib PMGToolsLib + PATInterfaces + FTagAnalysisInterfacesLib + MuonAnalysisInterfacesLib + #TriggerAnalysisInterfacesLib + PMGAnalysisInterfacesLib + EgammaAnalysisInterfacesLib ${LHAPDF_LIBRARIES} ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/BTagScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/BTagScaleFactorCalculator.cxx index f1ce0e7a7d723f077d33809bdc57442b5485c0f2..68374fec6a39501c74ccc6705f0110f261f8fc4d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/BTagScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/BTagScaleFactorCalculator.cxx @@ -1,9 +1,10 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: BTagScaleFactorCalculator.cxx 802983 2017-04-16 18:31:29Z tpelzer $ +// $Id: BTagScaleFactorCalculator.cxx 809570 2017-08-18 13:15:17Z iconnell $ #include "TopCorrections/BTagScaleFactorCalculator.h" +#include "TopCorrections/TopCorrectionsTools.h" #include "TopConfiguration/TopConfig.h" #include "TopEvent/EventTools.h" @@ -12,86 +13,76 @@ #include <algorithm> #include <functional> -namespace top{ +// For debug function +#include "PATInterfaces/SystematicCode.h" +#include "PATInterfaces/SystematicSet.h" +#include "PATInterfaces/SystematicVariation.h" +#include "CalibrationDataInterface/CalibrationDataInterfaceROOT.h" +#include "PathResolver/PathResolver.h" - BTagScaleFactorCalculator::BTagScaleFactorCalculator( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + BTagScaleFactorCalculator::BTagScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - m_nominal( CP::SystematicSet() ) - { - declareProperty( "config" , m_config ); - + m_nominal(CP::SystematicSet()) { + declareProperty("config", m_config); } - StatusCode BTagScaleFactorCalculator::initialize() - { - ATH_MSG_INFO(" top::BTagScaleFactorCalculator initialize" ); - - std::string release_series = ""; - const char* rel_temp = std::getenv("ROOTCORE_RELEASE_SERIES"); - if (rel_temp) { - release_series = std::string(rel_temp); - } else { - ATH_MSG_WARNING("Can not access ROOTCORE_RELEASE_SERIES"); - } + StatusCode BTagScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::BTagScaleFactorCalculator initialize"); - if (release_series == "23") { - ATH_MSG_INFO("Setting release series to 2.3"); - m_release_series = 23; - } else if (release_series == "24") { - m_release_series = 24; - ATH_MSG_INFO("Setting release series to 2.4"); - } else { - ATH_MSG_WARNING("Unknown release series, assuming 2.4"); - } - // for calo jets std::vector<std::string> availableWPs = m_config->bTagWP_available(); for (auto& WP : availableWPs) { - m_btagSelTools[WP] = "BTaggingSelectionTool_"+WP+"_"+m_config->sgKeyJets(); - top::check( m_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool" ); + m_btagSelTools[WP] = "BTaggingSelectionTool_" + WP + "_" + m_config->sgKeyJets(); + top::check(m_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool"); if (std::find(m_config->bTagWP_calibrated().begin(), - m_config->bTagWP_calibrated().end(), WP) != m_config->bTagWP_calibrated().end()) {// need scale-factors only for calibrated WPs - m_btagEffTools[WP] = "BTaggingEfficiencyTool_"+WP+"_"+m_config->sgKeyJets(); - top::check( m_btagEffTools[WP].retrieve(), "Failed to retrieve b-tagging Efficiency tool" ); + m_config->bTagWP_calibrated().end(), WP) != m_config->bTagWP_calibrated().end()) {// need + // scale-factors + // only for + // calibrated WPs + m_btagEffTools[WP] = "BTaggingEfficiencyTool_" + WP + "_" + m_config->sgKeyJets(); + top::check(m_btagEffTools[WP].retrieve(), "Failed to retrieve b-tagging Efficiency tool"); m_systs[WP] = m_btagEffTools[WP]->affectingSystematics(); std::set<std::string> base_names = m_systs[WP].getBaseNames(); - m_config->setBTaggingSFSysts( WP, base_names ); + m_config->setBTaggingSFSysts(WP, base_names); } } // for track jets availableWPs = m_config->bTagWP_available_trkJet(); for (auto& WP : availableWPs) { - m_trkjet_btagSelTools[WP] = "BTaggingSelectionTool_"+WP+"_"+m_config->sgKeyTrackJets(); - top::check( m_trkjet_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool" ); + m_trkjet_btagSelTools[WP] = "BTaggingSelectionTool_" + WP + "_" + m_config->sgKeyTrackJets(); + top::check(m_trkjet_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool"); if (std::find(m_config->bTagWP_calibrated_trkJet().begin(), - m_config->bTagWP_calibrated_trkJet().end(), WP) != m_config->bTagWP_calibrated_trkJet().end()) {// need scale-factors only for calibrated WPs - m_trkjet_btagEffTools[WP] = "BTaggingEfficiencyTool_"+WP+"_"+m_config->sgKeyTrackJets(); - top::check( m_trkjet_btagEffTools[WP].retrieve(), "Failed to retrieve b-tagging Efficiency tool" ); + m_config->bTagWP_calibrated_trkJet().end(), WP) != m_config->bTagWP_calibrated_trkJet().end()) {// need + // scale-factors + // only + // for + // calibrated + // WPs + m_trkjet_btagEffTools[WP] = "BTaggingEfficiencyTool_" + WP + "_" + m_config->sgKeyTrackJets(); + top::check(m_trkjet_btagEffTools[WP].retrieve(), "Failed to retrieve b-tagging Efficiency tool"); m_trkjet_systs[WP] = m_trkjet_btagEffTools[WP]->affectingSystematics(); std::set<std::string> base_names = m_trkjet_systs[WP].getBaseNames(); - m_config->setBTaggingSFSysts( WP, base_names, true ); + m_config->setBTaggingSFSysts(WP, base_names, true); } } - + return StatusCode::SUCCESS; } - - StatusCode BTagScaleFactorCalculator::execute() - { - - top::check( apply( m_config->systSgKeyMapJets(false) ), - "Failed to apply btagging SFs" ); - if( m_config->useTrackJets() ) - top::check( apply( m_config->systSgKeyMapTrackJets(), true ), - "Failed to apply track jet btagging SFs" ); + StatusCode BTagScaleFactorCalculator::execute() { + top::check(apply(m_config->systSgKeyMapJets(false)), + "Failed to apply btagging SFs"); + if (m_config->useTrackJets()) top::check(apply(m_config->systSgKeyMapTrackJets(), true), + "Failed to apply track jet btagging SFs"); return StatusCode::SUCCESS; - } - StatusCode BTagScaleFactorCalculator::apply( const std::shared_ptr<std::unordered_map<std::size_t,std::string>>& jet_syst_collections, bool use_trackjets ){ + StatusCode BTagScaleFactorCalculator::apply(const std::shared_ptr<std::unordered_map<std::size_t, + std::string> >& jet_syst_collections, + bool use_trackjets) { ///-- Loop over all jet collections --/// ///-- Lets assume that we're not doing ElectronInJet subtraction --/// for (auto currentSystematic : *jet_syst_collections) { @@ -99,99 +90,101 @@ namespace top{ top::check(evtStore()->retrieve(jets, currentSystematic.second), "failed to retrieve jets"); ///-- Tell the SF tools to use the nominal systematic --/// - /// -- Loop over all jets in each collection --/// for (auto jetPtr : *jets) { - - bool passSelection(false); - if (jetPtr->isAvailable<char>("passPreORSelection")) { - if (jetPtr->auxdataConst<char>("passPreORSelection") == 1) { - passSelection = true; - } - } - if (jetPtr->isAvailable<char>("passPreORSelectionLoose")) { - if (jetPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { - passSelection = true; - } - } - - if (passSelection) { - - // now loop over all available WPs - - for( auto& tagWP : (use_trackjets ? m_config->bTagWP_available_trkJet() : m_config->bTagWP_available()) ){ + bool passSelection(false); + if (jetPtr->isAvailable<char>("passPreORSelection")) { + if (jetPtr->auxdataConst<char>("passPreORSelection") == 1) { + passSelection = true; + } + } + if (jetPtr->isAvailable<char>("passPreORSelectionLoose")) { + if (jetPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { + passSelection = true; + } + } + + if (passSelection) { + // now loop over all available WPs + + for (auto& tagWP : (use_trackjets ? m_config->bTagWP_available_trkJet() : m_config->bTagWP_available())) { // skip uncalibrated though available WPs - if (use_trackjets && + if (use_trackjets && std::find(m_config->bTagWP_calibrated_trkJet().begin(), m_config->bTagWP_calibrated_trkJet().end(), tagWP) - == m_config->bTagWP_calibrated_trkJet().end()) continue; - else if (!use_trackjets && - std::find(m_config->bTagWP_calibrated().begin(), - m_config->bTagWP_calibrated().end(), tagWP) - == m_config->bTagWP_calibrated().end()) continue; - ToolHandle<IBTaggingEfficiencyTool>& btageff = use_trackjets ? m_trkjet_btagEffTools[tagWP] : m_btagEffTools[tagWP]; - ToolHandle<IBTaggingSelectionTool>& btagsel = use_trackjets ? m_trkjet_btagSelTools[tagWP] : m_btagSelTools[tagWP]; + == m_config->bTagWP_calibrated_trkJet().end()) continue; + else if (!use_trackjets && + std::find(m_config->bTagWP_calibrated().begin(), + m_config->bTagWP_calibrated().end(), tagWP) + == m_config->bTagWP_calibrated().end()) continue; + ToolHandle<IBTaggingEfficiencyTool>& btageff = + use_trackjets ? m_trkjet_btagEffTools[tagWP] : m_btagEffTools[tagWP]; + ToolHandle<IBTaggingSelectionTool>& btagsel = + use_trackjets ? m_trkjet_btagSelTools[tagWP] : m_btagSelTools[tagWP]; CP::SystematicSet& sysSet = use_trackjets ? m_trkjet_systs[tagWP] : m_systs[tagWP]; // need now the DSID to find out which shower was used in the sample - unsigned int MapIndex = m_config -> getMapIndex(); - - btageff -> setMapIndex("Light", MapIndex); - btageff -> setMapIndex("C", MapIndex); - btageff -> setMapIndex("B", MapIndex); - btageff -> setMapIndex("T", MapIndex); - - top::check( btageff->applySystematicVariation(m_nominal), - "Failed to set new b-tagging SF to nominal" ); - - float btag_SF(1.0); - bool isTagged = false;//unused in case of Continuous - if (std::fabs(jetPtr->eta()) < 2.5 ) { - if (tagWP != "Continuous") { - isTagged = btagsel->accept(*jetPtr); - if(isTagged) - top::check( btageff->getScaleFactor(*jetPtr, btag_SF), - "Failed to get nominal b-tagging SF" ); - else - top::check( btageff->getInefficiencyScaleFactor(*jetPtr, btag_SF), - "Failed to get nominal b-tagging SF" ); - } - else { - top::check( btageff->getScaleFactor(*jetPtr, btag_SF), - "Failed to get nominal Continuous b-tagging SF" ); - } + unsigned int MapIndex = m_config->getMapIndex(); + + btageff->setMapIndex("Light", MapIndex); + btageff->setMapIndex("C", MapIndex); + btageff->setMapIndex("B", MapIndex); + btageff->setMapIndex("T", MapIndex); + + // Check if this jet collection systematic matches with one removed from the EV decomposition + // (TopCorrectionsTools) + std::string bTagSystName = top::bTagNamedSystCheck(m_config, currentSystematic.second, tagWP, use_trackjets, false); + // If this string is not empty, we need to search and find the appropriate systematic set to apply + if (bTagSystName != "") { + CP::SystematicSet bTagSyst; + bTagSyst.insert(sysSet.getSystematicByBaseName(bTagSystName)); + top::check(btageff->applySystematicVariation(bTagSyst), + "Failed to set new b-tagging SF to a shifted systematic set : " + bTagSystName); + } else { + top::check(btageff->applySystematicVariation(m_nominal), + "Failed to set new b-tagging SF to nominal"); } - jetPtr->auxdecor<float>("btag_SF_"+tagWP+"_nom") = btag_SF; - ///-- For nominal calibration, vary the SF systematics --/// - if (currentSystematic.first == m_config->nominalHashValue()) { + float btag_SF(1.0); + bool isTagged = false;//unused in case of Continuous + if (std::fabs(jetPtr->eta()) <= 2.5) { + if (tagWP.find("Continuous") == std::string::npos) { + isTagged = static_cast<bool>(btagsel->accept(*jetPtr)); + if (isTagged) top::check(btageff->getScaleFactor(*jetPtr, btag_SF), + "Failed to get nominal b-tagging SF"); + else top::check(btageff->getInefficiencyScaleFactor(*jetPtr, btag_SF), + "Failed to get nominal b-tagging SF"); + } else { + top::check(btageff->getScaleFactor(*jetPtr, btag_SF), + "Failed to get nominal Continuous b-tagging SF"); + } + } + jetPtr->auxdecor<float>("btag_SF_" + tagWP + "_nom") = btag_SF; - for( const auto& variation : sysSet ) { + ///-- For nominal calibration, vary the SF systematics --/// + if (currentSystematic.first == m_config->nominalHashValue()) { + for (const auto& variation : sysSet) { btag_SF = 1.; CP::SystematicSet syst_set; - syst_set.insert( variation ); - top::check( btageff->applySystematicVariation(syst_set), - "Failed to set new b-tagging systematic variation "+syst_set.name() ); - if (std::fabs(jetPtr->eta()) < 2.5 ) { - if (tagWP != "Continuous") { - if (isTagged) - top::check( btageff->getScaleFactor(*jetPtr, btag_SF), - "Failed to get b-tagging SF for variation "+syst_set.name() ); - else - top::check( btageff->getInefficiencyScaleFactor(*jetPtr, btag_SF), - "Failed to get b-tagging SF for variation "+syst_set.name() ); - } - else { - top::check( btageff->getScaleFactor(*jetPtr, btag_SF), - "Failed to get Continuous b-tagging SF for variation "+syst_set.name() ); + syst_set.insert(variation); + top::check(btageff->applySystematicVariation(syst_set), + "Failed to set new b-tagging systematic variation " + syst_set.name()); + if (std::fabs(jetPtr->eta()) <= 2.5) { + if (tagWP.find("Continuous") == std::string::npos) { + if (isTagged) top::check(btageff->getScaleFactor(*jetPtr, btag_SF), + "Failed to get b-tagging SF for variation " + syst_set.name()); + else top::check(btageff->getInefficiencyScaleFactor(*jetPtr, btag_SF), + "Failed to get b-tagging SF for variation " + syst_set.name()); + } else { + top::check(btageff->getScaleFactor(*jetPtr, btag_SF), + "Failed to get Continuous b-tagging SF for variation " + syst_set.name()); } } - jetPtr->auxdecor<float>( "btag_SF_"+tagWP+"_"+variation.name() ) = btag_SF; + jetPtr->auxdecor<float>("btag_SF_" + tagWP + "_" + variation.name()) = btag_SF; } // loop through b-tagging systematic variations - } // Calibration systematic is nominal, so calculate SF systematics - - } - } + } // Calibration systematic is nominal, so calculate SF systematics + } + } } } @@ -199,4 +192,59 @@ namespace top{ return StatusCode::SUCCESS; } + StatusCode BTagScaleFactorCalculator::debug() { + ATH_MSG_INFO("BTagScaleFactorCalculator::debug function"); + // Use after package is initialised otherwise vectors will be empty + for (auto& tagWP : m_config->bTagWP_available()) { + ATH_MSG_INFO("Tagger working point : " << tagWP); + ToolHandle<IBTaggingEfficiencyTool>& btageff = m_btagEffTools[tagWP]; + // Retrieve tool + top::check(btageff.retrieve(), "Failed to retrieve tool"); + // Retrieve list of systematics included + CP::SystematicSet systs = btageff->affectingSystematics(); + CP::SystematicSet recsysts = btageff->recommendedSystematics(); + + ATH_MSG_INFO("-----------------------------------------------------------------------"); + + const std::map<CP::SystematicVariation, + std::vector<std::string> > allowed_variations = btageff->listSystematics(); + + ATH_MSG_INFO("Allowed systematics variations for tool " << btageff->name()); + for (auto var : allowed_variations) { + std::string flvs = ""; + for (auto flv : var.second) flvs += flv; + ATH_MSG_INFO(" (" << flvs << ") - " << var.first); + } + + // Now use the new functions added into xAODBTaggingEfficiency-00-00-39 + // std::map<std::string, std::vector<std::string> > + ATH_MSG_INFO("-----------------------------------------------------------------------"); + ATH_MSG_INFO("List of b-tagging scale factor systematics"); + std::map<std::string, + std::vector<std::string> > listOfScaleFactorSystematics = btageff->listScaleFactorSystematics(false); + for (auto var : listOfScaleFactorSystematics) { + ATH_MSG_INFO("Jet flavour : " << var.first); + std::vector<std::string> systs = var.second; + std::sort(systs.begin(), systs.end()); + for (auto sys : systs) { + ATH_MSG_INFO(" (" << var.first << ") - " << sys); + } + ATH_MSG_INFO(" "); + } + + ATH_MSG_INFO("List of (named) b-tagging scale factor systematics"); + listOfScaleFactorSystematics = btageff->listScaleFactorSystematics(true); + for (auto var : listOfScaleFactorSystematics) { + ATH_MSG_INFO("Jet flavour : " << var.first); + std::vector<std::string> systs = var.second; + std::sort(systs.begin(), systs.end()); + for (auto sys : systs) { + ATH_MSG_INFO(" (" << var.first << ") - " << sys); + } + ATH_MSG_INFO(" "); + } + ATH_MSG_INFO("-----------------------------------------------------------------------"); + } + return StatusCode::SUCCESS; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ElectronScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ElectronScaleFactorCalculator.cxx index 3ae5e1323d666daac95e433a4f83a5b28b3ce2ff..cf6ade66fce65db50999a9a2550545ed9b864062 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ElectronScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ElectronScaleFactorCalculator.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // $Id: ElectronScaleFactorCalculator.cxx 799556 2017-03-05 19:46:03Z tpelzer $ #include "TopCorrections/ElectronScaleFactorCalculator.h" @@ -8,40 +8,36 @@ #include "TopEvent/EventTools.h" #include "xAODEgamma/ElectronContainer.h" +#include "TString.h" - -namespace top{ - - ElectronScaleFactorCalculator::ElectronScaleFactorCalculator( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + ElectronScaleFactorCalculator::ElectronScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - m_systNominal( CP::SystematicSet() ), - m_systTrigger_UP( CP::SystematicSet() ), - m_systTrigger_DOWN( CP::SystematicSet() ), - m_systReco_UP( CP::SystematicSet() ), - m_systReco_DOWN( CP::SystematicSet() ), - m_systID_UP( CP::SystematicSet() ), - m_systID_DOWN( CP::SystematicSet() ), - m_systIso_UP( CP::SystematicSet() ), - m_systIso_DOWN( CP::SystematicSet() ), - m_systChargeID_UP( CP::SystematicSet() ), - m_systChargeID_DOWN( CP::SystematicSet() ), - m_systChargeMisID_STAT_UP( CP::SystematicSet() ), - m_systChargeMisID_STAT_DOWN( CP::SystematicSet() ), - m_systChargeMisID_SYST_UP( CP::SystematicSet() ), - m_systChargeMisID_SYST_DOWN( CP::SystematicSet() ), + m_systNominal(CP::SystematicSet()), + m_systTrigger_UP(CP::SystematicSet()), + m_systTrigger_DOWN(CP::SystematicSet()), + m_systReco_UP(CP::SystematicSet()), + m_systReco_DOWN(CP::SystematicSet()), + m_systID_UP(CP::SystematicSet()), + m_systID_DOWN(CP::SystematicSet()), + m_systIso_UP(CP::SystematicSet()), + m_systIso_DOWN(CP::SystematicSet()), + m_systChargeID_UP(CP::SystematicSet()), + m_systChargeID_DOWN(CP::SystematicSet()), + m_systChargeMisID_STAT_UP(CP::SystematicSet()), + m_systChargeMisID_STAT_DOWN(CP::SystematicSet()), + m_systChargeMisID_SYST_UP(CP::SystematicSet()), + m_systChargeMisID_SYST_DOWN(CP::SystematicSet()), m_electronEffSFTrigger("AsgElectronEfficiencyCorrectionTool_TriggerSF"), m_electronEffSFTriggerLoose("AsgElectronEfficiencyCorrectionTool_TriggerSFLoose"), m_electronEffTrigger("AsgElectronEfficiencyCorrectionTool_Trigger"), m_electronEffTriggerLoose("AsgElectronEfficiencyCorrectionTool_TriggerLoose"), - m_electronEffSFReco("AsgElectronEfficiencyCorrectionTool_Reco"), - m_electronEffSFID("AsgElectronEfficiencyCorrectionTool_ID"), m_electronEffSFIDLoose("AsgElectronEfficiencyCorrectionTool_IDLoose"), - m_electronEffIso_exists(false), m_electronEffIsoLoose_exists(false), m_electronEffSFIso("AsgElectronEfficiencyCorrectionTool_Iso"), @@ -55,6 +51,16 @@ namespace top{ m_electronEffSFChargeMisID("ElectronChargeEfficiencyCorrection"), m_electronEffSFChargeMisIDLoose("ElectronChargeEfficiencyCorrectionLoose"), + m_electronEffSFTriggerCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_TriggerSF"), + m_electronEffSFTriggerLooseCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_TriggerSFLoose"), + m_electronEffTriggerCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_Trigger"), + m_electronEffTriggerLooseCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_TriggerLoose"), + m_electronEffSFRecoCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_Reco"), + m_electronEffSFIDCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_ID"), + m_electronEffSFIDLooseCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_IDLoose"), + m_electronEffSFIsoCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_Iso"), + m_electronEffSFIsoLooseCorrModel("AsgElectronEfficiencyCorrectionTool_CorrModel_IsoLoose"), + m_decor_triggerEff("SetMe"), m_decor_triggerEff_loose("SetMe"), m_decor_triggerSF("SetMe"), @@ -67,143 +73,230 @@ namespace top{ m_decor_chargeidSF("SetMe"), m_decor_chargeidSF_loose("SetMe"), m_decor_chargemisidSF("SetMe"), - m_decor_chargemisidSF_loose("SetMe") - { - declareProperty( "config" , m_config ); + m_decor_chargemisidSF_loose("SetMe") { + declareProperty("config", m_config); } - StatusCode ElectronScaleFactorCalculator::initialize() - { - ATH_MSG_INFO(" top::ElectronScaleFactorCalculator initialize" ); + StatusCode ElectronScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::ElectronScaleFactorCalculator initialize"); - top::check( m_electronEffSFTrigger.retrieve() , "Failed to retrieve electron SF Tool" ); - top::check( m_electronEffSFTriggerLoose.retrieve() , "Failed to retrieve electron SF Tool" ); + top::check(m_electronEffSFTrigger.retrieve(), "Failed to retrieve electron SF Tool"); + top::check(m_electronEffSFTriggerLoose.retrieve(), "Failed to retrieve electron SF Tool"); + + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + top::check(m_electronEffSFTriggerCorrModel.retrieve(), + "Failed to retrieve electron SF Tool for correlation model"); + top::check( + m_electronEffSFTriggerLooseCorrModel.retrieve(), "Failed to retrieve electron SF Tool for correlation model"); + } - top::check( m_electronEffSFReco.retrieve() , "Failed to retrieve electron SF Tool" ); + top::check(m_electronEffSFReco.retrieve(), "Failed to retrieve electron SF Tool"); + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + top::check(m_electronEffSFRecoCorrModel.retrieve(), "Failed to retrieve electron SF Tool for correlation model"); + } - if ( asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_Iso") ){ + if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_Iso")) { m_electronEffIso_exists = true; - top::check( m_electronEffSFIso.retrieve() , "Failed to retrieve electron SF Tool" ); + top::check(m_electronEffSFIso.retrieve(), "Failed to retrieve electron SF Tool"); + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + top::check(m_electronEffSFIsoCorrModel.retrieve(), "Failed to retrieve electron SF Tool for correlation model"); + } } - if ( asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_IsoLoose") ){ + if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_IsoLoose")) + { m_electronEffIsoLoose_exists = true; - top::check( m_electronEffSFIsoLoose.retrieve() , "Failed to retrieve loose electron SF Tool" ); + top::check(m_electronEffSFIsoLoose.retrieve(), "Failed to retrieve loose electron SF Tool"); + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + top::check( + m_electronEffSFIsoLooseCorrModel.retrieve(), + "Failed to retrieve loose electron SF Tool for correlation model"); + } } - // ChargeID efficiency and Charge mis-identification scale factors: to apply when enabling Electron Charge ID Selector - if ( asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_ChargeID") ){ + std::ostream& msgInfo = msg(MSG::Level::INFO); + // ChargeID efficiency and Charge mis-identification scale factors: to apply when enabling Electron Charge ID + // Selector + if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_ChargeID")) + { m_electronEffChargeID_exists = true; // this scale factor currently exists only for MediumLHH electron - top::check( m_electronEffSFChargeID.retrieve() , "Failed to retrieve electron charge flip efficiency SF Tool" ); - std::cout<<"------>Systematics:"<<std::endl; + top::check(m_electronEffSFChargeID.retrieve(), "Failed to retrieve electron charge flip efficiency SF Tool"); + msgInfo << "------>Systematics:\n"; for (auto sys:m_electronEffSFChargeID->recommendedSystematics()) - std::cout<<"---> "<<sys<<std::endl; + msgInfo << "---> " << sys << "\n"; } - if ( asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ("AsgElectronEfficiencyCorrectionTool_ChargeIDLoose") ){ + if (asg::ToolStore::contains<IAsgElectronEfficiencyCorrectionTool> ( + "AsgElectronEfficiencyCorrectionTool_ChargeIDLoose")) { m_electronEffChargeIDLoose_exists = true; // this scale factor currently exists only for MediumLHH electron - top::check( m_electronEffSFChargeIDLoose.retrieve() , "Failed to retrieve electron charge flip efficiency SF Tool" ); - std::cout<<"------>Systematics:"<<std::endl; + top::check(m_electronEffSFChargeIDLoose.retrieve(), "Failed to retrieve electron charge flip efficiency SF Tool"); + msgInfo << "------>Systematics:\n"; for (auto sys:m_electronEffSFChargeIDLoose->recommendedSystematics()) - std::cout<<"---> "<<sys<<std::endl; + msgInfo << "---> " << sys << "\n"; } - if ( asg::ToolStore::contains<CP::ElectronChargeEfficiencyCorrectionTool> ("ElectronChargeEfficiencyCorrection") && - m_config->doPileupReweighting() ){ // tool requires RandomRunNumber set from it + if (asg::ToolStore::contains<CP::ElectronChargeEfficiencyCorrectionTool> ("ElectronChargeEfficiencyCorrection") && + m_config->doPileupReweighting()) { // tool requires RandomRunNumber set from it m_electronEffChargeMisID_exists = true; - top::check( m_electronEffSFChargeMisID.retrieve() , "Failed to retrieve electron charge mis-id SF Tool" ); - std::cout<<"------>Systematics:"<<std::endl; + top::check(m_electronEffSFChargeMisID.retrieve(), "Failed to retrieve electron charge mis-id SF Tool"); + msgInfo << "------>Systematics:\n"; for (auto sys:m_electronEffSFChargeMisID->recommendedSystematics()) - std::cout<<"---> "<<sys<<std::endl; + msgInfo << "---> " << sys << "\n"; } - if ( asg::ToolStore::contains<CP::ElectronChargeEfficiencyCorrectionTool> ("ElectronChargeEfficiencyCorrectionLoose") && - m_config->doPileupReweighting() ){ // tool requires RandomRunNumber set from it + if (asg::ToolStore::contains<CP::ElectronChargeEfficiencyCorrectionTool> ("ElectronChargeEfficiencyCorrectionLoose") + && + m_config->doPileupReweighting()) { // tool requires RandomRunNumber set from it m_electronEffChargeMisIDLoose_exists = true; - top::check( m_electronEffSFChargeMisIDLoose.retrieve() , "Failed to retrieve electron charge mis-id SF Tool" ); - std::cout<<"------>Systematics:"<<std::endl; + top::check(m_electronEffSFChargeMisIDLoose.retrieve(), "Failed to retrieve electron charge mis-id SF Tool"); + msgInfo << "------>Systematics:\n"; for (auto sys:m_electronEffSFChargeMisIDLoose->recommendedSystematics()) - std::cout<<"---> "<<sys<<std::endl; + msgInfo << "---> " << sys << "\n"; } // If the isolation tool doesn't exist then check why... // valid reasons include you want no isolation or you know you are using an unsupported WP - if( !m_electronEffIso_exists ) - if( m_config->electronIsolation() != "None" ) - if( m_config->electronIsoSFs() ){ // ... check if we want to continue anyway without SFs anyway - ATH_MSG_WARNING( "No electron isolation SFs available. You can run with ElectronIsolation set to None if you don't want isolation, or add:\tElectronIsoSFs False\tto your config file." ); - return StatusCode::FAILURE; - } - - if( !m_electronEffIsoLoose_exists ) // If the electron isolation SFs don't exist - if( m_config->electronIsolationLoose() != "None" ) // If the isolation is not 'None' then... - if( m_config->electronIsoSFs() ){ // ... check if we want to continue anyway without SFs anyway - ATH_MSG_WARNING( "No (loose) electron isolation SFs available. You can run with ElectronIsolationLoose set to None if you don't want isolation, or add:\tElectronIsoSFs False\tto your config file." ); - return StatusCode::FAILURE; - } - - top::check( m_electronEffSFID.retrieve() , "Failed to retrieve electron SF Tool" ); - top::check( m_electronEffSFIDLoose.retrieve() , "Failed to retrieve electron SF Tool" ); - - m_systTrigger_UP.insert( CP::SystematicVariation("EL_EFF_Trigger_TOTAL_1NPCOR_PLUS_UNCOR" , 1 )); - m_systTrigger_DOWN.insert( CP::SystematicVariation("EL_EFF_Trigger_TOTAL_1NPCOR_PLUS_UNCOR" , -1 )); - m_systReco_UP.insert( CP::SystematicVariation("EL_EFF_Reco_TOTAL_1NPCOR_PLUS_UNCOR" , 1 )); - m_systReco_DOWN.insert( CP::SystematicVariation("EL_EFF_Reco_TOTAL_1NPCOR_PLUS_UNCOR" , -1 )); - m_systID_UP.insert( CP::SystematicVariation("EL_EFF_ID_TOTAL_1NPCOR_PLUS_UNCOR" , 1 )); - m_systID_DOWN.insert( CP::SystematicVariation("EL_EFF_ID_TOTAL_1NPCOR_PLUS_UNCOR" , -1 )); - m_systIso_UP.insert( CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR" , 1 )); - m_systIso_DOWN.insert( CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR" , -1 )); - m_systIso_UP.insert( CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR" , 1 )); - m_systIso_DOWN.insert( CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR" , -1 )); - m_systChargeID_UP.insert( CP::SystematicVariation("EL_EFF_ChargeIDSel_TOTAL_1NPCOR_PLUS_UNCOR" , 1 )); - m_systChargeID_DOWN.insert( CP::SystematicVariation("EL_EFF_ChargeIDSel_TOTAL_1NPCOR_PLUS_UNCOR" , -1 )); - m_systChargeMisID_STAT_UP.insert( CP::SystematicVariation("EL_CHARGEID_STAT" , 1 )); - m_systChargeMisID_STAT_DOWN.insert( CP::SystematicVariation("EL_CHARGEID_STAT" , -1 )); - m_systChargeMisID_SYST_UP.insert( CP::SystematicVariation("EL_CHARGEID_SYStotal" , 1 )); - m_systChargeMisID_SYST_DOWN.insert( CP::SystematicVariation("EL_CHARGEID_SYStotal" , -1 )); - - m_decor_triggerEff = "EL_EFF_Trigger_" + m_config->electronID(); - m_decor_triggerEff_loose = "EL_EFF_Trigger_" + m_config->electronIDLoose(); - m_decor_triggerSF = "EL_SF_Trigger_" + m_config->electronID(); - m_decor_triggerSF_loose = "EL_SF_Trigger_" + m_config->electronIDLoose(); - m_decor_recoSF = "EL_SF_Reco"; - m_decor_idSF = "EL_SF_ID_" + m_config->electronID(); - m_decor_idSF_loose = "EL_SF_ID_" + m_config->electronIDLoose(); - m_decor_isoSF = "EL_SF_Iso_" + m_config->electronIsolation(); - m_decor_isoSF_loose = "EL_SF_Iso_" + m_config->electronIsolationLoose(); - m_decor_chargeidSF = "EL_SF_ChargeID_" + m_config->electronID() + "_" + m_config->electronIsolation(); - m_decor_chargeidSF_loose = "EL_SF_ChargeID_" + m_config->electronIDLoose() + "_" + m_config->electronIsolationLoose(); - m_decor_chargemisidSF = "EL_SF_ChargeMisID_" + m_config->electronID() + "_" + m_config->electronIsolation(); - m_decor_chargemisidSF_loose = "EL_SF_ChargeMisID_" + m_config->electronIDLoose() + "_" + m_config->electronIsolationLoose(); + if (!m_electronEffIso_exists) + if (m_config->electronIsolation() != "None") + if (m_config->electronIsoSFs()) { // ... check if we want to continue anyway without SFs anyway + ATH_MSG_WARNING( + "No electron isolation SFs available. You can run with ElectronIsolation set to None if you don't want isolation, or add:\tElectronIsoSFs False\tto your config file."); + return StatusCode::FAILURE; + } + + if (!m_electronEffIsoLoose_exists) // If the electron isolation SFs don't + // exist + if (m_config->electronIsolationLoose() != "None") // If + // the + // isolation + // is + // not + // 'None' + // then... + if (m_config->electronIsoSFs()) { // ... check if we want to continue anyway without SFs anyway + ATH_MSG_WARNING( + "No (loose) electron isolation SFs available. You can run with ElectronIsolationLoose set to None if you don't want isolation, or add:\tElectronIsoSFs False\tto your config file."); + return StatusCode::FAILURE; + } + + top::check(m_electronEffSFID.retrieve(), "Failed to retrieve electron SF Tool"); + top::check(m_electronEffSFIDLoose.retrieve(), "Failed to retrieve electron SF Tool"); + + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + top::check(m_electronEffSFIDCorrModel.retrieve(), "Failed to retrieve electron SF Tool for correlation model"); + top::check(m_electronEffSFIDLooseCorrModel.retrieve(), + "Failed to retrieve electron SF Tool for correlation model"); + } + + m_systTrigger_UP.insert(CP::SystematicVariation("EL_EFF_Trigger_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systTrigger_DOWN.insert(CP::SystematicVariation("EL_EFF_Trigger_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + m_systReco_UP.insert(CP::SystematicVariation("EL_EFF_Reco_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systReco_DOWN.insert(CP::SystematicVariation("EL_EFF_Reco_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + m_systID_UP.insert(CP::SystematicVariation("EL_EFF_ID_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systID_DOWN.insert(CP::SystematicVariation("EL_EFF_ID_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + m_systIso_UP.insert(CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systIso_DOWN.insert(CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + m_systIso_UP.insert(CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systIso_DOWN.insert(CP::SystematicVariation("EL_EFF_Iso_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + m_systChargeID_UP.insert(CP::SystematicVariation("EL_EFF_ChargeIDSel_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systChargeID_DOWN.insert(CP::SystematicVariation("EL_EFF_ChargeIDSel_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + m_systChargeMisID_STAT_UP.insert(CP::SystematicVariation("EL_CHARGEID_STAT", 1)); + m_systChargeMisID_STAT_DOWN.insert(CP::SystematicVariation("EL_CHARGEID_STAT", -1)); + m_systChargeMisID_SYST_UP.insert(CP::SystematicVariation("EL_CHARGEID_SYStotal", 1)); + m_systChargeMisID_SYST_DOWN.insert(CP::SystematicVariation("EL_CHARGEID_SYStotal", -1)); + + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + CP::SystematicSet triggerSet = m_electronEffSFTrigger->recommendedSystematics(); //currently we have only the + // TOTAL model implemented for + // trigger SF, it's useless to + // use an advanced model here + CP::SystematicSet recoSet = m_electronEffSFRecoCorrModel->recommendedSystematics(); + CP::SystematicSet idSet = m_electronEffSFIDCorrModel->recommendedSystematics(); + CP::SystematicSet isoSet = m_electronEffSFIsoCorrModel->recommendedSystematics(); + + m_systTriggerCorrModel = CP::make_systematics_vector(triggerSet); + m_systRecoCorrModel = CP::make_systematics_vector(recoSet); + m_systIDCorrModel = CP::make_systematics_vector(idSet); + m_systIsoCorrModel = CP::make_systematics_vector(isoSet); + + ATH_MSG_INFO( + "For electron RECO, ID, ISOLATION using the correlation model " << + m_config->electronEfficiencySystematicModel()); + int count = 0, count2 = 0; + for (const CP::SystematicSet& isyst : m_systRecoCorrModel) { + count++; + if (count % 2 == 1) continue; + TString name = isyst.name(); + name.ReplaceAll("__1down", ""); + ATH_MSG_INFO( + "--->electron RECO " << m_config->electronEfficiencySystematicModel() << " component " << (count2++) << " is " << + name); + } + count = 0; + count2 = 0; + for (const CP::SystematicSet& isyst : m_systIDCorrModel) { + count++; + if (count % 2 == 1) continue; + TString name = isyst.name(); + name.ReplaceAll("__1down", ""); + ATH_MSG_INFO( + "--->electron ID " << m_config->electronEfficiencySystematicModel() << " component " << (count2++) << " is " << + name); + } + count = 0; + count2 = 0; + for (const CP::SystematicSet& isyst : m_systIsoCorrModel) { + count++; + if (count % 2 == 1) continue; + TString name = isyst.name(); + name.ReplaceAll("__1down", ""); + ATH_MSG_INFO( + "--->electron ISO " << m_config->electronEfficiencySystematicModel() << " component " << (count2++) << " is " << + name); + } + } + + m_decor_triggerEff = "EL_EFF_Trigger_" + m_config->electronID(); + m_decor_triggerEff_loose = "EL_LOOSE_EFF_Trigger_" + m_config->electronIDLoose(); + m_decor_triggerSF = "EL_SF_Trigger_" + m_config->electronID(); + m_decor_triggerSF_loose = "EL_LOOSE_SF_Trigger_" + m_config->electronIDLoose(); + m_decor_recoSF = "EL_SF_Reco"; + m_decor_idSF = "EL_SF_ID_" + m_config->electronID(); + m_decor_idSF_loose = "EL_LOOSE_SF_ID_" + m_config->electronIDLoose(); + m_decor_isoSF = "EL_SF_Iso_" + m_config->electronIsolation(); + m_decor_isoSF_loose = "EL_LOOSE_SF_Iso_" + m_config->electronIsolationLoose(); + m_decor_chargeidSF = "EL_SF_ChargeID_" + m_config->electronID() + "_" + m_config->electronIsolation(); + m_decor_chargeidSF_loose = "EL_LOOSE_SF_ChargeID_" + m_config->electronIDLoose() + "_" + + m_config->electronIsolationLoose(); + m_decor_chargemisidSF = "EL_SF_ChargeMisID_" + m_config->electronID() + "_" + m_config->electronIsolation(); + m_decor_chargemisidSF_loose = "EL_LOOSE_SF_ChargeMisID_" + m_config->electronIDLoose() + "_" + + m_config->electronIsolationLoose(); return StatusCode::SUCCESS; } - - StatusCode ElectronScaleFactorCalculator::execute() - { + StatusCode ElectronScaleFactorCalculator::execute() { ///-- Loop over all electron collections --/// for (auto currentSystematic : *m_config->systSgKeyMapElectrons()) { const xAOD::ElectronContainer* electrons(nullptr); top::check(evtStore()->retrieve(electrons, currentSystematic.second), "failed to retrieve electrons"); ///-- Tell the SF tools to use the nominal systematic --/// - top::check(m_electronEffSFTrigger->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffSFTriggerLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffSFReco->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffSFID->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffSFIDLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - if( m_electronEffIso_exists ) - top::check(m_electronEffSFIso->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - if( m_electronEffIsoLoose_exists ) - top::check(m_electronEffSFIsoLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - if( m_electronEffChargeID_exists ) - top::check(m_electronEffSFChargeID->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - if( m_electronEffChargeIDLoose_exists ) - top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - if( m_electronEffChargeMisID_exists ) - top::check(m_electronEffSFChargeMisID->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - if( m_electronEffChargeMisIDLoose_exists ) - top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); + top::check(m_electronEffSFTrigger->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFTriggerLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFReco->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFID->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + if (m_electronEffIso_exists) top::check(m_electronEffSFIso->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + if (m_electronEffIsoLoose_exists) top::check(m_electronEffSFIsoLoose->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + if (m_electronEffChargeID_exists) top::check(m_electronEffSFChargeID->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + if (m_electronEffChargeIDLoose_exists) top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + if (m_electronEffChargeMisID_exists) top::check(m_electronEffSFChargeMisID->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + if (m_electronEffChargeMisIDLoose_exists) top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( + m_systNominal), "Failed to set systematic"); /// -- Loop over all electrons in each collection --/// for (auto electronPtr : *electrons) { - /// -- Does the electron pass object selection? --/// bool passSelection(false); if (electronPtr->isAvailable<char>("passPreORSelection")) { @@ -218,278 +311,599 @@ namespace top{ } if (passSelection) { - - double Eff_Trigger(1.), Eff_TriggerLoose(1.); - double SF_Trigger(1.), SF_TriggerLoose(1.); - double SF_Reco(1.); - double SF_ID(1.),SF_IDLoose(1.); - double SF_Isol(1.),SF_IsolLoose(1.); - double SF_ChargeID(1.), SF_ChargeIDLoose(1.); - double SF_ChargeMisID(1.), SF_ChargeMisIDLoose(1.); - - ///-- Get Efficiencies --/// - top::check(m_electronEffTrigger -> getEfficiencyScaleFactor( *electronPtr , Eff_Trigger ) , "Failed to get SF"); - top::check(m_electronEffTriggerLoose -> getEfficiencyScaleFactor( *electronPtr , Eff_TriggerLoose ) , "Failed to get SF"); - - ///-- Get Scale Factors --/// - top::check(m_electronEffSFTrigger -> getEfficiencyScaleFactor( *electronPtr , SF_Trigger ) , "Failed to get SF"); - top::check(m_electronEffSFTriggerLoose -> getEfficiencyScaleFactor( *electronPtr , SF_TriggerLoose ) , "Failed to get SF"); - top::check(m_electronEffSFReco -> getEfficiencyScaleFactor( *electronPtr , SF_Reco ) , "Failed to get SF"); - top::check(m_electronEffSFID -> getEfficiencyScaleFactor( *electronPtr , SF_ID ) , "Failed to get SF"); - top::check(m_electronEffSFIDLoose -> getEfficiencyScaleFactor( *electronPtr , SF_IDLoose ) , "Failed to get SF"); - if( m_electronEffIso_exists ) - top::check(m_electronEffSFIso -> getEfficiencyScaleFactor( *electronPtr , SF_Isol ) , "Failed to get SF"); - if( m_electronEffIsoLoose_exists ) - top::check(m_electronEffSFIsoLoose -> getEfficiencyScaleFactor( *electronPtr , SF_IsolLoose ) , "Failed to get SF"); - if( m_electronEffChargeID_exists ) - top::check(m_electronEffSFChargeID -> getEfficiencyScaleFactor( *electronPtr , SF_ChargeID ) , "Failed to get SF"); - if( m_electronEffChargeIDLoose_exists ) - top::check(m_electronEffSFChargeIDLoose -> getEfficiencyScaleFactor( *electronPtr , SF_ChargeIDLoose ) , "Failed to get SF"); - if( m_electronEffChargeMisID_exists ) - top::check(m_electronEffSFChargeMisID -> getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisID ) , "Failed to get SF"); - if( m_electronEffChargeMisIDLoose_exists ) - top::check(m_electronEffSFChargeMisIDLoose -> getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisIDLoose ) , "Failed to get SF"); - + double Eff_Trigger(1.), Eff_TriggerLoose(1.); + double SF_Trigger(1.), SF_TriggerLoose(1.); + double SF_Reco(1.); + double SF_ID(1.), SF_IDLoose(1.); + double SF_Isol(1.), SF_IsolLoose(1.); + double SF_ChargeID(1.), SF_ChargeIDLoose(1.); + double SF_ChargeMisID(1.), SF_ChargeMisIDLoose(1.); + + ///-- Get Efficiencies --/// + top::check(m_electronEffTrigger->getEfficiencyScaleFactor(*electronPtr, Eff_Trigger), "Failed to get SF"); + top::check(m_electronEffTriggerLoose->getEfficiencyScaleFactor(*electronPtr, + Eff_TriggerLoose), "Failed to get SF"); + + ///-- Get Scale Factors --/// + top::check(m_electronEffSFTrigger->getEfficiencyScaleFactor(*electronPtr, SF_Trigger), "Failed to get SF"); + top::check(m_electronEffSFTriggerLoose->getEfficiencyScaleFactor(*electronPtr, + SF_TriggerLoose), "Failed to get SF"); + top::check(m_electronEffSFReco->getEfficiencyScaleFactor(*electronPtr, SF_Reco), "Failed to get SF"); + top::check(m_electronEffSFID->getEfficiencyScaleFactor(*electronPtr, SF_ID), "Failed to get SF"); + top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor(*electronPtr, SF_IDLoose), "Failed to get SF"); + if (m_electronEffIso_exists) top::check(m_electronEffSFIso->getEfficiencyScaleFactor(*electronPtr, + SF_Isol), + "Failed to get SF"); + if (m_electronEffIsoLoose_exists) top::check(m_electronEffSFIsoLoose->getEfficiencyScaleFactor(*electronPtr, + SF_IsolLoose), + "Failed to get SF"); + if (m_electronEffChargeID_exists) top::check(m_electronEffSFChargeID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeID), + "Failed to get SF"); + if (m_electronEffChargeIDLoose_exists) top::check(m_electronEffSFChargeIDLoose->getEfficiencyScaleFactor(* + electronPtr, + SF_ChargeIDLoose), + "Failed to get SF"); + if (m_electronEffChargeMisID_exists) top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor(* + electronPtr, + SF_ChargeMisID), + "Failed to get SF"); + if (m_electronEffChargeMisIDLoose_exists) top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor( + *electronPtr, + SF_ChargeMisIDLoose), "Failed to get SF"); + + + ///-- Decorate --/// + electronPtr->auxdecor<float>(m_decor_triggerEff) = Eff_Trigger; + electronPtr->auxdecor<float>(m_decor_triggerEff_loose) = Eff_TriggerLoose; + electronPtr->auxdecor<float>(m_decor_triggerSF) = SF_Trigger; + electronPtr->auxdecor<float>(m_decor_triggerSF_loose) = SF_TriggerLoose; + electronPtr->auxdecor<float>(m_decor_recoSF) = SF_Reco; + electronPtr->auxdecor<float>(m_decor_idSF) = SF_ID; + electronPtr->auxdecor<float>(m_decor_idSF_loose) = SF_IDLoose; + electronPtr->auxdecor<float>(m_decor_isoSF) = SF_Isol; + electronPtr->auxdecor<float>(m_decor_isoSF_loose) = SF_IsolLoose; + electronPtr->auxdecor<float>(m_decor_chargeidSF) = SF_ChargeID; + electronPtr->auxdecor<float>(m_decor_chargeidSF_loose) = SF_ChargeIDLoose; + electronPtr->auxdecor<float>(m_decor_chargemisidSF) = SF_ChargeMisID; + electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose) = SF_ChargeMisIDLoose; + + ///-- For nominal calibration, vary the SF systematics --/// + if (currentSystematic.first == m_config->nominalHashValue()) { + double EFF_Trigger_UP(1.), EFF_TriggerLoose_UP(1.); + double SF_Trigger_UP(1.), SF_TriggerLoose_UP(1.); + double SF_Reco_UP(1.); + double SF_ID_UP(1.), SF_IDLoose_UP(1.); + double SF_Isol_UP(1.), SF_IsolLoose_UP(1.); + double SF_ChargeID_UP(1.), SF_ChargeIDLoose_UP(1.); + double SF_ChargeMisID_STAT_UP(1.), SF_ChargeMisIDLoose_STAT_UP(1.); + double SF_ChargeMisID_SYST_UP(1.), SF_ChargeMisIDLoose_SYST_UP(1.); + + double EFF_Trigger_DOWN(1.), EFF_TriggerLoose_DOWN(1.); + double SF_Trigger_DOWN(1.), SF_TriggerLoose_DOWN(1.); + double SF_Reco_DOWN(1.); + double SF_ID_DOWN(1.), SF_IDLoose_DOWN(1.); + double SF_Isol_DOWN(1.), SF_IsolLoose_DOWN(1.); + double SF_ChargeID_DOWN(1.), SF_ChargeIDLoose_DOWN(1.); + double SF_ChargeMisID_STAT_DOWN(1.), SF_ChargeMisIDLoose_STAT_DOWN(1.); + double SF_ChargeMisID_SYST_DOWN(1.), SF_ChargeMisIDLoose_SYST_DOWN(1.); + + ///-- Trigger --/// + ///-- Trigger UP --/// + top::check(m_electronEffSFTrigger->applySystematicVariation(m_systTrigger_UP), "Failed to set systematic"); + top::check(m_electronEffSFTriggerLoose->applySystematicVariation( + m_systTrigger_UP), "Failed to set systematic"); + top::check(m_electronEffSFTrigger->getEfficiencyScaleFactor(*electronPtr, SF_Trigger_UP), + "Failed to get SF"); + top::check(m_electronEffSFTriggerLoose->getEfficiencyScaleFactor(*electronPtr, + SF_TriggerLoose_UP), "Failed to get SF"); + top::check(m_electronEffTrigger->applySystematicVariation(m_systTrigger_UP), "Failed to set systematic"); + top::check(m_electronEffTriggerLoose->applySystematicVariation(m_systTrigger_UP), + "Failed to set systematic"); + top::check(m_electronEffTrigger->getEfficiencyScaleFactor(*electronPtr, EFF_Trigger_UP), + "Failed to get SF"); + top::check(m_electronEffTriggerLoose->getEfficiencyScaleFactor(*electronPtr, + EFF_TriggerLoose_UP), "Failed to get SF"); + + ///-- Trigger DOWN --/// + top::check(m_electronEffSFTrigger->applySystematicVariation(m_systTrigger_DOWN), + "Failed to set systematic"); + top::check(m_electronEffSFTriggerLoose->applySystematicVariation( + m_systTrigger_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFTrigger->getEfficiencyScaleFactor(*electronPtr, + SF_Trigger_DOWN), "Failed to get SF"); + top::check(m_electronEffSFTriggerLoose->getEfficiencyScaleFactor(*electronPtr, + SF_TriggerLoose_DOWN), "Failed to get SF"); + top::check(m_electronEffTrigger->applySystematicVariation(m_systTrigger_DOWN), "Failed to set systematic"); + top::check(m_electronEffTriggerLoose->applySystematicVariation( + m_systTrigger_DOWN), "Failed to set systematic"); + top::check(m_electronEffTrigger->getEfficiencyScaleFactor(*electronPtr, + EFF_Trigger_DOWN), "Failed to get SF"); + top::check(m_electronEffTriggerLoose->getEfficiencyScaleFactor(*electronPtr, + EFF_TriggerLoose_DOWN), "Failed to get SF"); + + + ///-- Trigger reset to nominal --/// + top::check(m_electronEffSFTrigger->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFTriggerLoose->applySystematicVariation(m_systNominal), + "Failed to set systematic"); + top::check(m_electronEffTrigger->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffTriggerLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + + + ///-- Reco --/// + ///-- Reco up --/// + top::check(m_electronEffSFReco->applySystematicVariation(m_systReco_UP), "Failed to set systematic"); + top::check(m_electronEffSFReco->getEfficiencyScaleFactor(*electronPtr, SF_Reco_UP), "Failed to get SF"); + + ///-- Reco down --/// + top::check(m_electronEffSFReco->applySystematicVariation(m_systReco_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFReco->getEfficiencyScaleFactor(*electronPtr, SF_Reco_DOWN), "Failed to get SF"); + + ///-- Reco reset to nominal --/// + top::check(m_electronEffSFReco->applySystematicVariation(m_systNominal), "Failed to set systematic"); + + ///-- ID --/// + ///-- ID UP --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systID_UP), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systID_UP), "Failed to set systematic"); + top::check(m_electronEffSFID->getEfficiencyScaleFactor(*electronPtr, SF_ID_UP), "Failed to get SF"); + top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor(*electronPtr, SF_IDLoose_UP), + "Failed to get SF"); + ///-- ID DOWN --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systID_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systID_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFID->getEfficiencyScaleFactor(*electronPtr, SF_ID_DOWN), "Failed to get SF"); + top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_IDLoose_DOWN), "Failed to get SF"); + + ///-- ID reset to nominal --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + + ///-- Iso --/// + ///-- Iso UP --/// + if (m_electronEffIso_exists) { + top::check(m_electronEffSFIso->applySystematicVariation(m_systIso_UP), "Failed to set systematic"); + top::check(m_electronEffSFIso->getEfficiencyScaleFactor(*electronPtr, SF_Isol_UP), "Failed to get SF"); + ///-- Iso DOWN --/// + top::check(m_electronEffSFIso->applySystematicVariation(m_systIso_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFIso->getEfficiencyScaleFactor(*electronPtr, SF_Isol_DOWN), "Failed to get SF"); + ///-- Iso reset to nominal --/// + top::check(m_electronEffSFIso->applySystematicVariation(m_systNominal), "Failed to set systematic"); + } + if (m_electronEffIsoLoose_exists) { + top::check(m_electronEffSFIsoLoose->applySystematicVariation(m_systIso_UP), "Failed to set systematic"); + top::check(m_electronEffSFIsoLoose->getEfficiencyScaleFactor(*electronPtr, + SF_IsolLoose_UP), "Failed to get SF"); + ///-- Iso DOWN --/// + top::check(m_electronEffSFIsoLoose->applySystematicVariation(m_systIso_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFIsoLoose->getEfficiencyScaleFactor(*electronPtr, + SF_IsolLoose_DOWN), "Failed to get SF"); + ///-- Iso reset to nominal --/// + top::check(m_electronEffSFIsoLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + } + + ///-- Charge ID --/// + if (m_electronEffChargeID_exists) { + ///-- Charge ID UP --/// + top::check(m_electronEffSFChargeID->applySystematicVariation( + m_systChargeID_UP), "Failed to set systematic"); + top::check(m_electronEffSFChargeID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeID_UP), "Failed to get SF"); + ///-- Charge ID DOWN --/// + top::check(m_electronEffSFChargeID->applySystematicVariation( + m_systChargeID_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFChargeID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeID_DOWN), "Failed to get SF"); + ///-- Charge ID reset to nominal --/// + top::check(m_electronEffSFChargeID->applySystematicVariation(m_systNominal), "Failed to set systematic"); + } + if (m_electronEffChargeIDLoose_exists) { + ///-- Charge ID UP --/// + top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( + m_systChargeID_UP), "Failed to set systematic"); + top::check(m_electronEffSFChargeIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeIDLoose_UP), + "Failed to get SF"); + ///-- Charge ID DOWN --/// + top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( + m_systChargeID_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFChargeIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeIDLoose_DOWN), + "Failed to get SF"); + ///-- Charge ID reset to nominal --/// + top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + } + + ///-- Charge Mis ID --/// + if (m_electronEffChargeMisID_exists) { + ///-- Charge Mis ID STAT_UP --/// + top::check(m_electronEffSFChargeMisID->applySystematicVariation( + m_systChargeMisID_STAT_UP), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisID_STAT_UP), + "Failed to get SF"); + ///-- Charge Mis ID STAT_DOWN --/// + top::check(m_electronEffSFChargeMisID->applySystematicVariation( + m_systChargeMisID_STAT_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisID_STAT_DOWN), + "Failed to get SF"); + ///-- Charge Mis ID SYS_UP --/// + top::check(m_electronEffSFChargeMisID->applySystematicVariation( + m_systChargeMisID_SYST_UP), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisID_SYST_UP), + "Failed to get SF"); + ///-- Charge Mis ID SYS_DOWN --/// + top::check(m_electronEffSFChargeMisID->applySystematicVariation( + m_systChargeMisID_SYST_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisID_SYST_DOWN), + "Failed to get SF"); + ///-- Charge Mis ID reset to nominal --/// + top::check(m_electronEffSFChargeMisID->applySystematicVariation(m_systNominal), + "Failed to set systematic"); + } + if (m_electronEffChargeMisIDLoose_exists) { + ///-- Charge Mis ID STAT_UP --/// + top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( + m_systChargeMisID_STAT_UP), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisIDLoose_STAT_UP), + "Failed to get SF"); + ///-- Charge Mis ID STAT_DOWN --/// + top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( + m_systChargeMisID_STAT_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisIDLoose_STAT_DOWN), + "Failed to get SF"); + ///-- Charge Mis ID SYS_UP --/// + top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( + m_systChargeMisID_SYST_UP), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisIDLoose_SYST_UP), + "Failed to get SF"); + ///-- Charge Mis ID SYS_DOWN --/// + top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( + m_systChargeMisID_SYST_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_ChargeMisIDLoose_SYST_DOWN), + "Failed to get SF"); + ///-- Charge Mis ID reset to nominal --/// + top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + } ///-- Decorate --/// - electronPtr->auxdecor<float>(m_decor_triggerEff) = Eff_Trigger; - electronPtr->auxdecor<float>(m_decor_triggerEff_loose) = Eff_TriggerLoose; - electronPtr->auxdecor<float>(m_decor_triggerSF) = SF_Trigger; - electronPtr->auxdecor<float>(m_decor_triggerSF_loose) = SF_TriggerLoose; - electronPtr->auxdecor<float>(m_decor_recoSF) = SF_Reco; - electronPtr->auxdecor<float>(m_decor_idSF) = SF_ID; - electronPtr->auxdecor<float>(m_decor_idSF_loose) = SF_IDLoose; - electronPtr->auxdecor<float>(m_decor_isoSF) = SF_Isol; - electronPtr->auxdecor<float>(m_decor_isoSF_loose) = SF_IsolLoose; - electronPtr->auxdecor<float>(m_decor_chargeidSF) = SF_ChargeID; - electronPtr->auxdecor<float>(m_decor_chargeidSF_loose) = SF_ChargeIDLoose; - electronPtr->auxdecor<float>(m_decor_chargemisidSF) = SF_ChargeMisID; - electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose) = SF_ChargeMisIDLoose; - - ///-- For nominal calibration, vary the SF systematics --/// - if (currentSystematic.first == m_config->nominalHashValue()) { - - double EFF_Trigger_UP(1.),EFF_TriggerLoose_UP(1.); - double SF_Trigger_UP(1.),SF_TriggerLoose_UP(1.); - double SF_Reco_UP(1.); - double SF_ID_UP(1.),SF_IDLoose_UP(1.); - double SF_Isol_UP(1.),SF_IsolLoose_UP(1.); - double SF_ChargeID_UP(1.),SF_ChargeIDLoose_UP(1.); - double SF_ChargeMisID_STAT_UP(1.),SF_ChargeMisIDLoose_STAT_UP(1.); - double SF_ChargeMisID_SYST_UP(1.),SF_ChargeMisIDLoose_SYST_UP(1.); - - double EFF_Trigger_DOWN(1.),EFF_TriggerLoose_DOWN(1.); - double SF_Trigger_DOWN(1.),SF_TriggerLoose_DOWN(1.); - double SF_Reco_DOWN(1.); - double SF_ID_DOWN(1.),SF_IDLoose_DOWN(1.); - double SF_Isol_DOWN(1.),SF_IsolLoose_DOWN(1.); - double SF_ChargeID_DOWN(1.),SF_ChargeIDLoose_DOWN(1.); - double SF_ChargeMisID_STAT_DOWN(1.),SF_ChargeMisIDLoose_STAT_DOWN(1.); - double SF_ChargeMisID_SYST_DOWN(1.),SF_ChargeMisIDLoose_SYST_DOWN(1.); - - ///-- Trigger --/// - ///-- Trigger UP --/// - top::check(m_electronEffSFTrigger -> applySystematicVariation( m_systTrigger_UP ),"Failed to set systematic"); - top::check(m_electronEffSFTriggerLoose -> applySystematicVariation( m_systTrigger_UP ),"Failed to set systematic"); - top::check(m_electronEffSFTrigger -> getEfficiencyScaleFactor( *electronPtr , SF_Trigger_UP ) , "Failed to get SF"); - top::check(m_electronEffSFTriggerLoose -> getEfficiencyScaleFactor( *electronPtr , SF_TriggerLoose_UP ) , "Failed to get SF"); - top::check(m_electronEffTrigger -> applySystematicVariation( m_systTrigger_UP ),"Failed to set systematic"); - top::check(m_electronEffTriggerLoose -> applySystematicVariation( m_systTrigger_UP ),"Failed to set systematic"); - top::check(m_electronEffTrigger -> getEfficiencyScaleFactor( *electronPtr , EFF_Trigger_UP ) , "Failed to get SF"); - top::check(m_electronEffTriggerLoose -> getEfficiencyScaleFactor( *electronPtr , EFF_TriggerLoose_UP ) , "Failed to get SF"); - - ///-- Trigger DOWN --/// - top::check(m_electronEffSFTrigger -> applySystematicVariation( m_systTrigger_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFTriggerLoose -> applySystematicVariation( m_systTrigger_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFTrigger -> getEfficiencyScaleFactor( *electronPtr , SF_Trigger_DOWN ) , "Failed to get SF"); - top::check(m_electronEffSFTriggerLoose -> getEfficiencyScaleFactor( *electronPtr , SF_TriggerLoose_DOWN ) , "Failed to get SF"); - top::check(m_electronEffTrigger -> applySystematicVariation( m_systTrigger_DOWN ),"Failed to set systematic"); - top::check(m_electronEffTriggerLoose -> applySystematicVariation( m_systTrigger_DOWN ),"Failed to set systematic"); - top::check(m_electronEffTrigger -> getEfficiencyScaleFactor( *electronPtr , EFF_Trigger_DOWN ) , "Failed to get SF"); - top::check(m_electronEffTriggerLoose -> getEfficiencyScaleFactor( *electronPtr , EFF_TriggerLoose_DOWN ) , "Failed to get SF"); - + electronPtr->auxdecor<float>(m_decor_triggerEff + "_UP") = EFF_Trigger_UP; + electronPtr->auxdecor<float>(m_decor_triggerEff_loose + "_UP") = EFF_TriggerLoose_UP; + electronPtr->auxdecor<float>(m_decor_triggerSF + "_UP") = SF_Trigger_UP; + electronPtr->auxdecor<float>(m_decor_triggerSF_loose + "_UP") = SF_TriggerLoose_UP; + electronPtr->auxdecor<float>(m_decor_recoSF + "_UP") = SF_Reco_UP; + electronPtr->auxdecor<float>(m_decor_idSF + "_UP") = SF_ID_UP; + electronPtr->auxdecor<float>(m_decor_idSF_loose + "_UP") = SF_IDLoose_UP; + electronPtr->auxdecor<float>(m_decor_isoSF + "_UP") = SF_Isol_UP; + electronPtr->auxdecor<float>(m_decor_isoSF_loose + "_UP") = SF_IsolLoose_UP; + electronPtr->auxdecor<float>(m_decor_chargeidSF + "_UP") = SF_ChargeID_UP; + electronPtr->auxdecor<float>(m_decor_chargeidSF_loose + "_UP") = SF_ChargeIDLoose_UP; + electronPtr->auxdecor<float>(m_decor_chargemisidSF + "_STAT_UP") = SF_ChargeMisID_STAT_UP; + electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose + "_STAT_UP") = SF_ChargeMisIDLoose_STAT_UP; + electronPtr->auxdecor<float>(m_decor_chargemisidSF + "_SYST_UP") = SF_ChargeMisID_SYST_UP; + electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose + "_SYST_UP") = SF_ChargeMisIDLoose_SYST_UP; + + electronPtr->auxdecor<float>(m_decor_triggerEff + "_DOWN") = EFF_Trigger_DOWN; + electronPtr->auxdecor<float>(m_decor_triggerEff_loose + "_DOWN") = EFF_TriggerLoose_DOWN; + electronPtr->auxdecor<float>(m_decor_triggerSF + "_DOWN") = SF_Trigger_DOWN; + electronPtr->auxdecor<float>(m_decor_triggerSF_loose + "_DOWN") = SF_TriggerLoose_DOWN; + electronPtr->auxdecor<float>(m_decor_recoSF + "_DOWN") = SF_Reco_DOWN; + electronPtr->auxdecor<float>(m_decor_idSF + "_DOWN") = SF_ID_DOWN; + electronPtr->auxdecor<float>(m_decor_idSF_loose + "_DOWN") = SF_IDLoose_DOWN; + electronPtr->auxdecor<float>(m_decor_isoSF + "_DOWN") = SF_Isol_DOWN; + electronPtr->auxdecor<float>(m_decor_isoSF_loose + "_DOWN") = SF_IsolLoose_DOWN; + electronPtr->auxdecor<float>(m_decor_chargeidSF + "_DOWN") = SF_ChargeID_DOWN; + electronPtr->auxdecor<float>(m_decor_chargeidSF_loose + "_DOWN") = SF_ChargeIDLoose_DOWN; + electronPtr->auxdecor<float>(m_decor_chargemisidSF + "_STAT_DOWN") = SF_ChargeMisID_STAT_DOWN; + electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose + "_STAT_DOWN") = SF_ChargeMisIDLoose_STAT_DOWN; + electronPtr->auxdecor<float>(m_decor_chargemisidSF + "_SYST_DOWN") = SF_ChargeMisID_SYST_DOWN; + electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose + "_SYST_DOWN") = SF_ChargeMisIDLoose_SYST_DOWN; + + ///-- Debug messages --/// + + ATH_MSG_DEBUG("Electron Trigger Eff = " << electronPtr->auxdataConst<float>(m_decor_triggerEff) << " + " << + electronPtr->auxdataConst<float>(m_decor_triggerEff + "_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_triggerEff + "_DOWN") + ); + + ATH_MSG_DEBUG("Electron Trigger MediumLH SF = " << electronPtr->auxdataConst<float>( + m_decor_triggerSF) << " + " << + electronPtr->auxdataConst<float>(m_decor_triggerSF + "_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_triggerSF + "_DOWN") + ); + + ATH_MSG_DEBUG("Electron Reco SF = " << electronPtr->auxdataConst<float>(m_decor_recoSF) << " + " << + electronPtr->auxdataConst<float>(m_decor_recoSF + "_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_recoSF + "_DOWN") + ); + + ATH_MSG_DEBUG("Electron ID SF = " << electronPtr->auxdataConst<float>(m_decor_idSF) << " + " << + electronPtr->auxdataConst<float>(m_decor_idSF + "_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_idSF + "_DOWN") + ); + + ATH_MSG_DEBUG("Electron Charge ID SF = " << electronPtr->auxdataConst<float>(m_decor_chargeidSF) << " + " << + electronPtr->auxdataConst<float>(m_decor_chargeidSF + "_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_chargeidSF + "_DOWN") + ); + + ATH_MSG_DEBUG("Electron Charge Mis-ID SF = " << electronPtr->auxdataConst<float>( + m_decor_chargemisidSF) << " + " << + electronPtr->auxdataConst<float>(m_decor_chargemisidSF + "_STAT_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_chargemisidSF + "_STAT_DOWN") << " + " << + electronPtr->auxdataConst<float>(m_decor_chargemisidSF + "_SYST_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_chargemisidSF + "_SYST_DOWN") + ); + + + /////now taking care of additional systematic model if needed + if (m_config->electronEfficiencySystematicModel() != "TOTAL") { + std::vector<float> vec_Eff_Trigger_UP, vec_Eff_Trigger_DOWN, vec_Eff_TriggerLoose_UP, + vec_Eff_TriggerLoose_DOWN; + std::vector<float> vec_SF_Trigger_UP, vec_SF_Trigger_DOWN, vec_SF_TriggerLoose_UP, + vec_SF_TriggerLoose_DOWN; + std::vector<float> vec_SF_Reco_UP, vec_SF_Reco_DOWN; + std::vector<float> vec_SF_ID_UP, vec_SF_ID_DOWN, vec_SF_IDLoose_UP, vec_SF_IDLoose_DOWN; + std::vector<float> vec_SF_Isol_UP, vec_SF_Isol_DOWN, vec_SF_IsolLoose_UP, vec_SF_IsolLoose_DOWN; + std::vector<float> vec_SF_ChargeID_UP, vec_SF_ChargeID_DOWN, vec_SF_ChargeIDLoose_UP, + vec_SF_ChargeIDLoose_DOWN; + std::vector<float> vec_SF_ChargeMisID_UP, vec_SF_ChargeMisID_DOWN, vec_SF_ChargeMisIDLoose_UP, + vec_SF_ChargeMisIDLoose_DOWN; + + double EFF_Trigger(1.), EFF_TriggerLoose(1.); + double SF_Trigger(1.), SF_TriggerLoose(1.); + double SF_Reco(1.); + double SF_ID(1.), SF_IDLoose(1.); + double SF_Isol(1.), SF_IsolLoose(1.); + + /// --Trigger-- /// + int count = 0; + for (const CP::SystematicSet& isyst : m_systTriggerCorrModel) { + if (count == 0) { //0 is nominal + count++; + continue; + } + + top::check(m_electronEffSFTriggerCorrModel->applySystematicVariation(isyst), + "Failed to set systematic"); + top::check(m_electronEffSFTriggerLooseCorrModel->applySystematicVariation( + isyst), "Failed to set systematic"); + top::check(m_electronEffSFTriggerCorrModel->getEfficiencyScaleFactor(*electronPtr, + SF_Trigger), "Failed to get SF"); + top::check(m_electronEffSFTriggerLooseCorrModel->getEfficiencyScaleFactor(*electronPtr, + SF_TriggerLoose), + "Failed to get SF"); + top::check(m_electronEffTriggerCorrModel->applySystematicVariation(isyst), "Failed to set systematic"); + top::check(m_electronEffTriggerLooseCorrModel->applySystematicVariation( + isyst), "Failed to set systematic"); + top::check(m_electronEffTriggerCorrModel->getEfficiencyScaleFactor(*electronPtr, + EFF_Trigger), "Failed to get SF"); + top::check(m_electronEffTriggerLooseCorrModel->getEfficiencyScaleFactor(*electronPtr, + EFF_TriggerLoose), + "Failed to get SF"); + + // split by down and up + if (count % 2 == 1) { + vec_SF_Trigger_DOWN.emplace_back(SF_Trigger); + vec_SF_TriggerLoose_DOWN.emplace_back(SF_TriggerLoose); + vec_Eff_Trigger_DOWN.emplace_back(EFF_Trigger); + vec_Eff_TriggerLoose_DOWN.emplace_back(EFF_TriggerLoose); + } else { + vec_SF_Trigger_UP.emplace_back(SF_Trigger); + vec_SF_TriggerLoose_UP.emplace_back(SF_TriggerLoose); + vec_Eff_Trigger_UP.emplace_back(EFF_Trigger); + vec_Eff_TriggerLoose_UP.emplace_back(EFF_TriggerLoose); + } + + count++; + } + + // Do some sanity check + if (vec_SF_Trigger_DOWN.size() != vec_SF_Trigger_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of trigger SF for up and down are different" + }; + } + if (vec_SF_TriggerLoose_DOWN.size() != vec_SF_TriggerLoose_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of triggerLoose SF for up and down are different" + }; + } + if (vec_Eff_Trigger_DOWN.size() != vec_Eff_Trigger_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of trigger Eff for up and down are different" + }; + } + if (vec_Eff_TriggerLoose_DOWN.size() != vec_Eff_TriggerLoose_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of triggerLoose Eff for up and down are different" + }; + } ///-- Trigger reset to nominal --/// - top::check(m_electronEffSFTrigger -> applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffSFTriggerLoose -> applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffTrigger -> applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffTriggerLoose -> applySystematicVariation( m_systNominal ),"Failed to set systematic"); - - - ///-- Reco --/// - ///-- Reco up --/// - top::check( m_electronEffSFReco->applySystematicVariation( m_systReco_UP ) , "Failed to set systematic" ); - top::check( m_electronEffSFReco->getEfficiencyScaleFactor( *electronPtr , SF_Reco_UP ) , "Failed to get SF"); - - ///-- Reco down --/// - top::check( m_electronEffSFReco->applySystematicVariation( m_systReco_DOWN ) , "Failed to set systematic" ); - top::check( m_electronEffSFReco->getEfficiencyScaleFactor( *electronPtr , SF_Reco_DOWN ) , "Failed to get SF"); + top::check(m_electronEffSFTriggerCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFTriggerLooseCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + top::check(m_electronEffTriggerCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + top::check(m_electronEffTriggerLooseCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + + /// --Reco-- /// + count = 0; + for (const CP::SystematicSet& isyst : m_systRecoCorrModel) { + if (count == 0) { //0 is nominal + count++; + continue; + } + + top::check(m_electronEffSFRecoCorrModel->applySystematicVariation(isyst), "Failed to set systematic"); + top::check(m_electronEffSFRecoCorrModel->getEfficiencyScaleFactor(*electronPtr, + SF_Reco), "Failed to get SF"); + + if (count % 2 == 1) { + vec_SF_Reco_DOWN.emplace_back(SF_Reco); + } else { + vec_SF_Reco_UP.emplace_back(SF_Reco); + } + ++count; + } + if (vec_SF_Reco_DOWN.size() != vec_SF_Reco_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of Reco SF for up and down are different" + }; + } ///-- Reco reset to nominal --/// - top::check( m_electronEffSFReco->applySystematicVariation( m_systNominal ) , "Failed to set systematic" ); - - ///-- ID --/// - ///-- ID UP --/// - top::check(m_electronEffSFID->applySystematicVariation( m_systID_UP ),"Failed to set systematic"); - top::check(m_electronEffSFIDLoose->applySystematicVariation( m_systID_UP ),"Failed to set systematic"); - top::check(m_electronEffSFID->getEfficiencyScaleFactor( *electronPtr , SF_ID_UP ) , "Failed to get SF"); - top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_IDLoose_UP ) , "Failed to get SF"); - ///-- ID DOWN --/// - top::check(m_electronEffSFID->applySystematicVariation( m_systID_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFIDLoose->applySystematicVariation( m_systID_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFID->getEfficiencyScaleFactor( *electronPtr , SF_ID_DOWN ) , "Failed to get SF"); - top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_IDLoose_DOWN ) , "Failed to get SF"); + top::check(m_electronEffSFRecoCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + + /// --ID-- /// + count = 0; + for (const CP::SystematicSet& isyst : m_systIDCorrModel) { + if (count == 0) { //0 is nominal + count++; + continue; + } + + top::check(m_electronEffSFIDCorrModel->applySystematicVariation(isyst), "Failed to set systematic"); + top::check(m_electronEffSFIDLooseCorrModel->applySystematicVariation(isyst), + "Failed to set systematic"); + top::check(m_electronEffSFIDCorrModel->getEfficiencyScaleFactor(*electronPtr, SF_ID), + "Failed to get SF"); + top::check(m_electronEffSFIDLooseCorrModel->getEfficiencyScaleFactor(*electronPtr, + SF_IDLoose), "Failed to get SF"); + + if (count % 2 == 1) { + vec_SF_ID_DOWN.emplace_back(SF_ID); + vec_SF_IDLoose_DOWN.emplace_back(SF_IDLoose); + } else { + vec_SF_ID_UP.emplace_back(SF_ID); + vec_SF_IDLoose_UP.emplace_back(SF_IDLoose); + } + ++count; + } + if (vec_SF_ID_DOWN.size() != vec_SF_ID_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of ID SF for up and down are different" + }; + } + if (vec_SF_IDLoose_DOWN.size() != vec_SF_IDLoose_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of IDLoose SF for up and down are different" + }; + } ///-- ID reset to nominal --/// - top::check(m_electronEffSFID->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - top::check(m_electronEffSFIDLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); + top::check(m_electronEffSFIDCorrModel->applySystematicVariation(m_systNominal), + "Failed to set systematic"); + top::check(m_electronEffSFIDLooseCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); ///-- Iso --/// - ///-- Iso UP --/// - if( m_electronEffIso_exists ) { - top::check(m_electronEffSFIso -> applySystematicVariation( m_systIso_UP ),"Failed to set systematic"); - top::check(m_electronEffSFIso -> getEfficiencyScaleFactor( *electronPtr , SF_Isol_UP ) , "Failed to get SF"); - ///-- Iso DOWN --/// - top::check(m_electronEffSFIso -> applySystematicVariation( m_systIso_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFIso -> getEfficiencyScaleFactor( *electronPtr , SF_Isol_DOWN ) , "Failed to get SF"); - ///-- Iso reset to nominal --/// - top::check(m_electronEffSFIso -> applySystematicVariation( m_systNominal ),"Failed to set systematic"); - } - if( m_electronEffIsoLoose_exists ) { - top::check(m_electronEffSFIsoLoose -> applySystematicVariation( m_systIso_UP ),"Failed to set systematic"); - top::check(m_electronEffSFIsoLoose -> getEfficiencyScaleFactor( *electronPtr , SF_IsolLoose_UP ) , "Failed to get SF"); - ///-- Iso DOWN --/// - top::check(m_electronEffSFIsoLoose -> applySystematicVariation( m_systIso_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFIsoLoose -> getEfficiencyScaleFactor( *electronPtr , SF_IsolLoose_DOWN ) , "Failed to get SF"); - ///-- Iso reset to nominal --/// - top::check(m_electronEffSFIsoLoose -> applySystematicVariation( m_systNominal ),"Failed to set systematic"); - } - - ///-- Charge ID --/// - if( m_electronEffChargeID_exists ) { - ///-- Charge ID UP --/// - top::check(m_electronEffSFChargeID->applySystematicVariation( m_systChargeID_UP ),"Failed to set systematic"); - top::check(m_electronEffSFChargeID->getEfficiencyScaleFactor( *electronPtr , SF_ChargeID_UP ) , "Failed to get SF"); - ///-- Charge ID DOWN --/// - top::check(m_electronEffSFChargeID->applySystematicVariation( m_systChargeID_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFChargeID->getEfficiencyScaleFactor( *electronPtr , SF_ChargeID_DOWN ) , "Failed to get SF"); - ///-- Charge ID reset to nominal --/// - top::check(m_electronEffSFChargeID->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - } - if( m_electronEffChargeIDLoose_exists ) { - ///-- Charge ID UP --/// - top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( m_systChargeID_UP ),"Failed to set systematic"); - top::check(m_electronEffSFChargeIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_ChargeIDLoose_UP ) , "Failed to get SF"); - ///-- Charge ID DOWN --/// - top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( m_systChargeID_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFChargeIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_ChargeIDLoose_DOWN ) , "Failed to get SF"); - ///-- Charge ID reset to nominal --/// - top::check(m_electronEffSFChargeIDLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - } - - ///-- Charge Mis ID --/// - if( m_electronEffChargeID_exists ) { - ///-- Charge Mis ID STAT_UP --/// - top::check(m_electronEffSFChargeMisID->applySystematicVariation( m_systChargeMisID_STAT_UP ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisID_STAT_UP ) , "Failed to get SF"); - ///-- Charge Mis ID STAT_DOWN --/// - top::check(m_electronEffSFChargeMisID->applySystematicVariation( m_systChargeMisID_STAT_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisID_STAT_DOWN ) , "Failed to get SF"); - ///-- Charge Mis ID SYS_UP --/// - top::check(m_electronEffSFChargeMisID->applySystematicVariation( m_systChargeMisID_SYST_UP ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisID_SYST_UP ) , "Failed to get SF"); - ///-- Charge Mis ID SYS_DOWN --/// - top::check(m_electronEffSFChargeMisID->applySystematicVariation( m_systChargeMisID_SYST_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisID->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisID_SYST_DOWN ) , "Failed to get SF"); - ///-- Charge Mis ID reset to nominal --/// - top::check(m_electronEffSFChargeMisID->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - } - if( m_electronEffChargeIDLoose_exists ) { - ///-- Charge Mis ID STAT_UP --/// - top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( m_systChargeMisID_STAT_UP ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisIDLoose_STAT_UP ) , "Failed to get SF"); - ///-- Charge Mis ID STAT_DOWN --/// - top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( m_systChargeMisID_STAT_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisIDLoose_STAT_DOWN ) , "Failed to get SF"); - ///-- Charge Mis ID SYS_UP --/// - top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( m_systChargeMisID_SYST_UP ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisIDLoose_SYST_UP ) , "Failed to get SF"); - ///-- Charge Mis ID SYS_DOWN --/// - top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( m_systChargeMisID_SYST_DOWN ),"Failed to set systematic"); - top::check(m_electronEffSFChargeMisIDLoose->getEfficiencyScaleFactor( *electronPtr , SF_ChargeMisIDLoose_SYST_DOWN ) , "Failed to get SF"); - ///-- Charge Mis ID reset to nominal --/// - top::check(m_electronEffSFChargeMisIDLoose->applySystematicVariation( m_systNominal ),"Failed to set systematic"); - } + count = 0; + for (const CP::SystematicSet& isyst : m_systIsoCorrModel) { + if (count == 0) { //0 is nominal + count++; + continue; + } + + if (m_electronEffIso_exists) { + top::check(m_electronEffSFIsoCorrModel->applySystematicVariation(isyst), "Failed to set systematic"); + top::check(m_electronEffSFIsoCorrModel->getEfficiencyScaleFactor(*electronPtr, + SF_Isol), "Failed to get SF"); + ///-- Iso reset to nominal --/// + top::check(m_electronEffSFIsoCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + } + if (m_electronEffIsoLoose_exists) { + top::check(m_electronEffSFIsoLooseCorrModel->applySystematicVariation( + isyst), "Failed to set systematic"); + top::check(m_electronEffSFIsoLooseCorrModel->getEfficiencyScaleFactor(*electronPtr, + SF_IsolLoose), + "Failed to get SF"); + ///-- Iso reset to nominal --/// + top::check(m_electronEffSFIsoLooseCorrModel->applySystematicVariation( + m_systNominal), "Failed to set systematic"); + } + if (count % 2 == 1) { + vec_SF_Isol_DOWN.emplace_back(SF_Isol); + vec_SF_IsolLoose_DOWN.emplace_back(SF_IsolLoose); + } else { + vec_SF_Isol_UP.emplace_back(SF_Isol); + vec_SF_IsolLoose_UP.emplace_back(SF_IsolLoose); + } + ++count; + } + if (vec_SF_Isol_DOWN.size() != vec_SF_Isol_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of Isol SF for up and down are different" + }; + } + if (vec_SF_IsolLoose_DOWN.size() != vec_SF_IsolLoose_UP.size()) { + throw std::runtime_error { + "ElectronScaleFactorCalculator::execute: Sizes of IsolLoose SF for up and down are different" + }; + } + ///-- Decorate --/// - electronPtr->auxdecor<float>(m_decor_triggerEff+"_UP") = EFF_Trigger_UP; - electronPtr->auxdecor<float>(m_decor_triggerEff_loose+"_UP") = EFF_TriggerLoose_UP; - electronPtr->auxdecor<float>(m_decor_triggerSF+"_UP") = SF_Trigger_UP; - electronPtr->auxdecor<float>(m_decor_triggerSF_loose+"_UP") = SF_TriggerLoose_UP; - electronPtr->auxdecor<float>(m_decor_recoSF+"_UP") = SF_Reco_UP; - electronPtr->auxdecor<float>(m_decor_idSF+"_UP") = SF_ID_UP; - electronPtr->auxdecor<float>(m_decor_idSF_loose+"_UP") = SF_IDLoose_UP; - electronPtr->auxdecor<float>(m_decor_isoSF+"_UP") = SF_Isol_UP; - electronPtr->auxdecor<float>(m_decor_isoSF_loose+"_UP") = SF_IsolLoose_UP; - electronPtr->auxdecor<float>(m_decor_chargeidSF+"_UP") = SF_ChargeID_UP; - electronPtr->auxdecor<float>(m_decor_chargeidSF_loose+"_UP") = SF_ChargeIDLoose_UP; - electronPtr->auxdecor<float>(m_decor_chargemisidSF+"_STAT_UP") = SF_ChargeMisID_STAT_UP; - electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose+"_STAT_UP") = SF_ChargeMisIDLoose_STAT_UP; - electronPtr->auxdecor<float>(m_decor_chargemisidSF+"_SYST_UP") = SF_ChargeMisID_SYST_UP; - electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose+"_SYST_UP") = SF_ChargeMisIDLoose_SYST_UP; - - electronPtr->auxdecor<float>(m_decor_triggerEff+"_DOWN") = EFF_Trigger_DOWN; - electronPtr->auxdecor<float>(m_decor_triggerEff_loose+"_DOWN") = EFF_TriggerLoose_DOWN; - electronPtr->auxdecor<float>(m_decor_triggerSF+"_DOWN") = SF_Trigger_DOWN; - electronPtr->auxdecor<float>(m_decor_triggerSF_loose+"_DOWN") = SF_TriggerLoose_DOWN; - electronPtr->auxdecor<float>(m_decor_recoSF+"_DOWN") = SF_Reco_DOWN; - electronPtr->auxdecor<float>(m_decor_idSF+"_DOWN") = SF_ID_DOWN; - electronPtr->auxdecor<float>(m_decor_idSF_loose+"_DOWN") = SF_IDLoose_DOWN; - electronPtr->auxdecor<float>(m_decor_isoSF+"_DOWN") = SF_Isol_DOWN; - electronPtr->auxdecor<float>(m_decor_isoSF_loose+"_DOWN") = SF_IsolLoose_DOWN; - electronPtr->auxdecor<float>(m_decor_chargeidSF+"_DOWN") = SF_ChargeID_DOWN; - electronPtr->auxdecor<float>(m_decor_chargeidSF_loose+"_DOWN") = SF_ChargeIDLoose_DOWN; - electronPtr->auxdecor<float>(m_decor_chargemisidSF+"_STAT_DOWN") = SF_ChargeMisID_STAT_DOWN; - electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose+"_STAT_DOWN") = SF_ChargeMisIDLoose_STAT_DOWN; - electronPtr->auxdecor<float>(m_decor_chargemisidSF+"_SYST_DOWN") = SF_ChargeMisID_SYST_DOWN; - electronPtr->auxdecor<float>(m_decor_chargemisidSF_loose+"_SYST_DOWN") = SF_ChargeMisIDLoose_SYST_DOWN; - - ///-- Debug messages --/// - - ATH_MSG_DEBUG("Electron Trigger Eff = "<<electronPtr->auxdataConst<float>(m_decor_triggerEff) << " + "<< - electronPtr->auxdataConst<float>(m_decor_triggerEff+"_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_triggerEff+"_DOWN") - ); - - ATH_MSG_DEBUG("Electron Trigger MediumLH SF = "<<electronPtr->auxdataConst<float>(m_decor_triggerSF) << " + "<< - electronPtr->auxdataConst<float>(m_decor_triggerSF+"_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_triggerSF+"_DOWN") - ); - - ATH_MSG_DEBUG("Electron Reco SF = "<<electronPtr->auxdataConst<float>(m_decor_recoSF) << " + "<< - electronPtr->auxdataConst<float>(m_decor_recoSF+"_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_recoSF+"_DOWN") - ); - - ATH_MSG_DEBUG("Electron ID SF = "<<electronPtr->auxdataConst<float>(m_decor_idSF) << " + "<< - electronPtr->auxdataConst<float>(m_decor_idSF+"_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_idSF+"_DOWN") - ); - - ATH_MSG_DEBUG("Electron Charge ID SF = "<<electronPtr->auxdataConst<float>(m_decor_chargeidSF) << " + "<< - electronPtr->auxdataConst<float>(m_decor_chargeidSF+"_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_chargeidSF+"_DOWN") - ); - - ATH_MSG_DEBUG("Electron Charge Mis-ID SF = "<<electronPtr->auxdataConst<float>(m_decor_chargemisidSF) << " + "<< - electronPtr->auxdataConst<float>(m_decor_chargemisidSF+"_STAT_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_chargemisidSF+"_STAT_DOWN") << " + "<< - electronPtr->auxdataConst<float>(m_decor_chargemisidSF+"_SYST_UP") << " - "<< - electronPtr->auxdataConst<float>(m_decor_chargemisidSF+"_SYST_DOWN") - ); - - } // Calibration systematic is nominal, so calculate SF systematics + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerEff + "_CorrModel_UP") = vec_Eff_Trigger_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerEff_loose + + "_CorrModel_UP") = vec_Eff_TriggerLoose_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerSF + "_CorrModel_UP") = vec_SF_Trigger_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerSF_loose + + "_CorrModel_UP") = vec_SF_TriggerLoose_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_recoSF + "_CorrModel_UP") = vec_SF_Reco_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_idSF + "_CorrModel_UP") = vec_SF_ID_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_idSF_loose + "_CorrModel_UP") = vec_SF_IDLoose_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_isoSF + "_CorrModel_UP") = vec_SF_Isol_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_isoSF_loose + "_CorrModel_UP") = vec_SF_IsolLoose_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargeidSF + "_CorrModel_UP") = vec_SF_ChargeID_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargeidSF_loose + + "_CorrModel_UP") = vec_SF_ChargeIDLoose_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargemisidSF + + "_CorrModel_UP") = vec_SF_ChargeMisID_UP; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargemisidSF_loose + + "_CorrModel_UP") = vec_SF_ChargeMisIDLoose_UP; + + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerEff + "_CorrModel_DOWN") = vec_Eff_Trigger_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerEff_loose + + "_CorrModel_DOWN") = vec_Eff_TriggerLoose_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerSF + "_CorrModel_DOWN") = vec_SF_Trigger_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_triggerSF_loose + + "_CorrModel_DOWN") = vec_SF_TriggerLoose_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_recoSF + "_CorrModel_DOWN") = vec_SF_Reco_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_idSF + "_CorrModel_DOWN") = vec_SF_ID_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_idSF_loose + "_CorrModel_DOWN") = vec_SF_IDLoose_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_isoSF + "_CorrModel_DOWN") = vec_SF_Isol_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_isoSF_loose + + "_CorrModel_DOWN") = vec_SF_IsolLoose_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargeidSF + "_CorrModel_DOWN") = vec_SF_ChargeID_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargeidSF_loose + + "_CorrModel_DOWN") = vec_SF_ChargeIDLoose_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargemisidSF + + "_CorrModel_DOWN") = vec_SF_ChargeMisID_DOWN; + electronPtr->auxdecor<std::vector<float> >(m_decor_chargemisidSF_loose + + "_CorrModel_DOWN") = vec_SF_ChargeMisIDLoose_DOWN; + }//end of saving additional systematic model + + + ///////////////////////////////////////// + } // Calibration systematic is nominal, so calculate SF systematics } } } @@ -497,5 +911,4 @@ namespace top{ return StatusCode::SUCCESS; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/FwdElectronScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/FwdElectronScaleFactorCalculator.cxx new file mode 100644 index 0000000000000000000000000000000000000000..54fbedf498ee7dbd0138c5dbd6bcfe7d9a15adab --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/FwdElectronScaleFactorCalculator.cxx @@ -0,0 +1,125 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +// $Id: ElectronScaleFactorCalculator.cxx 799556 2017-03-05 19:46:03Z tpelzer $ +#include "TopCorrections/FwdElectronScaleFactorCalculator.h" +#include "TopConfiguration/TopConfig.h" +#include "TopEvent/EventTools.h" + +#include "xAODEgamma/ElectronContainer.h" + + +namespace top { + FwdElectronScaleFactorCalculator::FwdElectronScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + + m_systNominal(CP::SystematicSet()), + m_systID_UP(CP::SystematicSet()), + m_systID_DOWN(CP::SystematicSet()), + m_electronEffSFID("AsgFwdElectronEfficiencyCorrectionTool_ID"), + m_electronEffSFIDLoose("AsgFwdElectronEfficiencyCorrectionTool_IDLoose"), + m_decor_idSF("SetMe"), + m_decor_idSF_loose("SetMe") { + declareProperty("config", m_config); + } + + StatusCode FwdElectronScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::FwdElectronScaleFactorCalculator initialize"); + + top::check(m_electronEffSFID.retrieve(), "Failed to retrieve FWD electron SF Tool"); + top::check(m_electronEffSFIDLoose.retrieve(), "Failed to retrieve FWD electron Loose SF Tool"); + + m_systID_UP.insert(CP::SystematicVariation("EL_EFF_FwdID_TOTAL_1NPCOR_PLUS_UNCOR", 1)); + m_systID_DOWN.insert(CP::SystematicVariation("EL_EFF_FwdID_TOTAL_1NPCOR_PLUS_UNCOR", -1)); + + m_decor_idSF = "FWDEL_SF_ID_" + m_config->fwdElectronID(); + m_decor_idSF_loose = "FWDEL_LOOSE_SF_ID_" + m_config->fwdElectronIDLoose(); + + return StatusCode::SUCCESS; + } + + StatusCode FwdElectronScaleFactorCalculator::execute() { + ///-- Loop over all electron collections --/// + for (auto currentSystematic : *m_config->systSgKeyMapFwdElectrons()) { + const xAOD::ElectronContainer* electrons(nullptr); + top::check(evtStore()->retrieve(electrons, currentSystematic.second), "failed to retrieve electrons"); + + ///-- Tell the SF tools to use the nominal systematic --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + + /// -- Loop over all electrons in each collection --/// + for (auto electronPtr : *electrons) { + /// -- Does the electron pass object selection? --/// + bool passSelection(false); + if (electronPtr->isAvailable<char>("passPreORSelection")) { + if (electronPtr->auxdataConst<char>("passPreORSelection") == 1) { + passSelection = true; + } + } + if (electronPtr->isAvailable<char>("passPreORSelectionLoose")) { + if (electronPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { + passSelection = true; + } + } + + if (passSelection) { + double SF_ID(1.), SF_IDLoose(1.); + + ///-- Get Efficiencies --/// + + top::check(m_electronEffSFID->getEfficiencyScaleFactor(*electronPtr, SF_ID), "Failed to get SF"); + top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor(*electronPtr, SF_IDLoose), "Failed to get SF"); + + + ///-- Decorate --/// + electronPtr->auxdecor<float>(m_decor_idSF) = SF_ID; + electronPtr->auxdecor<float>(m_decor_idSF_loose) = SF_IDLoose; + + ///-- For nominal calibration, vary the SF systematics --/// + if (currentSystematic.first == m_config->nominalHashValue()) { + double SF_ID_UP(1.), SF_IDLoose_UP(1.); + double SF_ID_DOWN(1.), SF_IDLoose_DOWN(1.); + + ///-- ID --/// + ///-- ID up --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systID_UP), "Failed to set systematic"); + top::check(m_electronEffSFID->getEfficiencyScaleFactor(*electronPtr, SF_ID_UP), "Failed to get SF"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systID_UP), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor(*electronPtr, SF_IDLoose_UP), + "Failed to get SF"); + + ///-- ID down --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systID_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFID->getEfficiencyScaleFactor(*electronPtr, SF_ID_DOWN), "Failed to get SF"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systID_DOWN), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->getEfficiencyScaleFactor(*electronPtr, + SF_IDLoose_DOWN), "Failed to get SF"); + + ///-- ID reset to nominal --/// + top::check(m_electronEffSFID->applySystematicVariation(m_systNominal), "Failed to set systematic"); + top::check(m_electronEffSFIDLoose->applySystematicVariation(m_systNominal), "Failed to set systematic"); + + ///-- Decorate --/// + electronPtr->auxdecor<float>(m_decor_idSF + "_UP") = SF_ID_UP; + electronPtr->auxdecor<float>(m_decor_idSF + "_DOWN") = SF_ID_DOWN; + electronPtr->auxdecor<float>(m_decor_idSF_loose + "_UP") = SF_IDLoose_UP; + electronPtr->auxdecor<float>(m_decor_idSF_loose + "_DOWN") = SF_IDLoose_DOWN; + + ///-- Debug messages --/// + + ATH_MSG_DEBUG("Fwd Electron ID SF = " << electronPtr->auxdataConst<float>(m_decor_idSF) << " + " << + electronPtr->auxdataConst<float>(m_decor_idSF + "_UP") << " - " << + electronPtr->auxdataConst<float>(m_decor_idSF + "_DOWN") + ); + } // Calibration systematic is nominal, so calculate SF systematics + } + } + } + + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/GlobalLeptonTriggerCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/GlobalLeptonTriggerCalculator.cxx new file mode 100644 index 0000000000000000000000000000000000000000..91b061a9cb1518716c5c363b7fe0453445a70646 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/GlobalLeptonTriggerCalculator.cxx @@ -0,0 +1,201 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopCorrections/GlobalLeptonTriggerCalculator.h" +#include "TopConfiguration/TopConfig.h" +#include "TopEvent/EventTools.h" +#include "TopEvent/SystematicEvent.h" + +#include "xAODEgamma/ElectronContainer.h" +#include "xAODEgamma/Electron.h" +#include "xAODMuon/MuonContainer.h" +#include "xAODMuon/Muon.h" +#include "xAODEventInfo/EventInfo.h" +#include "EgammaAnalysisInterfaces/IAsgElectronEfficiencyCorrectionTool.h" +#include "MuonAnalysisInterfaces/IMuonTriggerScaleFactors.h" +#include "ElectronEfficiencyCorrection/AsgElectronEfficiencyCorrectionTool.h" +#include <vector> + + +namespace top { + GlobalLeptonTriggerCalculator::GlobalLeptonTriggerCalculator(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + + m_globalTriggerSF("TrigGlobalEfficiencyCorrectionTool::TrigGlobal"), + m_globalTriggerSFLoose("TrigGlobalEfficiencyCorrectionTool::TrigGlobalLoose"), + + m_decor_triggerSF("AnalysisTop_Trigger_SF") { + declareProperty("config", m_config); + } + + StatusCode GlobalLeptonTriggerCalculator::initialize() { + ATH_MSG_INFO(" top::GlobalLeptonTriggerCalculator initialize"); + + if (m_config->doTightEvents()) top::check(m_globalTriggerSF.retrieve(), + "Failed to retrieve global trigger SF tool"); + if (m_config->doLooseEvents()) top::check( + m_globalTriggerSFLoose.retrieve(), "Failed to retrieve global trigger SF tool (loose)"); + + // Retrieve the systematic names we stored + for (auto& s : m_config->getGlobalTriggerElectronSystematics()) ATH_MSG_DEBUG(" - Electron systematics : " << s); + for (auto& s : m_config->getGlobalTriggerMuonSystematics()) ATH_MSG_DEBUG(" - Muon systematics : " << s); + + { + std::vector<ToolHandle<IAsgElectronEfficiencyCorrectionTool> > tools; + tools.reserve(m_config->getGlobalTriggerElectronTools().size()); + for (auto const& s : m_config->getGlobalTriggerElectronTools()) { + ATH_MSG_DEBUG(" - Electron tools : " << s); + tools.emplace_back(s); + top::check(tools.back().retrieve(), "Failed to retrieve electron tool"); + } + m_electronTools.swap(tools); + } + { + std::vector<ToolHandle<CP::IMuonTriggerScaleFactors> > tools; + tools.reserve(m_config->getGlobalTriggerMuonTools().size()); + for (auto const& s : m_config->getGlobalTriggerMuonTools()) { + ATH_MSG_DEBUG(" - Muon tools : " << s); + tools.emplace_back(s); + top::check(tools.back().retrieve(), "Failed to retrieve muon tool"); + } + m_muonTools.swap(tools); + } + + return StatusCode::SUCCESS; + } + + StatusCode GlobalLeptonTriggerCalculator::execute() { + ATH_MSG_DEBUG("Entered GlobalLeptonTriggerCalculator::execute"); + + auto const& nominalHash = m_config->nominalHashValue(); + if (m_config->doTightEvents()) { + xAOD::SystematicEventContainer const* systEvents = nullptr; + top::check(evtStore()->retrieve(systEvents, + m_config->sgKeyTopSystematicEvents()), + "Failed to get xAOD::SystematicEventContainer"); + for (const xAOD::SystematicEvent* systEvent : *systEvents) { + bool withScaleFactorVariations = (systEvent->hashValue() == nominalHash); + processEvent(systEvent, withScaleFactorVariations); + } + } + if (m_config->doLooseEvents()) { + xAOD::SystematicEventContainer const* systEvents = nullptr; + top::check(evtStore()->retrieve(systEvents, + m_config->sgKeyTopSystematicEventsLoose()), + "Failed to get xAOD::SystematicEventContainer"); + for (const xAOD::SystematicEvent* systEvent : *systEvents) { + bool withScaleFactorVariations = (systEvent->hashValue() == nominalHash); + processEvent(systEvent, withScaleFactorVariations); + } + } + + ATH_MSG_DEBUG("Leaving GlobalLeptonTriggerCalculator::execute"); + return StatusCode::SUCCESS; + } + + void GlobalLeptonTriggerCalculator::processEvent(const xAOD::SystematicEvent* systEvent, bool withScaleFactorVariations) { + auto const& hash = systEvent->hashValue(); + bool isLoose = systEvent->isLooseEvent(); + + std::string const& systname = m_config->systematicName(hash); + ATH_MSG_DEBUG("Calculating trigger SF for variation " << systname << " (" << hash << ") with isLoose=" << isLoose); + + // Retrieve nominal muons, retrieve nominal electrons + const xAOD::MuonContainer* muons(nullptr); + const xAOD::ElectronContainer* electrons(nullptr); + std::vector<const xAOD::Muon*> selectedMuons; + std::vector<const xAOD::Electron*> selectedElectrons; + + if (m_config->useMuons()) top::check(evtStore()->retrieve(muons, m_config->sgKeyMuons(hash)), "Failed to retrieve muons"); + + // Put into a vector + for (size_t index : systEvent->goodMuons()) { + selectedMuons.push_back(muons->at(index)); + } + + if (m_config->useElectrons()) top::check(evtStore()->retrieve(electrons, m_config->sgKeyElectrons(hash)), "Failed to retrieve electrons"); + // Put into a vector + for (size_t index : systEvent->goodElectrons()) { + selectedElectrons.push_back(electrons->at(index)); + } + + // manage current electron trigger SF variation + CP::SystematicSet electronSystSet; + auto setCurrentElectronVariation = [this, &electronSystSet](std::string const& parameterName, int value) { + electronSystSet.clear(); + if (!parameterName.empty()) electronSystSet.insert(CP::SystematicVariation( + parameterName, value)); + for (auto&& tool : m_electronTools) { + top::check(tool->applySystematicVariation( + electronSystSet), "Failed to apply systematic"); + } + }; + + // manage current muon trigger SF variation + CP::SystematicSet muonSystSet; + auto setCurrentMuonVariation = [this, &muonSystSet](std::string const& parameterName, int value) { + muonSystSet.clear(); + if (!parameterName.empty()) muonSystSet.insert(CP::SystematicVariation( + parameterName, value)); + for (auto&& tool : m_muonTools) { + top::check(tool->applySystematicVariation( + muonSystSet), "Failed to apply systematic"); + } + }; + + // compute and store trigger SF for current variation + auto&& globalTriggerTool = (isLoose ? m_globalTriggerSFLoose : m_globalTriggerSF); + auto decorateEventForCurrentVariation = [&]() { + double sf; + + if (selectedElectrons.empty() && selectedMuons.empty()) { + sf = 1.; + } else { + sf = NAN; + top::check(globalTriggerTool->getEfficiencyScaleFactor( + selectedElectrons, + selectedMuons, + sf), "Failed to get global trigger SF"); + } + std::string auxname(m_decor_triggerSF); + auxname += "_"; + if (!(electronSystSet.empty() && muonSystSet.empty())) { + CP::SystematicSet systSet; + systSet.insert(electronSystSet); + systSet.insert(muonSystSet); + auxname += systSet.name(); + } + ATH_MSG_DEBUG("Adding decoration " << auxname << " = " << sf); + systEvent->auxdecor<float>(auxname) = sf; + }; + + ///-- Set the nominal --/// + setCurrentElectronVariation("", 0); + setCurrentMuonVariation("", 0); + decorateEventForCurrentVariation(); + + ///-- Apply and calculate variations on nominal --/// + if (withScaleFactorVariations) { + ATH_MSG_DEBUG("Calculating trigger SF variations"); + std::unordered_set<std::string> variations; + ///-- Set nominal muon for electron systematic --/// + for (auto& s : m_config->getGlobalTriggerElectronSystematics()) { + for (int val : {1, -1}) { + setCurrentElectronVariation(s, val); + decorateEventForCurrentVariation(); + } + } + ///-- Set nominal electron for muon systematic --/// + setCurrentElectronVariation("", 0); + for (auto& s : m_config->getGlobalTriggerMuonSystematics()) { + for (int val : {1, -1}) { + setCurrentMuonVariation(s, val); + decorateEventForCurrentVariation(); + } + } + setCurrentMuonVariation("", 0); + } + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/JetScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/JetScaleFactorCalculator.cxx index 837ee1ebc5d9d4eb4761bcf95eb00a1ac29a7104..8e45a9fb34f517351557ab42b0be62c0ad586e34 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/JetScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/JetScaleFactorCalculator.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // $Id: JetScaleFactorCalculator.cxx 794672 2017-01-31 00:41:04Z tpelzer $ #include "TopCorrections/JetScaleFactorCalculator.h" @@ -11,7 +11,6 @@ namespace top { - JetScaleFactorCalculator::JetScaleFactorCalculator(const std::string& name) : asg::AsgTool(name), m_config(nullptr), @@ -19,8 +18,9 @@ namespace top { m_systNominal(CP::SystematicSet()), m_systUP(CP::SystematicSet()), m_systDOWN(CP::SystematicSet()), - m_jvt_tool("JetJvtEfficiencyTool") { - declareProperty("config" , m_config); + m_jvt_tool("JetJvtEfficiencyTool"), + m_fjvt_tool("JetForwardJvtEfficiencyTool") { + declareProperty("config", m_config); } StatusCode JetScaleFactorCalculator::initialize() { @@ -31,21 +31,43 @@ namespace top { m_systUP.insert(CP::SystematicVariation(CP::JvtEfficiencyUp)); m_systDOWN.insert(CP::SystematicVariation(CP::JvtEfficiencyDown)); + // fJVT Efficiency tool is only set up if user requests it + if (m_config->getfJVTWP() != "None") { + top::check(m_fjvt_tool.retrieve(), "Failed to retrieve fJVT tool"); + + m_systUP.insert(CP::SystematicVariation(CP::fJvtEfficiencyUp)); + m_systDOWN.insert(CP::SystematicVariation(CP::fJvtEfficiencyDown)); + } + + return StatusCode::SUCCESS; } - StatusCode JetScaleFactorCalculator::execute() { ///-- Loop over all jet collections --/// - ///-- Lets assume that we're not doing ElectronInJet subtraction --/// + for (auto currentSystematic : *m_config->systSgKeyMapJets(false)) { const xAOD::JetContainer* jets(nullptr); - top::check(evtStore()->retrieve(jets, currentSystematic.second), "failed to retrieve jets"); - - ///-- Tell the SF tools to use the nominal systematic --/// - - /// -- Loop over all jets in each collection --/// - for (auto jetPtr : *jets) { + top::check(evtStore()->retrieve(jets, currentSystematic.second), "failed to retrieve jets in JetScaleFactorCalculator::execute()"); + top::check(this->decorateJets(jets,currentSystematic.first == m_config->nominalHashValue()),"failed to decorate jets in JetScaleFactorCalculator::execute()"); + } + + if(m_config->doLooseEvents() && m_config->applyElectronInJetSubtraction()) + { + for (auto currentSystematic : *m_config->systSgKeyMapJets(true)) { + const xAOD::JetContainer* jets(nullptr); + top::check(evtStore()->retrieve(jets, currentSystematic.second), "failed to retrieve loose jets in JetScaleFactorCalculator::execute()"); + top::check(this->decorateJets(jets,currentSystematic.first == m_config->nominalHashValue()),"failed to decorate loose jets in JetScaleFactorCalculator::execute()"); + } + } + + return StatusCode::SUCCESS; + } + + StatusCode JetScaleFactorCalculator::decorateJets(const xAOD::JetContainer* jets, bool isNominal){ + + /// -- Loop over all jets in each collection --/// + for (const xAOD::Jet *jetPtr : *jets) { /// -- Does the jet pass object selection? --/// // WARNING: this doesn't include the JVT cut anymore bool passSelection(false); @@ -61,6 +83,7 @@ namespace top { } if (passSelection) { + ///-- JVT first --/// // Set to nominal first... top::check(m_jvt_tool->applySystematicVariation(m_systNominal), "Failed to set JVT nominal SF"); @@ -72,11 +95,11 @@ namespace top { return StatusCode::FAILURE; } - bool passes_jvt = jetPtr->auxdataConst< char >("passJVT"); + int passes_jvt = jetPtr->auxdataConst< char >("passJVT"); + if (passes_jvt < 0) continue; - if (passes_jvt) - top::check(m_jvt_tool->getEfficiencyScaleFactor(*jetPtr, jvtSF), - "Failed to getEfficiencyScaleFactor for JVT"); + if (passes_jvt) top::check(m_jvt_tool->getEfficiencyScaleFactor(*jetPtr, jvtSF), + "Failed to getEfficiencyScaleFactor for JVT"); else { top::check(m_jvt_tool->getInefficiencyScaleFactor(*jetPtr, jvtSF), "Failed to getInefficiencyScaleFactor for JVT"); @@ -85,8 +108,7 @@ namespace top { jetPtr->auxdecor<float>("JET_SF_jvt") = jvtSF; ///-- For nominal calibration, vary the SF systematics --/// - if (currentSystematic.first == m_config->nominalHashValue()) { - + if (isNominal) { float jvtSF_up(1.), jvtSF_down(1.); // made up values if (passes_jvt) { @@ -98,8 +120,7 @@ namespace top { "Failed to applySystematicVariation down for JVT"); top::check(m_jvt_tool->getEfficiencyScaleFactor(*jetPtr, jvtSF_down), "Failed to get JVT SF (systematic down)"); - } - else { + } else { top::check(m_jvt_tool->applySystematicVariation(m_systUP), "Failed to applySystematicVariation up for JVT"); top::check(m_jvt_tool->getInefficiencyScaleFactor(*jetPtr, jvtSF_up), @@ -113,14 +134,58 @@ namespace top { ///-- Decorate --/// jetPtr->auxdecor<float>("JET_SF_jvt_UP") = jvtSF_up; jetPtr->auxdecor<float>("JET_SF_jvt_DOWN") = jvtSF_down; - } // Calibration systematic is nominal, so calculate SF systematics + } // Calibration systematic is nominal, so calculate SF systematics + + ///-- Then fJVT --/// + if (m_config->getfJVTWP() != "None") { + top::check(m_fjvt_tool->applySystematicVariation(m_systNominal), + "Failed to set fJVT nominal SF"); + float fjvtSF(1.); + + if (!jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")) { + ATH_MSG_ERROR(" Can't find jet decoration \"AnalysisTop_fJVTdecision\" - we need it to calculate the jet fJVT scale-factors!"); + return StatusCode::FAILURE; + } + int passes_fjvt = jetPtr->auxdataConst< char >("AnalysisTop_fJVTdecision"); + if (passes_fjvt < 0) continue; + if (passes_fjvt) top::check(m_fjvt_tool->getEfficiencyScaleFactor(*jetPtr, fjvtSF), + "Failed to getEfficiencyScaleFactor for fJVT"); + else { + top::check(m_fjvt_tool->getInefficiencyScaleFactor(*jetPtr, fjvtSF), + "Failed to getInefficiencyScaleFactor for fJVT"); + } + jetPtr->auxdecor<float>("JET_SF_fjvt") = fjvtSF; + + if (isNominal) { + float fjvtSF_up(1.), fjvtSF_down(1.); // made up values + if (passes_fjvt) { + top::check(m_fjvt_tool->applySystematicVariation(m_systUP), + "Failed to applySystematicVariation up for fJVT"); + top::check(m_fjvt_tool->getEfficiencyScaleFactor(*jetPtr, fjvtSF_up), + "Failed to get fJVT SF (systematic up)"); + top::check(m_fjvt_tool->applySystematicVariation(m_systDOWN), + "Failed to applySystematicVariation down for fJVT"); + top::check(m_fjvt_tool->getEfficiencyScaleFactor(*jetPtr, fjvtSF_down), + "Failed to get fJVT SF (systematic down)"); + } else { + top::check(m_fjvt_tool->applySystematicVariation(m_systUP), + "Failed to applySystematicVariation up for fJVT"); + top::check(m_fjvt_tool->getInefficiencyScaleFactor(*jetPtr, fjvtSF_up), + "Failed to get fJVT SF (systematic up)"); + top::check(m_fjvt_tool->applySystematicVariation(m_systDOWN), + "Failed to applySystematicVariation down for fJVT"); + top::check(m_fjvt_tool->getInefficiencyScaleFactor(*jetPtr, fjvtSF_down), + "Failed to get fJVT SF (systematic down)"); + } + ///-- Decorate --/// + jetPtr->auxdecor<float>("JET_SF_fjvt_UP") = fjvtSF_up; + jetPtr->auxdecor<float>("JET_SF_fjvt_DOWN") = fjvtSF_down; + + } // Calibration systematic is nominal, so calculate SF systematics + } } } - } - - return StatusCode::SUCCESS; } - } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/LinkDef.h new file mode 100644 index 0000000000000000000000000000000000000000..a1934eb914beb69cc9e417a5d901f0ecf90e288b --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/LinkDef.h @@ -0,0 +1,18 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration. + */ + +#include "TopCorrections/ScaleFactorRetriever.h" + +#ifdef __CINT__ + +#pragma extra_include "TopCorrections/ScaleFactorRetriever.h"; + +#pragma link off all globals; +#pragma link off all classes; +#pragma link off all functions; +#pragma link C++ nestedclass; + +#pragma link C++ class top::ScaleFactorRetriever+; + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MsgCategory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MsgCategory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..cb158bc6f7e0f5ccca24679a3f8f63273c81b1de --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MsgCategory.cxx @@ -0,0 +1,6 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#include "TopCorrections/MsgCategory.h" + +ANA_MSG_SOURCE(TopCorrections, "TopCorrections") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MuonScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MuonScaleFactorCalculator.cxx index 9ddd85ef40328f3fda2f494b990c511ef16fc30b..be233b338490a6766ca405fdf853c592fde2f82e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MuonScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/MuonScaleFactorCalculator.cxx @@ -1,8 +1,8 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: MuonScaleFactorCalculator.cxx 796972 2017-02-14 03:08:26Z tpelzer $ +// $Id: MuonScaleFactorCalculator.cxx 805964 2017-06-05 19:27:16Z iconnell $ #include "TopCorrections/MuonScaleFactorCalculator.h" #include <string> @@ -16,18 +16,13 @@ #include "xAODMuon/MuonContainer.h" namespace top { - MuonScaleFactorCalculator::MuonScaleFactorCalculator(const std::string& name) : asg::AsgTool(name), m_config(nullptr), m_systNominal(CP::SystematicSet()), - m_muonTriggerScaleFactors_2015("CP::MuonTriggerScaleFactors_2015"), - m_muonTriggerScaleFactorsLoose_2015("CP::MuonTriggerScaleFactorsLoose_2015"), - m_muonTriggerScaleFactors_2016("CP::MuonTriggerScaleFactors_2016"), - m_muonTriggerScaleFactorsLoose_2016("CP::MuonTriggerScaleFactorsLoose_2016"), - m_muonEfficiencyCorrectionsTool("CP::MuonEfficiencyScaleFactorsTool"), + m_softmuonEfficiencyCorrectionsTool("CP::SoftMuonEfficiencyScaleFactorsTool"), m_muonEfficiencyCorrectionsToolLoose("CP::MuonEfficiencyScaleFactorsToolLoose"), m_muonEfficiencyCorrectionsToolIso("CP::MuonEfficiencyScaleFactorsToolIso"), m_muonEfficiencyCorrectionsToolLooseIso("CP::MuonEfficiencyScaleFactorsToolLooseIso"), @@ -39,6 +34,8 @@ namespace top { m_decor_isoSF("SetMe"), m_decor_isoSF_loose("SetMe"), m_decor_TTVA("MU_SF_TTVA"), + m_decor_softmuon_idSF("SetMe"), + m_do_muon_isolation_SFs(true), m_do_muon_isolation_SFs_loose(true), // The systematics are defined here... @@ -47,57 +44,69 @@ namespace top { m_trig_sf_syst_UP("MUON_EFF_TrigSystUncertainty__1up"), m_trig_sf_syst_DOWN("MUON_EFF_TrigSystUncertainty__1down"), - m_reco_stat_UP("MUON_EFF_STAT__1up"), - m_reco_stat_DOWN("MUON_EFF_STAT__1down"), - m_reco_syst_UP("MUON_EFF_SYS__1up"), - m_reco_syst_DOWN("MUON_EFF_SYS__1down"), - - m_reco_stat_lowpt_UP("MUON_EFF_STAT_LOWPT__1up"), - m_reco_stat_lowpt_DOWN("MUON_EFF_STAT_LOWPT__1down"), - m_reco_syst_lowpt_UP("MUON_EFF_SYS_LOWPT__1up"), - m_reco_syst_lowpt_DOWN("MUON_EFF_SYS_LOWPT__1down"), - - m_iso_stat_UP("MUON_ISO_STAT__1up"), - m_iso_stat_DOWN("MUON_ISO_STAT__1down"), - m_iso_syst_UP("MUON_ISO_SYS__1up"), - m_iso_syst_DOWN("MUON_ISO_SYS__1down"), - - m_TTVA_stat_UP("MUON_TTVA_STAT__1up"), - m_TTVA_stat_DOWN("MUON_TTVA_STAT__1down"), - m_TTVA_syst_UP("MUON_TTVA_SYS__1up"), - m_TTVA_syst_DOWN("MUON_TTVA_SYS__1down") { + m_reco_stat_UP("MUON_EFF_RECO_STAT__1up"), + m_reco_stat_DOWN("MUON_EFF_RECO_STAT__1down"), + m_reco_syst_UP("MUON_EFF_RECO_SYS__1up"), + m_reco_syst_DOWN("MUON_EFF_RECO_SYS__1down"), + + m_reco_stat_lowpt_UP("MUON_EFF_RECO_STAT_LOWPT__1up"), + m_reco_stat_lowpt_DOWN("MUON_EFF_RECO_STAT_LOWPT__1down"), + m_reco_syst_lowpt_UP("MUON_EFF_RECO_SYS_LOWPT__1up"), + m_reco_syst_lowpt_DOWN("MUON_EFF_RECO_SYS_LOWPT__1down"), + + m_iso_stat_UP("MUON_EFF_ISO_STAT__1up"), + m_iso_stat_DOWN("MUON_EFF_ISO_STAT__1down"), + m_iso_syst_UP("MUON_EFF_ISO_SYS__1up"), + m_iso_syst_DOWN("MUON_EFF_ISO_SYS__1down"), + + m_TTVA_stat_UP("MUON_EFF_TTVA_STAT__1up"), + m_TTVA_stat_DOWN("MUON_EFF_TTVA_STAT__1down"), + m_TTVA_syst_UP("MUON_EFF_TTVA_SYS__1up"), + m_TTVA_syst_DOWN("MUON_EFF_TTVA_SYS__1down") { declareProperty("config", m_config); } StatusCode MuonScaleFactorCalculator::initialize() { ATH_MSG_INFO(" top::MuonScaleFactorCalculator initialize"); - std::set<std::string> implemented_systematics = - {"MUON_EFF_TrigStatUncertainty", - "MUON_EFF_TrigSystUncertainty", - "MUON_EFF_STAT", - "MUON_EFF_SYS", - "MUON_EFF_STAT_LOWPT", - "MUON_EFF_SYS_LOWPT", - "MUON_ISO_STAT", - "MUON_ISO_SYS", - "MUON_TTVA_STAT", - "MUON_TTVA_SYS"}; + m_muonTriggerScaleFactors_R21 = ToolHandle<CP::IMuonTriggerScaleFactors>("CP::MuonTriggerScaleFactors_R21"); + m_muonTriggerScaleFactorsLoose_R21 = + ToolHandle<CP::IMuonTriggerScaleFactors>("CP::MuonTriggerScaleFactorsLoose_R21"); + + std::set<std::string> implemented_systematics; + implemented_systematics = { + "MUON_EFF_RECO_STAT", + "MUON_EFF_RECO_STAT_LOWPT", + "MUON_EFF_RECO_SYS", + "MUON_EFF_RECO_SYS_LOWPT", + "MUON_EFF_TrigStatUncertainty", + "MUON_EFF_TrigSystUncertainty", + "MUON_EFF_ISO_STAT", + "MUON_EFF_ISO_SYS", + "MUON_EFF_TTVA_STAT", + "MUON_EFF_TTVA_SYS" + }; std::set<std::string> recommended_systematics; - this->retrieveSystematicTool(m_muonTriggerScaleFactors_2015, - recommended_systematics); - this->retrieveSystematicTool(m_muonTriggerScaleFactorsLoose_2015, - recommended_systematics); - this->retrieveSystematicTool(m_muonTriggerScaleFactors_2016, + + // For R21, a single tool + this->retrieveSystematicTool(m_muonTriggerScaleFactors_R21, recommended_systematics); - this->retrieveSystematicTool(m_muonTriggerScaleFactorsLoose_2016, + this->retrieveSystematicTool(m_muonTriggerScaleFactorsLoose_R21, recommended_systematics); + this->retrieveSystematicTool(m_muonEfficiencyCorrectionsTool, recommended_systematics); + + if (m_config->useSoftMuons()) { + this->retrieveSystematicTool(m_softmuonEfficiencyCorrectionsTool, + recommended_systematics); + } + this->retrieveSystematicTool(m_muonEfficiencyCorrectionsToolLoose, recommended_systematics); + if (asg::ToolStore::contains<CP::IMuonEfficiencyScaleFactors>("CP::MuonEfficiencyScaleFactorsToolIso")) { this->retrieveSystematicTool(m_muonEfficiencyCorrectionsToolIso, recommended_systematics); @@ -112,14 +121,14 @@ namespace top { } ///-- Not a good reason for this happening at the moment --/// - if (m_config->muonIsolation() != "None" && !m_do_muon_isolation_SFs) { + if (m_config->muonIsolationSF() != "None" && !m_do_muon_isolation_SFs) { ATH_MSG_WARNING("No muon isolation SFs available." " You can run with MuonIsolation set to" " None if you don't want isolation."); return StatusCode::FAILURE; } ///-- Not a good reason for this happening at the moment --/// - if (m_config->muonIsolationLoose() != "None" && !m_do_muon_isolation_SFs_loose) { + if (m_config->muonIsolationSFLoose() != "None" && !m_do_muon_isolation_SFs_loose) { ATH_MSG_WARNING("No loose muon isolation SFs available." " You can run with MuonIsolationLoose set to" " None if you don't want isolation."); @@ -135,26 +144,27 @@ namespace top { " muon SF systematic uncertainties"); - m_decor_triggerEff = "MU_EFF_Trigger_" + m_config->muonQuality(); - m_decor_triggerEff_loose = "MU_EFF_Trigger_" + m_config->muonQualityLoose(); - m_decor_triggerSF = "MU_SF_Trigger_" + m_config->muonQuality(); - m_decor_triggerSF_loose = "MU_SF_Trigger_" + m_config->muonQualityLoose(); - m_decor_idSF = "MU_SF_ID_" + m_config->muonQuality(); - m_decor_idSF_loose = "MU_SF_ID_" + m_config->muonQualityLoose(); - m_decor_isoSF = "MU_SF_Isol_" + m_config->muonIsolation(); - m_decor_isoSF_loose = "MU_SF_Isol_" + m_config->muonIsolationLoose(); + m_decor_triggerEff = "MU_EFF_Trigger_" + m_config->muonQuality(); + m_decor_triggerEff_loose = "MU_LOOSE_EFF_Trigger_" + m_config->muonQualityLoose(); + m_decor_triggerSF = "MU_SF_Trigger_" + m_config->muonQuality(); + m_decor_triggerSF_loose = "MU_LOOSE_SF_Trigger_" + m_config->muonQualityLoose(); + m_decor_idSF = "MU_SF_ID_" + m_config->muonQuality(); + m_decor_idSF_loose = "MU_LOOSE_SF_ID_" + m_config->muonQualityLoose(); + m_decor_isoSF = "MU_SF_Isol_" + m_config->muonIsolationSF(); + m_decor_isoSF_loose = "MU_LOOSE_SF_Isol_" + m_config->muonIsolationSFLoose(); + + m_decor_softmuon_idSF = "SOFTMU_SF_ID_" + m_config->softmuonQuality(); return StatusCode::SUCCESS; } - StatusCode MuonScaleFactorCalculator::execute() { /************************************************************* - * - * The muon trigger SF tool wants a random run number, - * which we can get from the PRW tool. - * - *************************************************************/ + * + * The muon trigger SF tool wants a random run number, + * which we can get from the PRW tool. + * + *************************************************************/ if (m_config->doPileupReweighting()) { const xAOD::EventInfo* eventInfo(nullptr); @@ -163,36 +173,36 @@ namespace top { // This is the default value in the MuonTriggerScaleFactors tool unsigned int runNumber = 267639; - if (eventInfo->isAvailable<unsigned int>("RandomRunNumber")) - runNumber = eventInfo->auxdataConst<unsigned int>("RandomRunNumber"); - else - ATH_MSG_WARNING("Event has not been decorated with RandomRunNumber"); - - if (runNumber > 284484 || runNumber == 0) { - m_muonTriggerScaleFactors = m_muonTriggerScaleFactors_2016; - m_muonTriggerScaleFactorsLoose = m_muonTriggerScaleFactors_2016; + if (eventInfo->isAvailable<unsigned int>("RandomRunNumber")) runNumber = eventInfo->auxdataConst<unsigned int>( + "RandomRunNumber"); + else ATH_MSG_WARNING("Event has not been decorated with RandomRunNumber"); + + // Keep an eye here for trigger strings + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15#Supported_triggers + m_muonTriggerScaleFactors = m_muonTriggerScaleFactors_R21; + m_muonTriggerScaleFactorsLoose = m_muonTriggerScaleFactorsLoose_R21; + m_muon_trigger_sf_config = ""; + + if (runNumber == 0) { m_muon_trigger_sf_config = "HLT_mu26_ivarmedium_OR_HLT_mu50"; - } else { - m_muonTriggerScaleFactors = m_muonTriggerScaleFactors_2015; - m_muonTriggerScaleFactorsLoose = m_muonTriggerScaleFactors_2015; + } + // 2015 + else if (runNumber > 0 && runNumber <= 284484) { m_muon_trigger_sf_config = "HLT_mu20_iloose_L1MU15_OR_HLT_mu50"; } + // 2016 (set to a large value but split as we may need to have strings for 2016 -> certain 2017 run) + else if (runNumber > 284484 && runNumber < 324320) { + m_muon_trigger_sf_config = "HLT_mu26_ivarmedium_OR_HLT_mu50"; + } + // 2017+ (324320+) + else { + m_muon_trigger_sf_config = "HLT_mu26_ivarmedium_OR_HLT_mu50"; + } - // The PRW tool can give run numbers of zero for unrepresented - // mu values. If we give the muon tool a run number of zero it - // complains with the message: - // "WARNING I am using run #0 but I cannot find corresponding run period. - // Now setting to use 2016 period B. - // This might give problems! Please check which year and mc you - // have set up". - // We do this by hand to avoid the messages. - if (runNumber == 0) runNumber = 300345; - - top::check(m_muonTriggerScaleFactors->setRunNumber(runNumber), - "Failed to set run number for muon trigger SFs"); - top::check(m_muonTriggerScaleFactorsLoose->setRunNumber(runNumber), - "Failed to set run number for (loose) muon trigger SFs"); - } + ATH_MSG_DEBUG("Muon trigger scale factor config is : " + m_muon_trigger_sf_config); + ATH_MSG_DEBUG("RunNumber (0 < 2015 < 284484 < 2016 < 324320 < 2017) : "); + ATH_MSG_DEBUG(runNumber); + }//end of if (m_config->doPileupReweighting()) ///-- Loop over all muon collections --/// for (auto currentSystematic : *m_config->systSgKeyMapMuons()) { @@ -226,10 +236,9 @@ namespace top { this->applySystematicVariation(m_muonEfficiencyCorrectionsToolTTVA, m_systNominal); //-- Only do isolation if we actually get the tools --// - if (m_do_muon_isolation_SFs) - this->applySystematicVariation(m_muonEfficiencyCorrectionsToolIso, m_systNominal); - if (m_do_muon_isolation_SFs_loose) - this->applySystematicVariation(m_muonEfficiencyCorrectionsToolLooseIso, m_systNominal); + if (m_do_muon_isolation_SFs) this->applySystematicVariation(m_muonEfficiencyCorrectionsToolIso, m_systNominal); + if (m_do_muon_isolation_SFs_loose) this->applySystematicVariation(m_muonEfficiencyCorrectionsToolLooseIso, + m_systNominal); // The nominal SFs/efficiencies. // Include are:: @@ -275,19 +284,19 @@ namespace top { m_systNominal, *muonPtr, TTVA_decor); /********************************************************************** - * Muon Trigger Scale Factors - * TOM : The MCP tool takes a container of muons. The examples seem to - * suggest these should somehow be selected muons but it isn't clear - * to me what level of selection should be applied. - * - * *** To be followed up with MCP people by Jay *** - * - * TOM : We trick it by creating a view container - * with a single muon in. - * NOTE: This also happens later on for the systematics so if we ever - * get a nice function make sure we change it there too! - * - **********************************************************************/ + * Muon Trigger Scale Factors + * TOM : The MCP tool takes a container of muons. The examples seem to + * suggest these should somehow be selected muons but it isn't clear + * to me what level of selection should be applied. + * + * *** To be followed up with MCP people by Jay *** + * + * TOM : We trick it by creating a view container + * with a single muon in. + * NOTE: This also happens later on for the systematics so if we ever + * get a nice function make sure we change it there too! + * + **********************************************************************/ ConstDataVector<xAOD::MuonContainer> trigger_SF_muon(SG::VIEW_ELEMENTS); trigger_SF_muon.push_back(muonPtr); @@ -302,7 +311,7 @@ namespace top { trig_sf_decor, trig_eff_decor); this->decorateTrigSFandEff(m_muonTriggerScaleFactorsLoose, m_systNominal, trigger_SF_muon, - trig_sf_loose_decor, trig_eff_decor); + trig_sf_loose_decor, trig_eff_loose_decor); // If we are running on the nominal tree, then do the // SF systematic variations too. @@ -319,6 +328,46 @@ namespace top { this->decorateTTVASystematics(*muonPtr); } } + + ///-- Loop over all soft muon collections --/// + for (const std::pair<std::size_t, std::string>& currentSystematic : *m_config->systSgKeyMapSoftMuons()) { + const xAOD::MuonContainer* softmuons(nullptr); + top::check(evtStore()->retrieve(softmuons, currentSystematic.second), + "Failed to retrieve softmuons"); + + /// -- Loop over all soft muons in each collection --/// + for (const xAOD::Muon* muonPtr : *softmuons) { + /// -- Does the soft muon pass object selection? --/// + bool passSelection(false); + if (muonPtr->isAvailable<char>("passPreORSelection")) { + if (muonPtr->auxdataConst<char>("passPreORSelection") == 1) { + passSelection = true; + } + } + + if (!passSelection) continue; + + // Tell the SF tools to use the nominal systematic + // To be extra sure we do this when we try and get a SF too! + this->applySystematicVariation(m_softmuonEfficiencyCorrectionsTool, m_systNominal); + + // Reco efficiency and ID SF decorations + static SG::AuxElement::Decorator<float> id_sf_decor(m_decor_softmuon_idSF); + + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_systNominal, *muonPtr, + id_sf_decor); + + // If we are running on the nominal tree, then do the + // SF systematic variations too. + // Otherwise just move onto the next muon... + if (currentSystematic.first != m_config->nominalHashValue()) continue; + + // ID systematics + this->decorateIDSFandRecoEffSystematicsSoftMuon(*muonPtr); + }//end of loop on soft muons + } + return StatusCode::SUCCESS; } @@ -333,7 +382,6 @@ namespace top { recommended_systematics.insert(std::string(s)); } - template<typename T> void MuonScaleFactorCalculator::applySystematicVariation(ToolHandle<T>& tool, const CP::SystematicSet& systematic) { @@ -352,6 +400,12 @@ namespace top { implemented.end(), std::back_inserter(different_systematics)); if (different_systematics.size()) { + ATH_MSG_WARNING("WE ARE EXPECTING THE FOLLOWING SYSTEMATICS:"); + for (auto syst : recommended) + ATH_MSG_WARNING("\t" << syst); + ATH_MSG_WARNING("WE HAVE THE FOLLOWING SYSTEMATICS:"); + for (auto syst : implemented) + ATH_MSG_WARNING("\t" << syst); ATH_MSG_WARNING("WE ARE MISSING THE FOLLOWING SYSTEMATICS:"); for (auto syst : different_systematics) ATH_MSG_WARNING("\t" << syst); @@ -364,6 +418,7 @@ namespace top { const xAOD::Muon& muon, const SG::AuxElement::Decorator<float>& decor) { double trigEff = 1.0; + top::check(tool->getTriggerEfficiency(muon, trigEff, m_muon_trigger_sf_config, !m_config->isMC()), @@ -375,6 +430,7 @@ namespace top { const ConstDataVector<xAOD::MuonContainer>& muon_cont, const SG::AuxElement::Decorator<float>& decor) { double trigSF = 1.0; + top::check(tool->getTriggerScaleFactor(*muon_cont.asDataVector(), trigSF, m_muon_trigger_sf_config), "Failed to get muon trigger scale factor"); @@ -394,7 +450,8 @@ namespace top { this->decorateTriggerEfficiency(tool, *muon_cont[0], eff_decor); } - void MuonScaleFactorCalculator::decorateTriggerSystematics(const ConstDataVector<xAOD::MuonContainer>& trigger_SF_muon) { + void MuonScaleFactorCalculator::decorateTriggerSystematics(const ConstDataVector<xAOD::MuonContainer>& trigger_SF_muon) + { // Perform all trigger systematic variations, for loose and tight, // (stat/syst up/down) static SG::AuxElement::Decorator<float> trig_eff_decor_stat_up(m_decor_triggerEff + "_STAT_UP"); @@ -482,16 +539,16 @@ namespace top { void MuonScaleFactorCalculator::decorateIsolationSystematics(const xAOD::Muon& muon) { // Decorate 'tight' isolation SFs - static SG::AuxElement::Decorator<float> iso_sf_decor_stat_up(m_decor_isoSF+"_STAT_UP"); - static SG::AuxElement::Decorator<float> iso_sf_decor_stat_down(m_decor_isoSF+"_STAT_DOWN"); - static SG::AuxElement::Decorator<float> iso_sf_decor_syst_up(m_decor_isoSF+"_SYST_UP"); - static SG::AuxElement::Decorator<float> iso_sf_decor_syst_down(m_decor_isoSF+"_SYST_DOWN"); + static SG::AuxElement::Decorator<float> iso_sf_decor_stat_up(m_decor_isoSF + "_STAT_UP"); + static SG::AuxElement::Decorator<float> iso_sf_decor_stat_down(m_decor_isoSF + "_STAT_DOWN"); + static SG::AuxElement::Decorator<float> iso_sf_decor_syst_up(m_decor_isoSF + "_SYST_UP"); + static SG::AuxElement::Decorator<float> iso_sf_decor_syst_down(m_decor_isoSF + "_SYST_DOWN"); // Decorate 'loose' isolation SFs - static SG::AuxElement::Decorator<float> iso_sf_loose_decor_stat_up(m_decor_isoSF_loose+"_STAT_UP"); - static SG::AuxElement::Decorator<float> iso_sf_loose_decor_stat_down(m_decor_isoSF_loose+"_STAT_DOWN"); - static SG::AuxElement::Decorator<float> iso_sf_loose_decor_syst_up(m_decor_isoSF_loose+"_SYST_UP"); - static SG::AuxElement::Decorator<float> iso_sf_loose_decor_syst_down(m_decor_isoSF_loose+"_SYST_DOWN"); + static SG::AuxElement::Decorator<float> iso_sf_loose_decor_stat_up(m_decor_isoSF_loose + "_STAT_UP"); + static SG::AuxElement::Decorator<float> iso_sf_loose_decor_stat_down(m_decor_isoSF_loose + "_STAT_DOWN"); + static SG::AuxElement::Decorator<float> iso_sf_loose_decor_syst_up(m_decor_isoSF_loose + "_SYST_UP"); + static SG::AuxElement::Decorator<float> iso_sf_loose_decor_syst_down(m_decor_isoSF_loose + "_SYST_DOWN"); if (m_do_muon_isolation_SFs) { ///-- Stat UP --/// @@ -547,10 +604,10 @@ namespace top { } void MuonScaleFactorCalculator::decorateTTVASystematics(const xAOD::Muon& muon) { - static SG::AuxElement::Decorator<float> TTVA_decor_stat_up(m_decor_TTVA+"_STAT_UP"); - static SG::AuxElement::Decorator<float> TTVA_decor_stat_down(m_decor_TTVA+"_STAT_DOWN"); - static SG::AuxElement::Decorator<float> TTVA_decor_syst_up(m_decor_TTVA+"_SYST_UP"); - static SG::AuxElement::Decorator<float> TTVA_decor_syst_down(m_decor_TTVA+"_SYST_DOWN"); + static SG::AuxElement::Decorator<float> TTVA_decor_stat_up(m_decor_TTVA + "_STAT_UP"); + static SG::AuxElement::Decorator<float> TTVA_decor_stat_down(m_decor_TTVA + "_STAT_DOWN"); + static SG::AuxElement::Decorator<float> TTVA_decor_syst_up(m_decor_TTVA + "_SYST_UP"); + static SG::AuxElement::Decorator<float> TTVA_decor_syst_down(m_decor_TTVA + "_SYST_DOWN"); this->decorateEfficiencySF(m_muonEfficiencyCorrectionsToolTTVA, m_TTVA_stat_UP, muon, TTVA_decor_stat_up); @@ -660,4 +717,63 @@ namespace top { m_reco_syst_lowpt_DOWN, muon, id_sf_loose_decor_syst_lowpt_down); } + + void MuonScaleFactorCalculator::decorateIDSFandRecoEffSystematicsSoftMuon(const xAOD::Muon& muon) { + static SG::AuxElement::Decorator<float> id_sf_decor_stat_up(m_decor_softmuon_idSF + "_STAT_UP"); + + static SG::AuxElement::Decorator<float> id_sf_decor_stat_down(m_decor_softmuon_idSF + "_STAT_DOWN"); + + static SG::AuxElement::Decorator<float> id_sf_decor_syst_up(m_decor_softmuon_idSF + "_SYST_UP"); + + static SG::AuxElement::Decorator<float> id_sf_decor_syst_down(m_decor_softmuon_idSF + "_SYST_DOWN"); + + + ///-- Stat UP --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_stat_UP, muon, + id_sf_decor_stat_up); + + ///-- Stat DOWN --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_stat_DOWN, muon, + id_sf_decor_stat_down); + + ///-- Syst UP --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_syst_UP, muon, + id_sf_decor_syst_up); + + ///-- Syst DOWN --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_syst_DOWN, muon, + id_sf_decor_syst_down); + + static SG::AuxElement::Decorator<float> id_sf_decor_stat_lowpt_up(m_decor_softmuon_idSF + "_STAT_LOWPT_UP"); + + static SG::AuxElement::Decorator<float> id_sf_decor_stat_lowpt_down(m_decor_softmuon_idSF + "_STAT_LOWPT_DOWN"); + + static SG::AuxElement::Decorator<float> id_sf_decor_syst_lowpt_up(m_decor_softmuon_idSF + "_SYST_LOWPT_UP"); + + static SG::AuxElement::Decorator<float> id_sf_decor_syst_lowpt_down(m_decor_softmuon_idSF + "_SYST_LOWPT_DOWN"); + + ///-- Stat UP --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_stat_lowpt_UP, muon, + id_sf_decor_stat_lowpt_up); + + ///-- Stat DOWN --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_stat_lowpt_DOWN, muon, + id_sf_decor_stat_lowpt_down); + + ///-- Syst UP --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_syst_lowpt_UP, muon, + id_sf_decor_syst_lowpt_up); + + ///-- Syst DOWN --/// + this->decorateIDSFandRecoEff(m_softmuonEfficiencyCorrectionsTool, + m_reco_syst_lowpt_DOWN, muon, + id_sf_decor_syst_lowpt_down); + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PDFScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PDFScaleFactorCalculator.cxx index 1abf2f9743bf91e183f9d37e09dcc2b58b0b6cd7..b308b56fa2f1ef847b3c74fcf8d51cc4eb37521a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PDFScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PDFScaleFactorCalculator.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopCorrections/PDFScaleFactorCalculator.h" @@ -12,123 +12,110 @@ #include "xAODEventInfo/EventInfo.h" namespace top { - - PDFScaleFactorCalculator::PDFScaleFactorCalculator( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr){ - - declareProperty( "config" , m_config ); - + PDFScaleFactorCalculator::PDFScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr) { + declareProperty("config", m_config); } - StatusCode PDFScaleFactorCalculator::initialize() - { - - ATH_MSG_INFO(" top::PDFScaleFactorCalculator initialize" ); + StatusCode PDFScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::PDFScaleFactorCalculator initialize"); // This prints all the available PDFsets we can use //printAvailablePDFs(); - for( const std::string& set_name : m_config->LHAPDFSets() ) { - m_pdf_sets[ set_name ] = PDFSet( set_name ); + for (const std::string& set_name : m_config->LHAPDFSets()) { + m_pdf_sets[ set_name ] = PDFSet(set_name); } m_base_pdf_name = m_config->baseLHAPDF(); if (!m_base_pdf_name.empty()) { - ATH_MSG_INFO("Enabling " << m_base_pdf_name << " to recompute PDF weights.\n Content of sumWeight and totalSumWeight trees might be inconsistent with this recalculation.\n Use only PDFSumWeight and for PDF uncertainty estimates.\n"); + ATH_MSG_INFO( + "Enabling " << m_base_pdf_name << + " to recompute PDF weights.\n Content of sumWeight and totalSumWeight trees might be inconsistent with this recalculation.\n Use only PDFSumWeight and for PDF uncertainty estimates.\n"); m_basepdf = LHAPDF::mkPDF(m_base_pdf_name, 0); } return StatusCode::SUCCESS; - } - StatusCode PDFScaleFactorCalculator::execute() - { - + StatusCode PDFScaleFactorCalculator::execute() { // Get the event info for the MC weight const xAOD::EventInfo* event_info(nullptr); + top::check(evtStore()->retrieve(event_info, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); const xAOD::TruthEventContainer* truthEventContainer(nullptr); - top::check( evtStore()->retrieve(truthEventContainer, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth PDF info" ); + top::check(evtStore()->retrieve(truthEventContainer, + m_config->sgKeyTruthEvent()), "PDFScaleFactorCalculator: Failed to retrieve TruthEvent container"); -// float mc_weight = event_info->mcEventWeight(); - float mc_weight = truthEventContainer->at(0)->weights()[0];// FIXME temporary bugfix + float mc_weight = event_info->auxdataConst<float>("AnalysisTop_eventWeight"); // try this... - top::check( ( truthEventContainer->size() == 1 ), "More than one truth event, not sure how to cope with PDF info" ); + top::check((truthEventContainer->size() == 1), "TruthEvent container size != 1, not sure how to cope with PDF info"); int PDFID1(0), PDFID2(0), PDGID1(0), PDGID2(0); - float X1(0), X2(0) ,Q(0), XF1(0), XF2(0); - - for (auto truthEvent : *truthEventContainer){ - - top::check( truthEvent->pdfInfoParameter( PDGID1, xAOD::TruthEvent::PdfParam::PDGID1 ), "Failed to get PDFInfo: PDGID1" ); - top::check( truthEvent->pdfInfoParameter( PDGID2, xAOD::TruthEvent::PdfParam::PDGID2 ), "Failed to get PDFInfo: PDGID2" ); - top::check( truthEvent->pdfInfoParameter( PDFID1, xAOD::TruthEvent::PdfParam::PDFID1 ), "Failed to get PDFInfo: PDFID1" ); - top::check( truthEvent->pdfInfoParameter( PDFID2, xAOD::TruthEvent::PdfParam::PDFID2 ), "Failed to get PDFInfo: PDFID2" ); - top::check( truthEvent->pdfInfoParameter( X1, xAOD::TruthEvent::PdfParam::X1 ), "Failed to get PDFInfo: X1" ); - top::check( truthEvent->pdfInfoParameter( X2, xAOD::TruthEvent::PdfParam::X2 ), "Failed to get PDFInfo: X2" ); - top::check( truthEvent->pdfInfoParameter( Q, xAOD::TruthEvent::PdfParam::Q ), "Failed to get PDFInfo: Q" ); - top::check( truthEvent->pdfInfoParameter( XF1, xAOD::TruthEvent::PdfParam::XF1 ), "Failed to get PDFInfo: XF1" ); - top::check( truthEvent->pdfInfoParameter( XF2, xAOD::TruthEvent::PdfParam::XF2 ), "Failed to get PDFInfo: XF2" ); - - // This isn't working ( nor the helper to get the PDF Info ) - //top::check( pdfInfo.valid(), "PDFInfo not valid" ); - - if( XF1*XF2==0 ) { - if( !m_base_pdf_name.empty()) { - XF1 = m_basepdf->xfxQ( PDGID1, X1, Q ); - XF2 = m_basepdf->xfxQ( PDGID2, X2, Q ); - } else { - ATH_MSG_FATAL("Not enough info to recompute PDF weights (empty XF1,XF2).\n Please try to set LHAPDFBaseSet to a valid PDF set.\n XF1=" << XF1 << " XF2=" << XF2 << " LHAPDFBaseSet=" << m_base_pdf_name); - return StatusCode::FAILURE; - } + float X1(0), X2(0), Q(0), XF1(0), XF2(0); + + const xAOD::TruthEvent* truthEvent = truthEventContainer->at(0); + top::check(truthEvent->pdfInfoParameter(PDGID1, + xAOD::TruthEvent::PdfParam::PDGID1), "Failed to get PDFInfo: PDGID1"); + top::check(truthEvent->pdfInfoParameter(PDGID2, + xAOD::TruthEvent::PdfParam::PDGID2), "Failed to get PDFInfo: PDGID2"); + top::check(truthEvent->pdfInfoParameter(PDFID1, + xAOD::TruthEvent::PdfParam::PDFID1), "Failed to get PDFInfo: PDFID1"); + top::check(truthEvent->pdfInfoParameter(PDFID2, + xAOD::TruthEvent::PdfParam::PDFID2), "Failed to get PDFInfo: PDFID2"); + top::check(truthEvent->pdfInfoParameter(X1, xAOD::TruthEvent::PdfParam::X1), "Failed to get PDFInfo: X1"); + top::check(truthEvent->pdfInfoParameter(X2, xAOD::TruthEvent::PdfParam::X2), "Failed to get PDFInfo: X2"); + top::check(truthEvent->pdfInfoParameter(Q, xAOD::TruthEvent::PdfParam::Q), "Failed to get PDFInfo: Q"); + top::check(truthEvent->pdfInfoParameter(XF1, xAOD::TruthEvent::PdfParam::XF1), "Failed to get PDFInfo: XF1"); + top::check(truthEvent->pdfInfoParameter(XF2, xAOD::TruthEvent::PdfParam::XF2), "Failed to get PDFInfo: XF2"); + + if (XF1 * XF2 == 0) { + if (!m_base_pdf_name.empty()) { + XF1 = m_basepdf->xfxQ(PDGID1, X1, Q); + XF2 = m_basepdf->xfxQ(PDGID2, X2, Q); + } else { + ATH_MSG_FATAL( + "Not enough info to recompute PDF weights (empty XF1,XF2).\n Please try to set LHAPDFBaseSet to a valid PDF set.\n XF1=" << XF1 << " XF2=" << XF2 << " LHAPDFBaseSet=" << + m_base_pdf_name); + return StatusCode::FAILURE; } + } - for( auto& pdf : m_pdf_sets ){ - - // Being cautious... - pdf.second.event_weights.clear(); - pdf.second.event_weights.resize(pdf.second.pdf_members.size()); - - int i = 0; - - for( const auto& pdf_member : pdf.second.pdf_members ){ - - float new_xf1 = pdf_member->xfxQ( PDGID1, X1, Q ); - float new_xf2 = pdf_member->xfxQ( PDGID2, X2, Q ); + for (auto& pdf : m_pdf_sets) { + // Being cautious... + pdf.second.event_weights.clear(); + pdf.second.event_weights.resize(pdf.second.pdf_members.size()); - float weight = (new_xf1*new_xf2)/(XF1*XF2); + int i = 0; - // This is the reweighting each event - pdf.second.event_weights[i] = weight; - // This is the sum of all event weights for a final scaling - pdf.second.sum_of_event_weights[i] += (weight*mc_weight); - i++; - } + for (const auto& pdf_member : pdf.second.pdf_members) { + float new_xf1 = pdf_member->xfxQ(PDGID1, X1, Q); + float new_xf2 = pdf_member->xfxQ(PDGID2, X2, Q); - // decorate each truth event with a vector of PDF weights - if( m_config->saveLHAPDFEvent() ) - truthEvent->auxdecor< std::vector< float > >( "AnalysisTop_"+pdf.first+"_Weights" ) = pdf.second.event_weights; + float weight = (new_xf1 * new_xf2) / (XF1 * XF2); + // This is the reweighting each event + pdf.second.event_weights[i] = weight; + // This is the sum of all event weights for a final scaling + pdf.second.sum_of_event_weights[i] += (weight * mc_weight); + i++; } + // decorate each truth event with a vector of PDF weights + if (m_config->saveLHAPDFEvent()) truthEvent->auxdecor< std::vector< float > >( + "AnalysisTop_" + pdf.first + "_Weights") = pdf.second.event_weights; } return StatusCode::SUCCESS; - } - StatusCode PDFScaleFactorCalculator::finalize() - { - - for( auto& pdf : m_pdf_sets ) - m_config->addLHAPDFResult( pdf.first, pdf.second.sum_of_event_weights ); + StatusCode PDFScaleFactorCalculator::finalize() { + for (auto& pdf : m_pdf_sets) + m_config->addLHAPDFResult(pdf.first, pdf.second.sum_of_event_weights); if (m_basepdf) delete m_basepdf; return StatusCode::SUCCESS; - } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PhotonScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PhotonScaleFactorCalculator.cxx index 658c5ebfc1a23be3de9c0a363458e60ae5c1a323..fd8355f5cb05b6e6c1c4ac90abca84236a80c7fc 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PhotonScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PhotonScaleFactorCalculator.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // $Id: PhotonScaleFactorCalculator.cxx 802226 2017-04-04 16:13:10Z grancagn $ #include "TopCorrections/PhotonScaleFactorCalculator.h" @@ -13,226 +13,183 @@ #include "xAODEgamma/PhotonContainer.h" namespace top { -PhotonScaleFactorCalculator::PhotonScaleFactorCalculator(const std::string& name) : - asg::AsgTool(name), - m_config(nullptr), - m_systNominal(CP::SystematicSet()), - m_systEffIDUp("PH_EFF_ID_Uncertainty__1up"), - m_systEffIDDown("PH_EFF_ID_Uncertainty__1down"), - m_systEffLowPtIsoUp("PH_EFF_LOWPTISO_Uncertainty__1up"), - m_systEffLowPtIsoDown("PH_EFF_LOWPTISO_Uncertainty__1down"), - m_systEffTrkIsoUp("PH_EFF_TRKISO_Uncertainty__1up"), - m_systEffTrkIsoDown("PH_EFF_TRKISO_Uncertainty__1down"), - m_photonEffSF("AsgPhotonEfficiencyCorrectionTool"), - m_photonIsoSF(), - m_photonLooseIsoSF(), - m_photonIsoSF_exists(false), - m_photonLooseIsoSF_exists(false), - m_decor_isoSF("SetMe"), - m_decor_isoSF_loose("SetMe") - { - declareProperty("config" , m_config); -} + PhotonScaleFactorCalculator::PhotonScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + m_systNominal(CP::SystematicSet()), + m_systEffIDUp("PH_EFF_ID_Uncertainty__1up"), + m_systEffIDDown("PH_EFF_ID_Uncertainty__1down"), + m_systEffIsoUp("PH_EFF_ISO_Uncertainty__1up"), + m_systEffIsoDown("PH_EFF_ISO_Uncertainty__1down"), + m_photonEffSF("AsgPhotonEfficiencyCorrectionTool"), + m_photonIsoSF(), + m_photonLooseIsoSF(), + m_photonIsoSF_exists(false), + m_photonLooseIsoSF_exists(false), + m_decor_isoSF("SetMe"), + m_decor_isoSF_loose("SetMe") { + declareProperty("config", m_config); + } StatusCode PhotonScaleFactorCalculator::initialize() { ATH_MSG_INFO(" top::PhotonScaleFactorCalculator initialize"); top::check(m_photonEffSF.retrieve(), "Failed to retrieve photon efficiency SF calculator"); - std::cout<<"------>Systematics:"<<std::endl; + std::ostream& msgInfo = msg(MSG::Level::INFO); + msgInfo << "------>Systematics:\n"; for (auto sys:m_photonEffSF->recommendedSystematics()) - std::cout<<"---> "<<sys<<std::endl; + msgInfo << "---> " << sys << "\n"; // remove "FixedCut" if present std::string s = "FixedCut"; std::string isoName = m_config->photonIsolation(); m_decor_isoSF = "PH_SF_Iso_" + isoName; std::string::size_type i = isoName.find(s); - if (i != std::string::npos) - isoName.erase(i, s.length()); + if (i != std::string::npos) isoName.erase(i, s.length()); std::string photonIsoSFName = "AsgPhotonEfficiencyCorrectionTool_IsoSF" + isoName; m_photonIsoSF.setName(photonIsoSFName); if (asg::ToolStore::contains<IAsgPhotonEfficiencyCorrectionTool>(photonIsoSFName)) { m_photonIsoSF_exists = true; top::check(m_photonIsoSF.retrieve(), - "Failed to retrieve photon isolation efficiency SF calculator"); - std::cout<<"------>Systematics:"<<std::endl; + "Failed to retrieve photon isolation efficiency SF calculator"); + msgInfo << "------>Systematics:\n"; for (auto sys:m_photonIsoSF->recommendedSystematics()) - std::cout<<"---> "<<sys<<std::endl; + msgInfo << "---> " << sys << "\n"; } std::string isoNameLoose = m_config->photonIsolationLoose(); - m_decor_isoSF_loose = "PH_SF_Iso_" + isoNameLoose; + m_decor_isoSF_loose = "PH_LOOSE_SF_Iso_" + isoNameLoose; i = isoNameLoose.find(s); - if (i != std::string::npos) - isoNameLoose.erase(i, s.length()); + if (i != std::string::npos) isoNameLoose.erase(i, s.length()); std::string photonLooseIsoSFName = "AsgPhotonEfficiencyCorrectionTool_IsoSF" + isoNameLoose; m_photonLooseIsoSF.setName(photonLooseIsoSFName); if (asg::ToolStore::contains<IAsgPhotonEfficiencyCorrectionTool>(photonLooseIsoSFName)) { m_photonLooseIsoSF_exists = true; top::check(m_photonLooseIsoSF.retrieve(), - "Failed to retrieve loose photon isolation efficiency SF calculator"); - //std::cout<<"------>Systematics:"<<std::endl; - //for (auto sys:m_photonIsoSF->recommendedSystematics()) - //std::cout<<"---> "<<sys<<std::endl; + "Failed to retrieve loose photon isolation efficiency SF calculator"); } return StatusCode::SUCCESS; } - -StatusCode PhotonScaleFactorCalculator::execute() { - // Loop over all photon collections - for (auto currentSystematic : *m_config->systSgKeyMapPhotons()) { - const xAOD::PhotonContainer* photons(nullptr); - top::check(evtStore()->retrieve(photons, currentSystematic.second), - "Failed to retrieve photons"); - - // Loop over all photons in each collection - for (auto photonPtr : *photons) { - // Does the photon pass object selection? - bool passSelection(false); - if (photonPtr->isAvailable<char>("passPreORSelection")) { - if (photonPtr->auxdataConst<char>("passPreORSelection") == 1) { - passSelection = true; + StatusCode PhotonScaleFactorCalculator::execute() { + // Loop over all photon collections + for (auto currentSystematic : *m_config->systSgKeyMapPhotons()) { + const xAOD::PhotonContainer* photons(nullptr); + + top::check(evtStore()->retrieve(photons, currentSystematic.second), + "Failed to retrieve photons"); + + // Loop over all photons in each collection + for (auto photonPtr : *photons) { + // Does the photon pass object selection? + bool passSelection(false); + if (photonPtr->isAvailable<char>("passPreORSelection")) { + if (photonPtr->auxdataConst<char>("passPreORSelection") == 1) { + passSelection = true; + } } - } - if (photonPtr->isAvailable<char>("passPreORSelectionLoose")) { - if (photonPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { - passSelection = true; + if (photonPtr->isAvailable<char>("passPreORSelectionLoose")) { + if (photonPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { + passSelection = true; + } } - } - if (!passSelection) continue; + if (!passSelection) continue; - top::check(m_photonEffSF->applySystematicVariation(m_systNominal), - "Failed to set photon efficiency SF tool to nominal"); + top::check(m_photonEffSF->applySystematicVariation(m_systNominal), + "Failed to set photon efficiency SF tool to nominal"); - double effSF(1.); - top::check(m_photonEffSF->getEfficiencyScaleFactor(*photonPtr, effSF), + double effSF(1.); + top::check(m_photonEffSF->getEfficiencyScaleFactor(*photonPtr, effSF), "Failed to get nominal photon SF"); - static SG::AuxElement::Decorator<float> ph_effID_dec("EFF_ID_SF"); - ph_effID_dec(*photonPtr) = effSF; + static SG::AuxElement::Decorator<float> ph_effID_dec("EFF_ID_SF"); + ph_effID_dec(*photonPtr) = effSF; + + double isoSF(1.), isoLooseSF(1.); + if (m_photonIsoSF_exists) { + top::check(m_photonIsoSF->applySystematicVariation(m_systNominal), + "Failed to set photon efficiency SF tool to nominal"); + top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, isoSF), + "Failed to get nominal photon SF"); + static SG::AuxElement::Decorator<float> ph_isoID_dec(m_decor_isoSF); + ph_isoID_dec(*photonPtr) = isoSF; + } + if (m_photonLooseIsoSF_exists) { + top::check(m_photonLooseIsoSF->applySystematicVariation(m_systNominal), + "Failed to set photon efficiency SF tool to nominal"); + top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, isoLooseSF), + "Failed to get nominal photon SF"); + static SG::AuxElement::Decorator<float> ph_isoID_dec(m_decor_isoSF_loose); + ph_isoID_dec(*photonPtr) = isoLooseSF; + } - double isoSF(1.), isoLooseSF(1.); - if (m_photonIsoSF_exists) { - top::check(m_photonIsoSF->applySystematicVariation(m_systNominal), - "Failed to set photon efficiency SF tool to nominal"); - top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, isoSF), - "Failed to get nominal photon SF"); - static SG::AuxElement::Decorator<float> ph_isoID_dec(m_decor_isoSF); - ph_isoID_dec(*photonPtr) = isoSF; - } - if (m_photonLooseIsoSF_exists) { - top::check(m_photonLooseIsoSF->applySystematicVariation(m_systNominal), - "Failed to set photon efficiency SF tool to nominal"); - top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, isoLooseSF), - "Failed to get nominal photon SF"); - static SG::AuxElement::Decorator<float> ph_isoID_dec(m_decor_isoSF_loose); - ph_isoID_dec(*photonPtr) = isoLooseSF; - } + // For nominal calibration, vary the SF systematics + if (currentSystematic.first != m_config->nominalHashValue()) continue; + + double effSF_up(1.), effSF_down(1.); + top::check(m_photonEffSF->applySystematicVariation(m_systEffIDUp), + "Failed to set photon efficiency SF tool to" + " ID up systematic"); + top::check(m_photonEffSF->getEfficiencyScaleFactor(*photonPtr, effSF_up), + "Failed to get photon efficiency SF:" + " systematic up ID SF"); + + top::check(m_photonEffSF->applySystematicVariation(m_systEffIDDown), + "Failed to set photon efficiency SF tool to" + " ID up systematic"); + top::check(m_photonEffSF->getEfficiencyScaleFactor(*photonPtr, effSF_down), + "Failed to get photon efficiency SF:" + " systematic down ID SF"); + + static SG::AuxElement::Decorator<float> ph_effIDUp_dec("EFF_ID_SF_UP"); + static SG::AuxElement::Decorator<float> ph_effIDDown_dec("EFF_ID_SF_DOWN"); + ph_effIDUp_dec(*photonPtr) = effSF_up; + ph_effIDDown_dec(*photonPtr) = effSF_down; + + // isolation systematic uncertainties + double effIsoSF_up(1.), effIsoSF_down(1.); + double effLooseIsoSF_up(1.), effLooseIsoSF_down(1.); + if (m_photonIsoSF_exists) { + top::check(m_photonIsoSF->applySystematicVariation(m_systEffIsoUp), + "Failed to set photon efficiency SF tool to" + " isolation up systematic"); + top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, effIsoSF_up), + "Failed to get photon efficiency SF:" + " up systematic isolation"); + top::check(m_photonIsoSF->applySystematicVariation(m_systEffIsoDown), + "Failed to set photon efficiency SF tool to" + " isolation down systematic"); + top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, effIsoSF_down), + "Failed to get photon efficiency SF:" + " down systematic isolation"); + } + if (m_photonLooseIsoSF_exists) { + top::check(m_photonLooseIsoSF->applySystematicVariation(m_systEffIsoUp), + "Failed to set photon efficiency SF tool to" + " isolation up systematic"); + top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, effLooseIsoSF_up), + "Failed to get photon efficiency SF:" + " up systematic isolation"); + top::check(m_photonLooseIsoSF->applySystematicVariation(m_systEffIsoDown), + "Failed to set photon efficiency SF tool to" + " isolation down systematic"); + top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, effLooseIsoSF_down), + "Failed to get photon efficiency SF:" + " down systematic isolation"); + } - // For nominal calibration, vary the SF systematics - if (currentSystematic.first != m_config->nominalHashValue()) - continue; - - double effSF_up(1.), effSF_down(1.); - top::check(m_photonEffSF->applySystematicVariation(m_systEffIDUp), - "Failed to set photon efficiency SF tool to" - " ID up systematic"); - top::check(m_photonEffSF->getEfficiencyScaleFactor(*photonPtr, effSF_up), - "Failed to get photon efficiency SF:" - " systematic up ID SF"); - - top::check(m_photonEffSF->applySystematicVariation(m_systEffIDDown), - "Failed to set photon efficiency SF tool to" - " ID up systematic"); - top::check(m_photonEffSF->getEfficiencyScaleFactor(*photonPtr, effSF_down), - "Failed to get photon efficiency SF:" - " systematic down ID SF"); - - static SG::AuxElement::Decorator<float> ph_effIDUp_dec("EFF_ID_SF_UP"); - static SG::AuxElement::Decorator<float> ph_effIDDown_dec("EFF_ID_SF_DOWN"); - ph_effIDUp_dec(*photonPtr) = effSF_up; - ph_effIDDown_dec(*photonPtr) = effSF_down; - - // isolation systematic uncertainties - double effLowPtIsoSF_up(1.), effTrkIsoSF_up(1.); - double effLowPtIsoSF_down(1.), effTrkIsoSF_down(1.); - double effLowPtLooseIsoSF_up(1.), effTrkLooseIsoSF_up(1.); - double effLowPtLooseIsoSF_down(1.), effTrkLooseIsoSF_down(1.); - if (m_photonIsoSF_exists) { - top::check(m_photonIsoSF->applySystematicVariation(m_systEffLowPtIsoUp), - "Failed to set photon efficiency SF tool to" - " Radiative Z (low ET) up systematic "); - top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, effLowPtIsoSF_up), - "Failed to get photon efficiency SF:" - " up systematic Radiative Z (low ET)"); - top::check(m_photonIsoSF->applySystematicVariation(m_systEffLowPtIsoDown), - "Failed to set photon efficiency SF tool to" - " Radiative Z (low ET) down systematic"); - top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, effLowPtIsoSF_down), - "Failed to get photon efficiency SF:" - " down systematic Radiative Z (low ET)"); - - top::check(m_photonIsoSF->applySystematicVariation(m_systEffTrkIsoUp), - "Failed to set photon efficiency SF tool to" - " Track isolation (ptcone, intermediate and high ET) up systematic"); - top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, effTrkIsoSF_up), - "Failed to get photon efficiency SF:" - " up systematic Track isolation (ptcone, intermediate and high ET)"); - top::check(m_photonIsoSF->applySystematicVariation(m_systEffTrkIsoDown), - "Failed to set photon efficiency SF tool to" - " Track isolation (ptcone, intermediate and high ET) down systematic"); - top::check(m_photonIsoSF->getEfficiencyScaleFactor(*photonPtr, effTrkIsoSF_down), - "Failed to get photon efficiency SF:" - " down systematic Track isolation (ptcone, intermediate and high ET)"); - } - if (m_photonLooseIsoSF_exists) { - top::check(m_photonLooseIsoSF->applySystematicVariation(m_systEffLowPtIsoUp), - "Failed to set photon efficiency SF tool to" - " Radiative Z (low ET) up systematic "); - top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, effLowPtLooseIsoSF_up), - "Failed to get photon efficiency SF:" - " up systematic Radiative Z (low ET)"); - top::check(m_photonLooseIsoSF->applySystematicVariation(m_systEffLowPtIsoDown), - "Failed to set photon efficiency SF tool to" - " Radiative Z (low ET) down systematic"); - top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, effLowPtLooseIsoSF_down), - "Failed to get photon efficiency SF:" - " down systematic Radiative Z (low ET)"); - - top::check(m_photonLooseIsoSF->applySystematicVariation(m_systEffTrkIsoUp), - "Failed to set photon efficiency SF tool to" - " Track isolation (ptcone, intermediate and high ET) up systematic"); - top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, effTrkLooseIsoSF_up), - "Failed to get photon efficiency SF:" - " up systematic Track isolation (ptcone, intermediate and high ET)"); - top::check(m_photonLooseIsoSF->applySystematicVariation(m_systEffTrkIsoDown), - "Failed to set photon efficiency SF tool to" - " Track isolation (ptcone, intermediate and high ET) down systematic"); - top::check(m_photonLooseIsoSF->getEfficiencyScaleFactor(*photonPtr, effTrkLooseIsoSF_down), - "Failed to get photon efficiency SF:" - " down systematic Track isolation (ptcone, intermediate and high ET)"); - } + static SG::AuxElement::Decorator<float> ph_effIsoUp_dec(m_decor_isoSF + "_UP"); + static SG::AuxElement::Decorator<float> ph_effIsoDown_dec(m_decor_isoSF + "_DOWN"); + static SG::AuxElement::Decorator<float> ph_effLooseIsoUp_dec(m_decor_isoSF_loose + "_UP"); + static SG::AuxElement::Decorator<float> ph_effLooseIsoDown_dec(m_decor_isoSF_loose + "_DOWN"); - static SG::AuxElement::Decorator<float> ph_effLowPtIsoUp_dec(m_decor_isoSF+"_LOWPT_UP"); - static SG::AuxElement::Decorator<float> ph_effLowPtIsoDown_dec(m_decor_isoSF+"_LOWPT_DOWN"); - static SG::AuxElement::Decorator<float> ph_effTrkIsoUp_dec(m_decor_isoSF+"_TRK_UP"); - static SG::AuxElement::Decorator<float> ph_effTrkIsoDown_dec(m_decor_isoSF+"_TRK_DOWN"); - static SG::AuxElement::Decorator<float> ph_effLowPtLooseIsoUp_dec(m_decor_isoSF_loose+"_LOWPT_UP"); - static SG::AuxElement::Decorator<float> ph_effLowPtLooseIsoDown_dec(m_decor_isoSF_loose+"_LOWPT_DOWN"); - static SG::AuxElement::Decorator<float> ph_effTrkLooseIsoUp_dec(m_decor_isoSF_loose+"_TRK_UP"); - static SG::AuxElement::Decorator<float> ph_effTrkLooseIsoDown_dec(m_decor_isoSF_loose+"_TRK_DOWN"); - ph_effLowPtIsoUp_dec(*photonPtr) = effLowPtIsoSF_up; - ph_effLowPtIsoDown_dec(*photonPtr) = effLowPtIsoSF_down; - ph_effTrkIsoUp_dec(*photonPtr) = effTrkIsoSF_up; - ph_effTrkIsoDown_dec(*photonPtr) = effTrkIsoSF_down; - ph_effLowPtLooseIsoUp_dec(*photonPtr) = effLowPtLooseIsoSF_up; - ph_effLowPtLooseIsoDown_dec(*photonPtr) = effLowPtLooseIsoSF_down; - ph_effTrkLooseIsoUp_dec(*photonPtr) = effTrkLooseIsoSF_up; - ph_effTrkLooseIsoDown_dec(*photonPtr) = effTrkLooseIsoSF_down; + ph_effIsoUp_dec(*photonPtr) = effIsoSF_up; + ph_effIsoDown_dec(*photonPtr) = effIsoSF_down; + ph_effLooseIsoUp_dec(*photonPtr) = effLooseIsoSF_up; + ph_effLooseIsoDown_dec(*photonPtr) = effLooseIsoSF_down; + } } + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PileupScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PileupScaleFactorCalculator.cxx index 918b6e72ce6cb3ea9900cb3c257eb50c94abd82c..82bf77123b1fb7dba65af2f4d5d13c11cc10fff6 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PileupScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/PileupScaleFactorCalculator.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #include "TopCorrections/PileupScaleFactorCalculator.h" #include "TopConfiguration/TopConfig.h" @@ -8,91 +8,107 @@ #include "xAODEventInfo/EventInfo.h" -namespace top{ - - PileupScaleFactorCalculator::PileupScaleFactorCalculator( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + PileupScaleFactorCalculator::PileupScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), m_pileupReweightingTool("CP::PileupReweightingTool"), - m_systNominal( CP::SystematicSet() ), - m_systDataSFUp( CP::SystematicSet() ), - m_systDataSFDown( CP::SystematicSet() ) - { - declareProperty( "config" , m_config ); + m_systNominal(CP::SystematicSet()), + m_systDataSFUp(CP::SystematicSet()), + m_systDataSFDown(CP::SystematicSet()) { + declareProperty("config", m_config); } - StatusCode PileupScaleFactorCalculator::initialize() - { - ATH_MSG_INFO(" top::PileupScaleFactorCalculator initialize" ); + StatusCode PileupScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::PileupScaleFactorCalculator initialize"); - top::check( m_pileupReweightingTool.retrieve(), "Failed to retireve pileup reweighting tool" ); + top::check(m_pileupReweightingTool.retrieve(), "Failed to retireve pileup reweighting tool"); - m_systDataSFUp.insert( CP::SystematicVariation("PRW_DATASF", 1) ); - m_systDataSFDown.insert( CP::SystematicVariation("PRW_DATASF", -1) ); + m_systDataSFUp.insert(CP::SystematicVariation("PRW_DATASF", 1)); + m_systDataSFDown.insert(CP::SystematicVariation("PRW_DATASF", -1)); m_mu_dependent_PRW = m_config->PileupMuDependent(); return StatusCode::SUCCESS; } - - StatusCode PileupScaleFactorCalculator::execute() - { - + StatusCode PileupScaleFactorCalculator::execute() { // get the event info const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), - "Failed to retrieve EventInfo"); + "Failed to retrieve EventInfo"); - top::check( m_pileupReweightingTool->applySystematicVariation( m_systNominal ), - "Failed to set pileup reweighting to nominal value" ); + top::check(m_pileupReweightingTool->applySystematicVariation(m_systNominal), + "Failed to set pileup reweighting to nominal value"); top::check(m_pileupReweightingTool->apply(*eventInfo, m_mu_dependent_PRW), - "Failed to apply pileup weight"); + "Failed to apply pileup weight"); + + // Apply correction to actual mu for data + if (!m_config->isMC()) { + float actualMu = m_pileupReweightingTool->getCorrectedActualInteractionsPerCrossing(*eventInfo); + eventInfo->auxdecor<float>("corrected_actualInteractionsPerCrossing") = actualMu; + } // Get hash value which can be used later for reweighting if (m_config->isMC()) { unsigned long long prw_hash = m_pileupReweightingTool->getPRWHash(*eventInfo); eventInfo->auxdecor<unsigned long long>("PileupWeight_Hash") = prw_hash; } - + // Now get the up and down pileup variations // We want the SF for MC and the mu value for data // Switch tool to DataSFUp - top::check( m_pileupReweightingTool->applySystematicVariation( m_systDataSFUp ), - "Failed to switch pileup reweighting tool to data SF up" ); - - if( m_config->isMC() ){ + top::check(m_pileupReweightingTool->applySystematicVariation(m_systDataSFUp), + "Failed to switch pileup reweighting tool to data SF up"); + + if (m_config->isMC()) { // The apply method above has pileupWeight as // a double (although the function returns a float) // so here we do the same for consistency - float pileupWeight = m_pileupReweightingTool->getCombinedWeight( *eventInfo ); + float pileupWeight = m_pileupReweightingTool->getCombinedWeight(*eventInfo); eventInfo->auxdecor<float>("PileupWeight_UP") = pileupWeight; - } - else { - float lumiBlockMu = m_pileupReweightingTool->getCorrectedMu( *eventInfo ); + } else { + float lumiBlockMu { + 1 + }; + if (m_config->isAFII() && m_config->PileupActualMu_AF().size() > 0) { + lumiBlockMu = m_pileupReweightingTool->getCorrectedActualInteractionsPerCrossing(*eventInfo); + } else if (!m_config->isAFII() && m_config->PileupActualMu_FS().size() > 0) { + lumiBlockMu = m_pileupReweightingTool->getCorrectedActualInteractionsPerCrossing(*eventInfo); + } else { + lumiBlockMu = m_pileupReweightingTool->getCorrectedAverageInteractionsPerCrossing(*eventInfo); + } eventInfo->auxdecor<float>("corrected_averageInteractionsPerCrossing_UP") = lumiBlockMu; } - + // Switch tool to DataSFDown - top::check( m_pileupReweightingTool->applySystematicVariation( m_systDataSFDown ), - "Failed to switch pileup reweighting tool to data SF down" ); + top::check(m_pileupReweightingTool->applySystematicVariation(m_systDataSFDown), + "Failed to switch pileup reweighting tool to data SF down"); - if( m_config->isMC() ){ - float pileupWeight = m_pileupReweightingTool->getCombinedWeight( *eventInfo ); + if (m_config->isMC()) { + float pileupWeight = m_pileupReweightingTool->getCombinedWeight(*eventInfo); eventInfo->auxdecor<float>("PileupWeight_DOWN") = pileupWeight; - } - else { - float lumiBlockMu = m_pileupReweightingTool->getCorrectedMu( *eventInfo ); + } else { + float lumiBlockMu { + 1 + }; + if (m_config->isAFII() && m_config->PileupActualMu_AF().size() > 0) { + lumiBlockMu = m_pileupReweightingTool->getCorrectedActualInteractionsPerCrossing(*eventInfo); + } else if (!m_config->isAFII() && m_config->PileupActualMu_FS().size() > 0) { + lumiBlockMu = m_pileupReweightingTool->getCorrectedActualInteractionsPerCrossing(*eventInfo); + } else { + lumiBlockMu = m_pileupReweightingTool->getCorrectedAverageInteractionsPerCrossing(*eventInfo); + } eventInfo->auxdecor<float>("corrected_averageInteractionsPerCrossing_DOWN") = lumiBlockMu; } - + // Switch tool to back to nominal to be extra careful... - top::check( m_pileupReweightingTool->applySystematicVariation( m_systNominal ), - "Failed to switch pileup reweighting tool back to nominal" ); + top::check(m_pileupReweightingTool->applySystematicVariation(m_systNominal), + "Failed to switch pileup reweighting tool back to nominal"); return StatusCode::SUCCESS; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorCalculator.cxx index 733581f8f832616c1557ae1f6526fbd8a9a5e71e..315b8013e317b2f6383dedcad65eb846b4904835 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorCalculator.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopCorrections/ScaleFactorCalculator.h" @@ -10,146 +10,273 @@ #include "TopEvent/EventTools.h" #include "xAODEventInfo/EventInfo.h" -#include "xAODTruth/TruthEventContainer.h" + +#include <sstream> namespace top { + ScaleFactorCalculator::ScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), -ScaleFactorCalculator::ScaleFactorCalculator(const std::string& name) : - asg::AsgTool(name), - m_config(nullptr), - - m_photonSF(nullptr), - m_electronSF(nullptr), - m_muonSF(nullptr), - m_tauSF(nullptr), - m_jetSF(nullptr), - m_btagSF(nullptr), - m_pileupSF(nullptr), - m_sherpa_22_reweight_tool("PMGSherpa22VJetsWeightTool") { - declareProperty("config", m_config); -} - -StatusCode ScaleFactorCalculator::initialize() { - ATH_MSG_INFO(" top::ScaleFactorCalculator initialize"); - - m_photonSF = std::make_unique<top::PhotonScaleFactorCalculator>("top::PhotonScaleFactorCalculator"); - m_electronSF = std::make_unique<top::ElectronScaleFactorCalculator>("top::ElectronScaleFactorCalculator"); - m_muonSF = std::make_unique<top::MuonScaleFactorCalculator>("top::MuonScaleFactorCalculator"); - m_tauSF = std::make_unique<top::TauScaleFactorCalculator>("top::TauScaleFactorCalculator"); - m_jetSF = std::make_unique<top::JetScaleFactorCalculator>("top::JetScaleFactorCalculator"); - m_btagSF = std::make_unique<top::BTagScaleFactorCalculator>("top::BTagScaleFactorCalculator"); - m_pileupSF = std::make_unique<top::PileupScaleFactorCalculator>("top::PileupScaleFactorCalculator"); - - if (m_config->isMC()) { - if (m_config->usePhotons()) { - top::check(m_photonSF->setProperty("config", m_config), "Failed to setProperty"); - top::check(m_photonSF->initialize(), "Failed to initialize"); - } + m_photonSF(nullptr), + m_electronSF(nullptr), + m_fwdElectronSF(nullptr), + m_muonSF(nullptr), + m_tauSF(nullptr), + m_jetSF(nullptr), + m_btagSF(nullptr), + m_pileupSF(nullptr), + m_sherpa_22_reweight_tool("PMGSherpa22VJetsWeightTool"), + m_globalLeptonTriggerSF(nullptr), + m_pmg_truth_weight_tool("PMGTruthWeightTool"), + m_sample_multiple_MCweights(false), + m_nominal_weight_name("") { + declareProperty("config", m_config); + } - if (m_config->useElectrons()) { - top::check(m_electronSF->setProperty("config", m_config), "Failed to setProperty"); - // m_electronSF->msg().setLevel(MSG::DEBUG); - top::check(m_electronSF->initialize(), "Failed to initialize"); - } + StatusCode ScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::ScaleFactorCalculator initialize"); - if (m_config->useMuons() && !m_config->isTruthDxAOD()) { - top::check(m_muonSF->setProperty("config", m_config), "Failed to setProperty"); - // m_muonSF->msg().setLevel(MSG::DEBUG); - top::check(m_muonSF->initialize(), "Failed to initialize"); - } + m_photonSF = std::make_unique<top::PhotonScaleFactorCalculator>("top::PhotonScaleFactorCalculator"); + m_electronSF = std::make_unique<top::ElectronScaleFactorCalculator>("top::ElectronScaleFactorCalculator"); + m_fwdElectronSF = std::make_unique<top::FwdElectronScaleFactorCalculator>("top::FwdElectronScaleFactorCalculator"); + m_muonSF = std::make_unique<top::MuonScaleFactorCalculator>("top::MuonScaleFactorCalculator"); + m_tauSF = std::make_unique<top::TauScaleFactorCalculator>("top::TauScaleFactorCalculator"); + m_jetSF = std::make_unique<top::JetScaleFactorCalculator>("top::JetScaleFactorCalculator"); + m_btagSF = std::make_unique<top::BTagScaleFactorCalculator>("top::BTagScaleFactorCalculator"); + m_pileupSF = std::make_unique<top::PileupScaleFactorCalculator>("top::PileupScaleFactorCalculator"); + m_globalLeptonTriggerSF = + std::make_unique<top::GlobalLeptonTriggerCalculator>("top::GlobalLeptonTriggerCalculator"); - if (m_config->useTaus()) { - top::check(m_tauSF->setProperty("config", m_config), "Failed to setProperty"); - top::check(m_tauSF->initialize(), "Failed to initialize"); - } + if (m_config->isMC()) { + if (m_config->usePhotons()) { + top::check(m_photonSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_photonSF->initialize(), "Failed to initialize"); + } + + if (m_config->useElectrons()) { + top::check(m_electronSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_electronSF->initialize(), "Failed to initialize"); + } + + if (m_config->useFwdElectrons()) { + top::check(m_fwdElectronSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_fwdElectronSF->initialize(), "Failed to initialize"); + } - if (m_config->useJets()) { - top::check(m_jetSF->setProperty("config", m_config), "Failed to setProperty"); - top::check(m_jetSF->initialize(), "Failed to initialize"); + if (m_config->useMuons() && !m_config->isTruthDxAOD()) { + top::check(m_muonSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_muonSF->initialize(), "Failed to initialize"); + } - top::check(m_btagSF->setProperty("config", m_config), "Failed to setProperty"); - top::check(m_btagSF->initialize(), "Failed to initialize"); + if (m_config->useTaus()) { + top::check(m_tauSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_tauSF->initialize(), "Failed to initialize"); + } + + if (m_config->useJets()) { + top::check(m_jetSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_jetSF->initialize(), "Failed to initialize"); + + top::check(m_btagSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_btagSF->initialize(), "Failed to initialize"); + } + + if (m_config->isSherpa22Vjets()) top::check(m_sherpa_22_reweight_tool.retrieve(), + "Failed to retrieve PMGSherpa22VJetsWeightTool"); + + if ((m_config->useElectrons() || m_config->useMuons()) && m_config->useGlobalTrigger()) { + top::check(m_globalLeptonTriggerSF->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_globalLeptonTriggerSF->initialize(), "Failed to initalize"); + } + + top::check(initialize_nominal_MC_weight(), "Failed to initialize nominal MC weight in SF calculator"); } - if (m_config->isSherpa22Vjets()) - top::check(m_sherpa_22_reweight_tool.retrieve(), - "Failed to retrieve PMGSherpa22VJetsWeightTool"); - } + if (m_config->doPileupReweighting()) { + top::check(m_pileupSF->setProperty("config", m_config), "Failed to add config to pileup SF calculator"); + top::check(m_pileupSF->initialize(), "Failed to initialize pileup SF calculator"); + } - if (m_config->doPileupReweighting()) { - top::check(m_pileupSF->setProperty("config", m_config), "Failed to add config to pileup SF calculator"); - top::check(m_pileupSF->initialize(), "Failed to initialize pileup SF calculator"); + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} - -StatusCode ScaleFactorCalculator::execute() { - if (m_config->isMC()) { - if (m_config->usePhotons()) - top::check(m_photonSF->execute(), "Failed to execute photon SF"); - if (m_config->useElectrons()) - top::check(m_electronSF->execute(), "Failed to execute electron SF"); - if (m_config->useMuons() && !m_config->isTruthDxAOD()) - top::check(m_muonSF->execute(), "Failed to execute muon SF"); - if (m_config->useTaus()) - top::check(m_tauSF->execute(), "Failed to execute tau SF"); - if (m_config->useJets()) - top::check(m_jetSF->execute(), "Failed to execute jet SF"); - if (m_config->useJets()) { - top::check(m_btagSF->execute(), "Failed to execute btag SF"); + StatusCode ScaleFactorCalculator::initialize_nominal_MC_weight() { + // check if user force-requested to use plain MC weights vector index + // in that case ignore all the additional checks if metadata broken + // as well as the method to determine nominal weight by name + if (m_config->forceNominalWeightFallbackIndex()) { + ATH_MSG_WARNING("ForceNominalWeightFallbackIndex option was set to true." + << "\nWill use weight with index: " << m_config->nominalWeightIndex() + << " instead of determining it from metadata!"); + return StatusCode::SUCCESS; + } + ///-- Start using the PMG tool to get the nominal event weights --/// + // in case PMGTruthWeightTool init fails, e.g. due to broken metadata + if (!m_pmg_truth_weight_tool.retrieve()) { + // we don't know how many MC weights there are and user didn't specify nominal index + if (m_config->MCweightsVectorSize() == size_t(-1) + && m_config->nominalWeightIndex() == size_t(-1)) { + ATH_MSG_ERROR("\nPMGTruthWeightTool instance could not be retrieved." + << "We could not determine the number of MC generator weights in this sample.\n" + << "We cannot determine the nominal MC weight. Please specify the index of " + << "nominal MC weight via config option NominalWeightFallbackIndex."); + return StatusCode::FAILURE; + } + // we know there are multiple MC weights and user didn't specify nominal index + if (m_config->MCweightsVectorSize() > 1 + && m_config->nominalWeightIndex() == size_t(-1)) { + ATH_MSG_ERROR("\nPMGTruthWeightTool instance could not be retrieved." + << "We detect multiple MC generator weights in the sample.\n " + << "We cannot determine which one is nominal. Please specify the index of " + << "nominal MC weight via config option NominalWeightFallbackIndex."); + return StatusCode::FAILURE; + } + // only one MC weight in the sample, this is sovable unambiguously + if (m_config->MCweightsVectorSize() == 1) { + m_config->setNominalWeightIndex(0); + ATH_MSG_WARNING("PMGTruthWeightTool instance could not be retrieved." + << "This sample has only one MC weight, will use that one."); + return StatusCode::SUCCESS; + } + // possibly multiple weights, but the user already gave us fallback option + ATH_MSG_WARNING("PMGTruthWeightTool instance could not be retrieved." + << "Falling back to specified NominalWeightFallbackIndex " + << m_config->nominalWeightIndex()); + return StatusCode::SUCCESS; } - // Add Sherpa 22 weights directly here, if we get more - // PMG tools for reweighting then we should consider making - // a m_PMG_SF class, as with other corrections - if (m_config->isSherpa22Vjets()) { - const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), - "Failed to retrieve EventInfo"); - double sherpa_weight = m_sherpa_22_reweight_tool->getWeight(); - eventInfo->auxdecor<double>("Sherpa22VJetsWeight") = sherpa_weight; + // PMGTruthWeightTool was initialized succesfully, let's see if we have weights + const std::vector<std::string>& pmg_weight_names = m_pmg_truth_weight_tool->getWeightNames(); + m_sample_multiple_MCweights = (pmg_weight_names.size() > 1); + if (!m_sample_multiple_MCweights) { + ATH_MSG_WARNING("PMGTruthWeightTool did not find multiple MC generator weights in metadata for this sample." + << "\nThis most likely means that the sample has only one weight." + << "\nCheck the top-xaod output for PMGTruthWeightTool-related errors just to be sure."); + if (m_config->nominalWeightIndex() != size_t(-1)) { + ATH_MSG_WARNING("Using MC weight index " << m_config->nominalWeightIndex() + << " as specified in config."); + } else { + ATH_MSG_WARNING("Will use 0th weight index. " + << "If you want a different weight, specify it via config option NominalWeightFallbackIndex"); + m_config->setNominalWeightIndex(0); + } + return StatusCode::SUCCESS; } + // here we try to find the first weight name from the NominalWeightNames config option, that matches any MC weight in the sample + const std::vector<std::string> &nominal_weight_names = m_config->nominalWeightNames(); + bool found_match = false; + std::vector<std::string> multiple_matches; + for (const std::string& weight_name : nominal_weight_names) { + // Check whether this weight name does exist + if (m_pmg_truth_weight_tool->hasWeight(weight_name)) { + // pick only the first match, but check if there are multiple matches -- that is a problem + if (!found_match) + m_nominal_weight_name = weight_name; + found_match = true; + multiple_matches.push_back(weight_name); + } + } + // we have to find the index, because PMGTruthWeightTool has no method to give us the index + auto weight_index = std::find(pmg_weight_names.begin(), pmg_weight_names.end(), m_nominal_weight_name); + m_config->setNominalWeightName(m_nominal_weight_name); + m_config->setNominalWeightIndex(weight_index - pmg_weight_names.begin()); + if (multiple_matches.size() > 1) { + std::stringstream s_multiple_matches; + for (const std::string &wname : multiple_matches) + s_multiple_matches << "\"" << wname << "\"\n"; + ATH_MSG_WARNING("Multiple NominalWeightNames match for this MC sample!\n" + s_multiple_matches.str() + + "\nThe one we will use is \"" + m_nominal_weight_name + "\". Check whether this is really correct!"); + } + if (!found_match) { + // if we get here, it means we are missing the correct name of the nominal weight + // user has to find it in the sample meta-data and add it to AT config file + ATH_MSG_ERROR("No MC weight matches any of the names specified by NominalWeightNames " + "option\nThis may indicate a sample with non-standard nominal MC weight name!"); + std::stringstream weights_log; + for (size_t w_indx=0; w_indx < pmg_weight_names.size(); ++w_indx) { + weights_log << "Weight " << w_indx << ": \"" << pmg_weight_names.at(w_indx) << "\"\n"; + } + ATH_MSG_ERROR("The following weight names are available based on sample metadata:\n" + weights_log.str() + + "\nAdd the correct nominal weight name from this list into the NominalWeightNames option in your config file."); + return StatusCode::FAILURE; + } + + ATH_MSG_INFO("Using the following MC weight as nominal: \"" + m_config->nominalWeightName() + << "\", index: " << m_config->nominalWeightIndex()); + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} - -StatusCode ScaleFactorCalculator::executePileup() { - if (m_config->doPileupReweighting()) - top::check(m_pileupSF->execute(), "Failed to execute pileup SF"); - return StatusCode::SUCCESS; -} - -float ScaleFactorCalculator::pileupWeight() const { - float sf(1.); - if (!m_config->isMC()) { - return sf; + + StatusCode ScaleFactorCalculator::execute() { + if (m_config->isMC()) { + if (m_config->usePhotons()) top::check(m_photonSF->execute(), "Failed to execute photon SF"); + if (m_config->useElectrons()) top::check(m_electronSF->execute(), "Failed to execute electron SF"); + if (m_config->useFwdElectrons()) top::check(m_fwdElectronSF->execute(), "Failed to execute fwd electron SF"); + if (m_config->useMuons() && + !m_config->isTruthDxAOD()) top::check(m_muonSF->execute(), "Failed to execute muon SF"); + if (m_config->useTaus()) top::check(m_tauSF->execute(), "Failed to execute tau SF"); + if (m_config->useJets()) top::check(m_jetSF->execute(), "Failed to execute jet SF"); + if (m_config->useJets()) { + top::check(m_btagSF->execute(), "Failed to execute btag SF"); + } + // Add Sherpa 22 weights directly here, if we get more + // PMG tools for reweighting then we should consider making + // a m_PMG_SF class, as with other corrections + if (m_config->isSherpa22Vjets()) { + const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + double sherpa_weight = m_sherpa_22_reweight_tool->getWeight(); + eventInfo->auxdecor<double>("Sherpa22VJetsWeight") = sherpa_weight; + } + if ((m_config->useElectrons() || m_config->useMuons()) && m_config->useGlobalTrigger()) { + top::check(m_globalLeptonTriggerSF->execute(), "Failed to exectute global trigger SF"); + } + } + return StatusCode::SUCCESS; + } + + StatusCode ScaleFactorCalculator::executePileup() { + if (m_config->doPileupReweighting()) top::check(m_pileupSF->execute(), "Failed to execute pileup SF"); + return StatusCode::SUCCESS; } - const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), - "Failed to retrieve EventInfo"); + float ScaleFactorCalculator::pileupWeight() const { + float sf(1.); + + if (!m_config->isMC()) { + return sf; + } - if (eventInfo->isAvailable<float>("PileupWeight")) - sf = eventInfo->auxdataConst<float>("PileupWeight"); + const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), + "Failed to retrieve EventInfo"); - return sf; -} + if (eventInfo->isAvailable<float>("PileupWeight")) sf = eventInfo->auxdataConst<float>("PileupWeight"); -float ScaleFactorCalculator::mcEventWeight() const { - float sf(1.); - if (!m_config->isMC()) { return sf; } - const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), - "Failed to retrieve EventInfo"); - const xAOD::TruthEventContainer* truthEventContainer(nullptr); - top::check( evtStore()->retrieve(truthEventContainer, m_config->sgKeyTruthEvent()) , "Failed to retrieve truth PDF info" ); + float ScaleFactorCalculator::mcEventWeight() const { + float sf(1.); + + if (!m_config->isMC()) { + return sf; + } + // Decorate the updated nominal weight if appropriate - note this is called early in top-xaod + const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); -// sf = eventInfo->mcEventWeight(); - sf = truthEventContainer->at(0)->weights()[0];// FIXME temporary bugfix + // Check if the decoration is already present, and return it if so + if (eventInfo->isAvailable<float>("AnalysisTop_eventWeight")) return eventInfo->auxdataConst<float>( + "AnalysisTop_eventWeight"); - return sf; -} + try { + sf = eventInfo->mcEventWeights().at(m_config->nominalWeightIndex()); + eventInfo->auxdecor<float>("AnalysisTop_eventWeight") = sf; + } catch (std::out_of_range &e) { + ATH_MSG_ERROR("MC weight specified by index " << m_config->nominalWeightIndex() + << " does not exist: "); + throw; + } + return sf; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorRetriever.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorRetriever.cxx index b777c655d8908eb54bcc0033e9ef974f2125049d..65cdd47b26d759143688538048066396d490a2b4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorRetriever.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/ScaleFactorRetriever.cxx @@ -1,33 +1,53 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopCorrections/ScaleFactorRetriever.h" +#include "TopCorrections/TopCorrectionsTools.h" #include <vector> #include <string> #include "TopEvent/Event.h" #include "TopEvent/EventTools.h" +#include "TopEvent/SystematicEvent.h" +#include "TopConfiguration/ConfigurationSettings.h" #include "TopConfiguration/TopConfig.h" #include "AthContainers/AuxElement.h" +#include "xAODRootAccess/TStore.h" +#include "xAODEventInfo/EventInfo.h" namespace top { + ScaleFactorRetriever::ScaleFactorRetriever(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + m_preferGlobalTriggerSF(ConfigurationSettings::get()->feature("PreferGlobalTriggerSF")) { + declareProperty("config", m_config); + } + + StatusCode ScaleFactorRetriever::initialize() { + ATH_MSG_INFO("Initialising " << this->name()); - ScaleFactorRetriever::ScaleFactorRetriever(std::shared_ptr<top::TopConfig> config) : - m_config(config) { - std::shared_ptr<std::vector<std::string>> selectors = config -> allSelectionNames(); + std::shared_ptr<std::vector<std::string> > selectors = m_config->allSelectionNames(); for (std::string selPtr : *selectors) { - std::vector<std::string> muonTrig = config -> muonTriggers(selPtr); - std::vector<std::string> electronTrig = config -> electronTriggers(selPtr); + std::vector<std::string> muonTrig_Tight = m_config->muonTriggers_Tight(selPtr); + std::vector<std::string> electronTrig_Tight = m_config->electronTriggers_Tight(selPtr); + std::vector<std::string> muonTrig_Loose = m_config->muonTriggers_Loose(selPtr); + std::vector<std::string> electronTrig_Loose = m_config->electronTriggers_Loose(selPtr); - for (auto trig : muonTrig) - m_muonTriggers.push_back(trig); + for (auto trig : muonTrig_Tight) + m_muonTriggers_Tight.push_back(trig); + for (auto trig : muonTrig_Loose) + m_muonTriggers_Loose.push_back(trig); - for (auto trig : electronTrig) - m_electronTriggers.push_back(trig); + for (auto trig : electronTrig_Tight) + m_electronTriggers_Tight.push_back(trig); + for (auto trig : electronTrig_Loose) + m_electronTriggers_Loose.push_back(trig); } + + return StatusCode::SUCCESS; } // Pile up SF @@ -40,14 +60,13 @@ namespace top { float sf(1.); if (var == 0) { // nominal - if (event.m_info->isAvailable<float>("PileupWeight")) - sf = event.m_info->auxdataConst<float>("PileupWeight"); + if (event.m_info->isAvailable<float>("PileupWeight")) sf = event.m_info->auxdataConst<float>("PileupWeight"); } else if (var == 1) { // dataSF up - if (event.m_info->isAvailable<float>("PileupWeight_UP")) - sf = event.m_info->auxdataConst<float>("PileupWeight_UP"); + if (event.m_info->isAvailable<float>("PileupWeight_UP")) sf = + event.m_info->auxdataConst<float>("PileupWeight_UP"); } else if (var == -1) { // dataSF down - if (event.m_info->isAvailable<float>("PileupWeight_DOWN")) - sf = event.m_info->auxdataConst<float>("PileupWeight_DOWN"); + if (event.m_info->isAvailable<float>("PileupWeight_DOWN")) sf = event.m_info->auxdataConst<float>( + "PileupWeight_DOWN"); } return sf; @@ -61,8 +80,82 @@ namespace top { * triggerSF(event, SFSyst); } + float ScaleFactorRetriever::globalTriggerSF(const top::Event& event, const top::topSFSyst SFSyst) const { + float sf(1.0); + + static const std::string prefix = "AnalysisTop_Trigger_SF_"; + + xAOD::SystematicEvent const* eventInfo = event.m_systematicEvent; + top::check(eventInfo, "Failed to retrieve SystematicEvent"); + const bool electronTriggerIsEmpty = event.m_isLoose ? m_electronTriggers_Loose.empty() : m_electronTriggers_Tight.empty(); + const bool muonTriggerIsEmpty = event.m_isLoose ? m_muonTriggers_Loose.empty() : m_muonTriggers_Tight.empty(); + + // Create a hard-coded map linking top::topSFSyst <-> EventInfo decoration + switch (SFSyst) { + case top::topSFSyst::EL_SF_Trigger_UP: + if (electronTriggerIsEmpty) { + sf = 1; + } else { + sf = eventInfo->auxdataConst<float>(prefix + "EL_EFF_Trigger_TOTAL_1NPCOR_PLUS_UNCOR__1up"); + } + break; + + case top::topSFSyst::EL_SF_Trigger_DOWN: + if (electronTriggerIsEmpty) { + sf = 1; + } else { + sf = eventInfo->auxdataConst<float>(prefix + "EL_EFF_Trigger_TOTAL_1NPCOR_PLUS_UNCOR__1down"); + } + break; + + case top::topSFSyst::MU_SF_Trigger_STAT_UP: + if (muonTriggerIsEmpty) { + sf = 1; + } else { + sf = eventInfo->auxdataConst<float>(prefix + "MUON_EFF_TrigStatUncertainty__1up"); + } + break; + + case top::topSFSyst::MU_SF_Trigger_STAT_DOWN: + if (muonTriggerIsEmpty) { + sf = 1; + } else { + sf = eventInfo->auxdataConst<float>(prefix + "MUON_EFF_TrigStatUncertainty__1down"); + } + break; + + case top::topSFSyst::MU_SF_Trigger_SYST_UP: + if (muonTriggerIsEmpty) { + sf = 1; + } else { + sf = eventInfo->auxdataConst<float>(prefix + "MUON_EFF_TrigSystUncertainty__1up"); + } + break; + + case top::topSFSyst::MU_SF_Trigger_SYST_DOWN: + if (muonTriggerIsEmpty) { + sf = 1; + } else { + sf = eventInfo->auxdataConst<float>(prefix + "MUON_EFF_TrigSystUncertainty__1down"); + } + break; + + default: + // Nominal weight + sf = eventInfo->auxdataConst<float>(prefix); + break; + } + return sf; + } + float ScaleFactorRetriever::triggerSF(const top::Event& event, const top::topSFSyst SFSyst) const { + return(m_preferGlobalTriggerSF && + m_config->useGlobalTrigger() ? globalTriggerSF(event, SFSyst) : oldTriggerSF(event, SFSyst)); + } + + float ScaleFactorRetriever::oldTriggerSF(const top::Event& event, + const top::topSFSyst SFSyst) const { std::string electronID = m_config->electronID(); if (event.m_isLoose) { electronID = m_config->electronIDLoose(); @@ -79,43 +172,104 @@ namespace top { for (auto elPtr : event.m_electrons) { bool trigMatch = false; - for (const auto& trigger : m_electronTriggers) { + for (const auto& trigger : event.m_isLoose ? m_electronTriggers_Loose : m_electronTriggers_Tight) { std::string trig = "TRIGMATCH_" + trigger; if (elPtr->isAvailable<char>(trig)) { - if (elPtr->auxdataConst<char>(trig) == 1) - trigMatch = true; + if (elPtr->auxdataConst<char>(trig) == 1) trigMatch = true; } } - if (trigMatch) - triggerSFvec.push_back(electronSF_Trigger(*elPtr , electronID , SFSyst)); + if (trigMatch) triggerSFvec.push_back(electronSF_Trigger(*elPtr, electronID, SFSyst, event.m_isLoose)); } // Loop over muons for (auto muPtr : event.m_muons) { bool trigMatch = false; - for (const auto& trigger : m_muonTriggers) { + for (const auto& trigger : event.m_isLoose ? m_muonTriggers_Loose : m_muonTriggers_Tight) { std::string trig = "TRIGMATCH_" + trigger; if (muPtr->isAvailable<char>(trig)) { - if (muPtr->auxdataConst<char>(trig) == 1) - trigMatch = true; + if (muPtr->auxdataConst<char>(trig) == 1) trigMatch = true; } } - if (trigMatch) - triggerSFvec.push_back(muonSF_Trigger(*muPtr , muonID , SFSyst)); + if (trigMatch) triggerSFvec.push_back(muonSF_Trigger(*muPtr, muonID, SFSyst, event.m_isLoose)); } // for the cutflow histograms, in case the lepton triggers have not been checked yet - if (triggerSFvec.empty()) - return 1.0; + if (triggerSFvec.empty()) return 1.0; float trigSF = 1.0; for (float SF : triggerSFvec) trigSF *= (1.0 - SF); - return 1.0-trigSF; + return 1.0 - trigSF; + } + + std::vector<float> ScaleFactorRetriever::electronSFSystVariationVector(const top::Event& event, + const top::topSFComp SFComp, int var) const { + std::vector<float> sf; + if (abs(var) != 1) { + ATH_MSG_ERROR("ScaleFactorRetriever::electronSFSystVariationVector must be called with var=+1 (up) or -1 (down)"); + return sf; + } + if (SFComp != top::topSFComp::RECO && SFComp != top::topSFComp::ID && SFComp != top::topSFComp::ISOLATION) { + ATH_MSG_ERROR( + "ScaleFactorRetriever::electronSFSystVariationVector is currently implemented only for SFComp=RECO, ID, ISOLATION"); + return sf; + } + + std::string decorationName = "EL_SF_"; + if(event.m_isLoose && !m_config->applyTightSFsInLooseTree() && SFComp != top::topSFComp::RECO) decorationName = "EL_LOOSE_SF_"; + std::string electronID = ""; + std::string electronIso = ""; + + if (SFComp == top::topSFComp::RECO) decorationName += "Reco_"; + if (SFComp == top::topSFComp::ID) { + decorationName += "ID_"; + electronID = m_config->electronID(); + if (event.m_isLoose && !m_config->applyTightSFsInLooseTree()) { + electronID = m_config->electronIDLoose(); + } + decorationName += electronID; + decorationName += "_"; + } + if (SFComp == top::topSFComp::ISOLATION) { + decorationName += "Iso_"; + electronIso = m_config->electronIsolationSF(); + if (event.m_isLoose && !m_config->applyTightSFsInLooseTree()) { + electronIso = m_config->electronIsolationSFLoose(); + } + decorationName += electronIso; + decorationName += "_"; + } + + if (var == 1) decorationName += "CorrModel_UP"; + else decorationName += "CorrModel_DOWN"; + + for (auto elPtr : event.m_electrons) { + std::vector<float> sf_aux; + if (elPtr->isAvailable<std::vector<float> >(decorationName)) { + sf_aux = elPtr->auxdataConst<std::vector<float> >(decorationName); + } else { + ATH_MSG_ERROR( + "ScaleFactorRetriever::electronSFSystVariationVector error in accessing decoration " << decorationName); + } + + if (sf.size() == 0) sf = std::vector<float>(sf_aux.size(), leptonSF(event, top::topSFSyst::nominal)); + if (sf.size() != sf_aux.size()) ATH_MSG_ERROR( + "ScaleFactorRetriever::electronSFSystVariationVector error in size of vector of electron SFs"); + double oldSF = 1.; + if (SFComp == top::topSFComp::RECO) oldSF = electronSF_Reco(*elPtr, top::topSFSyst::nominal,event.m_isLoose); + if (SFComp == top::topSFComp::ID) oldSF = electronSF_ID(*elPtr, electronID, top::topSFSyst::nominal,event.m_isLoose); + if (SFComp == top::topSFComp::ISOLATION) oldSF = electronSF_Isol(*elPtr, electronIso, top::topSFSyst::nominal,event.m_isLoose); + + for (unsigned int i = 0; i < sf.size(); i++) { + sf[i] *= (sf_aux[i] / oldSF); + } + }//end of loop on electrons + + return sf; } // Obtain the electron SF @@ -128,12 +282,11 @@ namespace top { if (event.m_isLoose && !m_config->applyTightSFsInLooseTree()) { electronID = m_config->electronIDLoose(); } - std::string electronIso = m_config->electronIsolation(); + std::string electronIso = m_config->electronIsolationSF(); if (event.m_isLoose && !m_config->applyTightSFsInLooseTree()) { - electronIso = m_config->electronIsolationLoose(); + electronIso = m_config->electronIsolationSFLoose(); } - float trigger(1.); float reco(1.); float id(1.); float isol(1.); @@ -142,74 +295,99 @@ namespace top { // Loop over electrons for (auto elPtr : event.m_electrons) { - if (event.m_isLoose && m_config->applyTightSFsInLooseTree() && !elPtr->auxdataConst<char>("passPreORSelection")) - continue;// in case one want the tight SFs in the loose tree, need to only take the tight leptons - - // trigger *= electronSF_Trigger(*elPtr , electronID , SFSyst); - reco *= electronSF_Reco(*elPtr , SFSyst); - id *= electronSF_ID(*elPtr , electronID , SFSyst); - isol *= electronSF_Isol(*elPtr , electronIso , SFSyst); - chargeid *= electronSF_ChargeID(*elPtr, electronID , electronIso, SFSyst); - chargemisid *= electronSF_ChargeMisID(*elPtr, electronID , electronIso, SFSyst); - - } - - sf = trigger*reco*id*isol; // *chargeid*chargemisid; // let the charge id scale factors out until further tested by users - - // if (SFComp == top::topSFComp::TRIGGER) - // return trigger; - if (SFComp == top::topSFComp::RECO) - return reco; - else if (SFComp == top::topSFComp::ID) - return id; - else if (SFComp == top::topSFComp::ISOLATION) - return isol; - else if (SFComp == top::topSFComp::CHARGEID) - return chargeid; - else if (SFComp == top::topSFComp::CHARGEMISID) - return chargemisid; - else if (SFComp == top::topSFComp::ALL) - return sf; + if (event.m_isLoose && m_config->applyTightSFsInLooseTree() && + !elPtr->auxdataConst<char>("passPreORSelection")) continue; // in case one want the tight SFs in the loose + // tree, need to only take the tight leptons + + reco *= electronSF_Reco(*elPtr, SFSyst,event.m_isLoose); + id *= electronSF_ID(*elPtr, electronID, SFSyst,event.m_isLoose); + isol *= electronSF_Isol(*elPtr, electronIso, SFSyst,event.m_isLoose); + chargeid *= electronSF_ChargeID(*elPtr, electronID, electronIso, SFSyst,event.m_isLoose); + chargemisid *= electronSF_ChargeMisID(*elPtr, electronID, electronIso, SFSyst,event.m_isLoose); + } + + sf = reco * id * isol; // *chargeid*chargemisid; // let the charge id scale factors out until further tested by + // users + + if (SFComp == top::topSFComp::RECO) return reco; + else if (SFComp == top::topSFComp::ID) return id; + else if (SFComp == top::topSFComp::ISOLATION) return isol; + else if (SFComp == top::topSFComp::CHARGEID) return chargeid; + else if (SFComp == top::topSFComp::CHARGEMISID) return chargemisid; + else if (SFComp == top::topSFComp::ALL) return sf; return sf; } +// Obtain the electron SF + float ScaleFactorRetriever::fwdElectronSF(const top::Event& event, + const top::topSFSyst SFSyst, + const top::topSFComp SFComp) const { + float sf(1.); + std::string fwdElectronID = m_config->fwdElectronID(); + if (event.m_isLoose) { + fwdElectronID = m_config->fwdElectronIDLoose(); + } - float ScaleFactorRetriever::electronSF_Trigger(const xAOD::Electron& x, - const top::topSFSyst SFSyst, - bool isLoose) const { - - return electronSF_Trigger(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), SFSyst); + float reco(1.); + float id(1.); + float isol(1.); + float chargeid(1.); + float chargemisid(1.); + // Loop over electrons + for (auto elPtr : event.m_fwdElectrons) { + //currently on ID SFs are supported for fwd electrons + id *= fwdElectronSF_ID(*elPtr, fwdElectronID, SFSyst, event.m_isLoose); } - float ScaleFactorRetriever::electronEff_Trigger(const xAOD::Electron& x, - const top::topSFSyst SFSyst, - bool isLoose) const { + sf = reco * id * isol; - return electronEff_Trigger(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), SFSyst); + if (SFComp == top::topSFComp::RECO) return reco; + else if (SFComp == top::topSFComp::ID) return id; + else if (SFComp == top::topSFComp::ISOLATION) return isol; + else if (SFComp == top::topSFComp::CHARGEID) return chargeid; + else if (SFComp == top::topSFComp::CHARGEMISID) return chargemisid; + else if (SFComp == top::topSFComp::ALL) return sf; + return sf; } + float ScaleFactorRetriever::electronSF_Trigger(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const { + return electronSF_Trigger(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), SFSyst, isLoose); + } + + float ScaleFactorRetriever::electronEff_Trigger(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const { + return electronEff_Trigger(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), SFSyst, isLoose); + } float ScaleFactorRetriever::electronSF_Trigger(const xAOD::Electron& x, const std::string& id, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("EL_SF_Trigger_"+id)) { - sf = x.auxdataConst<float>("EL_SF_Trigger_"+id); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id)) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id); } if (SFSyst == top::topSFSyst::EL_SF_Trigger_UP) { - if (x.isAvailable<float>("EL_SF_Trigger_"+id+"_UP")) { - sf = x.auxdataConst<float>("EL_SF_Trigger_"+id+"_UP"); + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id + "_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id + "_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_Trigger_DOWN) { - if (x.isAvailable<float>("EL_SF_Trigger_"+id+"_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_Trigger_"+id+"_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id + "_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id + "_DOWN"); } } @@ -217,114 +395,158 @@ namespace top { } float ScaleFactorRetriever::electronEff_Trigger(const xAOD::Electron& x, - const std::string& id, - const top::topSFSyst SFSyst) const { + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const { float eff(1.); - if (x.isAvailable<float>("EL_EFF_Trigger_"+id)) { - eff = x.auxdataConst<float>("EL_EFF_Trigger_"+id); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id)) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id); } if (SFSyst == top::topSFSyst::EL_SF_Trigger_UP) { - if (x.isAvailable<float>("EL_EFF_Trigger_"+id+"_UP")) { - eff = x.auxdataConst<float>("EL_EFF_Trigger_"+id+"_UP"); + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id + "_UP")) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id + "_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_Trigger_DOWN) { - if (x.isAvailable<float>("EL_EFF_Trigger_"+id+"_DOWN")) { - eff = x.auxdataConst<float>("EL_EFF_Trigger_"+id+"_DOWN"); + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id + "_DOWN")) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id + "_DOWN"); } } return eff; } - float ScaleFactorRetriever::electronSF_Reco(const xAOD::Electron& x, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("EL_SF_Reco")) { - sf = x.auxdataConst<float>("EL_SF_Reco"); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_Reco")) { + sf = x.auxdataConst<float>(prefix+"_SF_Reco"); } if (SFSyst == top::topSFSyst::EL_SF_Reco_UP) { - if (x.isAvailable<float>("EL_SF_Reco_UP")) { - sf = x.auxdataConst<float>("EL_SF_Reco_UP"); + if (x.isAvailable<float>(prefix+"_SF_Reco_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Reco_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_Reco_DOWN) { - if (x.isAvailable<float>("EL_SF_Reco_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_Reco_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Reco_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Reco_DOWN"); } } return sf; } - float ScaleFactorRetriever::electronSF_ID(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const { - - return electronSF_ID(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), SFSyst); - + return electronSF_ID(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), SFSyst, isLoose); } + float ScaleFactorRetriever::fwdElectronSF_ID(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const { + return fwdElectronSF_ID(x, (isLoose ? m_config->fwdElectronIDLoose() : m_config->fwdElectronID()), SFSyst, isLoose); + } float ScaleFactorRetriever::electronSF_ID(const xAOD::Electron& x, const std::string& id, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("EL_SF_ID_"+id)) { - sf = x.auxdataConst<float>("EL_SF_ID_"+id); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_ID_" + id)) { + sf = x.auxdataConst<float>(prefix+"_SF_ID_" + id); } if (SFSyst == top::topSFSyst::EL_SF_ID_UP) { - if (x.isAvailable<float>("EL_SF_ID_"+id+"_UP")) { - sf = x.auxdataConst<float>("EL_SF_ID_"+id+"_UP"); + if (x.isAvailable<float>(prefix+"_SF_ID_" + id + "_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_ID_" + id + "_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_ID_DOWN) { - if (x.isAvailable<float>("EL_SF_ID_"+id+"_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_ID_"+id+"_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_ID_" + id + "_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_ID_" + id + "_DOWN"); } } return sf; } + float ScaleFactorRetriever::fwdElectronSF_ID(const xAOD::Electron& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const { + float sf(1.); + + std::string prefix="FWDEL"; + if(isLoose) prefix+="_LOOSE"; - float ScaleFactorRetriever::electronSF_Isol(const xAOD::Electron& x, - const top::topSFSyst SFSyst, - bool isLoose) const { + if (x.isAvailable<float>(prefix+"_SF_ID_" + id)) { + sf = x.auxdataConst<float>(prefix+"_SF_ID_" + id); + } - return electronSF_Isol(x, (isLoose ? m_config->electronIsolationLoose() : m_config->electronIsolation()), SFSyst); + if (SFSyst == top::topSFSyst::FWDEL_SF_ID_UP) { + if (x.isAvailable<float>(prefix+"_SF_ID_" + id + "_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_ID_" + id + "_UP"); + } + } + if (SFSyst == top::topSFSyst::FWDEL_SF_ID_DOWN) { + if (x.isAvailable<float>(prefix+"_SF_ID_" + id + "_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_ID_" + id + "_DOWN"); + } } + return sf; + } + + float ScaleFactorRetriever::electronSF_Isol(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const { + return electronSF_Isol(x, (isLoose ? m_config->electronIsolationSFLoose() : m_config->electronIsolationSF()), + SFSyst, isLoose); + } + float ScaleFactorRetriever::electronSF_Isol(const xAOD::Electron& x, const std::string& iso, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("EL_SF_Iso_"+iso)) { - sf = x.auxdataConst<float>("EL_SF_Iso_"+iso); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_Iso_" + iso)) { + sf = x.auxdataConst<float>(prefix+"_SF_Iso_" + iso); } if (SFSyst == top::topSFSyst::EL_SF_Isol_UP) { - - if (x.isAvailable<float>("EL_SF_Iso_"+iso+"_UP")) { - - sf = x.auxdataConst<float>("EL_SF_Iso_"+iso+"_UP"); - + if (x.isAvailable<float>(prefix+"_SF_Iso_" + iso + "_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Iso_" + iso + "_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_Isol_DOWN) { - if (x.isAvailable<float>("EL_SF_Iso_"+iso+"_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_Iso_"+iso+"_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Iso_" + iso + "_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Iso_" + iso + "_DOWN"); } } @@ -334,29 +556,32 @@ namespace top { float ScaleFactorRetriever::electronSF_ChargeID(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const { - return electronSF_ChargeID(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), - (isLoose ? m_config->electronIsolationLoose() : m_config->electronIsolation()), SFSyst); - + (isLoose ? m_config->electronIsolationLoose() : m_config->electronIsolation()), SFSyst, isLoose); } float ScaleFactorRetriever::electronSF_ChargeID(const xAOD::Electron& x, const std::string& id, const std::string& iso, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("EL_SF_ChargeID_"+id+"_"+iso)) { - sf = x.auxdataConst<float>("EL_SF_ChargeID_"+id+"_"+iso); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_ChargeID_" + id + "_" + iso)) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeID_" + id + "_" + iso); } if (SFSyst == top::topSFSyst::EL_SF_ChargeID_UP) { - if (x.isAvailable<float>("EL_SF_ChargeID_"+id+"_"+iso+"_UP")) { - sf = x.auxdataConst<float>("EL_SF_ChargeID_"+id+"_"+iso+"_UP"); + if (x.isAvailable<float>(prefix+"_SF_ChargeID_" + id + "_" + iso + "_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeID_" + id + "_" + iso + "_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_ChargeID_DOWN) { - if (x.isAvailable<float>("EL_SF_ChargeID_"+id+"_"+iso+"_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_ChargeID_"+id+"_"+iso+"_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_ChargeID_" + id + "_" + iso + "_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeID_" + id + "_" + iso + "_DOWN"); } } return sf; @@ -365,41 +590,45 @@ namespace top { float ScaleFactorRetriever::electronSF_ChargeMisID(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const { - return electronSF_ChargeMisID(x, (isLoose ? m_config->electronIDLoose() : m_config->electronID()), - (isLoose ? m_config->electronIsolationLoose() : m_config->electronIsolation()), SFSyst); - + (isLoose ? m_config->electronIsolationLoose() : m_config->electronIsolation()), + SFSyst, isLoose); } float ScaleFactorRetriever::electronSF_ChargeMisID(const xAOD::Electron& x, const std::string& id, const std::string& iso, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("EL_SF_ChargeMisID_"+id+"_"+iso)) { - sf = x.auxdataConst<float>("EL_SF_ChargeMisID_"+id+"_"+iso); + + std::string prefix="EL"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso)) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso); } if (SFSyst == top::topSFSyst::EL_SF_ChargeMisID_STAT_UP) { - if (x.isAvailable<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_STAT_UP")) { - sf = x.auxdataConst<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_STAT_UP"); + if (x.isAvailable<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_STAT_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_STAT_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_ChargeMisID_STAT_DOWN) { - if (x.isAvailable<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_STAT_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_STAT_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_STAT_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_STAT_DOWN"); } } if (SFSyst == top::topSFSyst::EL_SF_ChargeMisID_SYST_UP) { - if (x.isAvailable<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_SYST_UP")) { - sf = x.auxdataConst<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_SYST_UP"); + if (x.isAvailable<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_SYST_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_SYST_UP"); } } if (SFSyst == top::topSFSyst::EL_SF_ChargeMisID_SYST_DOWN) { - if (x.isAvailable<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_SYST_DOWN")) { - sf = x.auxdataConst<float>("EL_SF_ChargeMisID_"+id+"_"+iso+"_SYST_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_SYST_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_ChargeMisID_" + id + "_" + iso + "_SYST_DOWN"); } } @@ -413,14 +642,13 @@ namespace top { float sf(1.); std::string muonID = m_config->muonQuality(); - std::string muonIso = m_config->muonIsolation(); + std::string muonIso = m_config->muonIsolationSF(); if (event.m_isLoose && !m_config->applyTightSFsInLooseTree()) { muonID = m_config->muonQualityLoose(); - muonIso = m_config->muonIsolationLoose(); + muonIso = m_config->muonIsolationSFLoose(); } - float trigger(1.); float reco(1.); float id(1.); float isol(1.); @@ -428,72 +656,68 @@ namespace top { // Loop over muons for (auto muPtr : event.m_muons) { - if (event.m_isLoose && m_config->applyTightSFsInLooseTree() && !muPtr->auxdataConst<char>("passPreORSelection")) - continue;// in case one want the tight SFs in the loose tree, need to only take the tight leptons - - id *= muonSF_ID(*muPtr , muonID , SFSyst); - isol *= muonSF_Isol(*muPtr , muonIso , SFSyst); + if (event.m_isLoose && m_config->applyTightSFsInLooseTree() && + !muPtr->auxdataConst<char>("passPreORSelection")) continue; // in case one want the tight SFs in the loose + // tree, need to only take the tight leptons - if(m_config -> applyTTVACut()) // if not using TTVA cut, leave SF set to 1.0 - TTVA *= muonSF_TTVA(*muPtr , SFSyst); + id *= muonSF_ID(*muPtr, muonID, SFSyst, event.m_isLoose); + isol *= muonSF_Isol(*muPtr, muonIso, SFSyst, event.m_isLoose); + if (m_config->applyTTVACut()) // if not using TTVA cut, leave SF set to 1.0 + TTVA *= muonSF_TTVA(*muPtr, SFSyst); } - sf = trigger * id * isol * TTVA; + sf = id * isol * TTVA; - // if (SFComp == top::topSFComp::TRIGGER) - // return trigger; - if (SFComp == top::topSFComp::RECO) - return reco; - else if (SFComp == top::topSFComp::ID) - return id; - else if (SFComp == top::topSFComp::ISOLATION) - return isol; - else if (SFComp == top::topSFComp::TTVA) - return TTVA; - else if (SFComp == top::topSFComp::ALL) - return sf; + if (SFComp == top::topSFComp::RECO) return reco; + else if (SFComp == top::topSFComp::ID) return id; + else if (SFComp == top::topSFComp::ISOLATION) return isol; + else if (SFComp == top::topSFComp::TTVA) return TTVA; + else if (SFComp == top::topSFComp::ALL) return sf; return sf; - } float ScaleFactorRetriever::muonSF_Trigger(const xAOD::Muon& x, const top::topSFSyst SFSyst, bool isLoose) const { - return muonSF_Trigger(x, (isLoose ? m_config->muonQualityLoose() : m_config->muonQuality()), SFSyst); + return muonSF_Trigger(x, (isLoose ? m_config->muonQualityLoose() : m_config->muonQuality()), SFSyst, isLoose); } - float ScaleFactorRetriever::muonSF_Trigger(const xAOD::Muon& x, const std::string& id, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("MU_SF_Trigger_"+id)) { - sf = x.auxdataConst<float>("MU_SF_Trigger_"+id); + + std::string prefix="MU"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id)) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id); } if (SFSyst == top::topSFSyst::MU_SF_Trigger_STAT_UP) { - if (x.isAvailable<float>("MU_SF_Trigger_"+id+"_STAT_UP")) { - sf = x.auxdataConst<float>("MU_SF_Trigger_"+id+"_STAT_UP"); + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id + "_STAT_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id + "_STAT_UP"); } } if (SFSyst == top::topSFSyst::MU_SF_Trigger_STAT_DOWN) { - if (x.isAvailable<float>("MU_SF_Trigger_"+id+"_STAT_DOWN")) { - sf = x.auxdataConst<float>("MU_SF_Trigger_"+id+"_STAT_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id + "_STAT_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id + "_STAT_DOWN"); } } if (SFSyst == top::topSFSyst::MU_SF_Trigger_SYST_UP) { - if (x.isAvailable<float>("MU_SF_Trigger_"+id+"_SYST_UP")) { - sf = x.auxdataConst<float>("MU_SF_Trigger_"+id+"_SYST_UP"); + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id + "_SYST_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id + "_SYST_UP"); } } if (SFSyst == top::topSFSyst::MU_SF_Trigger_SYST_DOWN) { - if (x.isAvailable<float>("MU_SF_Trigger_"+id+"_SYST_DOWN")) { - sf = x.auxdataConst<float>("MU_SF_Trigger_"+id+"_SYST_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Trigger_" + id + "_SYST_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Trigger_" + id + "_SYST_DOWN"); } } @@ -502,44 +726,46 @@ namespace top { return sf; } - - float ScaleFactorRetriever::muonEff_Trigger(const xAOD::Muon& x, - const top::topSFSyst SFSyst, - bool isLoose) const { - return muonEff_Trigger(x, (isLoose ? m_config->muonQualityLoose() : m_config->muonQuality()), SFSyst); + const top::topSFSyst SFSyst, + bool isLoose) const { + return muonEff_Trigger(x, (isLoose ? m_config->muonQualityLoose() : m_config->muonQuality()), SFSyst, isLoose); } - float ScaleFactorRetriever::muonEff_Trigger(const xAOD::Muon& x, - const std::string& id, - const top::topSFSyst SFSyst) const { + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const { float eff(1.); - if (x.isAvailable<float>("MU_EFF_Trigger_"+id)) { - eff = x.auxdataConst<float>("MU_EFF_Trigger_"+id); + + std::string prefix="MU"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id)) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id); } if (SFSyst == top::topSFSyst::MU_SF_Trigger_STAT_UP) { - if (x.isAvailable<float>("MU_EFF_Trigger_"+id+"_STAT_UP")) { - eff = x.auxdataConst<float>("MU_EFF_Trigger_"+id+"_STAT_UP"); + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id + "_STAT_UP")) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id + "_STAT_UP"); } } if (SFSyst == top::topSFSyst::MU_SF_Trigger_STAT_DOWN) { - if (x.isAvailable<float>("MU_EFF_Trigger_"+id+"_STAT_DOWN")) { - eff = x.auxdataConst<float>("MU_EFF_Trigger_"+id+"_STAT_DOWN"); + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id + "_STAT_DOWN")) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id + "_STAT_DOWN"); } } if (SFSyst == top::topSFSyst::MU_SF_Trigger_SYST_UP) { - if (x.isAvailable<float>("MU_EFF_Trigger_"+id+"_SYST_UP")) { - eff = x.auxdataConst<float>("MU_EFF_Trigger_"+id+"_SYST_UP"); + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id + "_SYST_UP")) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id + "_SYST_UP"); } } if (SFSyst == top::topSFSyst::MU_SF_Trigger_SYST_DOWN) { - if (x.isAvailable<float>("MU_EFF_Trigger_"+id+"_SYST_DOWN")) { - eff = x.auxdataConst<float>("MU_EFF_Trigger_"+id+"_SYST_DOWN"); + if (x.isAvailable<float>(prefix+"_EFF_Trigger_" + id + "_SYST_DOWN")) { + eff = x.auxdataConst<float>(prefix+"_EFF_Trigger_" + id + "_SYST_DOWN"); } } @@ -548,43 +774,53 @@ namespace top { return eff; } - float ScaleFactorRetriever::muonSF_ID(const xAOD::Muon& x, - const top::topSFSyst SFSyst, - bool isLoose) const { - return muonSF_ID(x, (isLoose ? m_config->muonQualityLoose() : m_config->muonQuality()), SFSyst); + const top::topSFSyst SFSyst, + bool isLoose) const { + return muonSF_ID(x, (isLoose ? m_config->muonQualityLoose() : m_config->muonQuality()), SFSyst, isLoose); } float ScaleFactorRetriever::muonSF_ID(const xAOD::Muon& x, const std::string& id, - const top::topSFSyst SFSyst) const { + const top::topSFSyst SFSyst, + bool isLoose) const { + std::string decoration = "MU_SF_ID_"; + if(isLoose) decoration = "MU_LOOSE_SF_ID_"; + decoration+=id; - std::string decoration = "MU_SF_ID_"+id; switch (SFSyst) { case top::topSFSyst::MU_SF_ID_STAT_UP: decoration += "_STAT_UP"; break; + case top::topSFSyst::MU_SF_ID_STAT_DOWN: decoration += "_STAT_DOWN"; break; + case top::topSFSyst::MU_SF_ID_SYST_UP: decoration += "_SYST_UP"; break; + case top::topSFSyst::MU_SF_ID_SYST_DOWN: decoration += "_SYST_DOWN"; break; + case top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP: decoration += "_STAT_LOWPT_UP"; break; + case top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN: decoration += "_STAT_LOWPT_DOWN"; break; + case top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP: decoration += "_SYST_LOWPT_UP"; break; + case top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN: decoration += "_SYST_LOWPT_DOWN"; break; + default: // Do nothing, we have the decoration already break; @@ -599,51 +835,103 @@ namespace top { // This should never happen throw std::runtime_error("Something has gone wrong in mu ID SF retrieval"); } - + + float ScaleFactorRetriever::softmuonSF_ID(const xAOD::Muon& x, + const top::topSFSyst SFSyst) const { + return softmuonSF_ID(x, m_config->softmuonQuality(), SFSyst); + } + + float ScaleFactorRetriever::softmuonSF_ID(const xAOD::Muon& x, + const std::string& id, + const top::topSFSyst SFSyst) const { + std::string decoration = "SOFTMU_SF_ID_" + id; + switch (SFSyst) { + case top::topSFSyst::MU_SF_ID_STAT_UP: + decoration += "_STAT_UP"; + break; + + case top::topSFSyst::MU_SF_ID_STAT_DOWN: + decoration += "_STAT_DOWN"; + break; + + case top::topSFSyst::MU_SF_ID_SYST_UP: + decoration += "_SYST_UP"; + break; + + case top::topSFSyst::MU_SF_ID_SYST_DOWN: + decoration += "_SYST_DOWN"; + break; + + case top::topSFSyst::MU_SF_ID_STAT_LOWPT_UP: + decoration += "_STAT_LOWPT_UP"; + break; + + case top::topSFSyst::MU_SF_ID_STAT_LOWPT_DOWN: + decoration += "_STAT_LOWPT_DOWN"; + break; + + case top::topSFSyst::MU_SF_ID_SYST_LOWPT_UP: + decoration += "_SYST_LOWPT_UP"; + break; + + case top::topSFSyst::MU_SF_ID_SYST_LOWPT_DOWN: + decoration += "_SYST_LOWPT_DOWN"; + break; + + default: + // Do nothing, we have the decoration already + break; + } + + return x.auxdataConst<float>(decoration); + + // This should never happen + throw std::runtime_error("Something has gone wrong in mu ID SF retrieval"); + } + float ScaleFactorRetriever::muonSF_Isol(const xAOD::Muon& x, const top::topSFSyst SFSyst, bool isLoose) const { - - return muonSF_Isol(x, (isLoose ? m_config->muonIsolationLoose() : m_config->muonIsolation()), SFSyst); + return muonSF_Isol(x, (isLoose ? m_config->muonIsolationSFLoose() : m_config->muonIsolationSF()), SFSyst, isLoose); } - float ScaleFactorRetriever::muonSF_Isol(const xAOD::Muon& x, const std::string& iso, - const top::topSFSyst SFSyst) const { - + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("MU_SF_Isol_"+iso)) { - sf = x.auxdataConst<float>("MU_SF_Isol_"+iso); + + std::string prefix="MU"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_Isol_" + iso)) { + sf = x.auxdataConst<float>(prefix+"_SF_Isol_" + iso); } if (SFSyst == top::topSFSyst::MU_SF_Isol_SYST_UP) { - - if (x.isAvailable<float>("MU_SF_Isol_"+iso+"_SYST_UP")) { - sf = x.auxdataConst<float>("MU_SF_Isol_"+iso+"_SYST_UP"); + if (x.isAvailable<float>(prefix+"_SF_Isol_" + iso + "_SYST_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Isol_" + iso + "_SYST_UP"); } - } if (SFSyst == top::topSFSyst::MU_SF_Isol_SYST_DOWN) { - if (x.isAvailable<float>("MU_SF_Isol_"+iso+"_SYST_DOWN")) { - sf = x.auxdataConst<float>("MU_SF_Isol_"+iso+"_SYST_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Isol_" + iso + "_SYST_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Isol_" + iso + "_SYST_DOWN"); } } if (SFSyst == top::topSFSyst::MU_SF_Isol_STAT_UP) { - if (x.isAvailable<float>("MU_SF_Isol_"+iso+"_STAT_UP")) { - sf = x.auxdataConst<float>("MU_SF_Isol_"+iso+"_STAT_UP"); + if (x.isAvailable<float>(prefix+"_SF_Isol_" + iso + "_STAT_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Isol_" + iso + "_STAT_UP"); } } if (SFSyst == top::topSFSyst::MU_SF_Isol_STAT_DOWN) { - if (x.isAvailable<float>("MU_SF_Isol_"+iso+"_STAT_DOWN")) { - sf = x.auxdataConst<float>("MU_SF_Isol_"+iso+"_STAT_DOWN"); + if (x.isAvailable<float>(prefix+"_SF_Isol_" + iso + "_STAT_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Isol_" + iso + "_STAT_DOWN"); } } - return sf; } @@ -657,41 +945,46 @@ namespace top { **/ float ScaleFactorRetriever::muonSF_TTVA(const xAOD::Muon& x, const top::topSFSyst SFSyst) const { - // Nominal decoration: if not a TTVA // systematic then return the nominal std::string decoration = "MU_SF_TTVA"; + switch (SFSyst) { case top::topSFSyst::MU_SF_TTVA_STAT_UP: decoration += "_STAT_UP"; break; + case top::topSFSyst::MU_SF_TTVA_STAT_DOWN: decoration += "_STAT_DOWN"; break; + case top::topSFSyst::MU_SF_TTVA_SYST_UP: decoration += "_SYST_UP"; break; + case top::topSFSyst::MU_SF_TTVA_SYST_DOWN: decoration += "_SYST_DOWN"; break; + default: // Do nothing, we have the decoration already break; } if (!(x.isAvailable<float>(decoration))) { - std::cout << "Muon is not decorated with requested " - << "TTVA SF. 1.0 will be returned." << std::endl; + ATH_MSG_INFO("Muon is not decorated with requested TTVA SF. 1.0 will be returned."); return 1.0; } return x.auxdataConst<float>(decoration); + ; } float ScaleFactorRetriever::tauSF(const top::Event& event, const top::topSFSyst SFSyst) const { float sf(1.0); + for (auto tau : event.m_tauJets) sf *= tauSF(*tau, SFSyst, event.m_isLoose); return sf; @@ -701,97 +994,74 @@ namespace top { const top::topSFSyst SFSyst, bool isLoose) const { // See TauScaleFactorCalculator.cxx for uncertainties - static SG::AuxElement::ConstAccessor<float> acc_tauSF("tauSF"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_eleolr_total_up("tauSF_eleolr_total_up"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_eleolr_total_down("tauSF_eleolr_total_down"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_jetid_total_up("tauSF_jetid_total_up"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_jetid_total_down("tauSF_jetid_total_down"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_reco_total_up("tauSF_reco_total_up"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_reco_total_down("tauSF_reco_total_down"); - - static SG::AuxElement::ConstAccessor<float> acc_tauSF_loose("tauSF_loose"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_eleolr_total_up_loose("tauSF_eleolr_total_up_loose"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_eleolr_total_down_loose("tauSF_eleolr_total_down_loose"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_jetid_total_up_loose("tauSF_jetid_total_up_loose"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_jetid_total_down_loose("tauSF_jetid_total_down_loose"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_reco_total_up_loose("tauSF_reco_total_up_loose"); - static SG::AuxElement::ConstAccessor<float> acc_tauSF_reco_total_down_loose("tauSF_reco_total_down_loose"); + + static std::map<TString, const SG::AuxElement::ConstAccessor<float> > acc_tauSFs; + static std::map<TString, const SG::AuxElement::ConstAccessor<float> > acc_tauSFs_loose; if (!isLoose) { - switch (SFSyst) { - case top::topSFSyst::TAU_SF_ELEOLR_TOTAL_UP : - return acc_tauSF_eleolr_total_up(x); - case top::topSFSyst::TAU_SF_ELEOLR_TOTAL_DOWN : - return acc_tauSF_eleolr_total_down(x); - case top::topSFSyst::TAU_SF_JETID_TOTAL_UP : - return acc_tauSF_jetid_total_up(x); - case top::topSFSyst::TAU_SF_JETID_TOTAL_DOWN : - return acc_tauSF_jetid_total_down(x); - case top::topSFSyst::TAU_SF_RECO_TOTAL_UP : - return acc_tauSF_reco_total_up(x); - case top::topSFSyst::TAU_SF_RECO_TOTAL_DOWN : - return acc_tauSF_reco_total_down(x); - default : - // If not a tau systematic then return nominal SF - return acc_tauSF(x); - break; + if (tauSF_name.find(SFSyst) == tauSF_name.end()) { + if (acc_tauSFs.find(tauSF_name.at(top::topSFSyst::TAU_SF_NOMINAL)) == acc_tauSFs.end()) { + acc_tauSFs.insert(std::pair<TString, + const SG::AuxElement::ConstAccessor<float> > (tauSF_name.at(top::topSFSyst:: + TAU_SF_NOMINAL), + tauSF_name.at(top::topSFSyst:: + TAU_SF_NOMINAL).Data())); + } + return acc_tauSFs.at(tauSF_name.at(top::topSFSyst::TAU_SF_NOMINAL))(x); } + if (acc_tauSFs.find(tauSF_name.at(SFSyst)) == acc_tauSFs.end()) { + acc_tauSFs.insert(std::pair<TString, const SG::AuxElement::ConstAccessor<float> > (tauSF_name.at(SFSyst), + tauSF_name.at(SFSyst).Data())); + } + return acc_tauSFs.at(tauSF_name.at(SFSyst))(x); } else { - switch (SFSyst) { - case top::topSFSyst::TAU_SF_ELEOLR_TOTAL_UP : - return acc_tauSF_eleolr_total_up_loose(x); - case top::topSFSyst::TAU_SF_ELEOLR_TOTAL_DOWN : - return acc_tauSF_eleolr_total_down_loose(x); - case top::topSFSyst::TAU_SF_JETID_TOTAL_UP : - return acc_tauSF_jetid_total_up_loose(x); - case top::topSFSyst::TAU_SF_JETID_TOTAL_DOWN : - return acc_tauSF_jetid_total_down_loose(x); - case top::topSFSyst::TAU_SF_RECO_TOTAL_UP : - return acc_tauSF_reco_total_up_loose(x); - case top::topSFSyst::TAU_SF_RECO_TOTAL_DOWN : - return acc_tauSF_reco_total_down_loose(x); - default : - // If not a tau systematic then return nominal SF - return acc_tauSF_loose(x); - break; + if (tauSF_name.find(SFSyst) == tauSF_name.end()) { + if (acc_tauSFs_loose.find(tauSF_name.at(top::topSFSyst::TAU_SF_NOMINAL)) == acc_tauSFs_loose.end()) { + acc_tauSFs_loose.insert(std::pair<TString, + const SG::AuxElement::ConstAccessor<float> > (tauSF_name.at(top::topSFSyst:: + TAU_SF_NOMINAL) + + "_loose", + tauSF_name.at(top::topSFSyst:: + TAU_SF_NOMINAL).Data())); } + return acc_tauSFs_loose.at(tauSF_name.at(top::topSFSyst::TAU_SF_NOMINAL) + "_loose")(x); + } + if (acc_tauSFs_loose.find((tauSF_name.at(SFSyst) + "_loose")) == acc_tauSFs_loose.end()) { + acc_tauSFs_loose.insert(std::pair<TString, + const SG::AuxElement::ConstAccessor<float> > (tauSF_name.at(SFSyst) + "_loose", + (tauSF_name.at(SFSyst) + + "_loose").Data())); } + return acc_tauSFs_loose.at((tauSF_name.at(SFSyst) + "_loose"))(x); } + } float ScaleFactorRetriever::photonSF_Isol(const xAOD::Photon& x, - const top::topSFSyst SFSyst, - bool isLoose) const { - - return photonSF_Isol(x, (isLoose ? m_config->photonIsolationLoose() : m_config->photonIsolation()), SFSyst); - + const top::topSFSyst SFSyst, + bool isLoose) const { + return photonSF_Isol(x, (isLoose ? m_config->photonIsolationLoose() : m_config->photonIsolation()), SFSyst, isLoose); } float ScaleFactorRetriever::photonSF_Isol(const xAOD::Photon& x, - const std::string& iso, - const top::topSFSyst SFSyst) const { - + const std::string& iso, + const top::topSFSyst SFSyst, + bool isLoose) const { float sf(1.); - if (x.isAvailable<float>("PH_SF_Iso_" + iso)) { - sf = x.auxdataConst<float>("PH_SF_Iso_"+iso); - } - if (SFSyst == top::topSFSyst::PHOTON_EFF_LOWPTISO_UP) { - if (x.isAvailable<float>("PH_SF_Iso_"+iso+"_LOWPT_UP")) { - sf = x.auxdataConst<float>("PH_SF_Iso_"+iso+"_LOWPT_UP"); - } - } - if (SFSyst == top::topSFSyst::PHOTON_EFF_LOWPTISO_DOWN) { - if (x.isAvailable<float>("PH_SF_Iso_"+iso+"_LOWPT_DOWN")) { - sf = x.auxdataConst<float>("PH_SF_Iso_"+iso+"_LOWPT_DOWN"); - } + + std::string prefix="PH"; + if(isLoose) prefix+="_LOOSE"; + + if (x.isAvailable<float>(prefix+"_SF_Iso_" + iso)) { + sf = x.auxdataConst<float>(prefix+"_SF_Iso_" + iso); } - if (SFSyst == top::topSFSyst::PHOTON_EFF_LOWPTISO_UP) { - if (x.isAvailable<float>("PH_SF_Iso_"+iso+"_TRK_UP")) { - sf = x.auxdataConst<float>("PH_SF_Iso_"+iso+"_TRK_UP"); + if (SFSyst == top::topSFSyst::PHOTON_EFF_ISO_UP) { + if (x.isAvailable<float>(prefix+"_SF_Iso_" + iso + "_UP")) { + sf = x.auxdataConst<float>(prefix+"_SF_Iso_" + iso + "_UP"); } } - if (SFSyst == top::topSFSyst::PHOTON_EFF_LOWPTISO_DOWN) { - if (x.isAvailable<float>("PH_SF_Iso_"+iso+"_TRK_DOWN")) { - sf = x.auxdataConst<float>("PH_SF_Iso_"+iso+"_TRK_DOWN"); + if (SFSyst == top::topSFSyst::PHOTON_EFF_ISO_DOWN) { + if (x.isAvailable<float>(prefix+"_SF_Iso_" + iso + "_DOWN")) { + sf = x.auxdataConst<float>(prefix+"_SF_Iso_" + iso + "_DOWN"); } } return sf; @@ -799,68 +1069,90 @@ namespace top { float ScaleFactorRetriever::photonSF(const top::Event& event, const top::topSFSyst SFSyst) const { - float sf(1.0); - for (auto photon : event.m_photons) - sf *= photonSF(*photon, SFSyst, event.m_isLoose); + float sf(1.); + float reco(1.); + float isol(1.); + + for (auto photon : event.m_photons) { + reco *= photonSF_Reco(*photon, SFSyst); + isol *= photonSF_Isol(*photon, SFSyst, event.m_isLoose); + } + + sf = reco * isol; + return sf; } - float ScaleFactorRetriever::photonSF(const xAOD::Photon& photon, - const top::topSFSyst SFSyst, - bool isLoose) const { - - static SG::AuxElement::ConstAccessor<float> acc_ph_IDSF("EFF_ID_SF"); - static SG::AuxElement::ConstAccessor<float> acc_ph_IDSFUp("EFF_ID_SF_UP"); - static SG::AuxElement::ConstAccessor<float> acc_ph_IDSFDown("EFF_ID_SF_DOWN"); + float ScaleFactorRetriever::photonSF_Reco(const xAOD::Photon& photon, + const top::topSFSyst SFSyst) const { + static const SG::AuxElement::ConstAccessor<float> acc_ph_IDSF("EFF_ID_SF"); + static const SG::AuxElement::ConstAccessor<float> acc_ph_IDSFUp("EFF_ID_SF_UP"); + static const SG::AuxElement::ConstAccessor<float> acc_ph_IDSFDown("EFF_ID_SF_DOWN"); switch (SFSyst) { case top::topSFSyst::nominal: return acc_ph_IDSF(photon); + case top::topSFSyst::PHOTON_IDSF_UP: return acc_ph_IDSFUp(photon); + case top::topSFSyst::PHOTON_IDSF_DOWN: return acc_ph_IDSFDown(photon); + default: - return photonSF_Isol(photon, SFSyst, isLoose); + return acc_ph_IDSF(photon); } } - + /** - * @brief nominal SF or named systematics - */ + * @brief nominal SF or named systematics + */ float ScaleFactorRetriever::btagSF(const top::Event& event, const top::topSFSyst SFSyst, std::string WP, bool do_trackjets, std::string uncert_name) const { float sf(1.); - std::string decoration = "btag_SF_"+WP+"_nom"; + std::string decoration = "btag_SF_" + WP + "_nom"; + std::string systematicName, bTagSystName; switch (SFSyst) { - case top::topSFSyst::nominal : - break; // is btag_SF_nom by default - case top::topSFSyst::BTAG_SF_NAMED_UP : - if (uncert_name=="") { - std::cout << "Named b-tagging systematics should have a name. Please provide one." << std::endl; + case top::topSFSyst::nominal: + // If this is the nominal tree, we proceed as normal + // If not nominal tree, we need to know which systematic this event corresponds to, + // in case the systematic is removed from EV decomposition (will enter as a nominal retrieval) + systematicName = m_config->systematicName(event.m_hashValue); + bTagSystName = top::bTagNamedSystCheck(m_config, systematicName, WP, do_trackjets, false); + if (bTagSystName != "") decoration = "btag_SF_" + WP + "_" + bTagSystName; // Only change decoration if found, + // otherwise we will use the nominal + break; + + case top::topSFSyst::BTAG_SF_NAMED_UP: + if (uncert_name == "") { + ATH_MSG_INFO("Named b-tagging systematics should have a name. Please provide one."); return 0; } - decoration = "btag_SF_"+WP+"_"+uncert_name+"__1up"; + decoration = "btag_SF_" + WP + "_" + uncert_name + "__1up"; break; - case top::topSFSyst::BTAG_SF_NAMED_DOWN : - if (uncert_name=="") { - std::cout << "Named b-tagging systematics should have a name. Please provide one." << std::endl; + + case top::topSFSyst::BTAG_SF_NAMED_DOWN: + if (uncert_name == "") { + ATH_MSG_INFO("Named b-tagging systematics should have a name. Please provide one."); return 0; } - decoration = "btag_SF_"+WP+"_"+uncert_name+"__1down"; + decoration = "btag_SF_" + WP + "_" + uncert_name + "__1down"; break; - case top::topSFSyst::BTAG_SF_EIGEN_B : - case top::topSFSyst::BTAG_SF_EIGEN_C : - case top::topSFSyst::BTAG_SF_EIGEN_LIGHT : - std::cout << "For Eigenvectors please use ScaleFactorRetriever::btagSF_eigen_vars" << std::endl; + + case top::topSFSyst::BTAG_SF_EIGEN_B: + case top::topSFSyst::BTAG_SF_EIGEN_C: + case top::topSFSyst::BTAG_SF_EIGEN_LIGHT: + ATH_MSG_INFO("For Eigenvectors please use ScaleFactorRetriever::btagSF_eigen_vars"); return 0; + break; - default : - std::cout << "Not the right function: " - << __PRETTY_FUNCTION__ << std::endl; + + default: + ATH_MSG_INFO("Not the right function: " << __PRETTY_FUNCTION__); return 0; + break; } @@ -868,13 +1160,10 @@ namespace top { xAOD::JetContainer jets = event.m_jets; if (do_trackjets) jets = event.m_trackJets; for (auto jetPtr : jets) { - double weight = 1.0; - if (jetPtr -> isAvailable<float>(decoration)) - weight = jetPtr -> auxdataConst<float>(decoration); + if (jetPtr->isAvailable<float>(decoration)) weight = jetPtr->auxdataConst<float>(decoration); sf *= weight; - } // for now @@ -886,31 +1175,33 @@ namespace top { std::vector<float>& vec_btagSF_up, std::vector<float>& vec_btagSF_down, std::string WP, bool do_trackjets) const { - // just in case vec_btagSF_up.clear(); vec_btagSF_down.clear(); unsigned int n_eigen = 0; - std::string prefix = "btag_SF_"+WP+"_FT_EFF_Eigen_"; + std::string prefix = "btag_SF_" + WP + "_FT_EFF_Eigen_"; std::string flav = ""; switch (SFSyst) { - case top::topSFSyst::BTAG_SF_EIGEN_B : - n_eigen = do_trackjets ? m_config-> trkjet_btagging_num_B_eigenvars(WP) : m_config->btagging_num_B_eigenvars(WP); + case top::topSFSyst::BTAG_SF_EIGEN_B: + n_eigen = do_trackjets ? m_config->trkjet_btagging_num_B_eigenvars(WP) : m_config->btagging_num_B_eigenvars(WP); flav = "B_"; break; - case top::topSFSyst::BTAG_SF_EIGEN_C : - n_eigen = do_trackjets ? m_config-> trkjet_btagging_num_C_eigenvars(WP) : m_config->btagging_num_C_eigenvars(WP); + + case top::topSFSyst::BTAG_SF_EIGEN_C: + n_eigen = do_trackjets ? m_config->trkjet_btagging_num_C_eigenvars(WP) : m_config->btagging_num_C_eigenvars(WP); flav = "C_"; break; - case top::topSFSyst::BTAG_SF_EIGEN_LIGHT : - n_eigen = do_trackjets ? m_config-> trkjet_btagging_num_Light_eigenvars(WP) : m_config->btagging_num_Light_eigenvars(WP); + + case top::topSFSyst::BTAG_SF_EIGEN_LIGHT: + n_eigen = + do_trackjets ? m_config->trkjet_btagging_num_Light_eigenvars(WP) : m_config->btagging_num_Light_eigenvars(WP); flav = "Light_"; break; - default : - std::cout << "Not the right function: " - << __PRETTY_FUNCTION__ << std::endl; + + default: + ATH_MSG_INFO("Not the right function: " << __PRETTY_FUNCTION__); return; } vec_btagSF_up.resize(n_eigen); @@ -919,49 +1210,60 @@ namespace top { for (unsigned int i = 0; i < n_eigen; ++i) { float SF_up(1.0), SF_down(1.0); std::string num = std::to_string(i); - std::string SF_dec_up = prefix+flav+num+"__1up"; - std::string SF_dec_down = prefix+flav+num+"__1down"; + std::string SF_dec_up = prefix + flav + num + "__1up"; + std::string SF_dec_down = prefix + flav + num + "__1down"; xAOD::JetContainer jets = event.m_jets; if (do_trackjets) jets = event.m_trackJets; for (auto jetPtr : jets) { - if (jetPtr->isAvailable<float>(SF_dec_up)) - SF_up *= jetPtr->auxdataConst<float>(SF_dec_up); - if (jetPtr->isAvailable<float>(SF_dec_down)) - SF_down *= jetPtr->auxdataConst<float>(SF_dec_down); + if (jetPtr->isAvailable<float>(SF_dec_up)) SF_up *= jetPtr->auxdataConst<float>(SF_dec_up); + if (jetPtr->isAvailable<float>(SF_dec_down)) SF_down *= jetPtr->auxdataConst<float>(SF_dec_down); } vec_btagSF_up[i] = SF_up; vec_btagSF_down[i] = SF_down; - } return; } float ScaleFactorRetriever::jvtSF(const top::Event& event, const top::topSFSyst SFSyst) const { - xAOD::JetContainer jets = event.m_jets; switch (SFSyst) { case top::topSFSyst::JVT_UP: return event.m_jvtSF_UP; + case top::topSFSyst::JVT_DOWN: return event.m_jvtSF_DOWN; + default: return event.m_jvtSF; } + } + float ScaleFactorRetriever::fjvtSF(const top::Event& event, + const top::topSFSyst SFSyst) const { + xAOD::JetContainer jets = event.m_jets; + switch (SFSyst) { + case top::topSFSyst::FJVT_UP: + return event.m_fjvtSF_UP; + + case top::topSFSyst::FJVT_DOWN: + return event.m_fjvtSF_DOWN; + + default: + return event.m_fjvtSF; + } } /** - * @brief Print all the SF values to cout - */ + * @brief Print all the SF values to msg stream + */ void ScaleFactorRetriever::print(const top::Event& event) { - std::cout << "ScaleFactors" << "\n"; - std::cout << " MCEventWeight : " << event.m_info->mcEventWeight() << "\n"; - std::cout << " Pileup : " << pileupSF(event) << "\n"; - std::cout << " LeptonEventWeight : " << leptonSF(event, top::topSFSyst::nominal) << "\n"; - std::cout << " B-TagEventWeight : " << btagSF(event, top::topSFSyst::nominal) << "\n"; + ATH_MSG_INFO("ScaleFactors"); + ATH_MSG_INFO(" MCEventWeight : " << + std::to_string(event.m_info->auxdataConst<float>("AnalysisTop_eventWeight"))); + ATH_MSG_INFO(" Pileup : " << std::to_string(pileupSF(event))); + ATH_MSG_INFO(" LeptonEventWeight : " << std::to_string(leptonSF(event, top::topSFSyst::nominal))); + ATH_MSG_INFO(" B-TagEventWeight : " << std::to_string(btagSF(event, top::topSFSyst::nominal))); } - - } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TauScaleFactorCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TauScaleFactorCalculator.cxx index 03ce54848f669dcf7f59748c45a7779b0897d37b..3484f4d583a9bdd24f479428a577e0cd7db77a89 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TauScaleFactorCalculator.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TauScaleFactorCalculator.cxx @@ -1,8 +1,8 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ -// $Id: TauScaleFactorCalculator.cxx 712396 2015-12-03 16:25:25Z tneep $ +// $Id: TauScaleFactorCalculator.cxx 805414 2017-05-24 12:21:29Z yili $ #include <string> #include "TopCorrections/TauScaleFactorCalculator.h" @@ -10,132 +10,118 @@ #include "TopEvent/EventTools.h" #include "xAODTau/TauJetContainer.h" +#include "TopCorrections/ScaleFactorRetriever.h" namespace top { + TauScaleFactorCalculator::TauScaleFactorCalculator(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + m_tauEffCorrTool("TauAnalysisTools::TauEfficiencyCorrectionsTool"), + m_tauEffCorrToolLoose("TauAnalysisTools::TauEfficiencyCorrectionsToolLoose"), + + m_systNominal(CP::SystematicSet()) { + declareProperty("config", m_config); + } -TauScaleFactorCalculator::TauScaleFactorCalculator(const std::string& name) : - asg::AsgTool(name), - m_config(nullptr), - m_tauEffCorrTool("TauAnalysisTools::TauEfficiencyCorrectionsTool"), - m_tauEffCorrToolLoose("TauAnalysisTools::TauEfficiencyCorrectionsToolLoose"), - - m_systNominal(CP::SystematicSet()) { - declareProperty("config" , m_config); -} - -StatusCode TauScaleFactorCalculator::initialize() { - ATH_MSG_INFO(" top::TauScaleFactorCalculator initialize"); - - top::check(m_tauEffCorrTool.retrieve(), - "Failed to retrieve tau efficiency corrections tool"); - - // How to get the recommended/affecting systematics... - // CP::SystematicSet m_syst_rec = m_tauEffCorrTool->recommendedSystematics(); - // CP::SystematicSet m_syst_aff = m_tauEffCorrTool->affectingSystematics(); - - const std::string tauSysPrefix = "TAUS_TRUEHADTAU_EFF_"; - // Should be empty- but lets be sure - m_syst_map.clear(); - // Add all recommended systematics to be clear - // Tau-electron overlap removal up/down - m_syst_map["tauSF_eleolr_total_down"] - = CP::SystematicSet(tauSysPrefix+"ELEOLR_TOTAL__1down"); - m_syst_map["tauSF_eleolr_total_up"] - = CP::SystematicSet(tauSysPrefix+"ELEOLR_TOTAL__1up"); - // Tau Jet ID WP up/down - m_syst_map["tauSF_jetid_total_down"] - = CP::SystematicSet(tauSysPrefix+"JETID_TOTAL__1down"); - m_syst_map["tauSF_jetid_total_up"] - = CP::SystematicSet(tauSysPrefix+"JETID_TOTAL__1up"); - // Tau reconstruction up/down - m_syst_map["tauSF_reco_total_down"] - = CP::SystematicSet(tauSysPrefix+"RECO_TOTAL__1down"); - m_syst_map["tauSF_reco_total_up"] - = CP::SystematicSet(tauSysPrefix+"RECO_TOTAL__1up"); - - return StatusCode::SUCCESS; -} - - -StatusCode TauScaleFactorCalculator::execute() { - ///-- Loop over all muon collections --/// - for (auto currentSystematic : *m_config->systSgKeyMapTaus()) { - const xAOD::TauJetContainer* taus(nullptr); - top::check(evtStore()->retrieve(taus, currentSystematic.second), - "failed to retrieve taus"); - - ///-- Tell the SF tools to use the nominal systematic --/// - - /// -- Loop over all taus in each collection --/// - for (auto tauPtr : *taus) { - /// -- Does the tau pass object selection? --/// - bool passSelection(false); - if (tauPtr->isAvailable<char>("passPreORSelection")) { - if (tauPtr->auxdataConst<char>("passPreORSelection") == 1) { - passSelection = true; - } - } - if (tauPtr->isAvailable<char>("passPreORSelectionLoose")) { - if (tauPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { - passSelection = true; - } - } + StatusCode TauScaleFactorCalculator::initialize() { + ATH_MSG_INFO(" top::TauScaleFactorCalculator initialize"); - ///-- If we aren't selecting the tau, then don't bother --/// - if (!passSelection) continue; - - //============================================================ - // Find the nominal SF for the tight/loose tau IDs for every - // systematic uncertainty. - // - // Make sure we set both tools to nominal for each tau - //============================================================ - - top::check(m_tauEffCorrTool->applySystematicVariation(m_systNominal), - "Failed to set tau efficiency correction" - " tool to nominal value"); - top::check(m_tauEffCorrToolLoose->applySystematicVariation(m_systNominal), - "Failed to set (loose) tau efficiency correction" - " tool to nominal value"); - - double nominalSF(0.0), nominalSFLoose(0.0); - - top::check(m_tauEffCorrTool->getEfficiencyScaleFactor(*tauPtr, nominalSF), - "Failed to get nominal tau SF"); - top::check(m_tauEffCorrToolLoose->getEfficiencyScaleFactor(*tauPtr, - nominalSFLoose), - "Failed to get nominal (loose) tau SF"); - - ///-- Decorate the tau with the tight/loose SFs --/// - tauPtr->auxdecor<float>("tauSF") = nominalSF; - tauPtr->auxdecor<float>("tauSF_loose") = nominalSFLoose; - - ///-- For nominal calibration, vary the SF systematics --/// - if (currentSystematic.first == m_config->nominalHashValue()) { - for (const auto& i : m_syst_map) { - double SF(0.0), SF_loose(0.0); - const std::string decoration_name = i.first; - const std::string decoration_name_loose = i.first+"_loose"; - top::check(m_tauEffCorrTool->applySystematicVariation(i.second), - "Failed to set tau efficiency correction" - " tool to nominal value"); - top::check(m_tauEffCorrToolLoose->applySystematicVariation(i.second), - "Failed to set (loose) tau efficiency correction" - " tool to nominal value"); - top::check(m_tauEffCorrTool->getEfficiencyScaleFactor(*tauPtr, SF), - "Failed to get nominal tau SF"); - top::check(m_tauEffCorrToolLoose->getEfficiencyScaleFactor(*tauPtr, - SF_loose), - "Failed to get nominal (loose) tau SF"); - tauPtr->auxdecor<float>(decoration_name) = SF; - tauPtr->auxdecor<float>(decoration_name_loose) = SF_loose; - } - } // Calibration systematic is nominal, so calculate SF systematics + top::check(m_tauEffCorrTool.retrieve(), + "Failed to retrieve tau efficiency corrections tool"); + + // How to get the recommended/affecting systematics... + // Should be empty- but lets be sure + m_syst_map.clear(); + // Add all recommended systematics to be clear + // Tau-electron overlap removal up/down, true hadtau + + for (auto tauSFpair : top::tauSF_name) { + if (m_config->tauSFDoRNNID() == false && tauSFpair.second.Contains("RNN")) continue; + if (m_config->tauSFDoBDTID() == false && tauSFpair.second.Contains("JETID")) continue; + m_syst_map[tauSFpair.second.Data()] = CP::SystematicSet(tauSFpair.second.Data()); } + + return StatusCode::SUCCESS; } + StatusCode TauScaleFactorCalculator::execute() { + ///-- Loop over all muon collections --/// + for (auto currentSystematic : *m_config->systSgKeyMapTaus()) { + const xAOD::TauJetContainer* taus(nullptr); + top::check(evtStore()->retrieve(taus, currentSystematic.second), + "failed to retrieve taus"); + + ///-- Tell the SF tools to use the nominal systematic --/// + + /// -- Loop over all taus in each collection --/// + for (auto tauPtr : *taus) { + /// -- Does the tau pass object selection? --/// + bool passSelection(false); + if (tauPtr->isAvailable<char>("passPreORSelection")) { + if (tauPtr->auxdataConst<char>("passPreORSelection") == 1) { + passSelection = true; + } + } + if (tauPtr->isAvailable<char>("passPreORSelectionLoose")) { + if (tauPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) { + passSelection = true; + } + } + + ///-- If we aren't selecting the tau, then don't bother --/// + if (!passSelection) continue; + + //============================================================ + // Find the nominal SF for the tight/loose tau IDs for every + // systematic uncertainty. + // + // Make sure we set both tools to nominal for each tau + //============================================================ + + top::check(m_tauEffCorrTool->applySystematicVariation(m_systNominal), + "Failed to set tau efficiency correction" + " tool to nominal value"); + top::check(m_tauEffCorrToolLoose->applySystematicVariation(m_systNominal), + "Failed to set (loose) tau efficiency correction" + " tool to nominal value"); + + double nominalSF(0.0), nominalSFLoose(0.0); + + top::check(m_tauEffCorrTool->getEfficiencyScaleFactor(*tauPtr, nominalSF), + "Failed to get nominal tau SF"); + top::check(m_tauEffCorrToolLoose->getEfficiencyScaleFactor(*tauPtr, + nominalSFLoose), + "Failed to get nominal (loose) tau SF"); + + ///-- Decorate the tau with the tight/loose SFs --/// + tauPtr->auxdecor<float>("TAU_SF_NOMINAL") = nominalSF; + tauPtr->auxdecor<float>("TAU_SF_NOMINAL_loose") = nominalSFLoose; + + ///-- For nominal calibration, vary the SF systematics --/// + if (currentSystematic.first == m_config->nominalHashValue()) { + for (const auto& i : m_syst_map) { + double SF(0.0), SF_loose(0.0); + const std::string decoration_name = i.first; + const std::string decoration_name_loose = i.first + "_loose"; + top::check(m_tauEffCorrTool->applySystematicVariation(i.second), + "Failed to set tau efficiency correction" + " tool to nominal value"); + top::check(m_tauEffCorrToolLoose->applySystematicVariation(i.second), + "Failed to set (loose) tau efficiency correction" + " tool to nominal value"); + top::check(m_tauEffCorrTool->getEfficiencyScaleFactor(*tauPtr, SF), + "Failed to get nominal tau SF"); + top::check(m_tauEffCorrToolLoose->getEfficiencyScaleFactor(*tauPtr, + SF_loose), + "Failed to get nominal (loose) tau SF"); + tauPtr->auxdecor<float>(decoration_name) = SF; + tauPtr->auxdecor<float>(decoration_name_loose) = SF_loose; + } + } // Calibration systematic is nominal, so calculate SF systematics + } + } - return StatusCode::SUCCESS; -} + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TopCorrectionsTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TopCorrectionsTools.cxx new file mode 100644 index 0000000000000000000000000000000000000000..6044afeb2ea827e78e4495c893b73bd5a3b2fc50 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/Root/TopCorrectionsTools.cxx @@ -0,0 +1,62 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopCorrections/TopCorrectionsTools.h" +#include <iostream> + +#include "TopCorrections/MsgCategory.h" +using namespace TopCorrections; + +namespace top { + // B-tagging naming tool + std::string bTagNamedSystCheck(std::shared_ptr<top::TopConfig> config, + const std::string& systCollection, + const std::string& tagWP, + const bool isTrackJet, + const bool verbose = false) { + // TODO -- to be reworked to use new message level settings to be implemented + if (verbose) ATH_MSG_INFO("Searching for " << systCollection << " for WP " << tagWP); + if (isTrackJet) { + for (const std::string& name : config->trkjet_btagging_namedSysts(tagWP)) { + if (verbose) ATH_MSG_INFO("...Possible matches : "); + if (systCollection.find(betterBtagNamedSyst(name)) != std::string::npos) { + if (verbose) ATH_MSG_INFO("......Matched!"); + if (systCollection.find("up") != std::string::npos) return name + "__1up"; + else if (systCollection.find("down") != std::string::npos) return name + "__1down"; + else return name; + } + } + } else { + for (const std::string& name : config->btagging_namedSysts(tagWP)) { + if (verbose) ATH_MSG_INFO("...Possible matches : "); + if (systCollection.find(betterBtagNamedSyst(name)) != std::string::npos) { + if (verbose) ATH_MSG_INFO("......Matched!"); + if (systCollection.find("up") != std::string::npos) return name + "__1up"; + else if (systCollection.find("down") != std::string::npos) return name + "__1down"; + else return name; + } + } + } + return ""; + } + + // B-tagging naming tool + std::string betterBtagNamedSyst(const std::string& name) { + // remove "FT_EFF_", spaces, and "-" in named systematics + std::string str = "FT_EFF_"; + std::string out = name; + if (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), ""); + } + str = " "; + while (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), "_"); + } + str = "-"; + while (out.find(str) != std::string::npos) { + out.replace(out.find(str), str.length(), "_"); + } + return out; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/BTagScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/BTagScaleFactorCalculator.h index 41fc0f4ae4c3a437217d1364e1fa904415c1ab7b..a16c8ead2ce4f6e54b92935f7df8fddfed150fc1 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/BTagScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/BTagScaleFactorCalculator.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: BTagScaleFactorCalculator.h 754162 2016-06-10 15:01:10Z tpelzer $ +// $Id: BTagScaleFactorCalculator.h 807496 2017-06-28 14:52:29Z iconnell $ #ifndef ANALYSISTOP_TOPCORRECTIONS_BTAGSCALEFACTORCALCULATOR_H #define ANALYSISTOP_TOPCORRECTIONS_BTAGSCALEFACTORCALCULATOR_H /** - * @author Andrea Knue <aknue@cern.ch>, John Morris <john.morris@cern.ch> - * - * @brief BTagScaleFactorCalculator - * Calculate all jet scale factors and decorate - * - * $Revision: - * $Date: 2016-06-10 17:01:10 +0200 (Fri, 10 Jun 2016) $ - * - **/ + * @author Andrea Knue <aknue@cern.ch>, John Morris <john.morris@cern.ch> + * + * @brief BTagScaleFactorCalculator + * Calculate all jet scale factors and decorate + * + * $Revision: + * $Date: 2017-06-28 15:52:29 +0100 (Wed, 28 Jun 2017) $ + * + **/ // system include(s): #include <memory> @@ -27,48 +27,45 @@ // Systematic include(s): #include "PATInterfaces/SystematicSet.h" -#include "xAODBTaggingEfficiency/IBTaggingEfficiencyTool.h" -#include "xAODBTaggingEfficiency/IBTaggingSelectionTool.h" +#include "FTagAnalysisInterfaces/IBTaggingEfficiencyTool.h" +#include "FTagAnalysisInterfaces/IBTaggingSelectionTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class BTagScaleFactorCalculator final : public asg::AsgTool { - public: - explicit BTagScaleFactorCalculator( const std::string& name ); - virtual ~BTagScaleFactorCalculator(){} - - // Delete Standard constructors - BTagScaleFactorCalculator(const BTagScaleFactorCalculator& rhs) = delete; - BTagScaleFactorCalculator(BTagScaleFactorCalculator&& rhs) = delete; - BTagScaleFactorCalculator& operator=(const BTagScaleFactorCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - StatusCode apply( const std::shared_ptr<std::unordered_map<std::size_t,std::string>>& jet_syst_collections, - bool use_trackjets = false); - - private: - - std::shared_ptr<top::TopConfig> m_config; - - CP::SystematicSet m_nominal; - std::unordered_map<std::string, CP::SystematicSet> m_systs; - std::unordered_map<std::string, CP::SystematicSet> m_trkjet_systs; - - ///B-tagging efficiency tools - std::unordered_map<std::string, ToolHandle<IBTaggingEfficiencyTool>> m_btagEffTools; - std::unordered_map<std::string, ToolHandle<IBTaggingEfficiencyTool>> m_trkjet_btagEffTools; - ///B-tagging selection tools - std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool>> m_btagSelTools; - std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool>> m_trkjet_btagSelTools; - - int m_release_series = 24; // Default to 2.4 - +namespace top { + class BTagScaleFactorCalculator final: public asg::AsgTool { + public: + explicit BTagScaleFactorCalculator(const std::string& name); + virtual ~BTagScaleFactorCalculator() {} + + // Delete Standard constructors + BTagScaleFactorCalculator(const BTagScaleFactorCalculator& rhs) = delete; + BTagScaleFactorCalculator(BTagScaleFactorCalculator&& rhs) = delete; + BTagScaleFactorCalculator& operator = (const BTagScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + StatusCode apply(const std::shared_ptr<std::unordered_map<std::size_t, std::string> >& jet_syst_collections, + bool use_trackjets = false); + + // Function to print out information about internal tools + StatusCode debug(); + private: + std::shared_ptr<top::TopConfig> m_config; + + CP::SystematicSet m_nominal; + std::unordered_map<std::string, CP::SystematicSet> m_systs; + std::unordered_map<std::string, CP::SystematicSet> m_trkjet_systs; + + ///B-tagging efficiency tools + std::unordered_map<std::string, ToolHandle<IBTaggingEfficiencyTool> > m_btagEffTools; + std::unordered_map<std::string, ToolHandle<IBTaggingEfficiencyTool> > m_trkjet_btagEffTools; + ///B-tagging selection tools + std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool> > m_btagSelTools; + std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool> > m_trkjet_btagSelTools; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ElectronScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ElectronScaleFactorCalculator.h index 79984a325cf3a7d9e67347cd6716db55179d02b7..eba7b226cb6e3283b7256bd9728c35527ead5e0f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ElectronScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ElectronScaleFactorCalculator.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: ElectronScaleFactorCalculator.h 799556 2017-03-05 19:46:03Z tpelzer $ #ifndef ANALYSISTOP_TOPCORRECTIONS_ELECTRONSCALEFACTORCALCULATOR_H #define ANALYSISTOP_TOPCORRECTIONS_ELECTRONSCALEFACTORCALCULATOR_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief ElectronScaleFactorCalculator - * Calculate all electron scale factors and decorate - * - * $Revision: 799556 $ - * $Date: 2017-03-05 20:46:03 +0100 (Sun, 05 Mar 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief ElectronScaleFactorCalculator + * Calculate all electron scale factors and decorate + * + * $Revision: 799556 $ + * $Date: 2017-03-05 19:46:03 +0000 (Sun, 05 Mar 2017) $ + * + **/ // system include(s): #include <memory> @@ -27,85 +27,100 @@ // Systematic include(s): #include "PATInterfaces/SystematicSet.h" +#include "PATInterfaces/SystematicsUtil.h" // CP Tool include(s): -#include "ElectronEfficiencyCorrection/IAsgElectronEfficiencyCorrectionTool.h" +#include "EgammaAnalysisInterfaces/IAsgElectronEfficiencyCorrectionTool.h" #include "ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class ElectronScaleFactorCalculator final : public asg::AsgTool { - public: - explicit ElectronScaleFactorCalculator( const std::string& name ); - virtual ~ElectronScaleFactorCalculator(){} - - // Delete Standard constructors - ElectronScaleFactorCalculator(const ElectronScaleFactorCalculator& rhs) = delete; - ElectronScaleFactorCalculator(ElectronScaleFactorCalculator&& rhs) = delete; - ElectronScaleFactorCalculator& operator=(const ElectronScaleFactorCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - CP::SystematicSet m_systNominal; - CP::SystematicSet m_systTrigger_UP; - CP::SystematicSet m_systTrigger_DOWN; - CP::SystematicSet m_systReco_UP; - CP::SystematicSet m_systReco_DOWN; - CP::SystematicSet m_systID_UP; - CP::SystematicSet m_systID_DOWN; - CP::SystematicSet m_systIso_UP; - CP::SystematicSet m_systIso_DOWN; - CP::SystematicSet m_systChargeID_UP; - CP::SystematicSet m_systChargeID_DOWN; - CP::SystematicSet m_systChargeMisID_STAT_UP; - CP::SystematicSet m_systChargeMisID_STAT_DOWN; - CP::SystematicSet m_systChargeMisID_SYST_UP; - CP::SystematicSet m_systChargeMisID_SYST_DOWN; - - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTrigger; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerLoose; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTrigger; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerLoose; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFReco; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFID; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLoose; - - bool m_electronEffIso_exists; - bool m_electronEffIsoLoose_exists; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIso; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoLoose; - bool m_electronEffChargeID_exists; - bool m_electronEffChargeIDLoose_exists; - bool m_electronEffChargeMisID_exists; - bool m_electronEffChargeMisIDLoose_exists; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeID; - ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeIDLoose; - ToolHandle<CP::ElectronChargeEfficiencyCorrectionTool> m_electronEffSFChargeMisID; - ToolHandle<CP::ElectronChargeEfficiencyCorrectionTool> m_electronEffSFChargeMisIDLoose; - - std::string m_decor_triggerEff; - std::string m_decor_triggerEff_loose; - std::string m_decor_triggerSF; - std::string m_decor_triggerSF_loose; - std::string m_decor_recoSF; - std::string m_decor_idSF; - std::string m_decor_idSF_loose; - std::string m_decor_isoSF; - std::string m_decor_isoSF_loose; - std::string m_decor_chargeidSF; - std::string m_decor_chargeidSF_loose; - std::string m_decor_chargemisidSF; - std::string m_decor_chargemisidSF_loose; +namespace top { + class ElectronScaleFactorCalculator final: public asg::AsgTool { + public: + explicit ElectronScaleFactorCalculator(const std::string& name); + virtual ~ElectronScaleFactorCalculator() {} + // Delete Standard constructors + ElectronScaleFactorCalculator(const ElectronScaleFactorCalculator& rhs) = delete; + ElectronScaleFactorCalculator(ElectronScaleFactorCalculator&& rhs) = delete; + ElectronScaleFactorCalculator& operator = (const ElectronScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + private: + std::shared_ptr<top::TopConfig> m_config; + + CP::SystematicSet m_systNominal; + CP::SystematicSet m_systTrigger_UP; + CP::SystematicSet m_systTrigger_DOWN; + CP::SystematicSet m_systReco_UP; + CP::SystematicSet m_systReco_DOWN; + CP::SystematicSet m_systID_UP; + CP::SystematicSet m_systID_DOWN; + CP::SystematicSet m_systIso_UP; + CP::SystematicSet m_systIso_DOWN; + CP::SystematicSet m_systChargeID_UP; + CP::SystematicSet m_systChargeID_DOWN; + CP::SystematicSet m_systChargeMisID_STAT_UP; + CP::SystematicSet m_systChargeMisID_STAT_DOWN; + CP::SystematicSet m_systChargeMisID_SYST_UP; + CP::SystematicSet m_systChargeMisID_SYST_DOWN; + + std::vector<CP::SystematicSet> m_systTriggerCorrModel; + std::vector<CP::SystematicSet> m_systRecoCorrModel; + std::vector<CP::SystematicSet> m_systIDCorrModel; + std::vector<CP::SystematicSet> m_systIsoCorrModel; + + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTrigger; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerLoose; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTrigger; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerLoose; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFReco; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFID; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLoose; + + bool m_electronEffIso_exists; + bool m_electronEffIsoLoose_exists; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIso; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoLoose; + + + bool m_electronEffChargeID_exists; + bool m_electronEffChargeIDLoose_exists; + bool m_electronEffChargeMisID_exists; + bool m_electronEffChargeMisIDLoose_exists; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeID; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFChargeIDLoose; + ToolHandle<CP::ElectronChargeEfficiencyCorrectionTool> m_electronEffSFChargeMisID; + ToolHandle<CP::ElectronChargeEfficiencyCorrectionTool> m_electronEffSFChargeMisIDLoose; + + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFTriggerLooseCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffTriggerLooseCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFRecoCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLooseCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoCorrModel; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIsoLooseCorrModel; + + std::string m_decor_triggerEff; + std::string m_decor_triggerEff_loose; + std::string m_decor_triggerSF; + std::string m_decor_triggerSF_loose; + std::string m_decor_recoSF; + std::string m_decor_idSF; + std::string m_decor_idSF_loose; + std::string m_decor_isoSF; + std::string m_decor_isoSF_loose; + std::string m_decor_chargeidSF; + std::string m_decor_chargeidSF_loose; + std::string m_decor_chargemisidSF; + std::string m_decor_chargemisidSF_loose; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/FwdElectronScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/FwdElectronScaleFactorCalculator.h new file mode 100644 index 0000000000000000000000000000000000000000..45696874681112d84d22b9f6dce646022599af1f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/FwdElectronScaleFactorCalculator.h @@ -0,0 +1,63 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPCORRECTIONS_FWDELECTRONSCALEFACTORCALCULATOR_H +#define ANALYSISTOP_TOPCORRECTIONS_FWDELECTRONSCALEFACTORCALCULATOR_H + +/** + * @author Marco Vanadia <marco.vanadia@cern.ch> + * + * @brief FwdElectronScaleFactorCalculator + * Calculate all forward electron scale factors and decorate + * + **/ + +// system include(s): +#include <memory> +#include <set> + +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +// Systematic include(s): +#include "PATInterfaces/SystematicSet.h" + +// CP Tool include(s): +#include "EgammaAnalysisInterfaces/IAsgElectronEfficiencyCorrectionTool.h" +#include "ElectronEfficiencyCorrection/ElectronChargeEfficiencyCorrectionTool.h" + +// Forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class FwdElectronScaleFactorCalculator final: public asg::AsgTool { + public: + explicit FwdElectronScaleFactorCalculator(const std::string& name); + virtual ~FwdElectronScaleFactorCalculator() {} + + // Delete Standard constructors + FwdElectronScaleFactorCalculator(const FwdElectronScaleFactorCalculator& rhs) = delete; + FwdElectronScaleFactorCalculator(FwdElectronScaleFactorCalculator&& rhs) = delete; + FwdElectronScaleFactorCalculator& operator = (const FwdElectronScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + private: + std::shared_ptr<top::TopConfig> m_config; + + CP::SystematicSet m_systNominal; + CP::SystematicSet m_systID_UP; + CP::SystematicSet m_systID_DOWN; + + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFID; + ToolHandle<IAsgElectronEfficiencyCorrectionTool> m_electronEffSFIDLoose; + + std::string m_decor_idSF; + std::string m_decor_idSF_loose; + }; +} // namespace +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/GlobalLeptonTriggerCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/GlobalLeptonTriggerCalculator.h new file mode 100644 index 0000000000000000000000000000000000000000..94acaae813be59f21576b3d71cf44e999a702714 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/GlobalLeptonTriggerCalculator.h @@ -0,0 +1,68 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +// $Id: GlobalLeptonTriggerCalculator.h 799556 2017-03-05 19:46:03Z tpelzer $ +#ifndef ANALYSISTOP_TOPCORRECTIONS_GLOBALLEPTONTRIGGERCALCULATOR_H +#define ANALYSISTOP_TOPCORRECTIONS_GLOBALLEPTONTRIGGERCALCULATOR_H + +/** + * @author Ian Connelly <ian.connelly@cern.ch> + * + * @brief Global lepton trigger calculator + * Interface to retrieve the global lepton trigger scale factors + * + **/ + +// system include(s): +#include <memory> +#include <set> + +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +// Systematic include(s): +#include "PATInterfaces/SystematicSet.h" + +// CP Tool include(s): +#include "EgammaAnalysisInterfaces/IAsgElectronEfficiencyCorrectionTool.h" +#include "MuonAnalysisInterfaces/IMuonTriggerScaleFactors.h" +#include "TriggerAnalysisInterfaces/ITrigGlobalEfficiencyCorrectionTool.h" + +// Forward declaration(s): +namespace xAOD { + class SystematicEvent; +} +namespace top { + class TopConfig; +} + +namespace top { + class GlobalLeptonTriggerCalculator final: public asg::AsgTool { + public: + explicit GlobalLeptonTriggerCalculator(const std::string& name); + virtual ~GlobalLeptonTriggerCalculator() {} + + // Delete Standard constructors + GlobalLeptonTriggerCalculator(const GlobalLeptonTriggerCalculator& rhs) = delete; + GlobalLeptonTriggerCalculator(GlobalLeptonTriggerCalculator&& rhs) = delete; + GlobalLeptonTriggerCalculator& operator = (const GlobalLeptonTriggerCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + private: + void processEvent(const xAOD::SystematicEvent* systEvent, bool withScaleFactorVariations); + + std::shared_ptr<top::TopConfig> m_config; + + ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSF; + ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSFLoose; + + std::vector<ToolHandle<IAsgElectronEfficiencyCorrectionTool> > m_electronTools; + std::vector<ToolHandle<CP::IMuonTriggerScaleFactors> > m_muonTools; + + std::string m_decor_triggerSF; + }; +} // namespace +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/JetScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/JetScaleFactorCalculator.h index 2382c616ba530425be77f9fd3d76412207cd253a..1cbc8853d4b5d166fe94cefaaf5f0b1e0d06b2c7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/JetScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/JetScaleFactorCalculator.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // $Id: JetScaleFactorCalculator.h 724681 2016-02-17 18:20:27Z tneep $ #ifndef ANALYSISTOP_TOPCORRECTIONS_JETSCALEFACTORCALCULATOR_H #define ANALYSISTOP_TOPCORRECTIONS_JETSCALEFACTORCALCULATOR_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief JetScaleFactorCalculator - * Calculate all jet scale factors and decorate - * - * $Revision: 724681 $ - * $Date: 2016-02-17 19:20:27 +0100 (Wed, 17 Feb 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief JetScaleFactorCalculator + * Calculate all jet scale factors and decorate + * + * $Revision: 724681 $ + * $Date: 2016-02-17 18:20:27 +0000 (Wed, 17 Feb 2016) $ + * + **/ // system include(s): #include <memory> @@ -28,39 +28,40 @@ // Systematic include(s): #include "PATInterfaces/SystematicSet.h" -#include "JetJvtEfficiency/IJetJvtEfficiency.h" +#include "JetAnalysisInterfaces/IJetJvtEfficiency.h" // CP Tool include(s): // #include "ElectronEfficiencyCorrection/AsgElectronEfficiencyCorrectionTool.h" // Forward declaration(s): namespace top { -class TopConfig; + class TopConfig; } namespace top { + class JetScaleFactorCalculator final: public asg::AsgTool { + public: + explicit JetScaleFactorCalculator(const std::string& name); + virtual ~JetScaleFactorCalculator() {} -class JetScaleFactorCalculator final : public asg::AsgTool { - public: - explicit JetScaleFactorCalculator(const std::string& name); - virtual ~JetScaleFactorCalculator() {} + // Delete Standard constructors + JetScaleFactorCalculator(const JetScaleFactorCalculator& rhs) = delete; + JetScaleFactorCalculator(JetScaleFactorCalculator&& rhs) = delete; + JetScaleFactorCalculator& operator = (const JetScaleFactorCalculator& rhs) = delete; - // Delete Standard constructors - JetScaleFactorCalculator(const JetScaleFactorCalculator& rhs) = delete; - JetScaleFactorCalculator(JetScaleFactorCalculator&& rhs) = delete; - JetScaleFactorCalculator& operator=(const JetScaleFactorCalculator& rhs) = delete; + StatusCode initialize(); + StatusCode execute(); + private: + StatusCode decorateJets(const xAOD::JetContainer* jets, bool isNominal); + + std::shared_ptr<top::TopConfig> m_config; - StatusCode initialize(); - StatusCode execute(); + CP::SystematicSet m_systNominal; + CP::SystematicSet m_systUP; + CP::SystematicSet m_systDOWN; - private: - std::shared_ptr<top::TopConfig> m_config; - - CP::SystematicSet m_systNominal; - CP::SystematicSet m_systUP; - CP::SystematicSet m_systDOWN; - - ToolHandle<CP::IJetJvtEfficiency> m_jvt_tool; -}; + ToolHandle<CP::IJetJvtEfficiency> m_jvt_tool; + ToolHandle<CP::IJetJvtEfficiency> m_fjvt_tool; + }; } // namespace top #endif // ANALYSISTOP_TOPCORRECTIONS_JETSCALEFACTORCALCULATOR_H diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MsgCategory.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MsgCategory.h new file mode 100644 index 0000000000000000000000000000000000000000..e3ef1381b800b76a243f5f91ebd42a8bad44bd3d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MsgCategory.h @@ -0,0 +1,10 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#ifndef TOPCORRECTIONS_MSG_CATEGORY_H_ +#define TOPCORRECTIONS_MSG_CATEGORY_H_ +#include <AsgMessaging/MessageCheck.h> + +ANA_MSG_HEADER(TopCorrections) + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MuonScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MuonScaleFactorCalculator.h index 3a3e73956065b50905d60add77ba97f939dd2f06..e0ef1594aaf8cb41924ad768d9ab124809bde35e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MuonScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/MuonScaleFactorCalculator.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: MuonScaleFactorCalculator.h 786766 2016-11-28 03:21:13Z tpelzer $ #ifndef ANALYSISTOP_TOPCORRECTIONS_MUONSCALEFACTORCALCULATOR_H #define ANALYSISTOP_TOPCORRECTIONS_MUONSCALEFACTORCALCULATOR_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief MuonScaleFactorCalculator - * Calculate all muon scale factors and decorate - * - * $Revision: 786766 $ - * $Date: 2016-11-28 04:21:13 +0100 (Mon, 28 Nov 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief MuonScaleFactorCalculator + * Calculate all muon scale factors and decorate + * + * $Revision: 786766 $ + * $Date: 2016-11-28 03:21:13 +0000 (Mon, 28 Nov 2016) $ + * + **/ // system include(s): #include <memory> @@ -35,173 +35,178 @@ // Forward declaration(s): namespace top { -class TopConfig; + class TopConfig; } namespace top { - -class MuonScaleFactorCalculator final : public asg::AsgTool { - public: - explicit MuonScaleFactorCalculator(const std::string& name); - virtual ~MuonScaleFactorCalculator() {} - - // Delete Standard constructors - MuonScaleFactorCalculator(const MuonScaleFactorCalculator& rhs) = delete; - MuonScaleFactorCalculator(MuonScaleFactorCalculator&& rhs) = delete; - MuonScaleFactorCalculator& operator=(const MuonScaleFactorCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - private: - // Helper function to retrieve a toolhandle and - // get the recommended systematics of that tool - // into a std::set - template<typename T> + class MuonScaleFactorCalculator final: public asg::AsgTool { + public: + explicit MuonScaleFactorCalculator(const std::string& name); + virtual ~MuonScaleFactorCalculator() {} + + // Delete Standard constructors + MuonScaleFactorCalculator(const MuonScaleFactorCalculator& rhs) = delete; + MuonScaleFactorCalculator(MuonScaleFactorCalculator&& rhs) = delete; + MuonScaleFactorCalculator& operator = (const MuonScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + private: + // Helper function to retrieve a toolhandle and + // get the recommended systematics of that tool + // into a std::set + template<typename T> void retrieveSystematicTool(const ToolHandle<T>& tool, std::set<std::string>& recommended_systematics); - // We have (had) a lot of lines like :: - // top::check(tool->applySystematicVariation(...), - // "Failed to set systematic variation"); - // This function will essentially do that but try to give a more - // sensible and specific error message. - // If the SystematicSet is empty then it sets to the nominal, - // so edit error message accordingly. - // (This might be expensive). - // - // Since this is general, we should maybe move somewhere - // more common. - template<typename T> + // We have (had) a lot of lines like :: + // top::check(tool->applySystematicVariation(...), + // "Failed to set systematic variation"); + // This function will essentially do that but try to give a more + // sensible and specific error message. + // If the SystematicSet is empty then it sets to the nominal, + // so edit error message accordingly. + // (This might be expensive). + // + // Since this is general, we should maybe move somewhere + // more common. + template<typename T> void applySystematicVariation(ToolHandle<T>& tool, const CP::SystematicSet& systematic); - // Check that all recommended systematics are implemented - // The arguments are two c++ std::set, for recommended & implemented - // systematics. Recommended systematics can be automatically extracted - // from tools (see retrieveSystematicTool above) while the implemented - // systematics must be hard-coded by the maintainer of this class. - StatusCode checkSystematicsImplemented(const std::set<std::string>& recommended, - const std::set<std::string>& implemented); - - // Use this function to decorate the trigger efficiency - // onto the muon. Try not to use directly, instead use - // decorateTrigSFandEff(), see below. - void decorateTriggerEfficiency(ToolHandle<CP::IMuonTriggerScaleFactors>& tool, - const xAOD::Muon& muon, - const SG::AuxElement::Decorator<float>& decor); - - // Use this function to decorate the trigger SF - // onto the muon. Try not to use directly, instead use - // decorateTrigSFandEff(), see below. - void decorateTriggerSF(ToolHandle<CP::IMuonTriggerScaleFactors>& tool, - const ConstDataVector<xAOD::MuonContainer>& muon_cont, - const SG::AuxElement::Decorator<float>& decor); - - // This function is a nice wrapper of:: - // applySystematicVariation(...); - // decorateTriggerEfficiency(...); - // and:: - // decorateTriggerSF(...); - // We have this code block ~10 times so this hopefully - // keeps it simple and ensures each block is the same. - void decorateTrigSFandEff(ToolHandle<CP::IMuonTriggerScaleFactors>& tool, - const CP::SystematicSet& systematic, - const ConstDataVector<xAOD::MuonContainer>& muon_cont, - const SG::AuxElement::Decorator<float>& sf_decor, - const SG::AuxElement::Decorator<float>& eff_decor); - - // To keep things as readable as possible this function - // decorates the muon with the loose and tight trigger SFs and effs - void decorateTriggerSystematics(const ConstDataVector<xAOD::MuonContainer>& trigger_SF_muon); - - // As with ``applySystematicVariation``, we have (had) a - // lot of lines:: - // top::check(tool->getEfficiencyScaleFactor(muon, syst), - // "Failed to get efficiency SF"); - // This helper function will replace that, as well as calling - // applySystematicVariation try and avoid errors - void decorateEfficiencySF(ToolHandle<CP::IMuonEfficiencyScaleFactors>& tool, - const CP::SystematicSet& systematic, - const xAOD::Muon& muon, - const SG::AuxElement::Decorator<float>& decor); - - // Helper function to decorate isolation systematics - // if we have set isolation to None for either the - // tight or loose muon selections then this will still - // decorate the SFs all set to 1.0 - void decorateIsolationSystematics(const xAOD::Muon& muon); - - // Helper function to decorate all TTVA SF systematics onto muon - void decorateTTVASystematics(const xAOD::Muon& muon); - - // For a single systematic, decorate the ID SF onto muon - // no reco Eff since 2.4.22 - void decorateIDSFandRecoEff(ToolHandle<CP::IMuonEfficiencyScaleFactors>& tool, + // Check that all recommended systematics are implemented + // The arguments are two c++ std::set, for recommended & implemented + // systematics. Recommended systematics can be automatically extracted + // from tools (see retrieveSystematicTool above) while the implemented + // systematics must be hard-coded by the maintainer of this class. + StatusCode checkSystematicsImplemented(const std::set<std::string>& recommended, + const std::set<std::string>& implemented); + + // Use this function to decorate the trigger efficiency + // onto the muon. Try not to use directly, instead use + // decorateTrigSFandEff(), see below. + void decorateTriggerEfficiency(ToolHandle<CP::IMuonTriggerScaleFactors>& tool, + const xAOD::Muon& muon, + const SG::AuxElement::Decorator<float>& decor); + + // Use this function to decorate the trigger SF + // onto the muon. Try not to use directly, instead use + // decorateTrigSFandEff(), see below. + void decorateTriggerSF(ToolHandle<CP::IMuonTriggerScaleFactors>& tool, + const ConstDataVector<xAOD::MuonContainer>& muon_cont, + const SG::AuxElement::Decorator<float>& decor); + + // This function is a nice wrapper of:: + // applySystematicVariation(...); + // decorateTriggerEfficiency(...); + // and:: + // decorateTriggerSF(...); + // We have this code block ~10 times so this hopefully + // keeps it simple and ensures each block is the same. + void decorateTrigSFandEff(ToolHandle<CP::IMuonTriggerScaleFactors>& tool, + const CP::SystematicSet& systematic, + const ConstDataVector<xAOD::MuonContainer>& muon_cont, + const SG::AuxElement::Decorator<float>& sf_decor, + const SG::AuxElement::Decorator<float>& eff_decor); + + // To keep things as readable as possible this function + // decorates the muon with the loose and tight trigger SFs and effs + void decorateTriggerSystematics(const ConstDataVector<xAOD::MuonContainer>& trigger_SF_muon); + + // As with ``applySystematicVariation``, we have (had) a + // lot of lines:: + // top::check(tool->getEfficiencyScaleFactor(muon, syst), + // "Failed to get efficiency SF"); + // This helper function will replace that, as well as calling + // applySystematicVariation try and avoid errors + void decorateEfficiencySF(ToolHandle<CP::IMuonEfficiencyScaleFactors>& tool, const CP::SystematicSet& systematic, const xAOD::Muon& muon, - const SG::AuxElement::Decorator<float>& id_sf_decor); - - // Helper funciton to do above for all systematics - void decorateIDSFandRecoEffSystematics(const xAOD::Muon& muon); - - std::shared_ptr<top::TopConfig> m_config; - - CP::SystematicSet m_systNominal; - - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose; - - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2015; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2015; - - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2016; - ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2016; - - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsTool; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLoose; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolIso; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLooseIso; - ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolTTVA; - - std::string m_decor_triggerEff; - std::string m_decor_triggerEff_loose; - std::string m_decor_triggerSF; - std::string m_decor_triggerSF_loose; - std::string m_decor_idSF; - std::string m_decor_idSF_loose; - std::string m_decor_isoSF; - std::string m_decor_isoSF_loose; - std::string m_decor_TTVA; - - bool m_do_muon_isolation_SFs; - bool m_do_muon_isolation_SFs_loose; - - CP::SystematicSet m_trig_sf_stat_UP; - CP::SystematicSet m_trig_sf_stat_DOWN; - CP::SystematicSet m_trig_sf_syst_UP; - CP::SystematicSet m_trig_sf_syst_DOWN; - - CP::SystematicSet m_reco_stat_UP; - CP::SystematicSet m_reco_stat_DOWN; - CP::SystematicSet m_reco_syst_UP; - CP::SystematicSet m_reco_syst_DOWN; - - CP::SystematicSet m_reco_stat_lowpt_UP; - CP::SystematicSet m_reco_stat_lowpt_DOWN; - CP::SystematicSet m_reco_syst_lowpt_UP; - CP::SystematicSet m_reco_syst_lowpt_DOWN; - - CP::SystematicSet m_iso_stat_UP; - CP::SystematicSet m_iso_stat_DOWN; - CP::SystematicSet m_iso_syst_UP; - CP::SystematicSet m_iso_syst_DOWN; - - CP::SystematicSet m_TTVA_stat_UP; - CP::SystematicSet m_TTVA_stat_DOWN; - CP::SystematicSet m_TTVA_syst_UP; - CP::SystematicSet m_TTVA_syst_DOWN; - - std::string m_muon_trigger_sf_config = ""; -}; + const SG::AuxElement::Decorator<float>& decor); + + // Helper function to decorate isolation systematics + // if we have set isolation to None for either the + // tight or loose muon selections then this will still + // decorate the SFs all set to 1.0 + void decorateIsolationSystematics(const xAOD::Muon& muon); + + // Helper function to decorate all TTVA SF systematics onto muon + void decorateTTVASystematics(const xAOD::Muon& muon); + + // For a single systematic, decorate the ID SF onto muon + // no reco Eff since 2.4.22 + void decorateIDSFandRecoEff(ToolHandle<CP::IMuonEfficiencyScaleFactors>& tool, + const CP::SystematicSet& systematic, + const xAOD::Muon& muon, + const SG::AuxElement::Decorator<float>& id_sf_decor); + + // Helper funciton to do above for all systematics + void decorateIDSFandRecoEffSystematics(const xAOD::Muon& muon); + void decorateIDSFandRecoEffSystematicsSoftMuon(const xAOD::Muon& muon); + + std::shared_ptr<top::TopConfig> m_config; + + CP::SystematicSet m_systNominal; + + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose; + + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2015; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2015; + + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_2016; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_2016; + + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactors_R21; + ToolHandle<CP::IMuonTriggerScaleFactors> m_muonTriggerScaleFactorsLoose_R21; + + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsTool; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_softmuonEfficiencyCorrectionsTool; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLoose; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolIso; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolLooseIso; + ToolHandle<CP::IMuonEfficiencyScaleFactors> m_muonEfficiencyCorrectionsToolTTVA; + + std::string m_decor_triggerEff; + std::string m_decor_triggerEff_loose; + std::string m_decor_triggerSF; + std::string m_decor_triggerSF_loose; + std::string m_decor_idSF; + std::string m_decor_idSF_loose; + std::string m_decor_isoSF; + std::string m_decor_isoSF_loose; + std::string m_decor_TTVA; + + std::string m_decor_softmuon_idSF; + + bool m_do_muon_isolation_SFs; + bool m_do_muon_isolation_SFs_loose; + + CP::SystematicSet m_trig_sf_stat_UP; + CP::SystematicSet m_trig_sf_stat_DOWN; + CP::SystematicSet m_trig_sf_syst_UP; + CP::SystematicSet m_trig_sf_syst_DOWN; + + CP::SystematicSet m_reco_stat_UP; + CP::SystematicSet m_reco_stat_DOWN; + CP::SystematicSet m_reco_syst_UP; + CP::SystematicSet m_reco_syst_DOWN; + + CP::SystematicSet m_reco_stat_lowpt_UP; + CP::SystematicSet m_reco_stat_lowpt_DOWN; + CP::SystematicSet m_reco_syst_lowpt_UP; + CP::SystematicSet m_reco_syst_lowpt_DOWN; + + CP::SystematicSet m_iso_stat_UP; + CP::SystematicSet m_iso_stat_DOWN; + CP::SystematicSet m_iso_syst_UP; + CP::SystematicSet m_iso_syst_DOWN; + + CP::SystematicSet m_TTVA_stat_UP; + CP::SystematicSet m_TTVA_stat_DOWN; + CP::SystematicSet m_TTVA_syst_UP; + CP::SystematicSet m_TTVA_syst_DOWN; + + std::string m_muon_trigger_sf_config = ""; + }; } // namespace top #endif // ANALYSISTOP_TOPCORRECTIONS_MUONSCALEFACTORCALCULATOR_H diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PDFScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PDFScaleFactorCalculator.h index 52a34504717b17af107a3bb1fd627b735aba355e..f411f112545e47dfa0ae198f95e2545dd3790489 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PDFScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PDFScaleFactorCalculator.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef PDFSCALEFACTORCALCULATOR #define PDFSCALEFACTORCALCULATOR @@ -25,25 +25,25 @@ #include "TopEvent/Event.h" namespace top { - class TopConfig; /** * @brief For testing PDF reweighting with LHAPDF6. Not serious, just a toy. * * Lots of stuff is available on cvmfs, set this: - * export LHAPDF_DATA_PATH=$ROOTCOREBIN/data/Asg_Lhapdf_LHAPDF:/cvmfs/sft.cern.ch/lcg/external/lhapdfsets/current/:$LHAPDF_DATA_PATH + * export + *LHAPDF_DATA_PATH=$ROOTCOREBIN/data/Asg_Lhapdf_LHAPDF:/cvmfs/sft.cern.ch/lcg/external/lhapdfsets/current/:$LHAPDF_DATA_PATH */ - class PDFScaleFactorCalculator final : public asg::AsgTool { + class PDFScaleFactorCalculator final: public asg::AsgTool { public: - explicit PDFScaleFactorCalculator( const std::string& name ); - - virtual ~PDFScaleFactorCalculator(){}; + explicit PDFScaleFactorCalculator(const std::string& name); + + virtual ~PDFScaleFactorCalculator() {}; // Delete Standard constructors PDFScaleFactorCalculator(const PDFScaleFactorCalculator& rhs) = delete; PDFScaleFactorCalculator(PDFScaleFactorCalculator&& rhs) = delete; - PDFScaleFactorCalculator& operator=(const PDFScaleFactorCalculator& rhs) = delete; + PDFScaleFactorCalculator& operator = (const PDFScaleFactorCalculator& rhs) = delete; StatusCode initialize(); StatusCode execute(); @@ -51,6 +51,7 @@ namespace top { int numberInSet(const std::string& name) const { const LHAPDF::PDFSet set(name); + return set.size(); } @@ -61,14 +62,13 @@ namespace top { * variable. */ void printAvailablePDFs() const { - std::cout << "List of available PDFs:" << std::endl; + ATH_MSG_INFO("List of available PDFs:"); for (const std::string& pdfname : LHAPDF::availablePDFSets()) - std::cout << " " << pdfname << std::endl; + msg(MSG::Level::INFO) << " " << pdfname << "\n"; + msg(MSG::Level::INFO) << std::endl; } - private: - std::shared_ptr<top::TopConfig> m_config; std::vector< std::string > m_pdf_names; @@ -77,32 +77,25 @@ namespace top { // Small helper class to hold the information we need class PDFSet { - public: + PDFSet() {;}; - PDFSet(){;}; - - explicit PDFSet( const std::string& name ){ - - LHAPDF::mkPDFs( name, pdf_members ); - unsigned int n_members = pdf_members.size(); - event_weights.resize( n_members ); - sum_of_event_weights.resize( n_members ); - + explicit PDFSet(const std::string& name) { + LHAPDF::mkPDFs(name, pdf_members); + unsigned int n_members = pdf_members.size(); + event_weights.resize(n_members); + sum_of_event_weights.resize(n_members); }; - + std::vector< std::unique_ptr<const LHAPDF::PDF> > pdf_members = {}; std::vector< float > event_weights = {}; - + std::vector< float > sum_of_event_weights = {}; - }; std::unordered_map< std::string, PDFSet > m_pdf_sets; - }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PhotonScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PhotonScaleFactorCalculator.h index 87ef808a016e9e6556dfbdc3bcb78e353b5cb34f..2f579ea1eb0cebe7358958b9ed505e9bfc1ed658 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PhotonScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PhotonScaleFactorCalculator.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: PhotonScaleFactorCalculator.h 802226 2017-04-04 16:13:10Z grancagn $ #ifndef TOPCORRECTIONS_PHOTONSCALEFACTORCALCULATOR_H_ #define TOPCORRECTIONS_PHOTONSCALEFACTORCALCULATOR_H_ /** - * @author John Morris <john.morris@cern.ch> - * - * @brief PhotonScaleFactorCalculator - * Calculate all photon scale factors and decorate - * - * $Revision: 802226 $ - * $Date: 2017-04-04 18:13:10 +0200 (Tue, 04 Apr 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief PhotonScaleFactorCalculator + * Calculate all photon scale factors and decorate + * + * $Revision: 802226 $ + * $Date: 2017-04-04 17:13:10 +0100 (Tue, 04 Apr 2017) $ + * + **/ // system include(s): #include <memory> @@ -29,48 +29,42 @@ #include "PATInterfaces/SystematicSet.h" // CP Tool include(s): -#include "PhotonEfficiencyCorrection/IAsgPhotonEfficiencyCorrectionTool.h" +#include "EgammaAnalysisInterfaces/IAsgPhotonEfficiencyCorrectionTool.h" namespace top { // Forward declaration(s): -class TopConfig; - -class PhotonScaleFactorCalculator final : public asg::AsgTool { - public: - explicit PhotonScaleFactorCalculator(const std::string& name); - virtual ~PhotonScaleFactorCalculator() {} - - // Delete Standard constructors - PhotonScaleFactorCalculator(const PhotonScaleFactorCalculator& rhs) = delete; - PhotonScaleFactorCalculator(PhotonScaleFactorCalculator&& rhs) = delete; - PhotonScaleFactorCalculator& operator=(const PhotonScaleFactorCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - CP::SystematicSet m_systNominal; - CP::SystematicSet m_systEffIDUp; - CP::SystematicSet m_systEffIDDown; - CP::SystematicSet m_systEffLowPtIsoUp; - CP::SystematicSet m_systEffLowPtIsoDown; - CP::SystematicSet m_systEffTrkIsoUp; - CP::SystematicSet m_systEffTrkIsoDown; - CP::SystematicSet m_systIsoDDonoffUp; - CP::SystematicSet m_systIsoDDonoffDown; - - ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonEffSF; - ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonIsoSF; - ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonLooseIsoSF; - - bool m_photonIsoSF_exists; - bool m_photonLooseIsoSF_exists; - - std::string m_decor_isoSF; - std::string m_decor_isoSF_loose; - -}; + class TopConfig; + + class PhotonScaleFactorCalculator final: public asg::AsgTool { + public: + explicit PhotonScaleFactorCalculator(const std::string& name); + virtual ~PhotonScaleFactorCalculator() {} + + // Delete Standard constructors + PhotonScaleFactorCalculator(const PhotonScaleFactorCalculator& rhs) = delete; + PhotonScaleFactorCalculator(PhotonScaleFactorCalculator&& rhs) = delete; + PhotonScaleFactorCalculator& operator = (const PhotonScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + private: + std::shared_ptr<top::TopConfig> m_config; + + CP::SystematicSet m_systNominal; + CP::SystematicSet m_systEffIDUp; + CP::SystematicSet m_systEffIDDown; + CP::SystematicSet m_systEffIsoUp; + CP::SystematicSet m_systEffIsoDown; + + ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonEffSF; + ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonIsoSF; + ToolHandle<IAsgPhotonEfficiencyCorrectionTool> m_photonLooseIsoSF; + + bool m_photonIsoSF_exists; + bool m_photonLooseIsoSF_exists; + + std::string m_decor_isoSF; + std::string m_decor_isoSF_loose; + }; } // namespace top #endif // TOPCORRECTIONS_PHOTONSCALEFACTORCALCULATOR_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PileupScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PileupScaleFactorCalculator.h index 2c1c3bb255927653b5f42d81f9cc1472a99e7f99..1e60b01fe5e886b21bcd95c4536e2b6923e7105e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PileupScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/PileupScaleFactorCalculator.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPCORRECTIONS_PILEUPSCALEFACTORCALCULATOR_H #define ANALYSISTOP_TOPCORRECTIONS_PILEUPSCALEFACTORCALCULATOR_H @@ -15,37 +15,35 @@ #include "AsgAnalysisInterfaces/IPileupReweightingTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ +namespace top { + class PileupScaleFactorCalculator final: public asg::AsgTool { + public: + explicit PileupScaleFactorCalculator(const std::string& name); + virtual ~PileupScaleFactorCalculator() {} - class PileupScaleFactorCalculator final : public asg::AsgTool { - public: - explicit PileupScaleFactorCalculator( const std::string& name ); - virtual ~PileupScaleFactorCalculator(){} + // Delete Standard constructors + PileupScaleFactorCalculator(const PileupScaleFactorCalculator& rhs) = delete; + PileupScaleFactorCalculator(PileupScaleFactorCalculator&& rhs) = delete; + PileupScaleFactorCalculator& operator = (const PileupScaleFactorCalculator& rhs) = delete; - // Delete Standard constructors - PileupScaleFactorCalculator(const PileupScaleFactorCalculator& rhs) = delete; - PileupScaleFactorCalculator(PileupScaleFactorCalculator&& rhs) = delete; - PileupScaleFactorCalculator& operator=(const PileupScaleFactorCalculator& rhs) = delete; + StatusCode initialize(); + StatusCode execute(); + private: + std::shared_ptr<top::TopConfig> m_config; - StatusCode initialize(); - StatusCode execute(); + ///Pileup Reweighting Tool + ToolHandle<CP::IPileupReweightingTool> m_pileupReweightingTool; - private: - std::shared_ptr<top::TopConfig> m_config; - - ///Pileup Reweighting Tool - ToolHandle<CP::IPileupReweightingTool> m_pileupReweightingTool; + // systematics + CP::SystematicSet m_systNominal; + CP::SystematicSet m_systDataSFUp; + CP::SystematicSet m_systDataSFDown; - // systematics - CP::SystematicSet m_systNominal; - CP::SystematicSet m_systDataSFUp; - CP::SystematicSet m_systDataSFDown; - - bool m_mu_dependent_PRW = true; + bool m_mu_dependent_PRW = true; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorCalculator.h index 61e388e10789de80476b3d984dc3e22f2828481a..37a71aca316a546920ed28e3da05bbee5c316b3b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorCalculator.h @@ -1,20 +1,20 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef SCALEFACTORCALCULATOR_H_ #define SCALEFACTORCALCULATOR_H_ /** - * @author John Morris <john.morris@cern.ch> - * - * @brief ScaleFactorCalculator - * Scale factors for all objects - * - * $Revision: 766520 $ - * $Date: 2016-08-04 18:39:21 +0200 (Thu, 04 Aug 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief ScaleFactorCalculator + * Scale factors for all objects + * + * $Revision: 766520 $ + * $Date: 2016-08-04 17:39:21 +0100 (Thu, 04 Aug 2016) $ + * + **/ // system include(s): #include <vector> @@ -25,49 +25,56 @@ // PMG Tools #include "PMGTools/PMGSherpa22VJetsWeightTool.h" +#include "PMGAnalysisInterfaces/IPMGTruthWeightTool.h" // Local include(s): #include "TopCorrections/PhotonScaleFactorCalculator.h" #include "TopCorrections/ElectronScaleFactorCalculator.h" +#include "TopCorrections/FwdElectronScaleFactorCalculator.h" #include "TopCorrections/MuonScaleFactorCalculator.h" #include "TopCorrections/TauScaleFactorCalculator.h" #include "TopCorrections/JetScaleFactorCalculator.h" #include "TopCorrections/BTagScaleFactorCalculator.h" #include "TopCorrections/PileupScaleFactorCalculator.h" +#include "TopCorrections/GlobalLeptonTriggerCalculator.h" namespace top { + class TopConfig; -class TopConfig; + class ScaleFactorCalculator final: public asg::AsgTool { + public: + explicit ScaleFactorCalculator(const std::string& name); + virtual ~ScaleFactorCalculator() {} -class ScaleFactorCalculator final : public asg::AsgTool{ - public: - explicit ScaleFactorCalculator( const std::string& name ); - virtual ~ScaleFactorCalculator() {} - - ScaleFactorCalculator(const ScaleFactorCalculator& rhs) = delete; - ScaleFactorCalculator(ScaleFactorCalculator&& rhs) = delete; - ScaleFactorCalculator& operator=(const ScaleFactorCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - StatusCode executePileup(); - float pileupWeight() const; - float mcEventWeight() const; - - private: - std::shared_ptr<top::TopConfig> m_config; - - std::unique_ptr<top::PhotonScaleFactorCalculator> m_photonSF; - std::unique_ptr<top::ElectronScaleFactorCalculator> m_electronSF; - std::unique_ptr<top::MuonScaleFactorCalculator> m_muonSF; - std::unique_ptr<top::TauScaleFactorCalculator> m_tauSF; - std::unique_ptr<top::JetScaleFactorCalculator> m_jetSF; - std::unique_ptr<top::BTagScaleFactorCalculator> m_btagSF; - std::unique_ptr<top::PileupScaleFactorCalculator> m_pileupSF; - ToolHandle<PMGTools::PMGSherpa22VJetsWeightTool> m_sherpa_22_reweight_tool; - -}; + ScaleFactorCalculator(const ScaleFactorCalculator& rhs) = delete; + ScaleFactorCalculator(ScaleFactorCalculator&& rhs) = delete; + ScaleFactorCalculator& operator = (const ScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode initialize_nominal_MC_weight(); // determine what MC weight to use as nominal + StatusCode execute(); + + StatusCode executePileup(); + float pileupWeight() const; + float mcEventWeight() const; + private: + std::shared_ptr<top::TopConfig> m_config; + + std::unique_ptr<top::PhotonScaleFactorCalculator> m_photonSF; + std::unique_ptr<top::ElectronScaleFactorCalculator> m_electronSF; + std::unique_ptr<top::FwdElectronScaleFactorCalculator> m_fwdElectronSF; + std::unique_ptr<top::MuonScaleFactorCalculator> m_muonSF; + std::unique_ptr<top::TauScaleFactorCalculator> m_tauSF; + std::unique_ptr<top::JetScaleFactorCalculator> m_jetSF; + std::unique_ptr<top::BTagScaleFactorCalculator> m_btagSF; + std::unique_ptr<top::PileupScaleFactorCalculator> m_pileupSF; + ToolHandle<PMGTools::PMGSherpa22VJetsWeightTool> m_sherpa_22_reweight_tool; + std::unique_ptr<top::GlobalLeptonTriggerCalculator> m_globalLeptonTriggerSF; + ToolHandle<PMGTools::IPMGTruthWeightTool> m_pmg_truth_weight_tool; + + bool m_sample_multiple_MCweights; + std::string m_nominal_weight_name; + }; } // namespace top #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorRetriever.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorRetriever.h index 362fb0bbf276ee427f0dac42c83e5d46e57a478a..be78919ae6eabe5df51cd9f3467ce39ef8aae599 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorRetriever.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/ScaleFactorRetriever.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #ifndef SCALEFACTORRETRIEVER_H_ #define SCALEFACTORRETRIEVER_H_ @@ -9,6 +9,7 @@ #include <string> #include <vector> +#include "AsgTools/AsgTool.h" #include "xAODEgamma/ElectronContainer.h" #include "xAODEgamma/PhotonContainer.h" #include "xAODMuon/MuonContainer.h" @@ -17,268 +18,463 @@ // Forward declare: namespace top { -class Event; -class TopConfig; + class Event; + class TopConfig; } namespace top { - ///-- Top SF enmu, as CP::SystematicSet won't do the job --/// -enum topSFSyst{nominal = 0, - // Electron Trigger SFs - EL_SF_Trigger_UP, EL_SF_Trigger_DOWN, - // Electron reconstruction SFs - EL_SF_Reco_UP, EL_SF_Reco_DOWN, - // Electron ID SFs - EL_SF_ID_UP, EL_SF_ID_DOWN, - // Electron isolation SFs - EL_SF_Isol_UP, EL_SF_Isol_DOWN, - // Electron Charge flip SFs - EL_SF_ChargeID_UP, EL_SF_ChargeID_DOWN, - EL_SF_ChargeMisID_STAT_UP, EL_SF_ChargeMisID_STAT_DOWN, - EL_SF_ChargeMisID_SYST_UP, EL_SF_ChargeMisID_SYST_DOWN, - // Muon Trigger SFs - MU_SF_Trigger_UP, MU_SF_Trigger_DOWN, - MU_SF_Trigger_STAT_UP, MU_SF_Trigger_STAT_DOWN, - MU_SF_Trigger_SYST_UP, MU_SF_Trigger_SYST_DOWN, - // Muon ID SFs (regular) - MU_SF_ID_STAT_UP, MU_SF_ID_STAT_DOWN, - MU_SF_ID_SYST_UP, MU_SF_ID_SYST_DOWN, - // Muon ID SFs (low pT) - MU_SF_ID_STAT_LOWPT_UP, MU_SF_ID_STAT_LOWPT_DOWN, - MU_SF_ID_SYST_LOWPT_UP, MU_SF_ID_SYST_LOWPT_DOWN, - // Muon isolation SFs - MU_SF_Isol_STAT_UP, MU_SF_Isol_STAT_DOWN, - MU_SF_Isol_SYST_UP, MU_SF_Isol_SYST_DOWN, - // Muon TTVA SFs - MU_SF_TTVA_STAT_UP, MU_SF_TTVA_STAT_DOWN, - MU_SF_TTVA_SYST_UP, MU_SF_TTVA_SYST_DOWN, - // Tau SFs - TAU_SF_ELEOLR_TOTAL_UP, TAU_SF_ELEOLR_TOTAL_DOWN, - TAU_SF_JETID_TOTAL_UP, TAU_SF_JETID_TOTAL_DOWN, - TAU_SF_RECO_TOTAL_UP, TAU_SF_RECO_TOTAL_DOWN, - // Photon SFs - PHOTON_IDSF_UP, PHOTON_IDSF_DOWN, PHOTON_EFF_ISO, - PHOTON_EFF_LOWPTISO_UP, PHOTON_EFF_TRKISO_UP, - PHOTON_EFF_LOWPTISO_DOWN, PHOTON_EFF_TRKISO_DOWN, - // B-tagging SFs - BTAG_SF_EIGEN_B, BTAG_SF_EIGEN_C, - BTAG_SF_EIGEN_LIGHT, - BTAG_SF_NAMED_UP, BTAG_SF_NAMED_DOWN, - // JVT SFs - JVT_UP, JVT_DOWN, - - lastsys -}; - - -enum topSFComp{ALL = 0, TRIGGER, RECO, ID, ISOLATION, CHARGEID, CHARGEMISID, TTVA}; - - -class ScaleFactorRetriever final { - public: - explicit ScaleFactorRetriever(std::shared_ptr<top::TopConfig> config); - virtual ~ScaleFactorRetriever() {} - - // Delete Standard constructors - ScaleFactorRetriever(const ScaleFactorRetriever& rhs) = delete; - ScaleFactorRetriever(ScaleFactorRetriever&& rhs) = delete; - ScaleFactorRetriever& operator=(const ScaleFactorRetriever& rhs) = delete; - - // Pile up SF - static bool hasPileupSF(const top::Event& event); - static float pileupSF(const top::Event& event, int var = 0); - - // Obtain the lepton SF - float leptonSF(const top::Event& event, const top::topSFSyst SFSyst) const; - - // Obtain the trigger SF - float triggerSF(const top::Event& event, const top::topSFSyst SFSyst) const; - - // Obtain the electron SF - float electronSF(const top::Event& event, - const top::topSFSyst SFSyst, - const top::topSFComp SFComp) const; - - // Obtain the muon SF - float muonSF(const top::Event& event, - const top::topSFSyst SFSyst, - const top::topSFComp SFComp) const; - - /** - * @brief: get the tauSF for all taus in event - * @param: event, a top::Event object - * @param: SFSyst, systematic variation enum - */ - float tauSF(const top::Event& event, - const top::topSFSyst SFSyst) const; - - /** - * @brief: get the photonSF for all photons in event - * @param: event, a top::Event object - * @param: SFSyst, systematic variation enum - */ - float photonSF(const top::Event& event, - const top::topSFSyst SFSyst) const; - - /** - * @brief Missing important functionality, but testing... - */ - float btagSF(const top::Event& event, - const top::topSFSyst SFSyst = top::topSFSyst::nominal, - std::string WP = "FixedCutBEff_77", - bool do_trackjets = false, - std::string uncert_name = "") const; - - void btagSF_eigen_vars(const top::Event& event, - const top::topSFSyst SFSyst, - std::vector<float>& btagSF_up, - std::vector<float>& btagSF_down, - std::string WP = "FixedCutBEff_77", - bool do_trackjets = false) const; - - /** - * - * JVT Efficiency SFs - * @brief: Get the total JVT SF by taking the product of SFs for all jets - * - * @param: event, a top::Event object - * @param: SFSyst, systematic variation enum - * - * @return: prod_jvt, the product of the jvt SFs for selected jets - * - **/ - float jvtSF(const top::Event& event, - const top::topSFSyst SFsyst) const; - - - /** - * @brief Print all the SF values to cout - */ - void print(const top::Event& event); - - float electronSF_Reco(const xAOD::Electron& x, - const top::topSFSyst SFSyst) const; + enum topSFSyst { + nominal = 0, + // Electron Trigger SFs + EL_SF_Trigger_UP, EL_SF_Trigger_DOWN, + // Electron reconstruction SFs + EL_SF_Reco_UP, EL_SF_Reco_DOWN, + // Electron ID SFs + EL_SF_ID_UP, EL_SF_ID_DOWN, + // Electron isolation SFs + EL_SF_Isol_UP, EL_SF_Isol_DOWN, + // Electron Charge flip SFs + EL_SF_ChargeID_UP, EL_SF_ChargeID_DOWN, + EL_SF_ChargeMisID_STAT_UP, EL_SF_ChargeMisID_STAT_DOWN, + EL_SF_ChargeMisID_SYST_UP, EL_SF_ChargeMisID_SYST_DOWN, + // Muon Trigger SFs + MU_SF_Trigger_UP, MU_SF_Trigger_DOWN, + MU_SF_Trigger_STAT_UP, MU_SF_Trigger_STAT_DOWN, + MU_SF_Trigger_SYST_UP, MU_SF_Trigger_SYST_DOWN, + // Muon ID SFs (regular) + MU_SF_ID_STAT_UP, MU_SF_ID_STAT_DOWN, + MU_SF_ID_SYST_UP, MU_SF_ID_SYST_DOWN, + // Muon ID SFs (low pT) + MU_SF_ID_STAT_LOWPT_UP, MU_SF_ID_STAT_LOWPT_DOWN, + MU_SF_ID_SYST_LOWPT_UP, MU_SF_ID_SYST_LOWPT_DOWN, + // Muon isolation SFs + MU_SF_Isol_STAT_UP, MU_SF_Isol_STAT_DOWN, + MU_SF_Isol_SYST_UP, MU_SF_Isol_SYST_DOWN, + // Muon TTVA SFs + MU_SF_TTVA_STAT_UP, MU_SF_TTVA_STAT_DOWN, + MU_SF_TTVA_SYST_UP, MU_SF_TTVA_SYST_DOWN, + + TAU_SF_NOMINAL, + // Tau EleOLR SFs + TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1up, TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1down, + TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1up, TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1down, + TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1up, TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1down, + // Tau RNNID SFs + TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1up, TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1down, + TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1up, TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1down, + TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1up, TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1down, + TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1up, TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1down, + TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1up, TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1down, + TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1up, TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1down, + TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1up, TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1down, + TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1up, TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1down, + TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1up, TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1down, + TAUS_TRUEHADTAU_EFF_RNNID_SYST__1up, TAUS_TRUEHADTAU_EFF_RNNID_SYST__1down, + + // Tau BDTID SFs + TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1up, TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1down, + TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1up, TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1down, + TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1up, TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1down, + TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1up, TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1down, + TAUS_TRUEHADTAU_EFF_JETID_SYST__1up, + TAUS_TRUEHADTAU_EFF_JETID_SYST__1down, + TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1up, + TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1down, + // Tau Reconstruction SFs + TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1up, TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1down, + TAU_SF_END, + // Photon SFs + PHOTON_IDSF_UP, PHOTON_IDSF_DOWN, + PHOTON_EFF_ISO_UP, PHOTON_EFF_ISO_DOWN, + // B-tagging SFs + BTAG_SF_EIGEN_B, BTAG_SF_EIGEN_C, + BTAG_SF_EIGEN_LIGHT, + BTAG_SF_NAMED_UP, BTAG_SF_NAMED_DOWN, + // JVT SFs + JVT_UP, JVT_DOWN, + // fJVT SFs + FJVT_UP, FJVT_DOWN, + // FWD Electron ID SFs + FWDEL_SF_ID_UP, FWDEL_SF_ID_DOWN, + + lastsys + }; + const std::map<topSFSyst, TString> tauSF_name = { + {TAU_SF_NOMINAL, "TAU_SF_NOMINAL"}, + {TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1up, "TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1up"}, + {TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1down, "TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1down"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1up, "TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1up"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1down, "TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1down"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1up, "TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1up"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1down, "TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1down"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1up, "TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1up"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1down, "TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1down"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1up, "TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1up"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1down, "TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1down"}, + {TAUS_TRUEHADTAU_EFF_JETID_SYST__1up, "TAUS_TRUEHADTAU_EFF_JETID_SYST__1up"}, + {TAUS_TRUEHADTAU_EFF_JETID_SYST__1down, "TAUS_TRUEHADTAU_EFF_JETID_SYST__1down"}, + {TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1up, "TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1up"}, + {TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1down, "TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1up, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1down, + "TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1up, "TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1down, "TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1down"}, + {TAUS_TRUEHADTAU_EFF_RNNID_SYST__1up, "TAUS_TRUEHADTAU_EFF_RNNID_SYST__1up"}, + {TAUS_TRUEHADTAU_EFF_RNNID_SYST__1down, "TAUS_TRUEHADTAU_EFF_RNNID_SYST__1down"}, + {TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1up, "TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1up"}, + {TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1down, "TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1down"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1up, "TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1up"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1down, "TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1down"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1up, "TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1up"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1down, "TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1down"}, + }; + + const std::map<topSFSyst, TString> tauSF_alias = { + {TAU_SF_NOMINAL, "TAU_SF_NOMINAL"}, + {TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1up, "EFF_RECO_TOTAL_UP"}, + {TAUS_TRUEHADTAU_EFF_RECO_TOTAL__1down, "EFF_RECO_TOTAL_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1up, "EFF_RNNID_1PRONGSTATSYSTPT2025_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2025__1down, "EFF_RNNID_1PRONGSTATSYSTPT2025_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1up, "EFF_RNNID_1PRONGSTATSYSTPT2530_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT2530__1down, "EFF_RNNID_1PRONGSTATSYSTPT2530_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1up, "EFF_RNNID_1PRONGSTATSYSTPT3040_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPT3040__1down, "EFF_RNNID_1PRONGSTATSYSTPT3040_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1up, "EFF_RNNID_1PRONGSTATSYSTPTGE40_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_1PRONGSTATSYSTPTGE40__1down, "EFF_RNNID_1PRONGSTATSYSTPTGE40_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1up, "EFF_RNNID_1PRONGSTATSYSTPT2025_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2025__1down, "EFF_RNNID_3PRONGSTATSYSTPT2025_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1up, "EFF_RNNID_3PRONGSTATSYSTPT2530_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT2530__1down, "EFF_RNNID_3PRONGSTATSYSTPT2530_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1up, "EFF_RNNID_3PRONGSTATSYSTPT3040_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPT3040__1down, "EFF_RNNID_3PRONGSTATSYSTPT3040_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1up, "EFF_RNNID_3PRONGSTATSYSTPTGE40_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_3PRONGSTATSYSTPTGE40__1down, "EFF_RNNID_3PRONGSTATSYSTPTGE40_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1up, "EFF_RNNID_HIGHPT_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_HIGHPT__1down, "EFF_RNNID_HIGHPT_DOWN"}, + {TAUS_TRUEHADTAU_EFF_RNNID_SYST__1up, "EFF_RNNID_SYST_UP"}, + {TAUS_TRUEHADTAU_EFF_RNNID_SYST__1down, "EFF_RNNID_SYST_DOWN"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1up, "EFF_JETID_1PETAHIGH_UP"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETAHIGH__1down, "EFF_JETID_1PETAHIGH_DOWN"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1up, "EFF_JETID_1PETALOW_UP"}, + {TAUS_TRUEHADTAU_EFF_JETID_1PRONGSTATSYSTETALOW__1down, "EFF_JETID_1PETALOW_DOWN"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1up, "EFF_JETID_3PETAHIGH_UP"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETAHIGH__1down, "EFF_JETID_3PETAHIGH_DOWN"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1up, "EFF_JETID_3PETALOW_UP"}, + {TAUS_TRUEHADTAU_EFF_JETID_3PRONGSTATSYSTETALOW__1down, "EFF_JETID_3PETALOW_DOWN"}, + {TAUS_TRUEHADTAU_EFF_JETID_SYST__1up, "EFF_JETID_SYST_UP"}, + {TAUS_TRUEHADTAU_EFF_JETID_SYST__1down, "EFF_JETID_SYST_DOWN"}, + {TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1up, "EFF_JETID_HIGHPT_UP"}, + {TAUS_TRUEHADTAU_EFF_JETID_HIGHPT__1down, "EFF_JETID_HIGHPT_DOWN"}, + {TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1up, "EFF_ELEOLR_TOTAL_UP"}, + {TAUS_TRUEHADTAU_EFF_ELEOLR_TOTAL__1down, "EFF_ELEOLR_TOTAL_DOWN"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1up, "ELE_EFF_ELEOLR_STAT_UP"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_STAT__1down, "ELE_EFF_ELEOLR_STAT_DOWN"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1up, "ELE_EFF_ELEOLR_SYST_UP"}, + {TAUS_TRUEELECTRON_EFF_ELEOLR_SYST__1down, "ELE_EFF_ELEOLR_SYST_DOWN"}, + }; + + + enum topSFComp { + ALL = 0, TRIGGER, RECO, ID, ISOLATION, CHARGEID, CHARGEMISID, TTVA + }; + + class ScaleFactorRetriever final: public asg::AsgTool { + // Specify that we will overload print with top::Event later on + using asg::AsgTool::print; + public: + explicit ScaleFactorRetriever(const std::string& name); + virtual ~ScaleFactorRetriever() {} + + // Delete Standard constructors + ScaleFactorRetriever(const ScaleFactorRetriever& rhs) = delete; + ScaleFactorRetriever(ScaleFactorRetriever&& rhs) = delete; + ScaleFactorRetriever& operator = (const ScaleFactorRetriever& rhs) = delete; + + StatusCode initialize(); + + // Pile up SF + static bool hasPileupSF(const top::Event& event); + static float pileupSF(const top::Event& event, int var = 0); + + // Obtain the lepton SF + float leptonSF(const top::Event& event, const top::topSFSyst SFSyst) const; + + // Obtain the trigger SF + float triggerSF(const top::Event& event, const top::topSFSyst SFSyst) const; + + // Obtain trigger SF via global tool + float globalTriggerSF(const top::Event& event, const top::topSFSyst SFSyst) const; + + // Obtain the trigger SF via approximate formula + float oldTriggerSF(const top::Event& event, const top::topSFSyst SFSyst) const; + + // Obtain the electron SF + float electronSF(const top::Event& event, + const top::topSFSyst SFSyst, + const top::topSFComp SFComp) const; + + //get vector of systematic variations of electron SFs, var=1 for up, var=-1 for down + std::vector<float> electronSFSystVariationVector(const top::Event& event, const top::topSFComp SFComp, int var = 1) const; + + // Obtain the fwd electron SF + float fwdElectronSF(const top::Event& event, + const top::topSFSyst SFSyst, + const top::topSFComp SFComp = top::topSFComp::ALL) const; - float electronSF_Trigger(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const; + // Obtain the muon SF + float muonSF(const top::Event& event, + const top::topSFSyst SFSyst, + const top::topSFComp SFComp) const; - float electronEff_Trigger(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const ; + // Obtain the soft muon SF + float softmuonSF(const top::Event& event, + const top::topSFSyst SFSyst, + const top::topSFComp SFComp) const; - float electronSF_ID(const xAOD::Electron& x, - const top::topSFSyst SFSyst, - bool isLoose) const; + /** + * @brief: get the tauSF for all taus in event + * @param: event, a top::Event object + * @param: SFSyst, systematic variation enum + */ + float tauSF(const top::Event& event, + const top::topSFSyst SFSyst) const; + + /** + * @brief: get the photonSF for all photons in event + * @param: event, a top::Event object + * @param: SFSyst, systematic variation enum + */ + float photonSF(const top::Event& event, + const top::topSFSyst SFSyst) const; - float electronSF_Isol(const xAOD::Electron& x, + /** + * @brief Missing important functionality, but testing... + */ + float btagSF(const top::Event& event, + const top::topSFSyst SFSyst = top::topSFSyst::nominal, + std::string WP = "FixedCutBEff_77", + bool do_trackjets = false, + std::string uncert_name = "") const; + + void btagSF_eigen_vars(const top::Event& event, + const top::topSFSyst SFSyst, + std::vector<float>& btagSF_up, + std::vector<float>& btagSF_down, + std::string WP = "FixedCutBEff_77", + bool do_trackjets = false) const; + + /** + * + * JVT Efficiency SFs + * @brief: Get the total JVT SF by taking the product of SFs for all jets + * + * @param: event, a top::Event object + * @param: SFSyst, systematic variation enum + * + * @return: prod_jvt, the product of the jvt SFs for selected jets + * + **/ + float jvtSF(const top::Event& event, + const top::topSFSyst SFsyst) const; + + /** + * + * fJVT Efficiency SFs + * @brief: Get the total fJVT SF by taking the product of SFs for all jets, as of AnalysisBase124 by default central jets get a SF value of 1 + * + * @param: event, a top::Event object + * @param: SFSyst, systematic variation enum + * + * @return: prod_fjvt, the product of the fjvt SFs for selected jets + * + **/ + float fjvtSF(const top::Event& event, + const top::topSFSyst SFsyst) const; + + /** + * @brief Print all the SF values to msg stream + */ + void print(const top::Event& event); + + float electronSF_Reco(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const; + + float electronSF_Trigger(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const; + + float electronEff_Trigger(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const; + + float electronSF_ID(const xAOD::Electron& x, const top::topSFSyst SFSyst, bool isLoose) const; - float electronSF_ChargeID(const xAOD::Electron& x, - const top::topSFSyst SFSyst, - bool isLoose) const; + float electronSF_Isol(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const; + + float electronSF_ChargeID(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const; - float electronSF_ChargeMisID(const xAOD::Electron& x, - const top::topSFSyst SFSyst, - bool isLoose) const; + float electronSF_ChargeMisID(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonSF_Trigger(const xAOD::Muon& x, - const top::topSFSyst SFSyst, - bool isLoose) const; + float fwdElectronSF_ID(const xAOD::Electron& x, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonEff_Trigger(const xAOD::Muon& x, - const top::topSFSyst SFSyst, - bool isLoose) const; + float muonSF_Trigger(const xAOD::Muon& x, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonSF_ID(const xAOD::Muon& x, - const top::topSFSyst SFSyst, - bool isLoose) const; + float muonEff_Trigger(const xAOD::Muon& x, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonSF_Isol(const xAOD::Muon& x, + float muonSF_ID(const xAOD::Muon& x, const top::topSFSyst SFSyst, bool isLoose) const; - float muonSF_TTVA(const xAOD::Muon& x, - const top::topSFSyst SFSyst) const; - - /** - * @brief: get the tauSF for a single tau - * @param: x, an xAOD::TauJet object - * @param: SFSyst, systematic variation enum - * @param: whether you want the SF for loose event or not - */ - float tauSF(const xAOD::TauJet& x, - const top::topSFSyst SFSyst, - bool isLoose) const; - - /** - * @brief: get the photonSF for a single photon - * @param: x, an xAOD::Photon object - * @param: SFSyst, systematic variation enum - * @param: whether you want the SF for loose event or not - */ - float photonSF(const xAOD::Photon& x, - const top::topSFSyst SFSyst, - bool isLoose) const; - - float photonSF_Isol(const xAOD::Photon& x, + float muonSF_Isol(const xAOD::Muon& x, const top::topSFSyst SFSyst, bool isLoose) const; - private: - float electronSF_Trigger(const xAOD::Electron& x, - const std::string& id, - const top::topSFSyst SFSyst) const; + float muonSF_TTVA(const xAOD::Muon& x, + const top::topSFSyst SFSyst) const; - float electronEff_Trigger(const xAOD::Electron& x, - const std::string& id, - const top::topSFSyst SFSyst) const; + float softmuonSF_ID(const xAOD::Muon& x, + const top::topSFSyst SFSyst) const; - float electronSF_ID(const xAOD::Electron& x, - const std::string& id, - const top::topSFSyst SFSyst) const; + /** + * @brief: get the tauSF for a single tau + * @param: x, an xAOD::TauJet object + * @param: SFSyst, systematic variation enum + * @param: whether you want the SF for loose event or not + */ + float tauSF(const xAOD::TauJet& x, + const top::topSFSyst SFSyst, + bool isLoose) const; - float electronSF_Isol(const xAOD::Electron& x, + /** + * @brief: get the photonSF for a single photon + * @param: x, an xAOD::Photon object + * @param: SFSyst, systematic variation enum + */ + float photonSF_Reco(const xAOD::Photon& x, + const top::topSFSyst SFSyst) const; + + float photonSF_Isol(const xAOD::Photon& x, + const top::topSFSyst SFSyst, + bool isLoose) const; + private: + float electronSF_Trigger(const xAOD::Electron& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; + + float electronEff_Trigger(const xAOD::Electron& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; + + float electronSF_ID(const xAOD::Electron& x, const std::string& id, - const top::topSFSyst SFSyst) const; + const top::topSFSyst SFSyst, + bool isLoose) const; - float electronSF_ChargeID(const xAOD::Electron& x, - const std::string& id, const std::string& iso, - const top::topSFSyst SFSyst) const; + float electronSF_Isol(const xAOD::Electron& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; - float electronSF_ChargeMisID(const xAOD::Electron& x, - const std::string& id, const std::string& iso, - const top::topSFSyst SFSyst) const; + float electronSF_ChargeID(const xAOD::Electron& x, + const std::string& id, const std::string& iso, + const top::topSFSyst SFSyst, + bool isLoose) const; - float photonSF_Isol(const xAOD::Photon& x, - const std::string& iso, - const top::topSFSyst SFSyst) const; + float electronSF_ChargeMisID(const xAOD::Electron& x, + const std::string& id, const std::string& iso, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonSF_Trigger(const xAOD::Muon& x, - const std::string& id, - const top::topSFSyst SFSyst) const; - float muonEff_Trigger(const xAOD::Muon& x, - const std::string& id, - const top::topSFSyst SFSyst) const; + float fwdElectronSF_ID(const xAOD::Electron& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonSF_ID(const xAOD::Muon& x, - const std::string& id, - const top::topSFSyst SFSyst) const; + float photonSF_Isol(const xAOD::Photon& x, + const std::string& iso, + const top::topSFSyst SFSyst, + bool isLoose) const; - float muonSF_Isol(const xAOD::Muon& x, - const std::string& iso, - const top::topSFSyst SFSyst) const; + float muonSF_Trigger(const xAOD::Muon& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; + float muonEff_Trigger(const xAOD::Muon& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; + + float muonSF_ID(const xAOD::Muon& x, + const std::string& id, + const top::topSFSyst SFSyst, + bool isLoose) const; - float m_event_el_trigger; + float softmuonSF_ID(const xAOD::Muon& x, + const std::string& id, + const top::topSFSyst SFSyst) const; - // List of triggers to 'or' together for each event. - // If any one passes, the event passes - std::vector<std::string> m_electronTriggers; - std::vector<std::string> m_muonTriggers; - // Do we need to add tau triggers? + float muonSF_Isol(const xAOD::Muon& x, + const std::string& iso, + const top::topSFSyst SFSyst, + bool isLoose) const; - // Configuration - std::shared_ptr<top::TopConfig> m_config; -}; + // List of triggers to 'or' together for each event. + // If any one passes, the event passes + std::vector<std::string> m_electronTriggers_Tight; + std::vector<std::string> m_muonTriggers_Tight; + std::vector<std::string> m_electronTriggers_Loose; + std::vector<std::string> m_muonTriggers_Loose; + // Do we need to add tau triggers? + + // Configuration + std::shared_ptr<top::TopConfig> m_config; + bool m_preferGlobalTriggerSF; + }; } // namespace top #endif // SCALEFACTORRETRIEVER_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TauScaleFactorCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TauScaleFactorCalculator.h index abaff879c46cb391119ec239ffdb2322d90d153c..5181619c290d0159d030ccb1e6413b1107197b6e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TauScaleFactorCalculator.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TauScaleFactorCalculator.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: TauScaleFactorCalculator.h 718402 2016-01-19 11:58:25Z tneep $ #ifndef ANALYSISTOP_TOPCORRECTIONS_TAUSCALEFACTORCALCULATOR_H #define ANALYSISTOP_TOPCORRECTIONS_TAUSCALEFACTORCALCULATOR_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief TauScaleFactorCalculator - * Calculate all tau scale factors and decorate - * - * $Revision: 718402 $ - * $Date: 2016-01-19 12:58:25 +0100 (Tue, 19 Jan 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief TauScaleFactorCalculator + * Calculate all tau scale factors and decorate + * + * $Revision: 718402 $ + * $Date: 2016-01-19 11:58:25 +0000 (Tue, 19 Jan 2016) $ + * + **/ // system include(s): #include <memory> @@ -34,32 +34,30 @@ // Forward declaration(s): namespace top { -class TopConfig; + class TopConfig; } namespace top { - -class TauScaleFactorCalculator final : public asg::AsgTool { - public: - explicit TauScaleFactorCalculator(const std::string& name); - virtual ~TauScaleFactorCalculator() {} - - // Delete Standard constructors - TauScaleFactorCalculator(const TauScaleFactorCalculator& rhs) = delete; - TauScaleFactorCalculator(TauScaleFactorCalculator&& rhs) = delete; - TauScaleFactorCalculator& operator=(const TauScaleFactorCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrTool; - ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrToolLoose; - - CP::SystematicSet m_systNominal; - std::map< std::string, CP::SystematicSet > m_syst_map; -}; + class TauScaleFactorCalculator final: public asg::AsgTool { + public: + explicit TauScaleFactorCalculator(const std::string& name); + virtual ~TauScaleFactorCalculator() {} + + // Delete Standard constructors + TauScaleFactorCalculator(const TauScaleFactorCalculator& rhs) = delete; + TauScaleFactorCalculator(TauScaleFactorCalculator&& rhs) = delete; + TauScaleFactorCalculator& operator = (const TauScaleFactorCalculator& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(); + private: + std::shared_ptr<top::TopConfig> m_config; + + ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrTool; + ToolHandle<TauAnalysisTools::ITauEfficiencyCorrectionsTool> m_tauEffCorrToolLoose; + + CP::SystematicSet m_systNominal; + std::map< std::string, CP::SystematicSet > m_syst_map; + }; } // namespace top #endif // ANALYSISTOP_TOPCORRECTIONS_TAUSCALEFACTORCALCULATOR_H diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TopCorrectionsTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TopCorrectionsTools.h new file mode 100644 index 0000000000000000000000000000000000000000..e42a1f12023b543800a5125f0b2f8f65800e9fd9 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopCorrections/TopCorrections/TopCorrectionsTools.h @@ -0,0 +1,21 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TOPTOPCORRECTIONTOOLS_H__ +#define TOPTOPCORRECTIONTOOLS_H__ + +#include "TopConfiguration/TopConfig.h" +#include <string> + +namespace top { + // Functions useful for b-tagging systematic name mapping + std::string bTagNamedSystCheck(std::shared_ptr<top::TopConfig>, + const std::string&, + const std::string&, + const bool, + const bool); + std::string betterBtagNamedSyst(const std::string&); +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/CMakeLists.txt index ef2ff4ab1debfb6b4f2f9c78d2806048afa0c2b2..80a5a47fc21bfa39a700045d983be537cb776657 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopEvent ) @@ -17,17 +16,25 @@ atlas_depends_on_subdirs( PUBLIC xAODTau xAODMissingET xAODTracking + FourMomUtils TopConfiguration - TopPartons ) + TopPartons + JetAnalysisInterfaces + JetSubStructureMomentTools + JetSubStructureUtils + JetReclustering ) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) +# Need fast jet for the RC jet substructure code +find_package( FastJet COMPONENTS fastjetplugins fastjettools ) +find_package( FastJetContrib COMPONENTS EnergyCorrelator Nsubjettiness ) + # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopEvent _cintDictSource - ROOT_HEADERS TopEvent/SystematicEvent.h TopEvent/KLFitterResult.h - TopEvent/PseudoTopResult.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopEvent Root/*.cxx Root/*.h Root/*.icc @@ -47,8 +54,15 @@ atlas_add_library( TopEvent Root/*.cxx Root/*.h Root/*.icc xAODTau xAODMissingET xAODTracking + FourMomUtils TopConfiguration TopPartons + JetAnalysisInterfacesLib + JetSubStructureMomentToolsLib + JetSubStructureUtils + JetReclusteringLib + ${FASTJET_LIBRARIES} + ${FASTJETCONTRIB_LIBRARIES} ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/Event.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/Event.cxx index 64ed39fdfb138bbd73fc7f508c6819265d938072..d5832af222dc3013dc1e86016967217a33cfa8ee 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/Event.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/Event.cxx @@ -1,66 +1,88 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEvent/Event.h" #include "TopEvent/EventTools.h" #include "xAODEventInfo/EventInfo.h" #include "xAODEgamma/ElectronContainer.h" +#include "xAODEgamma/ElectronContainerFwd.h" #include "xAODMuon/MuonContainer.h" #include "xAODJet/JetContainer.h" #include "xAODTau/TauJetContainer.h" #include "xAODMissingET/MissingETContainer.h" +#include "xAODTracking/TrackParticleContainer.h" #include "xAODTruth/TruthParticleContainer.h" #include "xAODTruth/TruthVertex.h" #include "xAODCore/ShallowCopy.h" #include <iomanip> -std::ostream& operator<<(std::ostream& os, const TLorentzVector& v) { - os << "TLorentzVector" << - " pt=" << v.Pt() << - " eta " << v.Eta() << - " phi " << v.Phi() << - " m " << v.M(); +std::ostream & operator << (std::ostream& os, const TLorentzVector& v) { + os << "TLorentzVector" << + " pt=" << v.Pt() << + " eta " << v.Eta() << + " phi " << v.Phi() << + " m " << v.M(); - return os; + return os; } -std::ostream& operator<<(std::ostream& os, const top::Event& event) { - +std::ostream& operator << (std::ostream& os, const top::Event& event) { // os << *event.m_info << "\n"; - os << "Electrons: " << event.m_electrons.size() << "\n"; - for (const auto* const elPtr : event.m_electrons) - os << " " << *elPtr << "\n"; - - os << "Muons: " << event.m_muons.size() << "\n"; - for (const auto* const muPtr : event.m_muons) - os << " " << *muPtr << "\n"; - - os << "Jets: " << event.m_jets.size() << "\n"; - for (const auto* const jetPtr : event.m_jets) - os << " " << *jetPtr << "\n"; - - os << "Large jets: " << event.m_largeJets.size() << "\n"; - for (const auto* const jetPtr : event.m_largeJets) - os << " " << *jetPtr << "\n"; - - os << "Track jets: " << event.m_trackJets.size() << "\n"; - for (const auto* const jetPtr : event.m_trackJets) - os << " " << *jetPtr << "\n"; - - os << "Taus: " << event.m_tauJets.size() << "\n"; - for (const auto* const tauPtr : event.m_tauJets) - os << " " << *tauPtr << "\n"; - - os << *event.m_met; - return os; + os << "Electrons: " << event.m_electrons.size() << "\n"; + for (const auto* const elPtr : event.m_electrons) { + os << " " << *elPtr << "\n"; + } + os << "FwdElectrons: " << event.m_fwdElectrons.size() << "\n"; + for (const auto* const elPtr : event.m_fwdElectrons) { + os << " " << *elPtr << "\n"; + } + os << "Muons: " << event.m_muons.size() << "\n"; + for (const auto* const muPtr : event.m_muons) { + os << " " << *muPtr << "\n"; + } + os << "Soft Muons: " << event.m_softmuons.size() << "\n"; + for (const auto* const muPtr : event.m_softmuons) { + os << " " << *muPtr << "\n"; + } + os << "Jets: " << event.m_jets.size() << "\n"; + for (const auto* const jetPtr : event.m_jets) { + os << " " << *jetPtr << "\n"; + } + os << "Fail-JVT jets: " << event.m_failJvt_jets.size() << "\n"; + for (const auto* const jetPtr : event.m_failJvt_jets) { + os << " " << *jetPtr << "\n"; + } + os << "Fail-FJVT jets: " << event.m_failFJvt_jets.size() << "\n"; + for (const auto* const jetPtr : event.m_failFJvt_jets) { + os << " " << *jetPtr << "\n"; + } + os << "Large jets: " << event.m_largeJets.size() << "\n"; + for (const auto* const jetPtr : event.m_largeJets) { + os << " " << *jetPtr << "\n"; + } + os << "Track jets: " << event.m_trackJets.size() << "\n"; + for (const auto* const jetPtr : event.m_trackJets) { + os << " " << *jetPtr << "\n"; + } + os << "Tracks: " << event.m_tracks.size() << "\n"; + for (const auto* const trackPtr : event.m_tracks) { + os << " " << *trackPtr << "\n"; + } + os << "Taus: " << event.m_tauJets.size() << "\n"; + for (const auto* const tauPtr : event.m_tauJets) { + os << " " << *tauPtr << "\n"; + } + os << "MET: " << *event.m_met << "\n"; + + return os; } /* -std::ostream& operator<<(std::ostream& os, const xAOD::EventInfo& ei) { + std::ostream& operator<<(std::ostream& os, const xAOD::EventInfo& ei) { os << "EventInfo" << " isSimulation " << std::boolalpha << ei.eventType(xAOD::EventInfo::IS_SIMULATION) << " runNumber " << ei.runNumber() << @@ -73,73 +95,83 @@ std::ostream& operator<<(std::ostream& os, const xAOD::EventInfo& ei) { } return os; -}*/ + }*/ + +std::ostream& operator << (std::ostream& os, const xAOD::Electron& el) { + os << "Electron" << + " author " << el.author() << + " pt " << el.pt() << + " eta " << el.eta() << + " phi " << el.phi() << + " m " << el.m() << + " charge " << el.charge(); + + return os; +} -std::ostream& operator<<(std::ostream& os, const xAOD::Electron& el) { - os << "Electron" << - " author " << el.author() << - " pt " << el.pt() << - " eta " << el.eta() << - " phi " << el.phi() << - " m " << el.m() << - " charge " << el.charge(); +std::ostream& operator << (std::ostream& os, const xAOD::Muon& mu) { + os << "Muon" << + " author " << mu.author() << + " pt " << mu.pt() << + " eta " << mu.eta() << + " phi " << mu.phi() << + " m " << mu.m() << + " charge " << mu.charge(); - return os; + return os; } -std::ostream& operator<<(std::ostream& os, const xAOD::Muon& mu) { - os << "Muon" << - " author " << mu.author() << - " pt " << mu.pt() << - " eta " << mu.eta() << - " phi " << mu.phi() << - " m " << mu.m() << - " charge " << mu.charge(); +std::ostream& operator << (std::ostream& os, const xAOD::Jet& jet) { + os << "Jet" << + " pt " << jet.pt() << + " eta " << jet.eta() << + " phi " << jet.phi() << + " m " << jet.m(); - return os; + return os; } -std::ostream& operator<<(std::ostream& os, const xAOD::Jet& jet) { - os << "Jet" << - " pt " << jet.pt() << - " eta " << jet.eta() << - " phi " << jet.phi() << - " m " << jet.m(); +std::ostream& operator << (std::ostream& os, const xAOD::TauJet& tau) { + os << "TauJet" << + " pt " << tau.pt() << + " eta " << tau.eta() << + " phi " << tau.phi() << + " m " << tau.m() << + " charge " << tau.charge(); - return os; + return os; } -std::ostream& operator<<(std::ostream& os, const xAOD::TauJet& tau) { - os << "TauJet" << - " pt " << tau.pt() << - " eta " << tau.eta() << - " phi " << tau.phi() << - " m " << tau.m() << - " charge " << tau.charge(); +std::ostream& operator << (std::ostream& os, const xAOD::TrackParticle& track) { + os << "Track" << + " pt " << track.pt() << + " eta " << track.eta() << + " phi " << track.phi() << + " m " << track.m(); - return os; + return os; } -std::ostream& operator<<(std::ostream& os, const xAOD::TruthParticle& truth) { - const unsigned int w = 10; - os << "TruthParticle" << - " pdg " << std::setw(w) << truth.pdgId() << - " status " << std::setw(w) << truth.status() << - " pt " << std::setw(w) << truth.pt() << - " eta " << std::setw(w) << truth.eta() << - " phi " << std::setw(w) << truth.phi() << - " e " << std::setw(w) << truth.e() << - " m " << std::setw(w) << truth.p4().M(); - return os; -} +std::ostream& operator << (std::ostream& os, const xAOD::TruthParticle& truth) { + const unsigned int w = 10; -std::ostream& operator<<(std::ostream& os, const xAOD::MissingET& met) { - os << "MET" << - " et " << met.met() << - " phi " << met.phi() << "\n"; + os << "TruthParticle" << + " pdg " << std::setw(w) << truth.pdgId() << + " status " << std::setw(w) << truth.status() << + " pt " << std::setw(w) << truth.pt() << + " eta " << std::setw(w) << truth.eta() << + " phi " << std::setw(w) << truth.phi() << + " e " << std::setw(w) << truth.e() << + " m " << std::setw(w) << truth.p4().M(); - return os; + return os; } +std::ostream& operator << (std::ostream& os, const xAOD::MissingET& met) { + os << "MET" << + " et " << met.met() << + " phi " << met.phi() << "\n"; + return os; +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/EventTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/EventTools.cxx index 97443dcd43a966dcdf3853a7c4a0499b08ac7ac7..c43460f98efe80a6121b6b8c30ba81c983550502 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/EventTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/EventTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEvent/EventTools.h" #include "TopEvent/Event.h" @@ -9,51 +9,65 @@ #include "xAODBase/IParticle.h" -namespace top { +#include "TRandom3.h" -void check(bool thingToCheck, const std::string& usefulFailureMessage) { +namespace top { + void check(bool thingToCheck, const std::string& usefulFailureMessage) { if (!thingToCheck) { - std::cout << usefulFailureMessage << "\n"; - exit(1); + throw std::runtime_error("top::check: " + usefulFailureMessage); } -} + } -double deltaR(const xAOD::IParticle& p1, const xAOD::IParticle& p2) { + double deltaR(const xAOD::IParticle& p1, const xAOD::IParticle& p2) { return p1.p4().DeltaR(p2.p4()); -} + } -double deltaPhi(const xAOD::IParticle& p1, const xAOD::IParticle& p2) { + double deltaPhi(const xAOD::IParticle& p1, const xAOD::IParticle& p2) { return p1.p4().DeltaPhi(p2.p4()); -} + } -double mwt(const xAOD::IParticle& lepton, const xAOD::MissingET& met) { + double mwt(const xAOD::IParticle& lepton, const xAOD::MissingET& met) { return sqrt(2. * lepton.pt() * met.met() * (1. - cos(lepton.phi() - met.phi()))); -} + } -double ht(const top::Event& event) { + double ht(const top::Event& event) { double sumHt = 0.; + for (const auto el : event.m_electrons) - sumHt += el->pt(); + sumHt += el->pt(); for (const auto mu : event.m_muons) - sumHt += mu->pt(); + sumHt += mu->pt(); for (const auto jet : event.m_jets) - sumHt += jet->pt(); + sumHt += jet->pt(); return sumHt; -} + } -double invariantMass(const xAOD::IParticle& p1, const xAOD::IParticle& p2) { + double invariantMass(const xAOD::IParticle& p1, const xAOD::IParticle& p2) { return (p1.p4() + p2.p4()).M(); -} + } -bool isSimulation(const top::Event& event) { + bool isSimulation(const top::Event& event) { return event.m_info->eventType(xAOD::EventInfo::IS_SIMULATION); -} + } -bool descendingPtSorter(const xAOD::IParticle* p1, const xAOD::IParticle* p2) { + bool descendingPtSorter(const xAOD::IParticle* p1, const xAOD::IParticle* p2) { return CxxUtils::fpcompare::greater(p1->pt(), p2->pt()); -} + } + + std::vector<int> calculateBootstrapWeights(int nreplicas, int eventNumber, int mcChannelNumber) { + TRandom3 rand; + unsigned long long seed = eventNumber + 100 * mcChannelNumber; // Set the seed to be unique for this event, but + // reproducible for systematics + rand.SetSeed(seed); + std::vector<int> weight_poisson(nreplicas, 0); // Initialise vector of length nreplicas, to all have weight of 0 + for (int i = 0; i < nreplicas; i++) { + weight_poisson.at(i) = rand.PoissonD(1); // Fill with a weight drawn from Poisson distribution with mean of 1 + } + // Return the vector to be stored in top::Event + return weight_poisson; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/KLFitterResult.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/KLFitterResult.cxx index 24e16d26812f890e5b43310660a782ad873b2b3d..51b14390ff49f0690467e0fbbcd9e5b9e89a7db4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/KLFitterResult.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/KLFitterResult.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: SystematicEvent.cxx 661144 2015-04-17 09:09:07Z morrisj $ #include "TopEvent/KLFitterResult.h" @@ -9,135 +9,240 @@ #include "xAODCore/AuxStoreAccessorMacros.h" #include "xAODCore/AddDVProxy.h" -namespace xAOD{ +namespace xAOD { // Aux Container KLFitterResultAuxContainer::KLFitterResultAuxContainer() : - AuxContainerBase() - { - AUX_VARIABLE( minuitDidNotConverge ); - AUX_VARIABLE( fitAbortedDueToNaN ); - AUX_VARIABLE( atLeastOneFitParameterAtItsLimit ); - AUX_VARIABLE( invalidTransferFunctionAtConvergence ); - - AUX_VARIABLE( bestPermutation ); - AUX_VARIABLE( logLikelihood ); - AUX_VARIABLE( eventProbability ); - AUX_VARIABLE( parameters ); - AUX_VARIABLE( parameterErrors ); - - AUX_VARIABLE( model_bhad_pt ); - AUX_VARIABLE( model_bhad_eta ); - AUX_VARIABLE( model_bhad_phi ); - AUX_VARIABLE( model_bhad_E ); - AUX_VARIABLE( model_bhad_jetIndex ); - - AUX_VARIABLE( model_blep_pt ); - AUX_VARIABLE( model_blep_eta ); - AUX_VARIABLE( model_blep_phi ); - AUX_VARIABLE( model_blep_E ); - AUX_VARIABLE( model_blep_jetIndex ); - - AUX_VARIABLE( model_lq1_pt ); - AUX_VARIABLE( model_lq1_eta ); - AUX_VARIABLE( model_lq1_phi ); - AUX_VARIABLE( model_lq1_E ); - AUX_VARIABLE( model_lq1_jetIndex ); - - AUX_VARIABLE( model_lq2_pt ); - AUX_VARIABLE( model_lq2_eta ); - AUX_VARIABLE( model_lq2_phi ); - AUX_VARIABLE( model_lq2_E ); - AUX_VARIABLE( model_lq2_jetIndex ); - - AUX_VARIABLE( model_Higgs_b1_pt ); - AUX_VARIABLE( model_Higgs_b1_eta ); - AUX_VARIABLE( model_Higgs_b1_phi ); - AUX_VARIABLE( model_Higgs_b1_E ); - AUX_VARIABLE( model_Higgs_b1_jetIndex ); - - AUX_VARIABLE( model_Higgs_b2_pt ); - AUX_VARIABLE( model_Higgs_b2_eta ); - AUX_VARIABLE( model_Higgs_b2_phi ); - AUX_VARIABLE( model_Higgs_b2_E ); - AUX_VARIABLE( model_Higgs_b2_jetIndex ); - - AUX_VARIABLE( model_lep_pt ); - AUX_VARIABLE( model_lep_eta ); - AUX_VARIABLE( model_lep_phi ); - AUX_VARIABLE( model_lep_E ); - - AUX_VARIABLE( model_nu_pt ); - AUX_VARIABLE( model_nu_eta ); - AUX_VARIABLE( model_nu_phi ); - AUX_VARIABLE( model_nu_E ); - - + AuxContainerBase() { + AUX_VARIABLE(selectionCode); + + AUX_VARIABLE(minuitDidNotConverge); + AUX_VARIABLE(fitAbortedDueToNaN); + AUX_VARIABLE(atLeastOneFitParameterAtItsLimit); + AUX_VARIABLE(invalidTransferFunctionAtConvergence); + + AUX_VARIABLE(bestPermutation); + AUX_VARIABLE(logLikelihood); + AUX_VARIABLE(eventProbability); + AUX_VARIABLE(parameters); + AUX_VARIABLE(parameterErrors); + + AUX_VARIABLE(model_bhad_pt); + AUX_VARIABLE(model_bhad_eta); + AUX_VARIABLE(model_bhad_phi); + AUX_VARIABLE(model_bhad_E); + AUX_VARIABLE(model_bhad_jetIndex); + + AUX_VARIABLE(model_blep_pt); + AUX_VARIABLE(model_blep_eta); + AUX_VARIABLE(model_blep_phi); + AUX_VARIABLE(model_blep_E); + AUX_VARIABLE(model_blep_jetIndex); + + AUX_VARIABLE(model_lq1_pt); + AUX_VARIABLE(model_lq1_eta); + AUX_VARIABLE(model_lq1_phi); + AUX_VARIABLE(model_lq1_E); + AUX_VARIABLE(model_lq1_jetIndex); + + AUX_VARIABLE(model_lq2_pt); + AUX_VARIABLE(model_lq2_eta); + AUX_VARIABLE(model_lq2_phi); + AUX_VARIABLE(model_lq2_E); + AUX_VARIABLE(model_lq2_jetIndex); + + AUX_VARIABLE(model_Higgs_b1_pt); + AUX_VARIABLE(model_Higgs_b1_eta); + AUX_VARIABLE(model_Higgs_b1_phi); + AUX_VARIABLE(model_Higgs_b1_E); + AUX_VARIABLE(model_Higgs_b1_jetIndex); + + AUX_VARIABLE(model_Higgs_b2_pt); + AUX_VARIABLE(model_Higgs_b2_eta); + AUX_VARIABLE(model_Higgs_b2_phi); + AUX_VARIABLE(model_Higgs_b2_E); + AUX_VARIABLE(model_Higgs_b2_jetIndex); + + AUX_VARIABLE(model_lep_pt); + AUX_VARIABLE(model_lep_eta); + AUX_VARIABLE(model_lep_phi); + AUX_VARIABLE(model_lep_E); + AUX_VARIABLE(model_lep_index); + + AUX_VARIABLE(model_lepZ1_pt); + AUX_VARIABLE(model_lepZ1_eta); + AUX_VARIABLE(model_lepZ1_phi); + AUX_VARIABLE(model_lepZ1_E); + AUX_VARIABLE(model_lepZ1_index); + + AUX_VARIABLE(model_lepZ2_pt); + AUX_VARIABLE(model_lepZ2_eta); + AUX_VARIABLE(model_lepZ2_phi); + AUX_VARIABLE(model_lepZ2_E); + AUX_VARIABLE(model_lepZ2_index); + + AUX_VARIABLE(model_nu_pt); + AUX_VARIABLE(model_nu_eta); + AUX_VARIABLE(model_nu_phi); + AUX_VARIABLE(model_nu_E); + + AUX_VARIABLE(model_b_from_top1_pt); + AUX_VARIABLE(model_b_from_top1_eta); + AUX_VARIABLE(model_b_from_top1_phi); + AUX_VARIABLE(model_b_from_top1_E); + AUX_VARIABLE(model_b_from_top1_jetIndex); + + AUX_VARIABLE(model_b_from_top2_pt); + AUX_VARIABLE(model_b_from_top2_eta); + AUX_VARIABLE(model_b_from_top2_phi); + AUX_VARIABLE(model_b_from_top2_E); + AUX_VARIABLE(model_b_from_top2_jetIndex); + + AUX_VARIABLE(model_lj1_from_top1_pt); + AUX_VARIABLE(model_lj1_from_top1_eta); + AUX_VARIABLE(model_lj1_from_top1_phi); + AUX_VARIABLE(model_lj1_from_top1_E); + AUX_VARIABLE(model_lj1_from_top1_jetIndex); + + AUX_VARIABLE(model_lj2_from_top1_pt); + AUX_VARIABLE(model_lj2_from_top1_eta); + AUX_VARIABLE(model_lj2_from_top1_phi); + AUX_VARIABLE(model_lj2_from_top1_E); + AUX_VARIABLE(model_lj2_from_top1_jetIndex); + + AUX_VARIABLE(model_lj1_from_top2_pt); + AUX_VARIABLE(model_lj1_from_top2_eta); + AUX_VARIABLE(model_lj1_from_top2_phi); + AUX_VARIABLE(model_lj1_from_top2_E); + AUX_VARIABLE(model_lj1_from_top2_jetIndex); + + AUX_VARIABLE(model_lj2_from_top2_pt); + AUX_VARIABLE(model_lj2_from_top2_eta); + AUX_VARIABLE(model_lj2_from_top2_phi); + AUX_VARIABLE(model_lj2_from_top2_E); + AUX_VARIABLE(model_lj2_from_top2_jetIndex); } - + /// Interface class KLFitterResult::KLFitterResult() : - SG::AuxElement() - { - } - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , short , minuitDidNotConverge , setMinuitDidNotConverge ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , short , fitAbortedDueToNaN , setFitAbortedDueToNaN ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , short , atLeastOneFitParameterAtItsLimit , setAtLeastOneFitParameterAtItsLimit ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , short , invalidTransferFunctionAtConvergence , setInvalidTransferFunctionAtConvergence ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , bestPermutation , setBestPermutation ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , logLikelihood , setLogLikelihood ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , eventProbability , setEventProbability ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( KLFitterResult , std::vector<double> , parameters , setParameters ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( KLFitterResult , std::vector<double> , parameterErrors , setParameterErrors ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_bhad_pt , setModel_bhad_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_bhad_eta , setModel_bhad_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_bhad_phi , setModel_bhad_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_bhad_E , setModel_bhad_E ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , model_bhad_jetIndex , setModel_bhad_jetIndex ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_blep_pt , setModel_blep_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_blep_eta , setModel_blep_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_blep_phi , setModel_blep_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_blep_E , setModel_blep_E ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , model_blep_jetIndex , setModel_blep_jetIndex ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq1_pt , setModel_lq1_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq1_eta , setModel_lq1_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq1_phi , setModel_lq1_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq1_E , setModel_lq1_E ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , model_lq1_jetIndex , setModel_lq1_jetIndex ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq2_pt , setModel_lq2_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq2_eta , setModel_lq2_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq2_phi , setModel_lq2_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lq2_E , setModel_lq2_E ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , model_lq2_jetIndex , setModel_lq2_jetIndex ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b1_pt , setModel_Higgs_b1_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b1_eta , setModel_Higgs_b1_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b1_phi , setModel_Higgs_b1_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b1_E , setModel_Higgs_b1_E ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , model_Higgs_b1_jetIndex , setModel_Higgs_b1_jetIndex ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b2_pt , setModel_Higgs_b2_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b2_eta , setModel_Higgs_b2_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b2_phi , setModel_Higgs_b2_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_Higgs_b2_E , setModel_Higgs_b2_E ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , unsigned int , model_Higgs_b2_jetIndex , setModel_Higgs_b2_jetIndex ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lep_pt , setModel_lep_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lep_eta , setModel_lep_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lep_phi , setModel_lep_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_lep_E , setModel_lep_E ) - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_nu_pt , setModel_nu_pt ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_nu_eta , setModel_nu_eta ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_nu_phi , setModel_nu_phi ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( KLFitterResult , float , model_nu_E , setModel_nu_E ) - + SG::AuxElement() { + } + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, std::size_t, selectionCode, setSelectionCode) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, short, minuitDidNotConverge, setMinuitDidNotConverge) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, short, fitAbortedDueToNaN, setFitAbortedDueToNaN) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, short, atLeastOneFitParameterAtItsLimit, + setAtLeastOneFitParameterAtItsLimit) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, short, invalidTransferFunctionAtConvergence, + setInvalidTransferFunctionAtConvergence) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, bestPermutation, setBestPermutation) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, logLikelihood, setLogLikelihood) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, eventProbability, setEventProbability) + AUXSTORE_OBJECT_SETTER_AND_GETTER(KLFitterResult, std::vector<double>, parameters, setParameters) + AUXSTORE_OBJECT_SETTER_AND_GETTER(KLFitterResult, std::vector<double>, parameterErrors, setParameterErrors) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_bhad_pt, setModel_bhad_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_bhad_eta, setModel_bhad_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_bhad_phi, setModel_bhad_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_bhad_E, setModel_bhad_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_bhad_jetIndex, setModel_bhad_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_blep_pt, setModel_blep_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_blep_eta, setModel_blep_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_blep_phi, setModel_blep_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_blep_E, setModel_blep_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_blep_jetIndex, setModel_blep_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq1_pt, setModel_lq1_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq1_eta, setModel_lq1_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq1_phi, setModel_lq1_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq1_E, setModel_lq1_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lq1_jetIndex, setModel_lq1_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq2_pt, setModel_lq2_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq2_eta, setModel_lq2_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq2_phi, setModel_lq2_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lq2_E, setModel_lq2_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lq2_jetIndex, setModel_lq2_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b1_pt, setModel_Higgs_b1_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b1_eta, setModel_Higgs_b1_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b1_phi, setModel_Higgs_b1_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b1_E, setModel_Higgs_b1_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_Higgs_b1_jetIndex, + setModel_Higgs_b1_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b2_pt, setModel_Higgs_b2_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b2_eta, setModel_Higgs_b2_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b2_phi, setModel_Higgs_b2_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_Higgs_b2_E, setModel_Higgs_b2_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_Higgs_b2_jetIndex, + setModel_Higgs_b2_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lep_pt, setModel_lep_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lep_eta, setModel_lep_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lep_phi, setModel_lep_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lep_E, setModel_lep_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lep_index, setModel_lep_index) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ1_pt, setModel_lepZ1_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ1_eta, setModel_lepZ1_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ1_phi, setModel_lepZ1_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ1_E, setModel_lepZ1_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lepZ1_index, setModel_lepZ1_index) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ2_pt, setModel_lepZ2_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ2_eta, setModel_lepZ2_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ2_phi, setModel_lepZ2_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lepZ2_E, setModel_lepZ2_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lepZ2_index, setModel_lepZ2_index) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_nu_pt, setModel_nu_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_nu_eta, setModel_nu_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_nu_phi, setModel_nu_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_nu_E, setModel_nu_E) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top1_pt, setModel_b_from_top1_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top1_eta, setModel_b_from_top1_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top1_phi, setModel_b_from_top1_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top1_E, setModel_b_from_top1_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_b_from_top1_jetIndex, + setModel_b_from_top1_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top2_pt, setModel_b_from_top2_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top2_eta, setModel_b_from_top2_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top2_phi, setModel_b_from_top2_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_b_from_top2_E, setModel_b_from_top2_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_b_from_top2_jetIndex, + setModel_b_from_top2_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top1_pt, setModel_lj1_from_top1_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top1_eta, setModel_lj1_from_top1_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top1_phi, setModel_lj1_from_top1_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top1_E, setModel_lj1_from_top1_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lj1_from_top1_jetIndex, + setModel_lj1_from_top1_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top1_pt, setModel_lj2_from_top1_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top1_eta, setModel_lj2_from_top1_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top1_phi, setModel_lj2_from_top1_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top1_E, setModel_lj2_from_top1_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lj2_from_top1_jetIndex, + setModel_lj2_from_top1_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top2_pt, setModel_lj1_from_top2_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top2_eta, setModel_lj1_from_top2_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top2_phi, setModel_lj1_from_top2_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj1_from_top2_E, setModel_lj1_from_top2_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lj1_from_top2_jetIndex, + setModel_lj1_from_top2_jetIndex) + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top2_pt, setModel_lj2_from_top2_pt) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top2_eta, setModel_lj2_from_top2_eta) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top2_phi, setModel_lj2_from_top2_phi) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, float, model_lj2_from_top2_E, setModel_lj2_from_top2_E) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(KLFitterResult, unsigned int, model_lj2_from_top2_jetIndex, + setModel_lj2_from_top2_jetIndex) } -ADD_NS_DV_PROXY( xAOD , KLFitterResultContainer ); - +ADD_NS_DV_PROXY(xAOD, KLFitterResultContainer); diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/LinkDef.h index 16fcef788a76c06079e9683c56c236c07327e835..5a16ca6fa198ee39477f57c59511bc2f0c2a3baa 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/LinkDef.h @@ -1,15 +1,17 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopEvent/SystematicEvent.h" #include "TopEvent/KLFitterResult.h" #include "TopEvent/PseudoTopResult.h" +#include "TopEvent/RCJetMC15.h" #ifdef __CINT__ #pragma extra_include "TopEvent/SystematicEvent.h"; #pragma extra_include "TopEvent/KLFitterResult.h"; #pragma extra_include "TopEvent/PseudoTopResult.h"; +#pragma extra_include "TopEvent/RCJetMC15.h"; #pragma link off all globals; #pragma link off all classes; @@ -28,4 +30,6 @@ #pragma link C++ class xAOD::PseudoTopResultContainer+; #pragma link C++ class xAOD::PseudoTopResultAuxContainer+; +#pragma link C++ class RCJetMC15+; + #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/PseudoTopResult.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/PseudoTopResult.cxx index 92485f1dd7a6373d7e2334aa236bca0a8d9feacd..95448abe29d30cb611caa05e854de9b2b7bf20b1 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/PseudoTopResult.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/PseudoTopResult.cxx @@ -1,60 +1,50 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEvent/PseudoTopResult.h" #include "xAODCore/AddDVProxy.h" -namespace xAOD{ - /// Aux Container +namespace xAOD { + /// Aux Container PseudoTopResultAuxContainer::PseudoTopResultAuxContainer() : - AuxContainerBase() - { + AuxContainerBase() { } - + /// Interface class PseudoTopResult::PseudoTopResult() : - SG::AuxElement() - { + SG::AuxElement() { } //Initialize variables - void PseudoTopResult::IniVar(bool isReco){ - - if(isReco){ - - this->auxdecor< float >( "PseudoTop_Reco_ttbar_eta" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_ttbar_phi" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_ttbar_m" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_ttbar_pt" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_had_pt" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_had_eta" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_had_phi" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_had_m" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_lep_pt" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_lep_eta" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_lep_phi" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Reco_top_lep_m" ) = -100.0; - + void PseudoTopResult::IniVar(bool isReco) { + if (isReco) { + this->auxdecor< float >("PseudoTop_Reco_ttbar_eta") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_ttbar_phi") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_ttbar_m") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_ttbar_pt") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_had_pt") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_had_eta") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_had_phi") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_had_m") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_lep_pt") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_lep_eta") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_lep_phi") = -100.0; + this->auxdecor< float >("PseudoTop_Reco_top_lep_m") = -100.0; + } else { + this->auxdecor< float >("PseudoTop_Particle_ttbar_eta") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_ttbar_phi") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_ttbar_m") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_ttbar_pt") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_had_pt") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_had_eta") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_had_phi") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_had_m") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_lep_pt") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_lep_eta") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_lep_phi") = -100.0; + this->auxdecor< float >("PseudoTop_Particle_top_lep_m") = -100.0; } - else{ - - this->auxdecor< float >( "PseudoTop_Particle_ttbar_eta" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_ttbar_phi" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_ttbar_m" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_ttbar_pt" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_had_pt" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_had_eta" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_had_phi" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_had_m" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_lep_pt" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_lep_eta" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_lep_phi" ) = -100.0; - this->auxdecor< float >( "PseudoTop_Particle_top_lep_m" ) = -100.0; - - } - } - } -ADD_NS_DV_PROXY( xAOD , PseudoTopResultContainer ); +ADD_NS_DV_PROXY(xAOD, PseudoTopResultContainer); diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/RCJetMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/RCJetMC15.cxx new file mode 100644 index 0000000000000000000000000000000000000000..41195394b9ca945cf328f7bbe9564ab6669457d5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/RCJetMC15.cxx @@ -0,0 +1,653 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +/************************************************************** + // + // Created: 19 January 2016 + // Last Updated: 22 February 2016 + // + // Daniel Marley + // demarley@umich.edu + // University of Michigan, Ann Arbor, MI + // + // File for initializing and making re-clustered jets. + // + ***************************************************************/ +#include "TopEvent/RCJetMC15.h" + +#include "TopConfiguration/TopConfig.h" +#include "AsgTools/AsgTool.h" +#include "AthContainers/ConstDataVector.h" + +#include "xAODJet/JetContainer.h" +#include "xAODJet/JetAuxContainer.h" +#include "xAODEventInfo/EventInfo.h" +#include "xAODCore/ShallowCopy.h" +#include "xAODBase/IParticleHelpers.h" +#include "PATInterfaces/SystematicsUtil.h" + +#include "fastjet/ClusterSequence.hh" +#include <fastjet/contrib/EnergyCorrelator.hh> +#include <fastjet/contrib/Nsubjettiness.hh> +#include "JetSubStructureUtils/Qw.h" +#include "JetSubStructureUtils/KtSplittingScale.h" +#include "JetSubStructureUtils/EnergyCorrelatorGeneralized.h" +#include "JetSubStructureUtils/EnergyCorrelator.h" + +RCJetMC15::RCJetMC15(const std::string& name) : + asg::AsgTool(name), + m_name(name), + m_config(nullptr), + m_ptcut(0.), + m_etamax(0.), + m_inputJetPtMin(0.), + m_inputJetEtaMax(999.), + m_trim(0.), + m_radius(0.), + m_minradius(0.), + m_massscale(0.), + m_useJSS(false), + m_useAdditionalJSS(false), + m_egamma("EG_"), + m_jetsyst("JET_"), + m_muonsyst("MUON_"), + m_tracksyst("TRK_"), + m_InJetContainerBase("AntiKt4EMTopoJets_RC"), + m_OutJetContainerBase("AntiKtRCJets"), + m_InputJetContainer("AntiKt4EMTopoJets_RC"), + m_OutputJetContainer("AntiKtRCJets"), + m_loose_hashValue(2), + m_jet_def_rebuild(nullptr), + m_nSub1_beta1(nullptr), + m_nSub2_beta1(nullptr), + m_nSub3_beta1(nullptr), + m_ECF1(nullptr), + m_ECF2(nullptr), + m_ECF3(nullptr), + m_split12(nullptr), + m_split23(nullptr), + m_qw(nullptr), + m_gECF332(nullptr), + m_gECF461(nullptr), + m_gECF322(nullptr), + m_gECF331(nullptr), + m_gECF422(nullptr), + m_gECF441(nullptr), + m_gECF212(nullptr), + m_gECF321(nullptr), + m_gECF311(nullptr), + m_unique_syst(false) { + declareProperty("config", m_config); + declareProperty("VarRCjets", m_VarRCjets = false); + declareProperty("VarRCjets_rho", m_VarRCjets_rho = ""); + declareProperty("VarRCjets_mass_scale", m_VarRCjets_mass_scale = ""); +} + +RCJetMC15::~RCJetMC15() {} + + +StatusCode RCJetMC15::initialize() { + /* Initialize the re-clustered jets */ + ATH_MSG_INFO(" Initializing Re-clustered jets "); + + // load the necessary parameters from the Dynamic Keys in the config file + top::ConfigurationSettings* configSettings = top::ConfigurationSettings::get(); + + m_name = m_VarRCjets_rho + m_VarRCjets_mass_scale; + if (m_VarRCjets) { + m_ptcut = std::stof(configSettings->value("VarRCJetPt")); // 100 GeV + m_etamax = std::stof(configSettings->value("VarRCJetEta")); // 2.5 + m_trim = std::stof(configSettings->value("VarRCJetTrim")); // 0.05 (5% jet pT) + m_radius = std::stof(configSettings->value("VarRCJetMaxRadius")); // 1.2 (min=0.4) + m_minradius = 0.4; // 0.4 default (until we have smaller jets!) + std::string original_rho(m_VarRCjets_rho); + std::replace(original_rho.begin(), original_rho.end(), '_', '.'); + float rho = std::stof(original_rho); + float m_scale = mass_scales.at(m_VarRCjets_mass_scale); + m_massscale = rho * m_scale * 1e-3; // e.g., 2*m_top; in [GeV]! + + m_useJSS = m_config->useVarRCJetSubstructure(); + m_useAdditionalJSS = m_config->useVarRCJetAdditionalSubstructure(); + } else { + m_ptcut = std::stof(configSettings->value("RCJetPt")); // for initialize [GeV] & passSelection + m_etamax = std::stof(configSettings->value("RCJetEta")); // for passSelection + m_trim = std::stof(configSettings->value("RCJetTrim")); // for initialize + m_radius = std::stof(configSettings->value("RCJetRadius")); // for initialize + m_minradius = -1.0; + m_massscale = -1.0; + m_useJSS = m_config->useRCJetSubstructure(); + m_useAdditionalJSS = m_config->useRCJetAdditionalSubstructure(); + } + + m_inputJetPtMin = std::stof(configSettings->value("RCInputJetPtMin")); + m_inputJetEtaMax = std::stof(configSettings->value("RCInputJetEtaMax")); + + + if (m_useJSS || m_useAdditionalJSS) { + ATH_MSG_INFO("Calculating RCJet Substructure"); + + // Setup a bunch of FastJet stuff + //define the type of jets you will build (http://fastjet.fr/repo/doxygen-3.0.3/classfastjet_1_1JetDefinition.html) + m_jet_def_rebuild = std::make_shared<fastjet::JetDefinition>(fastjet::antikt_algorithm, 1.0, fastjet::E_scheme, + fastjet::Best); + } + if (m_useJSS) { + //Substructure tool definitions + m_nSub1_beta1 = std::make_shared<fastjet::contrib::Nsubjettiness>(1, + fastjet::contrib::OnePass_WTA_KT_Axes(), + fastjet::contrib::UnnormalizedMeasure(1.0)); + m_nSub2_beta1 = std::make_shared<fastjet::contrib::Nsubjettiness>(2, + fastjet::contrib::OnePass_WTA_KT_Axes(), + fastjet::contrib::UnnormalizedMeasure(1.0)); + m_nSub3_beta1 = std::make_shared<fastjet::contrib::Nsubjettiness>(3, + fastjet::contrib::OnePass_WTA_KT_Axes(), + fastjet::contrib::UnnormalizedMeasure(1.0)); + + + m_split12 = std::make_shared<JetSubStructureUtils::KtSplittingScale>(1); + m_split23 = std::make_shared<JetSubStructureUtils::KtSplittingScale>(2); + + m_qw = std::make_shared<JetSubStructureUtils::Qw>(); + + m_ECF1 = std::make_shared<fastjet::contrib::EnergyCorrelator>(1, 1.0, fastjet::contrib::EnergyCorrelator::pt_R); + m_ECF2 = std::make_shared<fastjet::contrib::EnergyCorrelator>(2, 1.0, fastjet::contrib::EnergyCorrelator::pt_R); + m_ECF3 = std::make_shared<fastjet::contrib::EnergyCorrelator>(3, 1.0, fastjet::contrib::EnergyCorrelator::pt_R); + + } + if (m_useAdditionalJSS) { + + m_gECF332 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(3, 3, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF461 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(6, 4, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF322 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(2, 3, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF331 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(3, 3, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF422 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(2, 4, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF441 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(4, 4, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF212 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(1, 2, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF321 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(2, 3, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF311 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(1, 3, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + } + + + + for (auto treeName : *m_config->systAllTTreeNames()) { + // only make a new tool if it is the nominal systematic or one that could affect small-r jets (el, mu, jet) + std::string hash_name(""); + + if (isUniqueSyst(treeName.second)) { + if (treeName.second.compare("nominal") != 0) hash_name = treeName.second; // no extra strings for nominal (so all + // other non-unique systs have same name + // as nominal) + + m_InputJetContainer = m_InJetContainerBase + hash_name; + m_OutputJetContainer = m_OutJetContainerBase + hash_name + m_name; + + // build a jet re-clustering tool for each case + std::shared_ptr<JetReclusteringTool> tool(new JetReclusteringTool(treeName.second + m_name)); + top::check(tool->setProperty("InputJetContainer", + m_InputJetContainer), "Failed inputjetcontainer initialize reclustering tool"); + top::check(tool->setProperty("OutputJetContainer", + m_OutputJetContainer), "Failed outputjetcontainer initialize reclustering tool"); + top::check(tool->setProperty("ReclusterRadius", + m_radius), "Failed re-clustering radius initialize reclustering tool"); + top::check(tool->setProperty("RCJetPtMin", m_ptcut * 1e-3), "Failed ptmin [GeV] initialize reclustering tool"); + top::check(tool->setProperty("InputJetPtMin", m_inputJetPtMin * 1e-3), "Failed InputJetPtMin [GeV] initialize reclustering tool"); + top::check(tool->setProperty("TrimPtFrac", m_trim), "Failed pT fraction initialize reclustering tool"); + top::check(tool->setProperty("VariableRMinRadius", + m_minradius), "Failed VarRC min radius initialize reclustering tool"); + top::check(tool->setProperty("VariableRMassScale", + m_massscale), "Failed VarRC mass scale initialize reclustering tool"); + top::check(tool->initialize(), "Failed to initialize reclustering tool"); + + m_jetReclusteringTool.insert({treeName.first, tool}); // insert the re-clustering tool into map + // this stores a tool for each systematic based on hash + // value + + // map of container names to access in event saver + m_inputContainerNames.insert({treeName.first, m_InputJetContainer}); + m_outputContainerNames.insert({treeName.first, m_OutputJetContainer}); + + // make a re-clustering tool for 'loose' events, too. + if (m_config->doLooseEvents()) { + std::shared_ptr<JetReclusteringTool> tool_loose(new JetReclusteringTool(treeName.second + m_name + "_Loose")); + top::check(tool_loose->setProperty("InputJetContainer", + m_InputJetContainer + "_Loose"), + "Failed inputjetcontainer reclustering tool"); + top::check(tool_loose->setProperty("OutputJetContainer", + m_OutputJetContainer + "_Loose"), + "Failed outputjetcontainer loose initialize reclustering tool"); + top::check(tool_loose->setProperty("ReclusterRadius", + m_radius), "Failed re-clustering radius initialize reclustering tool"); + top::check(tool_loose->setProperty("RCJetPtMin", m_ptcut * 1e-3), "Failed ptmin [GeV] reclustering tool"); + top::check(tool->setProperty("InputJetPtMin", m_inputJetPtMin * 1e-3), "Failed InputJetPtMin [GeV] initialize reclustering tool"); + top::check(tool_loose->setProperty("TrimPtFrac", m_trim), "Failed pT fraction initialize reclustering tool"); + top::check(tool_loose->setProperty("VariableRMinRadius", + m_minradius), "Failed VarRC min radius initialize reclustering tool"); + top::check(tool_loose->setProperty("VariableRMassScale", + m_massscale), "Failed VarRC mass scale initialize reclustering tool"); + top::check(tool_loose->initialize(), "Failed to initialize reclustering tool"); + + m_jetReclusteringTool.insert({m_loose_hashValue* treeName.first, tool_loose}); // making up a number as index + // for the loose event + // map of container names to access in event saver + m_inputContainerNames.insert({m_loose_hashValue* treeName.first, m_InputJetContainer + "_Loose"}); + m_outputContainerNames.insert({m_loose_hashValue* treeName.first, m_OutputJetContainer + "_Loose"}); + } // end if loose + } // end if unique syst + else { + m_InputJetContainer = m_InJetContainerBase; + m_OutputJetContainer = m_OutJetContainerBase + m_name; + + // map of container names to access in event saver + if (m_config->doLooseEvents()) { + m_inputContainerNames.insert({m_loose_hashValue* treeName.first, m_InputJetContainer + "_Loose"}); + m_outputContainerNames.insert({m_loose_hashValue* treeName.first, m_OutputJetContainer + "_Loose"}); + } else { + m_inputContainerNames.insert({treeName.first, m_InputJetContainer}); + m_outputContainerNames.insert({treeName.first, m_OutputJetContainer}); + } + } + + } // end for loop over systematics + + ATH_MSG_INFO(" Re-clustered jets initialized "); + + return StatusCode::SUCCESS; +} // end initialize() + +StatusCode RCJetMC15::execute(const top::Event& event) { + /* + Make the jet container (if necessary) and execute the re-clustering tool + https://svnweb.cern.ch/trac/atlasoff/browser/PhysicsAnalysis/TopPhys/xAOD/TopEvent/trunk/Root/TopEventMaker.cxx#L31 + */ + m_InputJetContainer = inputContainerName(event.m_hashValue, event.m_isLoose); + m_OutputJetContainer = rcjetContainerName(event.m_hashValue, event.m_isLoose); + + + // -- Save the jet container to the TStore (only if it doesn't already exist!) + // -- Then, we can access it with the re-clustering tool further down + if (!evtStore()->contains<xAOD::JetContainer>(m_InputJetContainer)) { + // Save the nominal container once, and each jet systematic container once + // Make the new jet container (only do this if we have to!) + // 22 Feb 2016: + // Code significantly shortened to make this container + // thanks to email exchange between Davide Gerbaudo & Attila Krasznahorkay + auto rcJetInputs = std::make_unique< ConstDataVector< xAOD::JetContainer >>(SG::VIEW_ELEMENTS); + for(const xAOD::Jet* jet : event.m_jets) { + if(jet->pt() < m_inputJetPtMin || std::abs(jet->eta()) > m_inputJetEtaMax) continue; + rcJetInputs->push_back(jet); + } + top::check(evtStore()->tds()->record(std::move(rcJetInputs), m_InputJetContainer), + "Failed to put jets in TStore for re-clustering"); + } // end if jet container exists + + // --- EXECUTE --- // + // only execute if the jet container doesn't exist + // (do not re-make the 'nominal' jet container over & over again!) + if (!evtStore()->contains<xAOD::JetContainer>(m_OutputJetContainer)) { + int hash_factor = (event.m_isLoose) ? m_loose_hashValue : 1; + + // tools only exist for unique systematics & nominal (save time/space)! + m_tool_iterator tool_iter = m_jetReclusteringTool.find(hash_factor * event.m_hashValue); + + // if this is a unique systematic or nominal, execute from the tool; else execute nominal + if (tool_iter != m_jetReclusteringTool.end()) tool_iter->second->execute(); + else m_jetReclusteringTool.at(hash_factor * m_config->nominalHashValue())->execute(); + + xAOD::JetContainer* myJets(nullptr); + top::check(evtStore()->retrieve(myJets, m_OutputJetContainer), "Failed to retrieve RC JetContainer"); + for (auto rcjet : *myJets) { + rcjet->auxdecor<bool>("PassedSelection") = passSelection(*rcjet); + } + + if (m_useJSS || m_useAdditionalJSS) { + static const SG::AuxElement::ConstAccessor<bool> passedSelection("PassedSelection"); + + for (auto rcjet : *myJets) { + if (!passedSelection(*rcjet)) continue; // Calculate JSS only if passed object selection + + // get the subjets and clusters of the rcjets + + std::vector<fastjet::PseudoJet> clusters; + + + if (m_config->sgKeyJetsTDS(hash_factor * m_config->nominalHashValue(), + false).find("AntiKt4EMTopoJets") != std::string::npos) { + getEMTopoClusters(clusters,rcjet); // use subjet constituents + } + else if (m_config->sgKeyJetsTDS(hash_factor * m_config->nominalHashValue(), + false).find("AntiKt4EMPFlowJets") != std::string::npos) { + getPflowConstituent(clusters, rcjet, event); // use ghost-matched tracks + } + else getLCTopoClusters(clusters, rcjet); // // use LCTOPO CLUSTERS matched to subjet + + if (m_config->sgKeyJetsTDS(hash_factor * m_config->nominalHashValue(), + false).find("AntiKt4EMPFlowJets") == std::string::npos) { + // In case of AntiKt4EMPFlowJets the tracks could be removed by the pile-up cuts + top::check( + !clusters.empty(), + "RCJetMC15::execute(const top::Event& event): Failed to get vector of clusters! Unable to calculate RC jets substructure variables!\n Aborting!"); + } + + if (clusters.size() != 0) { + // Now rebuild the large jet from the small jet constituents aka the original clusters + fastjet::ClusterSequence clust_seq_rebuild = fastjet::ClusterSequence(clusters, *m_jet_def_rebuild); + std::vector<fastjet::PseudoJet> my_pjets = fastjet::sorted_by_pt(clust_seq_rebuild.inclusive_jets(0.0)); + + + fastjet::PseudoJet correctedJet; + correctedJet = my_pjets[0]; + //Sometimes fastjet splits the jet into two, so need to correct for that!! + if (my_pjets.size() > 1) correctedJet += my_pjets[1]; + + if (m_useJSS) { + // Now finally we can calculate some substructure! + double tau32 = -1, tau21 = -1; + + double tau1 = m_nSub1_beta1->result(correctedJet); + double tau2 = m_nSub2_beta1->result(correctedJet); + double tau3 = m_nSub3_beta1->result(correctedJet); + + if (std::abs(tau1) > 1e-8) tau21 = tau2 / tau1; + else tau21 = -999.0; + if (std::abs(tau2) > 1e-8) tau32 = tau3 / tau2; + else tau32 = -999.0; + + + + double split12 = m_split12->result(correctedJet); + double split23 = m_split23->result(correctedJet); + double qw = m_qw->result(correctedJet); + + double D2 = -1; + + double vECF1 = m_ECF1->result(correctedJet); + double vECF2 = m_ECF2->result(correctedJet); + double vECF3 = m_ECF3->result(correctedJet); + if (std::abs(vECF2) > 1e-8) D2 = vECF3 * vECF1* vECF1* vECF1 / (vECF2 * vECF2 * vECF2); + else D2 = -999.0; + + + // now attach the results to the original jet + rcjet->auxdecor<float>("Tau32_clstr") = tau32; + rcjet->auxdecor<float>("Tau21_clstr") = tau21; + + // lets also write out the components so we can play with them later + rcjet->auxdecor<float>("Tau3_clstr") = tau3; + rcjet->auxdecor<float>("Tau2_clstr") = tau2; + rcjet->auxdecor<float>("Tau1_clstr") = tau1; + + rcjet->auxdecor<float>("d12_clstr") = split12; + rcjet->auxdecor<float>("d23_clstr") = split23; + rcjet->auxdecor<float>("Qw_clstr") = qw; + + rcjet->auxdecor<float>("nconstituent_clstr") = clusters.size(); + + rcjet->auxdecor<float>("ECF1_clstr") = vECF1; + rcjet->auxdecor<float>("ECF2_clstr") = vECF2; + rcjet->auxdecor<float>("ECF3_clstr") = vECF3; + rcjet->auxdecor<float>("D2_clstr") = D2; + + } // end of if useJSS + + if (m_useAdditionalJSS) { + + // MlB's t/H discriminators + // E = (a*n) / (b*m) + // for an ECFG_X_Y_Z, a=Y, n=Z -> dimenionless variable + double gECF332 = m_gECF332->result(correctedJet); + double gECF461 = m_gECF461->result(correctedJet); + double gECF322 = m_gECF322->result(correctedJet); + double gECF331 = m_gECF331->result(correctedJet); + double gECF422 = m_gECF422->result(correctedJet); + double gECF441 = m_gECF441->result(correctedJet); + double gECF212 = m_gECF212->result(correctedJet); + double gECF321 = m_gECF321->result(correctedJet); + double gECF311 = m_gECF311->result(correctedJet); + + double L1 = -999.0, L2 = -999.0, L3 = -999.0, L4 = -999.0, L5 = -999.0; + if (std::abs(gECF212) > 1e-12) { + L1 = gECF321 / gECF212; + L2 = gECF331 / sqrt(gECF212*gECF212*gECF212); + } + if (std::abs(gECF331) > 1e-12) { + L3 = gECF311 / pow(gECF331,1./3.); + L4 = gECF322 / pow(gECF331,4./3.); + } + if (std::abs(gECF441) > 1e-12) { + L5 = gECF422/gECF441; + } + + rcjet->auxdecor<float>("gECF332_clstr") = gECF332; + rcjet->auxdecor<float>("gECF461_clstr") = gECF461; + rcjet->auxdecor<float>("gECF322_clstr") = gECF322; + rcjet->auxdecor<float>("gECF331_clstr") = gECF331; + rcjet->auxdecor<float>("gECF422_clstr") = gECF422; + rcjet->auxdecor<float>("gECF441_clstr") = gECF441; + rcjet->auxdecor<float>("gECF212_clstr") = gECF212; + rcjet->auxdecor<float>("gECF321_clstr") = gECF321; + rcjet->auxdecor<float>("gECF311_clstr") = gECF311; + rcjet->auxdecor<float>("L1_clstr") = L1; + rcjet->auxdecor<float>("L2_clstr") = L2; + rcjet->auxdecor<float>("L3_clstr") = L3; + rcjet->auxdecor<float>("L4_clstr") = L4; + rcjet->auxdecor<float>("L5_clstr") = L5; + // lets also store the rebuilt jet incase we need it later + rcjet->auxdecor<float>("RRCJet_pt") = correctedJet.pt(); + rcjet->auxdecor<float>("RRCJet_eta") = correctedJet.eta(); + rcjet->auxdecor<float>("RRCJet_phi") = correctedJet.phi(); + rcjet->auxdecor<float>("RRCJet_e") = correctedJet.e(); + }// end of if useAdditional JSS + } + }// end of rcjet loop + }//m_useJSS || m_useAdditionalJSS + } //if (!evtStore()->contains<xAOD::JetContainer>(m_OutputJetContainer)) + + + + + + + + + + return StatusCode::SUCCESS; +} // end execute() + +StatusCode RCJetMC15::finalize() { + m_jetReclusteringTool.clear(); + + return StatusCode::SUCCESS; +} + +bool RCJetMC15::isUniqueSyst(const std::string syst_name) { + /* + Check if the given systematic (besides nominal) needs a unique container + Keep this in one function so it easier to update than having multiple checks everywhere. + Only need jet containers for EGamma, Muon, Jet and Nominal systematics + */ + + bool isSmallRJetSys = (syst_name.find(m_jetsyst) != std::string::npos); + + // Systematic branches for small-R and large-R jets both contain "JET_" string. We want to recluster only if they + // correspond to small-R jets. + if ((syst_name.find("_R10_") != std::string::npos) || + (syst_name.find("_CombMass_") != std::string::npos) || + (syst_name.find("_LargeR_") != std::string::npos) || + (syst_name.find("_MassRes_") != std::string::npos) || + (syst_name.find("_SigSF_") != std::string::npos) || + (syst_name.find("_BGSF_") != std::string::npos) ) isSmallRJetSys = false; + + m_unique_syst = (syst_name.find(m_egamma) == 0 || + syst_name.find(m_muonsyst) == 0 || + isSmallRJetSys || + syst_name.find(m_tracksyst) == 0 || + syst_name.compare("nominal") == 0); + + return m_unique_syst; +} + +std::string RCJetMC15::inputContainerName(std::size_t hash_value, bool isLooseEvent) { + /* Return the name of the input container */ + std::string this_container_name(""); + if (isLooseEvent) hash_value *= m_loose_hashValue; // loose events have a slightly different hash value to keep track + // of + + m_iterator iter = m_inputContainerNames.find(hash_value); + + if (iter != m_inputContainerNames.end()) this_container_name = iter->second; + else this_container_name = m_InJetContainerBase; + + return this_container_name; +} + +std::string RCJetMC15::rcjetContainerName(std::size_t hash_value, bool isLooseEvent) { + /* Return the name of the rcjet container for a given systematic */ + std::string this_container_name(""); + if (isLooseEvent) hash_value *= m_loose_hashValue; // loose events have a slightly different hash value + + m_iterator iter = m_outputContainerNames.find(hash_value); + + if (iter != m_outputContainerNames.end()) this_container_name = iter->second; + else this_container_name = m_OutJetContainerBase; + + return this_container_name; +} + +bool RCJetMC15::passSelection(const xAOD::Jet& jet) const { + /* + Check if the re-clustered jet passes selection. + Right now, this only does something for |eta| because + pT is taken care of in the re-clustering tool. When + small-r jet mass is available (calibrated+uncertainties), + we can cut on that. + */ + // [pT] calibrated to >~ 22 GeV (23 Jan 2016) + if (jet.pt() < m_ptcut) return false; + + // [|eta|] calibrated < 2.5 + if (std::abs(jet.eta()) > m_etamax) return false; + + // small-r jet mass not calibrated and no uncertainties + + return true; +} + +void RCJetMC15::getEMTopoClusters(std::vector<fastjet::PseudoJet>& clusters, const xAOD::Jet* rcjet) { + clusters.clear(); + + for (auto subjet : rcjet->getConstituents()) { + const xAOD::Jet* subjet_raw = static_cast<const xAOD::Jet*>(subjet->rawConstituent()); + + // Make sure we don't try to access jets that have had the clusters thinned + bool hasConstituents = true; + auto links = subjet_raw->constituentLinks(); + for (auto link : links) { + if (!link.isValid()) { + ATH_MSG_WARNING( + "Some of the RC Jet Constituents have been thinned - will not be included in RCJet JSS calculation"); + hasConstituents = false; + break; + } + } + if (!hasConstituents) { + continue; + } + + for (auto clus_itr : subjet_raw->getConstituents()) { + if (clus_itr->e() > 0) { + TLorentzVector temp_p4; + + double sf = 1.0; + temp_p4.SetPtEtaPhiM(clus_itr->pt() * sf, clus_itr->eta(), clus_itr->phi(), clus_itr->m()); + + clusters.push_back(fastjet::PseudoJet(temp_p4.Px(), temp_p4.Py(), temp_p4.Pz(), temp_p4.E())); + } + } + } +} + +void RCJetMC15::getLCTopoClusters(std::vector<fastjet::PseudoJet>& clusters, const xAOD::Jet* rcjet) { + //LCTOPO CLUSTERS + clusters.clear(); + + // get the clusters (directly we so can try using the LCTopo clusters) + const xAOD::CaloClusterContainer* myClusters(nullptr); + top::check(evtStore()->retrieve(myClusters, "CaloCalTopoClusters"), "Failed to retrieve CaloCalTopoClusters"); + + + + for (auto cluster : *myClusters) { + for (auto subjet : rcjet->getConstituents()) { + const xAOD::Jet* subjet_raw = static_cast<const xAOD::Jet*>(subjet->rawConstituent()); + + float dR = subjet_raw->p4().DeltaR(cluster->p4()); + if (dR < 0.4) { + TLorentzVector temp_p4; + temp_p4.SetPtEtaPhiE(cluster->pt((xAOD::CaloCluster_v1::State(1))), + cluster->eta((xAOD::CaloCluster_v1::State(1))), + cluster->phi((xAOD::CaloCluster_v1::State(1))), + cluster->e((xAOD::CaloCluster_v1::State(1)))); + clusters.push_back(fastjet::PseudoJet(temp_p4.Px(), temp_p4.Py(), temp_p4.Pz(), temp_p4.E())); + break; + } + } + } +} + +void RCJetMC15::getPflowConstituent(std::vector<fastjet::PseudoJet>& clusters, const xAOD::Jet* rcjet, + const top::Event& event) { + // At the moment the proper constituent of the PFlows aren't available in TOPQ1 and there is no strategy to provide + // uncertainty on that consequently + // at the moment just the tracks ghost matched to the PFLow objects are considered to define the substructure (under + // suggestion of the JSS group). + // As a consiquence all the neutral component of the jet is missing from the substructure, this choice is consistently + // copied at particle level + + clusters.clear(); + std::vector<const xAOD::TrackParticle*> jetTracks; + + + for (auto subjet : rcjet->getConstituents()) { + const xAOD::Jet* subjet_raw = static_cast<const xAOD::Jet*>(subjet->rawConstituent()); + + if(subjet->pt() < m_config->jetPtGhostTracks() || std::abs(subjet->eta()) > m_config->jetEtaGhostTracks()) continue; + + + jetTracks.clear(); + + jetTracks = subjet_raw->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(event.m_hashValue)); + bool haveJetTracks = jetTracks.size() != 0; + + if (haveJetTracks) { + + for ( const xAOD::TrackParticle* jet: jetTracks ){ + TLorentzVector temp_p4; + + if (jet != nullptr) { + + // Select on track quality, pt, eta and match to vertex + if(jet->auxdataConst< char >("passPreORSelection") != 1){ + continue; + } + + temp_p4.SetPtEtaPhiE(jet->pt(), jet->eta(), jet->phi(), jet->e()); + clusters.emplace_back(fastjet::PseudoJet(temp_p4.Px(), temp_p4.Py(), temp_p4.Pz(), temp_p4.E())); + + } + } + } else { + ATH_MSG_WARNING( + "RCJETMC15::No remaining tracks associated to the PFlow jet"); + } + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/SystematicEvent.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/SystematicEvent.cxx index c4b17f54dc686849805418c3dbc4f2bf29dd7b6c..996f51400d604ac9d9b70a48e7335cd1258115ec 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/SystematicEvent.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/SystematicEvent.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: SystematicEvent.cxx 692539 2015-09-02 00:20:52Z morrisj $ #include "TopEvent/SystematicEvent.h" @@ -9,40 +9,43 @@ #include "xAODCore/AuxStoreAccessorMacros.h" #include "xAODCore/AddDVProxy.h" -namespace xAOD{ +namespace xAOD { // Aux Container SystematicEventAuxContainer::SystematicEventAuxContainer() : - AuxContainerBase() - { - AUX_VARIABLE( hashValue ); - AUX_VARIABLE( ttreeIndex ); - AUX_VARIABLE( isLooseEvent ); + AuxContainerBase() { + AUX_VARIABLE(hashValue); + AUX_VARIABLE(ttreeIndex); + AUX_VARIABLE(isLooseEvent); - AUX_VARIABLE( goodPhotons ); - AUX_VARIABLE( goodElectrons ); - AUX_VARIABLE( goodMuons ); - AUX_VARIABLE( goodTaus ); - AUX_VARIABLE( goodJets ); - AUX_VARIABLE( goodLargeRJets ); - AUX_VARIABLE( goodTrackJets ); + AUX_VARIABLE(goodPhotons); + AUX_VARIABLE(goodElectrons); + AUX_VARIABLE(goodFwdElectrons); + AUX_VARIABLE(goodMuons); + AUX_VARIABLE(goodSoftMuons); + AUX_VARIABLE(goodTaus); + AUX_VARIABLE(goodJets); + AUX_VARIABLE(goodLargeRJets); + AUX_VARIABLE(goodTrackJets); + AUX_VARIABLE(goodTracks); } - + /// Interface class - SystematicEvent::SystematicEvent() : - SG::AuxElement() - { - } - - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( SystematicEvent , std::size_t , hashValue , setHashValue ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( SystematicEvent , unsigned int , ttreeIndex , setTtreeIndex ) - AUXSTORE_PRIMITIVE_SETTER_AND_GETTER( SystematicEvent , char , isLooseEvent , setIsLooseEvent ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodPhotons , setGoodPhotons ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodElectrons , setGoodElectrons ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodMuons , setGoodMuons ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodTaus , setGoodTaus ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodJets , setGoodJets ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodLargeRJets , setGoodLargeRJets ) - AUXSTORE_OBJECT_SETTER_AND_GETTER( SystematicEvent , std::vector<unsigned int> , goodTrackJets , setGoodTrackJets ) - + SystematicEvent::SystematicEvent() : + SG::AuxElement() { + } + + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(SystematicEvent, std::size_t, hashValue, setHashValue) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(SystematicEvent, unsigned int, ttreeIndex, setTtreeIndex) + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(SystematicEvent, char, isLooseEvent, setIsLooseEvent) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodPhotons, setGoodPhotons) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodElectrons, setGoodElectrons) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodFwdElectrons, setGoodFwdElectrons) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodMuons, setGoodMuons) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodSoftMuons, setGoodSoftMuons) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodTaus, setGoodTaus) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodJets, setGoodJets) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodLargeRJets, setGoodLargeRJets) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodTrackJets, setGoodTrackJets) + AUXSTORE_OBJECT_SETTER_AND_GETTER(SystematicEvent, std::vector<unsigned int>, goodTracks, setGoodTracks) } -ADD_NS_DV_PROXY( xAOD , SystematicEventContainer ); +ADD_NS_DV_PROXY(xAOD, SystematicEventContainer); diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/TopEventMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/TopEventMaker.cxx index 0438fabc7e1eb602baa7254e8b853c84bc56621b..631731bcd9c80eef7668e9280bab06b33c03eec0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/TopEventMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/Root/TopEventMaker.cxx @@ -1,8 +1,8 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: TopEventMaker.cxx 795594 2017-02-04 22:12:45Z tpelzer $ +// $Id: TopEventMaker.cxx 809847 2017-08-29 15:18:19Z iconnell $ #include "TopEvent/TopEventMaker.h" #include "TopEvent/EventTools.h" @@ -20,74 +20,131 @@ #include "xAODJet/JetAuxContainer.h" #include "xAODMissingET/MissingETContainer.h" #include "xAODCore/ShallowCopy.h" +#include "FourMomUtils/xAODP4Helpers.h" #include "TopPartons/PartonHistory.h" +#include <boost/algorithm/string.hpp> + +#include <iostream> + namespace top { + bool TopEventMaker::s_hasTruthEvent = true; - TopEventMaker::TopEventMaker( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr) - { - declareProperty( "config" , m_config ); + TopEventMaker::TopEventMaker(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr) { + declareProperty("config", m_config); } - + + StatusCode TopEventMaker::initialize() { + if (m_config->useRCJets() == true) { + m_rc = std::unique_ptr<RCJetMC15> (new RCJetMC15("RCJetMC15")); + top::check(m_rc->setProperty("config", m_config), "Failed to set config property of RCJetMC15"); + top::check(m_rc->initialize(), "Failed to initialize RCJetMC15"); + } + + if (m_config->useVarRCJets() == true) { + boost::split(m_VarRCJetRho, m_config->VarRCJetRho(), boost::is_any_of(",")); + boost::split(m_VarRCJetMassScale, m_config->VarRCJetMassScale(), boost::is_any_of(",")); + + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + m_VarRC[name] = std::unique_ptr<RCJetMC15> (new RCJetMC15("VarRCJetMC15_" + name)); + top::check(m_VarRC[name]->setProperty("config", m_config), "Failed to set config property of VarRCJetMC15"); + top::check(m_VarRC[name]->setProperty("VarRCjets", true), "Failed to set VarRCjets property of VarRCJetMC15"); + top::check(m_VarRC[name]->setProperty("VarRCjets_rho", + rho), "Failed to set VarRCjets rho property of VarRCJetMC15"); + top::check(m_VarRC[name]->setProperty("VarRCjets_mass_scale", + mass_scale), + "Failed to set VarRCjets mass scale property of VarRCJetMC15"); + top::check(m_VarRC[name]->initialize(), "Failed to initialize VarRCJetMC15"); + } // end loop over mass scale parameters (e.g., top mass, w mass, etc.) + } // end loop over mass scale multiplies (e.g., 1.,2.,etc.) + } + + return StatusCode::SUCCESS; + } + /// As top-xaod isn't an asg::AsgTool, it doesn't have access to all the information /// Very annoying, as it's actually quite simple - const xAOD::SystematicEventContainer* TopEventMaker::systematicEvents(const std::string& sgKey) const - { + const xAOD::SystematicEventContainer* TopEventMaker::systematicEvents(const std::string& sgKey) const { const xAOD::SystematicEventContainer* systEvents(nullptr); - top::check( evtStore()->retrieve(systEvents,sgKey) , "Failed to get xAOD::SystematicEventContainer"); + + top::check(evtStore()->retrieve(systEvents, sgKey), "Failed to get xAOD::SystematicEventContainer"); return systEvents; } - top::Event TopEventMaker::makeTopEvent(const xAOD::SystematicEvent& currentSystematic) - { + top::Event TopEventMaker::makeTopEvent(const xAOD::SystematicEvent* currentSystematicPtr) { + xAOD::SystematicEvent const& currentSystematic = *currentSystematicPtr; //create a new event object top::Event event; - + // Set systematic hash value std::size_t hash = currentSystematic.hashValue(); event.m_hashValue = hash; - + // TTree index event.m_ttreeIndex = currentSystematic.ttreeIndex(); - + // Is Loose event? - event.m_isLoose = currentSystematic.isLooseEvent(); + event.m_isLoose = currentSystematic.isLooseEvent(); //event info - top::check(evtStore()->retrieve(event.m_info, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); - + top::check(evtStore()->retrieve(event.m_info, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + event.m_systematicEvent = currentSystematicPtr; + //Primary Vertices if (evtStore()->contains<xAOD::VertexContainer>(m_config->sgKeyPrimaryVertices())) { - top::check(evtStore()->retrieve(event.m_primaryVertices, m_config->sgKeyPrimaryVertices()), "Failed to retrieve Primary Vertices"); - } - + top::check(evtStore()->retrieve(event.m_primaryVertices, + m_config->sgKeyPrimaryVertices()), "Failed to retrieve Primary Vertices"); + } + + //Poisson bootstrap weights + if (m_config->saveBootstrapWeights()) { + int second_seed; + if (m_config->isMC()) { + second_seed = event.m_info->mcChannelNumber(); + } else { + second_seed = event.m_info->runNumber(); + } + std::vector<int> weight_poisson = top::calculateBootstrapWeights(m_config->getNumberOfBootstrapReplicas(), + event.m_info->eventNumber(), + second_seed); + event.m_info->auxdecor< std::vector<int> >("weight_poisson") = weight_poisson; + } + //electrons if (m_config->useElectrons()) { ///-- Need to read const collections for mini-xaod read back --/// - + const xAOD::ElectronContainer* calibratedElectrons(nullptr); - top::check(evtStore()->retrieve(calibratedElectrons, m_config->sgKeyElectrons(hash) ), "Failed to retrieve electrons"); - + top::check(evtStore()->retrieve(calibratedElectrons, m_config->sgKeyElectrons( + hash)), "Failed to retrieve electrons"); + ///-- Shallow copy and save to TStore --/// if (!evtStore()->contains<xAOD::ElectronContainer>(m_config->sgKeyElectronsTDS(hash))) { - std::pair< xAOD::ElectronContainer*, xAOD::ShallowAuxContainer* > shallow_electrons = xAOD::shallowCopyContainer( *calibratedElectrons ); - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_electrons.first , m_config->sgKeyElectronsTDS(hash) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_electrons.second , m_config->sgKeyElectronsTDSAux(hash) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + std::pair< xAOD::ElectronContainer*, + xAOD::ShallowAuxContainer* > shallow_electrons = xAOD::shallowCopyContainer(*calibratedElectrons); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_electrons.first, m_config->sgKeyElectronsTDS(hash)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_electrons.second, m_config->sgKeyElectronsTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); } - + ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::ElectronContainer* calibratedElectronsTDS(nullptr); - top::check(evtStore()->retrieve(calibratedElectronsTDS, m_config->sgKeyElectronsTDS(hash) ), "Failed to retrieve electrons"); - - + top::check(evtStore()->retrieve(calibratedElectronsTDS, m_config->sgKeyElectronsTDS( + hash)), "Failed to retrieve electrons"); + + // re-write overlap information if it is decorated onto currentSystematic if (currentSystematic.isAvailable< std::vector<unsigned int> >("overlapsEl")) { - std::vector<unsigned int> overlapsEl = currentSystematic.auxdataConst< std::vector<unsigned int> >("overlapsEl"); + std::vector<unsigned int> overlapsEl = + currentSystematic.auxdataConst< std::vector<unsigned int> >("overlapsEl"); if (overlapsEl.size() == calibratedElectronsTDS->size()) { unsigned int counter(0); for (auto x : *calibratedElectronsTDS) { @@ -96,14 +153,47 @@ namespace top { } } } - + for (auto index : currentSystematic.goodElectrons()) { event.m_electrons.push_back(calibratedElectronsTDS->at(index)); } - + //shallow copies aren't sorted! - //sort only the selected muons (faster) - event.m_electrons.sort(top::descendingPtSorter); + //sort only the selected electrons (faster) + event.m_electrons.sort(top::descendingPtSorter); + } + + //forward electrons + if (m_config->useFwdElectrons()) { + const xAOD::ElectronContainer* calibratedFwdElectrons(nullptr); + top::check(evtStore()->retrieve(calibratedFwdElectrons, m_config->sgKeyFwdElectrons( + hash)), "Failed to retrieve fwd electrons"); + + ///-- Shallow copy and save to TStore --/// + if (!evtStore()->contains<xAOD::ElectronContainer>(m_config->sgKeyFwdElectronsTDS(hash))) { + std::pair< xAOD::ElectronContainer*, + xAOD::ShallowAuxContainer* > shallow_fwdelectrons = xAOD::shallowCopyContainer( + *calibratedFwdElectrons); + + xAOD::TReturnCode save = + evtStore()->tds()->record(shallow_fwdelectrons.first, m_config->sgKeyFwdElectronsTDS(hash)); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_fwdelectrons.second, m_config->sgKeyFwdElectronsTDSAux( + hash)); + top::check((save && saveAux), "Failed to store object in TStore"); + } + + ///-- Pull shallow copy back out of TStore in non-const way --/// + xAOD::ElectronContainer* calibratedFwdElectronsTDS(nullptr); + top::check(evtStore()->retrieve(calibratedFwdElectronsTDS, m_config->sgKeyFwdElectronsTDS( + hash)), "Failed to retrieve fwd electrons"); + + for (const auto& index : currentSystematic.goodFwdElectrons()) { + event.m_fwdElectrons.push_back(calibratedFwdElectronsTDS->at(index)); + } + + //shallow copies aren't sorted! + //sort only the selected fwd electrons (faster) + event.m_fwdElectrons.sort(top::descendingPtSorter); } //photons @@ -111,20 +201,23 @@ namespace top { ///-- Need to read const collections for mini-xaod read back --/// const xAOD::PhotonContainer* calibratedPhotons(nullptr); - top::check(evtStore()->retrieve(calibratedPhotons, m_config->sgKeyPhotons(hash) ), "Failed to retrieve photons"); + top::check(evtStore()->retrieve(calibratedPhotons, m_config->sgKeyPhotons(hash)), "Failed to retrieve photons"); ///-- Shallow copy and save to TStore --/// if (!evtStore()->contains<xAOD::PhotonContainer>(m_config->sgKeyPhotonsTDS(hash))) { - std::pair< xAOD::PhotonContainer*, xAOD::ShallowAuxContainer* > shallow_photons = xAOD::shallowCopyContainer( *calibratedPhotons ); + std::pair< xAOD::PhotonContainer*, xAOD::ShallowAuxContainer* > shallow_photons = xAOD::shallowCopyContainer( + *calibratedPhotons); - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_photons.first , m_config->sgKeyPhotonsTDS(hash) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_photons.second , m_config->sgKeyPhotonsTDSAux(hash) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_photons.first, m_config->sgKeyPhotonsTDS(hash)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_photons.second, m_config->sgKeyPhotonsTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); } ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::PhotonContainer* calibratedPhotonsTDS(nullptr); - top::check(evtStore()->retrieve(calibratedPhotonsTDS, m_config->sgKeyPhotonsTDS(hash) ), "Failed to retrieve photons"); + top::check(evtStore()->retrieve(calibratedPhotonsTDS, m_config->sgKeyPhotonsTDS( + hash)), "Failed to retrieve photons"); for (auto index : currentSystematic.goodPhotons()) { event.m_photons.push_back(calibratedPhotonsTDS->at(index)); @@ -136,26 +229,28 @@ namespace top { //muons if (m_config->useMuons()) { - ///-- Need to read const collections for mini-xaod read back --/// + ///-- Need to read const collections for mini-xaod read back --/// const xAOD::MuonContainer* calibratedMuons(nullptr); - top::check(evtStore()->retrieve(calibratedMuons, m_config->sgKeyMuons(hash) ), "Failed to retrieve muons"); - + top::check(evtStore()->retrieve(calibratedMuons, m_config->sgKeyMuons(hash)), "Failed to retrieve muons"); + ///-- Shallow copy and save to TStore --/// if (!evtStore()->contains<xAOD::MuonContainer>(m_config->sgKeyMuonsTDS(hash))) { - std::pair< xAOD::MuonContainer*, xAOD::ShallowAuxContainer* > shallow_muons = xAOD::shallowCopyContainer( *calibratedMuons ); - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_muons.first , m_config->sgKeyMuonsTDS(hash) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_muons.second , m_config->sgKeyMuonsTDSAux(hash) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + std::pair< xAOD::MuonContainer*, xAOD::ShallowAuxContainer* > shallow_muons = xAOD::shallowCopyContainer( + *calibratedMuons); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_muons.first, m_config->sgKeyMuonsTDS(hash)); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_muons.second, m_config->sgKeyMuonsTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); } - + ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::MuonContainer* calibratedMuonsTDS(nullptr); - top::check(evtStore()->retrieve(calibratedMuonsTDS, m_config->sgKeyMuonsTDS(hash) ), "Failed to retrieve muons"); - + top::check(evtStore()->retrieve(calibratedMuonsTDS, m_config->sgKeyMuonsTDS(hash)), "Failed to retrieve muons"); + // re-write overlap information if it is decorated onto currentSystematic if (currentSystematic.isAvailable< std::vector<unsigned int> >("overlapsMu")) { - std::vector<unsigned int> overlapsMu = currentSystematic.auxdataConst< std::vector<unsigned int> >("overlapsMu"); + std::vector<unsigned int> overlapsMu = + currentSystematic.auxdataConst< std::vector<unsigned int> >("overlapsMu"); if (overlapsMu.size() == calibratedMuonsTDS->size()) { unsigned int counter(0); for (auto x : *calibratedMuons) { @@ -163,40 +258,76 @@ namespace top { ++counter; } } - } - + } + for (auto index : currentSystematic.goodMuons()) { event.m_muons.push_back(calibratedMuonsTDS->at(index)); - } + } //shallow copies aren't sorted! //sort only the selected muons (faster) event.m_muons.sort(top::descendingPtSorter); } + //soft muons + if (m_config->useSoftMuons()) { + ///-- Need to read const collections for mini-xaod read back --/// + const xAOD::MuonContainer* calibratedSoftMuons(nullptr); + + top::check(evtStore()->retrieve(calibratedSoftMuons, m_config->sgKeySoftMuons(hash)), "Failed to retrieve muons"); + + + ///-- Shallow copy and save to TStore --/// + if (!evtStore()->contains<xAOD::MuonContainer>(m_config->sgKeySoftMuonsTDS(hash))) { + std::pair< xAOD::MuonContainer*, xAOD::ShallowAuxContainer* > shallow_softmuons = xAOD::shallowCopyContainer( + *calibratedSoftMuons); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_softmuons.first, m_config->sgKeySoftMuonsTDS(hash)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_softmuons.second, m_config->sgKeySoftMuonsTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); + } + + ///-- Pull shallow copy back out of TStore in non-const way --/// + xAOD::MuonContainer* calibratedSoftMuonsTDS(nullptr); + top::check(evtStore()->retrieve(calibratedSoftMuonsTDS, m_config->sgKeySoftMuonsTDS( + hash)), "Failed to retrieve soft muons"); + + //no overlap procedure applied to soft muons for the time being + + for (auto index : currentSystematic.goodSoftMuons()) { + event.m_softmuons.push_back(calibratedSoftMuonsTDS->at(index)); + } + + //shallow copies aren't sorted! + //sort only the selected soft muons (faster) + event.m_softmuons.sort(top::descendingPtSorter); + } + //taus if (m_config->useTaus()) { - ///-- Need to read const collections for mini-xaod read back --/// + ///-- Need to read const collections for mini-xaod read back --/// const xAOD::TauJetContainer* calibratedTaus(nullptr); - top::check(evtStore()->retrieve(calibratedTaus,m_config->sgKeyTaus(hash) ), "Failed to retrieve taus"); + top::check(evtStore()->retrieve(calibratedTaus, m_config->sgKeyTaus(hash)), "Failed to retrieve taus"); ///-- Shallow copy and save to TStore --/// if (!evtStore()->contains<xAOD::TauJetContainer>(m_config->sgKeyTausTDS(hash))) { - std::pair< xAOD::TauJetContainer*, xAOD::ShallowAuxContainer* > shallow_taus = xAOD::shallowCopyContainer( *calibratedTaus ); - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_taus.first , m_config->sgKeyTausTDS(hash) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_taus.second , m_config->sgKeyTausTDSAux(hash) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + std::pair< xAOD::TauJetContainer*, xAOD::ShallowAuxContainer* > shallow_taus = xAOD::shallowCopyContainer( + *calibratedTaus); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_taus.first, m_config->sgKeyTausTDS(hash)); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_taus.second, m_config->sgKeyTausTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); } - + ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::TauJetContainer* calibratedTausTDS(nullptr); - top::check(evtStore()->retrieve(calibratedTausTDS, m_config->sgKeyTausTDS(hash) ), "Failed to retrieve taus"); - + top::check(evtStore()->retrieve(calibratedTausTDS, m_config->sgKeyTausTDS(hash)), "Failed to retrieve taus"); + for (auto index : currentSystematic.goodTaus()) { event.m_tauJets.push_back(calibratedTausTDS->at(index)); - } - + } + //shallow copies aren't sorted! //sort only the selected taus (faster) event.m_tauJets.sort(top::descendingPtSorter); @@ -211,109 +342,240 @@ namespace top { looseJets = true; } } - + if (m_config->useJets()) { ///-- Need to read const collections for mini-xaod read back --/// - std::string sgKeyCalibrated( m_config->sgKeyJets(hash,looseJets) ); - std::string sgKeyTmp = "tmp_"+sgKeyCalibrated; - std::string sgKeyTmpAux = sgKeyTmp+"Aux."; - + std::string sgKeyCalibrated(m_config->sgKeyJets(hash, looseJets)); + std::string sgKeyTmp = "tmp_" + sgKeyCalibrated; + std::string sgKeyTmpAux = sgKeyTmp + "Aux."; + const xAOD::JetContainer* calibratedJets(nullptr); - top::check(evtStore()->retrieve(calibratedJets, m_config->sgKeyJets(hash,looseJets)), "Failed to retrieve jets"); + top::check(evtStore()->retrieve(calibratedJets, m_config->sgKeyJets(hash, looseJets)), "Failed to retrieve jets"); ///-- Shallow copy and save to TStore --/// - if (!evtStore()->contains<xAOD::JetContainer>(m_config->sgKeyJetsTDS(hash,looseJets))) { - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( *calibratedJets ); - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_jets.first , m_config->sgKeyJetsTDS(hash,looseJets) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_jets.second , m_config->sgKeyJetsTDSAux(hash,looseJets) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + if (!evtStore()->contains<xAOD::JetContainer>(m_config->sgKeyJetsTDS(hash, looseJets))) { + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( + *calibratedJets); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_jets.first, m_config->sgKeyJetsTDS(hash, looseJets)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_jets.second, m_config->sgKeyJetsTDSAux(hash, looseJets)); + top::check((save && saveAux), "Failed to store object in TStore"); } - + ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::JetContainer* calibratedJetsTDS(nullptr); - top::check(evtStore()->retrieve(calibratedJetsTDS, m_config->sgKeyJetsTDS(hash,looseJets) ), "Failed to retrieve taus"); - + top::check(evtStore()->retrieve(calibratedJetsTDS, m_config->sgKeyJetsTDS(hash, + looseJets)), "Failed to retrieve taus"); + + for (auto index : currentSystematic.goodJets()) { auto jet = calibratedJetsTDS->at(index); if (m_config->isMC()) { - // make product of SF (initialised to 1 in the header) - top::check( jet->isAvailable<float>("JET_SF_jvt") , " Can't find jet decoration \"JET_SF_jvt\" - we need it to calculate the jet scale-factors!"); + // JVT and fJVT, make product of SF (initialised to 1 in the header) + top::check(jet->isAvailable<float>( + "JET_SF_jvt"), + " Can't find jet decoration \"JET_SF_jvt\" - we need it to calculate the jet scale-factors!"); event.m_jvtSF *= jet->auxdataConst<float>("JET_SF_jvt"); - if (currentSystematic.hashValue() == m_config->nominalHashValue()) {// we only need the up/down JVT SF systs for nominal - top::check( jet->isAvailable<float>("JET_SF_jvt_UP") , " Can't find jet decoration \"JET_SF_jvt_UP\" - we need it to calculate the jet scale-factors!"); + + // fJVT scale factors not added to jets unless fJVT is requested + if (m_config->getfJVTWP() != "None") { + top::check(jet->isAvailable<float>( + "JET_SF_fjvt"), + " Can't find jet decoration \"JET_SF_fjvt\" - we need it to calculate the forward jet scale-factors!"); + event.m_fjvtSF *= jet->auxdataConst<float>("JET_SF_fjvt"); + } + if (currentSystematic.hashValue() == m_config->nominalHashValue()) {// we only need the up/down JVT SF systs + // for nominal + top::check(jet->isAvailable<float>( + "JET_SF_jvt_UP"), + " Can't find jet decoration \"JET_SF_jvt_UP\" - we need it to calculate the jet scale-factors!"); event.m_jvtSF_UP *= jet->auxdataConst<float>("JET_SF_jvt_UP"); - top::check( jet->isAvailable<float>("JET_SF_jvt_DOWN") , " Can't find jet decoration \"JET_SF_jvt_DOWN\" - we need it to calculate the jet scale-factors!"); + top::check(jet->isAvailable<float>( + "JET_SF_jvt_DOWN"), + " Can't find jet decoration \"JET_SF_jvt_DOWN\" - we need it to calculate the jet scale-factors!"); event.m_jvtSF_DOWN *= jet->auxdataConst<float>("JET_SF_jvt_DOWN"); - } - } - top::check( jet->isAvailable<char>("passJVT") , " Can't find jet decoration \"passJVT\" - we need it to decide if we should keep the jet in the top::Event instance or not!"); - if (jet->auxdataConst<char>( "passJVT" )) - event.m_jets.push_back(calibratedJetsTDS->at(index)); + // fJVT scale factors not added to jets unless fJVT is requested + if (m_config->getfJVTWP() != "None") { + top::check(jet->isAvailable<float>( + "JET_SF_fjvt_UP"), + " Can't find jet decoration \"JET_SF_fjvt_UP\" - we need it to calculate the forward jet scale-factors!"); + event.m_fjvtSF_UP *= jet->auxdataConst<float>("JET_SF_fjvt_UP"); + top::check(jet->isAvailable<float>( + "JET_SF_fjvt_DOWN"), + " Can't find jet decoration \"JET_SF_fjvt_DOWN\" - we need it to calculate the forward jet scale-factors!"); + event.m_fjvtSF_DOWN *= jet->auxdataConst<float>("JET_SF_fjvt_DOWN"); + } + } //isNominal + } //isMC + + top::check(jet->isAvailable<char>( + "passJVT"), + " Can't find jet decoration \"passJVT\" - we need it to decide if we should keep the jet in the top::Event instance or not!"); + bool passfJVT(true); + if (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None") { + top::check(jet->isAvailable<char>("AnalysisTop_fJVTdecision"), + " Can't find jet decoration \"AnalysisTop_fJVTdecision\" - we need it to decide if we should keep forward jets in the top::Event instance or not!"); + passfJVT = jet->auxdataConst<char>("AnalysisTop_fJVTdecision"); + if (m_config->saveFailForwardJVTJets()) { + if (!passfJVT) event.m_failFJvt_jets.push_back(calibratedJetsTDS->at(index)); + } + //Add to failFJVT collection but don't actually cut on fJVT if fJVT is only requested in MET calculation (I'm not sure people will ever actually do this) + if (m_config->getfJVTWP() == "None") passfJVT = true; + } + + if (jet->auxdataConst<char>("passJVT") && passfJVT) event.m_jets.push_back(calibratedJetsTDS->at(index)); + if (m_config->saveFailJVTJets()) { + if (!jet->auxdataConst<char>("passJVT")) event.m_failJvt_jets.push_back(calibratedJetsTDS->at(index)); + } } - + //shallow copies aren't sorted! //sort only the selected taus (faster) event.m_jets.sort(top::descendingPtSorter); + if (m_config->saveFailJVTJets()) event.m_failJvt_jets.sort(top::descendingPtSorter); + if ( (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None") && m_config->saveFailForwardJVTJets()){ + event.m_failFJvt_jets.sort(top::descendingPtSorter); + } + } + + // Reclustered jets + if (m_config->useRCJets()) { + top::check(m_rc->execute(event), "Failed to execute RCJetMC15 container"); + std::string rcJetContainerName = m_rc->rcjetContainerName(event.m_hashValue, event.m_isLoose); + const xAOD::JetContainer* rc_jets(nullptr); + top::check(evtStore()->retrieve(rc_jets, rcJetContainerName), "Failed to retrieve RC JetContainer"); + //Object selection + for (auto rcjet : *rc_jets) { + top::check(rcjet->isAvailable<bool>( + "PassedSelection"), + " Can't find jet decoration \"PassedSelection\" - we need it to decide if we should keep the reclustered jet in the top::Event instance or not!"); + if (rcjet->auxdataConst<bool>("PassedSelection")) event.m_RCJets.push_back((xAOD::Jet*) rcjet); + } + } + // Variable-R reclustered jets + if (m_config->useVarRCJets()) { + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + top::check(m_VarRC[name]->execute(event), "Failed to execute RCJetMC15 container"); + + // Get the name of the container of re-clustered jets in TStore + std::string varRCJetContainerName = m_VarRC[name]->rcjetContainerName(event.m_hashValue, event.m_isLoose); + + // -- Retrieve the re-clustered jets from TStore & save good re-clustered jets -- // + const xAOD::JetContainer* vrc_jets(nullptr); + top::check(evtStore()->retrieve(vrc_jets, varRCJetContainerName), "Failed to retrieve RC JetContainer"); + + event.m_VarRCJets[name] = std::make_shared<xAOD::JetContainer>(SG::VIEW_ELEMENTS); + for (auto vrcjet : *vrc_jets) { + top::check(vrcjet->isAvailable<bool>( + "PassedSelection"), + " Can't find jet decoration \"PassedSelection\" - we need it to decide if we should keep the variable-R reclustered jet in the top::Event instance or not!"); + if (vrcjet->auxdataConst<bool>("PassedSelection")) event.m_VarRCJets[name]->push_back((xAOD::Jet*) vrcjet); + } + } + } } + //large-R jets if (m_config->useLargeRJets()) { - ///-- Need to read const collections for mini-xaod read back --/// + ///-- Need to read const collections for mini-xaod read back --/// const xAOD::JetContainer* calibratedJets(nullptr); - top::check(evtStore()->retrieve(calibratedJets,m_config->sgKeyLargeRJets(hash) ), "Failed to retrieve largeR jets"); + top::check(evtStore()->retrieve(calibratedJets, m_config->sgKeyLargeRJets(hash)), + "Failed to retrieve largeR jets"); ///-- Shallow copy and save to TStore --/// if (!evtStore()->contains<xAOD::JetContainer>(m_config->sgKeyLargeRJetsTDS(hash))) { - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( *calibratedJets ); - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_jets.first , m_config->sgKeyLargeRJetsTDS(hash) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_jets.second , m_config->sgKeyLargeRJetsTDSAux(hash) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( + *calibratedJets); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_jets.first, m_config->sgKeyLargeRJetsTDS(hash)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_jets.second, m_config->sgKeyLargeRJetsTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); } - + ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::JetContainer* calibratedJetsTDS(nullptr); - top::check(evtStore()->retrieve(calibratedJetsTDS, m_config->sgKeyLargeRJetsTDS(hash) ), "Failed to retrieve largeR jets"); - + top::check(evtStore()->retrieve(calibratedJetsTDS, m_config->sgKeyLargeRJetsTDS( + hash)), "Failed to retrieve largeR jets"); + for (auto index : currentSystematic.goodLargeRJets()) { event.m_largeJets.push_back(calibratedJetsTDS->at(index)); - } - + } + //shallow copies aren't sorted! //sort only the selected jets (faster) event.m_largeJets.sort(top::descendingPtSorter); } - + //track jets if (m_config->useTrackJets()) { - ///-- Need to read const collections for mini-xaod read back --/// + ///-- Need to read const collections for mini-xaod read back --/// const xAOD::JetContainer* calibratedJets(nullptr); - top::check(evtStore()->retrieve(calibratedJets,m_config->sgKeyTrackJets(hash) ), "Failed to retrieve track jets"); + top::check(evtStore()->retrieve(calibratedJets, m_config->sgKeyTrackJets(hash)), "Failed to retrieve track jets"); ///-- Shallow copy and save to TStore --/// if (!evtStore()->contains<xAOD::JetContainer>(m_config->sgKeyTrackJetsTDS(hash))) { - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( *calibratedJets ); - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_jets.first , m_config->sgKeyTrackJetsTDS(hash) ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_jets.second , m_config->sgKeyTrackJetsTDSAux(hash) ); - top::check( (save && saveAux) , "Failed to store object in TStore"); + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( + *calibratedJets); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_jets.first, m_config->sgKeyTrackJetsTDS(hash)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_jets.second, m_config->sgKeyTrackJetsTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); } - + ///-- Pull shallow copy back out of TStore in non-const way --/// xAOD::JetContainer* calibratedJetsTDS(nullptr); - top::check(evtStore()->retrieve(calibratedJetsTDS, m_config->sgKeyTrackJetsTDS(hash) ), "Failed to retrieve track jets"); - + top::check(evtStore()->retrieve(calibratedJetsTDS, m_config->sgKeyTrackJetsTDS( + hash)), "Failed to retrieve track jets"); + for (auto index : currentSystematic.goodTrackJets()) { event.m_trackJets.push_back(calibratedJetsTDS->at(index)); - } - + } + //shallow copies aren't sorted! //sort only the selected jets (faster) event.m_trackJets.sort(top::descendingPtSorter); - } + } + + if (m_config->useTracks()) { + + ///-- Need to read const collections for mini-xaod read back --/// + const xAOD::TrackParticleContainer* calibratedTracks(nullptr); + top::check(evtStore()->retrieve(calibratedTracks, m_config->sgKeyTracks(hash)), "Failed to retrieve tracks"); + + ///-- Shallow copy and save to TStore --/// + if (!evtStore()->contains<xAOD::TrackParticleContainer>(m_config->sgKeyTracksTDS(hash))) { + + std::pair< xAOD::TrackParticleContainer*, xAOD::ShallowAuxContainer* > shallow_tracks = xAOD::shallowCopyContainer(*calibratedTracks); + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_tracks.first, m_config->sgKeyTracksTDS(hash)); + xAOD::TReturnCode saveAux = + evtStore()->tds()->record(shallow_tracks.second, m_config->sgKeyTracksTDSAux(hash)); + top::check((save && saveAux), "Failed to store object in TStore"); + } + + ///-- Pull shallow copy back out of TStore in non-const way --/// + xAOD::TrackParticleContainer* calibratedTracksTDS(nullptr); + top::check(evtStore()->retrieve(calibratedTracksTDS, m_config->sgKeyTracksTDS(hash)), "Failed to retrieve tracks"); + + for (auto index : currentSystematic.goodTracks()) { + event.m_tracks.push_back(calibratedTracksTDS->at(index)); + } + + //shallow copies aren't sorted! + //sort only the selected tracks (faster) + event.m_tracks.sort(top::descendingPtSorter); + + } + //met const xAOD::MissingETContainer* mets(nullptr); @@ -324,33 +586,90 @@ namespace top { top::check(evtStore()->retrieve(mets, m_config->sgKeyMissingEtLoose(hash)), "Failed to retrieve MET"); } event.m_met = (*mets)["FinalTrk"]; // MissingETBase::Source::total()]; - + //MC if (m_config->isMC()) { - // Truth particles (these are BIG) if (m_config->useTruthParticles()) { - top::check(evtStore()->retrieve(event.m_truth, m_config->sgKeyMCParticle()), "Failed to retrieve truth particles"); - } - + top::check(evtStore()->retrieve(event.m_truth, + m_config->sgKeyMCParticle()), "Failed to retrieve truth particles"); + } + // Truth Event - top::check(evtStore()->retrieve(event.m_truthEvent,m_config->sgKeyTruthEvent()),"Failed to retrieve truth Event"); - + if (TopEventMaker::s_hasTruthEvent) { + bool hasTruthEvent = evtStore()->retrieve(event.m_truthEvent, m_config->sgKeyTruthEvent()); + if (!hasTruthEvent) { + ATH_MSG_WARNING("Failed to retrieve truth Event. TopEvent::m_truthEvent will be nullptr!"); + TopEventMaker::s_hasTruthEvent = false; + } + } + // Parton History if (m_config->doTopPartonHistory()) { if (evtStore()->contains<xAOD::PartonHistoryContainer>(m_config->sgKeyTopPartonHistory())) { const xAOD::PartonHistoryContainer* partonHistory(nullptr); - top::check(evtStore()->retrieve(partonHistory, m_config->sgKeyTopPartonHistory()),"Failed to retrieve Top Parton History"); + top::check(evtStore()->retrieve(partonHistory, + m_config->sgKeyTopPartonHistory()), "Failed to retrieve Top Parton History"); if (partonHistory->size() == 1) { event.m_partonHistory = partonHistory->at(0); - } + } } } // end doTopPartonHistory - - } // end isMC - - + } // end isMC + decorateTopEvent(event); + return event; } + + void TopEventMaker::decorateTopEvent(top::Event &event) + { + if(m_config->useSoftMuons()) decorateTopEventSoftMuons(event); + } + + void TopEventMaker::decorateTopEventSoftMuons(top::Event &event) + { + if(!m_config->useJets()) return; + + //first we initialize decorations for all jets + for(const xAOD::Jet* jet : event.m_jets) + { + jet->auxdecor<int>("AT_SoftMuonIndex")=-1; + jet->auxdecor<float>("AT_SoftMuonDR")=-1; + } + + int imuon=0; + for(const xAOD::Muon* sm : event.m_softmuons) + { + //writing auxiliary info for SMT jet tagging + double dRmin=100.; + int nearestJetIndex=-1; + int ijet=0; + for(const xAOD::Jet *jet : event.m_jets) + { + double dr= xAOD::P4Helpers::deltaR(sm,jet,m_config->softmuonDRJetcutUseRapidity()); + if(dr<dRmin && dr<m_config->softmuonDRJetcut()) + { + dRmin=dr; + nearestJetIndex=ijet; + } + ijet++; + } + sm->auxdecor<int>("AT_SMTJetIndex")=nearestJetIndex; + sm->auxdecor<float>("AT_SMTJetDR")=dRmin; + + if(nearestJetIndex>=0) + { + const xAOD::Jet *jet = event.m_jets[nearestJetIndex]; + if(jet->auxdecor<int>("AT_SoftMuonIndex")<0) //in this way we only associate a jet with the highest pt soft muon + { + jet->auxdecor<int>("AT_SoftMuonIndex")=imuon; + jet->auxdecor<float>("AT_SoftMuonDR")=dRmin; + } + }//end of case where we found a jet nearby + + imuon++; + }//end of loop on muons + + }//end of TopEventMaker::decorateTopEvent } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/Event.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/Event.h index 6216e0afec9220123e6cfef6b5cdcf7eca21b981..205300b4823a50ff71e3ea1e973affeb274e2404 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/Event.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/Event.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPEVENT_H_ #define TOPEVENT_H_ @@ -9,6 +9,7 @@ #include "xAODTracking/VertexContainer.h" #include "xAODEgamma/ElectronContainer.h" +#include "xAODEgamma/ElectronContainerFwd.h" #include "xAODEgamma/PhotonContainer.h" #include "xAODMuon/MuonContainer.h" #include "xAODJet/JetContainer.h" @@ -24,12 +25,17 @@ #include <ostream> #include <iostream> + + +namespace xAOD { + class SystematicEvent; +} + /** * @brief A namespace for the top group, to avoid using the same name as * somewhere else in the code. */ namespace top { - /** * @brief Very simple class to hold event data after reading from a file. * @@ -40,32 +46,37 @@ namespace top { * The best way to ensure this is reset every event is probably to make a new * one every event, that way it'll tidy-up after itself. */ -class Event { -public: + class Event { + public: Event() : - m_hashValue(0), // this will be set properly by TopEventMaker - m_ttreeIndex(99999), // this will be set properly by TopEventMaker - m_isLoose(false), // this will be set properly by TopEventMaker - m_saveEvent(false), - m_info(nullptr), - m_primaryVertices(nullptr), - m_electrons(SG::VIEW_ELEMENTS), - m_muons(SG::VIEW_ELEMENTS), - m_jets(SG::VIEW_ELEMENTS), - m_photons(SG::VIEW_ELEMENTS), - m_largeJets(SG::VIEW_ELEMENTS), - m_trackJets(SG::VIEW_ELEMENTS), - m_tauJets(SG::VIEW_ELEMENTS), - m_met(nullptr), - - m_truthEvent(nullptr), - m_truth(nullptr), - m_partonHistory(nullptr), - m_KLFitterResults(nullptr), - m_PseudoTopResult(nullptr) - { + m_hashValue(0), // this will be set properly by TopEventMaker + m_ttreeIndex(99999), // this will be set properly by TopEventMaker + m_isLoose(false), // this will be set properly by TopEventMaker + m_saveEvent(false), + m_info(nullptr), + m_primaryVertices(nullptr), + m_electrons(SG::VIEW_ELEMENTS), + m_fwdElectrons(SG::VIEW_ELEMENTS), + m_muons(SG::VIEW_ELEMENTS), + m_softmuons(SG::VIEW_ELEMENTS), + m_jets(SG::VIEW_ELEMENTS), + m_failJvt_jets(SG::VIEW_ELEMENTS), + m_failFJvt_jets(SG::VIEW_ELEMENTS), + m_photons(SG::VIEW_ELEMENTS), + m_largeJets(SG::VIEW_ELEMENTS), + m_RCJets(SG::VIEW_ELEMENTS), + m_trackJets(SG::VIEW_ELEMENTS), + m_tracks(SG::VIEW_ELEMENTS), + m_tauJets(SG::VIEW_ELEMENTS), + m_met(nullptr), + + m_truthEvent(nullptr), + m_truth(nullptr), + m_partonHistory(nullptr), + m_KLFitterResults(nullptr), + m_PseudoTopResult(nullptr) { } - + ///systematic has value std::size_t m_hashValue; ///TTree index @@ -74,71 +85,97 @@ public: bool m_isLoose; ///save the event? bool m_saveEvent; - + ///Pointer to the event info - nullptr if not loaded, but that's probably a bad idea const xAOD::EventInfo* m_info; - + + ///Pointer to the systematic event info - nullptr if not loaded, but that's probably a bad idea + xAOD::SystematicEvent const* m_systematicEvent; + ///Primary Vertices - const xAOD::VertexContainer* m_primaryVertices; + const xAOD::VertexContainer* m_primaryVertices; ///Container of electrons (can be sorted) xAOD::ElectronContainer m_electrons; + ///Container of forward electrons (can be sorted) + xAOD::ElectronContainer m_fwdElectrons; + ///Container of muons (can be sorted) xAOD::MuonContainer m_muons; + ///Container of soft muons (can be sorted) + xAOD::MuonContainer m_softmuons; + ///Container of jets (can be sorted) xAOD::JetContainer m_jets; - - ///Container of photons (can be sorted) + + ///Container of fail-JVT jets (can be sorted) + xAOD::JetContainer m_failJvt_jets; + + ///Container of fail-FJVT jets (can be sorted) + xAOD::JetContainer m_failFJvt_jets; + + ///Container of photons (can be sorted) xAOD::PhotonContainer m_photons; ///Container of large jets (can be sorted) xAOD::JetContainer m_largeJets; - + + ///Container of recluster jets (can be sorted) + xAOD::JetContainer m_RCJets; + + /// Containers of variable-R reclustered jets (can be sorted) + mutable std::unordered_map< std::string, std::shared_ptr<xAOD::JetContainer> > m_VarRCJets; + ///Container of track jets (can be sorted) - xAOD::JetContainer m_trackJets; + xAOD::JetContainer m_trackJets; + + ///Container of tracks (can be sorted) + xAOD::TrackParticleContainer m_tracks; ///Container of taujets (can be sorted) xAOD::TauJetContainer m_tauJets; ///Pointer to MET if it is loaded const xAOD::MissingET* m_met; - + ///Truth event const xAOD::TruthEventContainer* m_truthEvent; ///Container of truth particles - const xAOD::TruthParticleContainer *m_truth; - + const xAOD::TruthParticleContainer* m_truth; + ///Top Parton TopPartonHistory - const xAOD::PartonHistory* m_partonHistory; - + const xAOD::PartonHistory* m_partonHistory; + ///KLFitter Results mutable const xAOD::KLFitterResultContainer* m_KLFitterResults; ///Pseudo Top Results mutable const xAOD::PseudoTopResultContainer* m_PseudoTopResult; - ///JVT SFs - now needed here because it includes jets that are good jets, + ///JVT and fJVT SFs - now needed here because they include jets that are good jets, ///but which are not in the top::Event::m_jets container float m_jvtSF = 1.; float m_jvtSF_UP = 1.; float m_jvtSF_DOWN = 1.; - -}; - + float m_fjvtSF = 1.; + float m_fjvtSF_UP = 1.; + float m_fjvtSF_DOWN = 1.; + }; } -std::ostream& operator<<(std::ostream& os, const TLorentzVector& v); -std::ostream& operator<<(std::ostream& os, const top::Event& event); -std::ostream& operator<<(std::ostream& os, const xAOD::EventInfo& ei); -std::ostream& operator<<(std::ostream& os, const xAOD::Electron& el); -std::ostream& operator<<(std::ostream& os, const xAOD::Muon& mu); -std::ostream& operator<<(std::ostream& os, const xAOD::Photon& ph); -std::ostream& operator<<(std::ostream& os, const xAOD::Jet& jet); -std::ostream& operator<<(std::ostream& os, const xAOD::TauJet& tau); -std::ostream& operator<<(std::ostream& os, const xAOD::TruthParticle& truth); -std::ostream& operator<<(std::ostream& os, const xAOD::MissingET& met); +std::ostream& operator << (std::ostream& os, const TLorentzVector& v); +std::ostream& operator << (std::ostream& os, const top::Event& event); +std::ostream& operator << (std::ostream& os, const xAOD::EventInfo& ei); +std::ostream& operator << (std::ostream& os, const xAOD::Electron& el); +std::ostream& operator << (std::ostream& os, const xAOD::Muon& mu); +std::ostream& operator << (std::ostream& os, const xAOD::Photon& ph); +std::ostream& operator << (std::ostream& os, const xAOD::Jet& jet); +std::ostream& operator << (std::ostream& os, const xAOD::TauJet& tau); +std::ostream& operator << (std::ostream& os, const xAOD::TruthParticle& truth); +std::ostream& operator << (std::ostream& os, const xAOD::MissingET& met); +std::ostream& operator << (std::ostream& os, const xAOD::TrackParticle& track); #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/EventTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/EventTools.h index b11b64ca534eac12ff1ae7552a79bc5ef55228d7..45dc2bcbcfad53a1232a8664f787884db64306f6 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/EventTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/EventTools.h @@ -1,11 +1,12 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTTOOLS_H_ #define EVENTTOOLS_H_ #include <string> +#include <vector> #include "xAODMissingET/MissingET.h" @@ -19,11 +20,62 @@ */ namespace xAOD { -class IParticle; + class IParticle; } namespace top { -class Event; + class Event; + + ///this enum defines a flag used to understand the partonic origin of a lepton (tipically a soft muon), i.e. if it is produced by the direct decay of a boson, + ///or, in the case it is from a HF hadron decay, what is the boson/parton that originated the HF hadron. + ///This flag will not work for Sherpa samples given the structure of Sherpa's truth record. + /// note that in case of light-hadrons->muons the muon will always be considered as from "unknown", because often we cannot reconstruct the history when light hadrons are involved... + enum class LepPartonOriginFlag{ + MissingTruthInfo=0, ///< e.g. this can mean the muon is coming from light hadrons and there is no truth history, or anyway it was impossible to reconstruct the history + FromAntiTopViaHadronicBosonToHF=-3, ///< tipically means that the muon is coming from tbar->W->...->muon in some way (or any tbar->W/Z/gamma*/H->...->muon), the "..." must involve HF hadrons + FromAntiTopViaLeptonicBoson=-2, ///< tipically means that the muon is coming from tbar->W->...->muon in some way (or any tbar->W/Z/gamma*/H->...->muon), the "..." cannot involve hadrons + FromAntiTopViaQuarkToHF=-1, ///< tipically means that the muon is coming from tbar->bbar->...->muon in some way (or any tbar->qbar->...->muon), the "..." will for sure involve HF hadrons + FromTopViaQuarkToHF=1, ///< tipically means that the muon is coming from t->b->...->muon in some way (or any t->q->...->muon), the "..." will for sure involve HF hadrons + FromTopViaLeptonicBoson=2, ///< tipically means that the muon is coming from t->W->...->muon in some way (or any t->W/Z/gamma*/H->...->muon), the "..." cannot involve hadrons + FromTopViaHadronicBosonToHF=3, ///< tipically means that the muon is coming from t->W->...->muon in some way (or any t->W/Z/gamma*/H->...->muon), the "..." must involve HF hadrons + FromLeptonicBoson=4, ///< general case of W/Z/gamma*/H->muon or W/Z/gamma*/H->tau->muon + FromHadronicBosonToHF=5, ///< general case of W/Z/gamma*/H->HF hadrons->muon + FromHFHadronOfUnkownOrigin=6, ///< HF hadron->muon or HF hadron->tau->muon, we're not sure where the HF hadron is coming from (maybe a gluon?) + FromHiggsViaLeptonicBosonToHF=7, ///H->VV->muon + FromHiggsViaHadronicBosonToHF=8, ///H->VV->HF->muon + FromHiggsToHF=9, ///H->HF->muon, not sure if this can happen in some generators + FromHiggs=10, ///direct H->muon + FromBSM=1000, /// BSMparticle->muon + FromBSMViaLeptonicBosonToHF=1001, /// BSMparticle->V->muon + FromBSMViaHadronicBosonToHF=1002, /// BSMparticle->V->HF->muon + FromBSMToHF=1003, /// BSMparticle->HF->muon + Unknown=9999, /// we have truth info but we were unable to classify the muon + }; + + ///this enum defines a flag used to understand the particle origin of a lepton (tipically a soft muon), + ///i.e. if it is from a boson decay, from a B-hadron, from a B->D->mu decay, etc... + enum class LepParticleOriginFlag{ + MissingTruthInfo=0, ///< no associated truth muon tipically this happens for muon from light-hadrons + FromPhoton=22, ///gamma*->muonmuon + FromPhotonToTau=2215, ///gamma*->tautau and tau->muon + FromLeptonicZ=23, ///< from Z->tau->lep (note: this will not work for Sherpa) + FromLeptonicZToTau=2315, ///< from Z->tau->lep (note: this will not work for Sherpa) + FromLeptonicW=24, ///< from W with leptonic decay (note: this will not work for Sherpa) + FromLeptonicWToTau=2415, ///< from W->tau->lep (note: this will not work for Sherpa) + FromHiggs=25, ///Higgs->muon + FromHiggsToTau=2515, ///Higgs->tau->mu + FromB=5, ///< from direct B-hadron decay + FromBtoTau=515, ///< from B-hadron to tau to mu decay + FromBtoC=54, ///< from B-hadron to C-hadron to muon decay + FromBtoCtoTau=5415, ///< from B-hadron to C-hadron to tau to muon decay + FromC=4, ///< from direct C-hadron (with no B-hadron parent) decay + FromCtoTau=415, ///< from C-hadron (with no B-hadron parent) to tau to mu decay + FromTau=15, ///< from Tau leptonic (not coming from W or HF-hadron, so not sure this can really happen) + FromLightHadron=100, ///< often these muons are Unknown, but in some cases we have the truth record and we can verify they are from light-hadrons + FromBSM=1000, ///BSMparticle->muon + FromBSMToTau=1001, ///BSMparticle->tau->muon + Unknown=9999, /// we have truth info but we were unable to classify the muon + }; /** * @brief Print an error message and terminate if thingToCheck is false. @@ -31,12 +83,12 @@ class Event; * Lots of the xAOD functions need checking to see if they work or not. I guess * we take the approach that if it didn't work, we should not really try to * recover but just print a message and quit as soon as we can. So, this will - * either return nothing or quit your program. + * either return nothing or quit your program via exception. * * @param thingToCheck The thing to check. If it's false then print the error - * message and quit. + * message via std::runtime_error exception. */ -void check(bool thingToCheck, const std::string& usefulFailureMessage); + void check(bool thingToCheck, const std::string& usefulFailureMessage); /** * @brief Calculate the delta-r distance between two particles (e.g. an Electron @@ -49,7 +101,7 @@ void check(bool thingToCheck, const std::string& usefulFailureMessage); * @param p2 The second particle of the two. * @return delta-R metric. */ -double deltaR(const xAOD::IParticle& p1, const xAOD::IParticle& p2); + double deltaR(const xAOD::IParticle& p1, const xAOD::IParticle& p2); /** * @brief Calculate delta-phi between two particles (e.g. an Electron and a @@ -59,7 +111,7 @@ double deltaR(const xAOD::IParticle& p1, const xAOD::IParticle& p2); * @param p2 The second particle of the two. * @return Signed delta-phi in radians. */ -double deltaPhi(const xAOD::IParticle& p1, const xAOD::IParticle& p2); + double deltaPhi(const xAOD::IParticle& p1, const xAOD::IParticle& p2); /** * @brief Calculate the transverse mass of the W from the charged lepton and @@ -69,7 +121,7 @@ double deltaPhi(const xAOD::IParticle& p1, const xAOD::IParticle& p2); * * @return The calculated value, obviously. */ -double mwt(const xAOD::IParticle& lepton, const xAOD::MissingET& met); + double mwt(const xAOD::IParticle& lepton, const xAOD::MissingET& met); /** * @brief HT calculation. @@ -79,7 +131,7 @@ double mwt(const xAOD::IParticle& lepton, const xAOD::MissingET& met); * * @return The HT value. */ -double ht(const top::Event& event); + double ht(const top::Event& event); /** * @brief Calculate the invariant mass of two particles. @@ -92,14 +144,14 @@ double ht(const top::Event& event); * * @return The invariant mass of the pair. */ -double invariantMass(const xAOD::IParticle& p1, const xAOD::IParticle& p2); + double invariantMass(const xAOD::IParticle& p1, const xAOD::IParticle& p2); /** * @brief Is this event MC simulation (True) or data (False)? * * @return True if the event is MC simulation. */ -bool isSimulation(const top::Event& event); + bool isSimulation(const top::Event& event); /** * @brief Used when sorting the e, mu, jet, tau containers after CP corrections. @@ -111,8 +163,16 @@ bool isSimulation(const top::Event& event); * @param p2 The second particle of the two. * */ -bool descendingPtSorter(const xAOD::IParticle* p0, const xAOD::IParticle* p1); + bool descendingPtSorter(const xAOD::IParticle* p0, const xAOD::IParticle* p1); +/** + * @brief Function used to create poisson weights (mean of 1) for bootstrapping + * + * @param nreplicas The number of replicas to fill (corresponds to size of output vector) + * @param eventNumber The event number used to seed TRandom3 + * @param mcChannelNumber The DSID of MC event used to seed TRandom3 + */ + std::vector<int> calculateBootstrapWeights(int nreplicas, int eventNumber, int mcChannelNumber); } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/KLFitterResult.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/KLFitterResult.h index d19b2bdbca6ded8f12ef1185d445f1aab67156e7..e38e742ef615b1ddacada63145c692435243b570 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/KLFitterResult.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/KLFitterResult.h @@ -1,25 +1,25 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: SystematicEvent.h 661144 2015-04-17 09:09:07Z morrisj $ #ifndef ANALYSISTOP_TOPEVENT_KLFITTERRESULT_H #define ANALYSISTOP_TOPEVENT_KLFITTERRESULT_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief KLFitterResult - * A simple xAOD class which we can persist into a mini-xAOD - * The xAOD EDM is way too complex, so let's simplify it - * It's not like ROOT can do schema evolution...... - * - * This class contains the result of the KLFitter algorithm - * - * $Revision: 661144 $ - * $Date: 2015-04-17 10:09:07 +0100 (Fri, 17 Apr 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief KLFitterResult + * A simple xAOD class which we can persist into a mini-xAOD + * The xAOD EDM is way too complex, so let's simplify it + * It's not like ROOT can do schema evolution...... + * + * This class contains the result of the KLFitter algorithm + * + * $Revision: 661144 $ + * $Date: 2015-04-17 10:09:07 +0100 (Fri, 17 Apr 2015) $ + * + **/ // EDM include(s): #include "AthContainers/DataVector.h" @@ -29,338 +29,594 @@ #include <vector> #include <stdint.h> -namespace xAOD{ - - /// Aux Container - class KLFitterResultAuxContainer : public AuxContainerBase { - public: - KLFitterResultAuxContainer(); - private: - - /// Error flags - std::vector<short> minuitDidNotConverge; - std::vector<short> fitAbortedDueToNaN; - std::vector<short> atLeastOneFitParameterAtItsLimit; - std::vector<short> invalidTransferFunctionAtConvergence; - - /// Global result - std::vector<unsigned int> bestPermutation; - std::vector<float> logLikelihood; - std::vector<float> eventProbability; - std::vector<std::vector<double>> parameters; - std::vector<std::vector<double>> parameterErrors; - - /// Model - std::vector<float> model_bhad_pt; - std::vector<float> model_bhad_eta; - std::vector<float> model_bhad_phi; - std::vector<float> model_bhad_E; - std::vector<unsigned int> model_bhad_jetIndex; - - std::vector<float> model_blep_pt; - std::vector<float> model_blep_eta; - std::vector<float> model_blep_phi; - std::vector<float> model_blep_E; - std::vector<unsigned int> model_blep_jetIndex; - - std::vector<float> model_lq1_pt; - std::vector<float> model_lq1_eta; - std::vector<float> model_lq1_phi; - std::vector<float> model_lq1_E; - std::vector<unsigned int> model_lq1_jetIndex; - - std::vector<float> model_lq2_pt; - std::vector<float> model_lq2_eta; - std::vector<float> model_lq2_phi; - std::vector<float> model_lq2_E; - std::vector<unsigned int> model_lq2_jetIndex; - - - // model particles in case of TTH topology - std::vector<float> model_Higgs_b1_pt; - std::vector<float> model_Higgs_b1_eta; - std::vector<float> model_Higgs_b1_phi; - std::vector<float> model_Higgs_b1_E; - std::vector<unsigned int> model_Higgs_b1_jetIndex; - - std::vector<float> model_Higgs_b2_pt; - std::vector<float> model_Higgs_b2_eta; - std::vector<float> model_Higgs_b2_phi; - std::vector<float> model_Higgs_b2_E; - std::vector<unsigned int> model_Higgs_b2_jetIndex; - - - std::vector<float> model_lep_pt; - std::vector<float> model_lep_eta; - std::vector<float> model_lep_phi; - std::vector<float> model_lep_E; - - std::vector<float> model_nu_pt; - std::vector<float> model_nu_eta; - std::vector<float> model_nu_phi; - std::vector<float> model_nu_E; - - - +namespace xAOD { + /// Aux Container + class KLFitterResultAuxContainer: public AuxContainerBase { + public: + KLFitterResultAuxContainer(); + private: + /// Name of selection run + std::vector<std::size_t> selectionCode; + + /// Error flags + std::vector<short> minuitDidNotConverge; + std::vector<short> fitAbortedDueToNaN; + std::vector<short> atLeastOneFitParameterAtItsLimit; + std::vector<short> invalidTransferFunctionAtConvergence; + + /// Global result + std::vector<unsigned int> bestPermutation; + std::vector<float> logLikelihood; + std::vector<float> eventProbability; + std::vector<std::vector<double> > parameters; + std::vector<std::vector<double> > parameterErrors; + + /// Model + std::vector<float> model_bhad_pt; + std::vector<float> model_bhad_eta; + std::vector<float> model_bhad_phi; + std::vector<float> model_bhad_E; + std::vector<unsigned int> model_bhad_jetIndex; + + std::vector<float> model_blep_pt; + std::vector<float> model_blep_eta; + std::vector<float> model_blep_phi; + std::vector<float> model_blep_E; + std::vector<unsigned int> model_blep_jetIndex; + + std::vector<float> model_lq1_pt; + std::vector<float> model_lq1_eta; + std::vector<float> model_lq1_phi; + std::vector<float> model_lq1_E; + std::vector<unsigned int> model_lq1_jetIndex; + + std::vector<float> model_lq2_pt; + std::vector<float> model_lq2_eta; + std::vector<float> model_lq2_phi; + std::vector<float> model_lq2_E; + std::vector<unsigned int> model_lq2_jetIndex; + + + // model particles in case of TTH topology + std::vector<float> model_Higgs_b1_pt; + std::vector<float> model_Higgs_b1_eta; + std::vector<float> model_Higgs_b1_phi; + std::vector<float> model_Higgs_b1_E; + std::vector<unsigned int> model_Higgs_b1_jetIndex; + + std::vector<float> model_Higgs_b2_pt; + std::vector<float> model_Higgs_b2_eta; + std::vector<float> model_Higgs_b2_phi; + std::vector<float> model_Higgs_b2_E; + std::vector<unsigned int> model_Higgs_b2_jetIndex; + + + std::vector<float> model_lep_pt; + std::vector<float> model_lep_eta; + std::vector<float> model_lep_phi; + std::vector<float> model_lep_E; + std::vector<unsigned int> model_lep_index; + + // model particles for the TTZ trilepton channel + std::vector<float> model_lepZ1_pt; + std::vector<float> model_lepZ1_eta; + std::vector<float> model_lepZ1_phi; + std::vector<float> model_lepZ1_E; + std::vector<unsigned int> model_lepZ1_index; + + std::vector<float> model_lepZ2_pt; + std::vector<float> model_lepZ2_eta; + std::vector<float> model_lepZ2_phi; + std::vector<float> model_lepZ2_E; + std::vector<unsigned int> model_lepZ2_index; + + std::vector<float> model_nu_pt; + std::vector<float> model_nu_eta; + std::vector<float> model_nu_phi; + std::vector<float> model_nu_E; + + // model particles for ttbar allhadronic channel + std::vector<float> model_b_from_top1_pt; + std::vector<float> model_b_from_top1_eta; + std::vector<float> model_b_from_top1_phi; + std::vector<float> model_b_from_top1_E; + std::vector<unsigned int> model_b_from_top1_jetIndex; + + std::vector<float> model_b_from_top2_pt; + std::vector<float> model_b_from_top2_eta; + std::vector<float> model_b_from_top2_phi; + std::vector<float> model_b_from_top2_E; + std::vector<unsigned int> model_b_from_top2_jetIndex; + + std::vector<float> model_lj1_from_top1_pt; + std::vector<float> model_lj1_from_top1_eta; + std::vector<float> model_lj1_from_top1_phi; + std::vector<float> model_lj1_from_top1_E; + std::vector<unsigned int> model_lj1_from_top1_jetIndex; + + std::vector<float> model_lj2_from_top1_pt; + std::vector<float> model_lj2_from_top1_eta; + std::vector<float> model_lj2_from_top1_phi; + std::vector<float> model_lj2_from_top1_E; + std::vector<unsigned int> model_lj2_from_top1_jetIndex; + + std::vector<float> model_lj1_from_top2_pt; + std::vector<float> model_lj1_from_top2_eta; + std::vector<float> model_lj1_from_top2_phi; + std::vector<float> model_lj1_from_top2_E; + std::vector<unsigned int> model_lj1_from_top2_jetIndex; + + std::vector<float> model_lj2_from_top2_pt; + std::vector<float> model_lj2_from_top2_eta; + std::vector<float> model_lj2_from_top2_phi; + std::vector<float> model_lj2_from_top2_E; + std::vector<unsigned int> model_lj2_from_top2_jetIndex; }; - + /// Interface class - class KLFitterResult : public SG::AuxElement { - public: - /// Default constructor - KLFitterResult(); - /// Default destructor - virtual ~KLFitterResult(){} - - /// get minuitDidNotConverge - short minuitDidNotConverge() const; - /// set minuitDidNotConverge - void setMinuitDidNotConverge(short); - - /// get fitAbortedDueToNaN - short fitAbortedDueToNaN() const; - /// set fitAbortedDueToNaN - void setFitAbortedDueToNaN(short); - - /// get atLeastOneFitParameterAtItsLimit - short atLeastOneFitParameterAtItsLimit() const; - /// set atLeastOneFitParameterAtItsLimit - void setAtLeastOneFitParameterAtItsLimit(short); - - /// get invalidTransferFunctionAtConvergence - short invalidTransferFunctionAtConvergence() const; - /// set invalidTransferFunctionAtConvergence - void setInvalidTransferFunctionAtConvergence(short); - - /// get bestPermutation - unsigned int bestPermutation() const; - /// set bestPermutation - void setBestPermutation(unsigned int); - - /// get logLikelihood - float logLikelihood() const; - /// set logLikelihood - void setLogLikelihood(float); - - /// get eventProbability - float eventProbability() const; - /// set eventProbability - void setEventProbability(float); - - /// get parameters - const std::vector<double>& parameters() const; - /// set parameters - void setParameters(const std::vector<double>&); - - /// get parameterErrors - const std::vector<double>& parameterErrors() const; - /// set parameterErrors - void setParameterErrors(const std::vector<double>&); - - - /// get model_bhad_pt - float model_bhad_pt() const; - /// set model_bhad_pt - void setModel_bhad_pt(float); - - /// get model_bhad_eta - float model_bhad_eta() const; - /// set model_bhad_eta - void setModel_bhad_eta(float); - - /// get model_bhad_phi - float model_bhad_phi() const; - /// set model_bhad_phi - void setModel_bhad_phi(float); - - /// get model_bhad_E - float model_bhad_E() const; - /// set model_bhad_E - void setModel_bhad_E(float); - - /// get model_bhad_jetIndex - unsigned int model_bhad_jetIndex() const; - /// set model_bhad_jetIndex - void setModel_bhad_jetIndex(unsigned int); - - - /// get model_blep_pt - float model_blep_pt() const; - /// set model_blep_pt - void setModel_blep_pt(float); - - /// get model_blep_eta - float model_blep_eta() const; - /// set model_blep_eta - void setModel_blep_eta(float); - - /// get model_blep_phi - float model_blep_phi() const; - /// set model_blep_phi - void setModel_blep_phi(float); - - /// get model_blep_E - float model_blep_E() const; - /// set model_blep_E - void setModel_blep_E(float); - - /// get model_blep_jetIndex - unsigned int model_blep_jetIndex() const; - /// set model_blep_jetIndex - void setModel_blep_jetIndex(unsigned int); - - - /// get model_lq1_pt - float model_lq1_pt() const; - /// set model_lq1_pt - void setModel_lq1_pt(float); - - /// get model_lq1_eta - float model_lq1_eta() const; - /// set model_lq1_eta - void setModel_lq1_eta(float); - - /// get model_lq1_phi - float model_lq1_phi() const; - /// set model_lq1_phi - void setModel_lq1_phi(float); - - /// get model_lq1_E - float model_lq1_E() const; - /// set model_lq1_E - void setModel_lq1_E(float); - - /// get model_lq1_jetIndex - unsigned int model_lq1_jetIndex() const; - /// set model_lq1_jetIndex - void setModel_lq1_jetIndex(unsigned int); - - - /// get model_lq2_pt - float model_lq2_pt() const; - /// set model_lq2_pt - void setModel_lq2_pt(float); - - /// get model_lq2_eta - float model_lq2_eta() const; - /// set model_lq2_eta - void setModel_lq2_eta(float); - - /// get model_lq2_phi - float model_lq2_phi() const; - /// set model_lq2_phi - void setModel_lq2_phi(float); - - /// get model_lq2_E - float model_lq2_E() const; - /// set model_lq2_E - void setModel_lq2_E(float); - - /// get model_lq2_jetIndex - unsigned int model_lq2_jetIndex() const; - /// set model_lq2_jetIndex - void setModel_lq2_jetIndex(unsigned int); - - /// get model_Higgs_b1_pt - float model_Higgs_b1_pt() const; - /// set model_Higgs_b1_pt - void setModel_Higgs_b1_pt(float); - - /// get model_Higgs_b1_eta - float model_Higgs_b1_eta() const; - /// set model_Higgs_b1_eta - void setModel_Higgs_b1_eta(float); - - /// get model_Higgs_b1_phi - float model_Higgs_b1_phi() const; - /// set model_Higgs_b1_phi - void setModel_Higgs_b1_phi(float); - - /// get model_Higgs_b1_E - float model_Higgs_b1_E() const; - /// set model_Higgs_b1_E - void setModel_Higgs_b1_E(float); - - /// get model_Higgs_b1_jetIndex - unsigned int model_Higgs_b1_jetIndex() const; - /// set model_Higgs_b1_jetIndex - void setModel_Higgs_b1_jetIndex(unsigned int); - - - /// get model_Higgs_b2_pt - float model_Higgs_b2_pt() const; - /// set model_Higgs_b2_pt - void setModel_Higgs_b2_pt(float); - - /// get model_Higgs_b2_eta - float model_Higgs_b2_eta() const; - /// set model_Higgs_b2_eta - void setModel_Higgs_b2_eta(float); - - /// get model_Higgs_b2_phi - float model_Higgs_b2_phi() const; - /// set model_Higgs_b2_phi - void setModel_Higgs_b2_phi(float); - - /// get model_Higgs_b2_E - float model_Higgs_b2_E() const; - /// set model_Higgs_b2_E - void setModel_Higgs_b2_E(float); - - /// get model_Higgs_b2_jetIndex - unsigned int model_Higgs_b2_jetIndex() const; - /// set model_Higgs_b2_jetIndex - void setModel_Higgs_b2_jetIndex(unsigned int); - - /// get model_lep_pt - float model_lep_pt() const; - /// set model_lep_pt - void setModel_lep_pt(float); - - /// get model_lep_eta - float model_lep_eta() const; - /// set model_lep_eta - void setModel_lep_eta(float); - - /// get model_lep_phi - float model_lep_phi() const; - /// set model_lep_phi - void setModel_lep_phi(float); - - /// get model_lep_E - float model_lep_E() const; - /// set model_lep_E - void setModel_lep_E(float); - - - /// get model_nu_pt - float model_nu_pt() const; - /// set model_nu_pt - void setModel_nu_pt(float); - - /// get model_nu_eta - float model_nu_eta() const; - /// set model_nu_eta - void setModel_nu_eta(float); - - /// get model_nu_phi - float model_nu_phi() const; - /// set model_nu_phi - void setModel_nu_phi(float); - - /// get model_nu_E - float model_nu_E() const; - /// set model_nu_E - void setModel_nu_E(float); - - + class KLFitterResult: public SG::AuxElement { + public: + /// Default constructor + KLFitterResult(); + /// Default destructor + virtual ~KLFitterResult() {} + + /// get selectionName + std::size_t selectionCode() const; + /// set selectionName + void setSelectionCode(std::size_t); + + /// get minuitDidNotConverge + short minuitDidNotConverge() const; + /// set minuitDidNotConverge + void setMinuitDidNotConverge(short); + + /// get fitAbortedDueToNaN + short fitAbortedDueToNaN() const; + /// set fitAbortedDueToNaN + void setFitAbortedDueToNaN(short); + + /// get atLeastOneFitParameterAtItsLimit + short atLeastOneFitParameterAtItsLimit() const; + /// set atLeastOneFitParameterAtItsLimit + void setAtLeastOneFitParameterAtItsLimit(short); + + /// get invalidTransferFunctionAtConvergence + short invalidTransferFunctionAtConvergence() const; + /// set invalidTransferFunctionAtConvergence + void setInvalidTransferFunctionAtConvergence(short); + + /// get bestPermutation + unsigned int bestPermutation() const; + /// set bestPermutation + void setBestPermutation(unsigned int); + + /// get logLikelihood + float logLikelihood() const; + /// set logLikelihood + void setLogLikelihood(float); + + /// get eventProbability + float eventProbability() const; + /// set eventProbability + void setEventProbability(float); + + /// get parameters + const std::vector<double>& parameters() const; + /// set parameters + void setParameters(const std::vector<double>&); + + /// get parameterErrors + const std::vector<double>& parameterErrors() const; + /// set parameterErrors + void setParameterErrors(const std::vector<double>&); + + + /// get model_bhad_pt + float model_bhad_pt() const; + /// set model_bhad_pt + void setModel_bhad_pt(float); + + /// get model_bhad_eta + float model_bhad_eta() const; + /// set model_bhad_eta + void setModel_bhad_eta(float); + + /// get model_bhad_phi + float model_bhad_phi() const; + /// set model_bhad_phi + void setModel_bhad_phi(float); + + /// get model_bhad_E + float model_bhad_E() const; + /// set model_bhad_E + void setModel_bhad_E(float); + + /// get model_bhad_jetIndex + unsigned int model_bhad_jetIndex() const; + /// set model_bhad_jetIndex + void setModel_bhad_jetIndex(unsigned int); + + + /// get model_blep_pt + float model_blep_pt() const; + /// set model_blep_pt + void setModel_blep_pt(float); + + /// get model_blep_eta + float model_blep_eta() const; + /// set model_blep_eta + void setModel_blep_eta(float); + + /// get model_blep_phi + float model_blep_phi() const; + /// set model_blep_phi + void setModel_blep_phi(float); + + /// get model_blep_E + float model_blep_E() const; + /// set model_blep_E + void setModel_blep_E(float); + + /// get model_blep_jetIndex + unsigned int model_blep_jetIndex() const; + /// set model_blep_jetIndex + void setModel_blep_jetIndex(unsigned int); + + + /// get model_lq1_pt + float model_lq1_pt() const; + /// set model_lq1_pt + void setModel_lq1_pt(float); + + /// get model_lq1_eta + float model_lq1_eta() const; + /// set model_lq1_eta + void setModel_lq1_eta(float); + + /// get model_lq1_phi + float model_lq1_phi() const; + /// set model_lq1_phi + void setModel_lq1_phi(float); + + /// get model_lq1_E + float model_lq1_E() const; + /// set model_lq1_E + void setModel_lq1_E(float); + + /// get model_lq1_jetIndex + unsigned int model_lq1_jetIndex() const; + /// set model_lq1_jetIndex + void setModel_lq1_jetIndex(unsigned int); + + + /// get model_lq2_pt + float model_lq2_pt() const; + /// set model_lq2_pt + void setModel_lq2_pt(float); + + /// get model_lq2_eta + float model_lq2_eta() const; + /// set model_lq2_eta + void setModel_lq2_eta(float); + + /// get model_lq2_phi + float model_lq2_phi() const; + /// set model_lq2_phi + void setModel_lq2_phi(float); + + /// get model_lq2_E + float model_lq2_E() const; + /// set model_lq2_E + void setModel_lq2_E(float); + + /// get model_lq2_jetIndex + unsigned int model_lq2_jetIndex() const; + /// set model_lq2_jetIndex + void setModel_lq2_jetIndex(unsigned int); + + /// get model_Higgs_b1_pt + float model_Higgs_b1_pt() const; + /// set model_Higgs_b1_pt + void setModel_Higgs_b1_pt(float); + + /// get model_Higgs_b1_eta + float model_Higgs_b1_eta() const; + /// set model_Higgs_b1_eta + void setModel_Higgs_b1_eta(float); + + /// get model_Higgs_b1_phi + float model_Higgs_b1_phi() const; + /// set model_Higgs_b1_phi + void setModel_Higgs_b1_phi(float); + + /// get model_Higgs_b1_E + float model_Higgs_b1_E() const; + /// set model_Higgs_b1_E + void setModel_Higgs_b1_E(float); + + /// get model_Higgs_b1_jetIndex + unsigned int model_Higgs_b1_jetIndex() const; + /// set model_Higgs_b1_jetIndex + void setModel_Higgs_b1_jetIndex(unsigned int); + + + /// get model_Higgs_b2_pt + float model_Higgs_b2_pt() const; + /// set model_Higgs_b2_pt + void setModel_Higgs_b2_pt(float); + + /// get model_Higgs_b2_eta + float model_Higgs_b2_eta() const; + /// set model_Higgs_b2_eta + void setModel_Higgs_b2_eta(float); + + /// get model_Higgs_b2_phi + float model_Higgs_b2_phi() const; + /// set model_Higgs_b2_phi + void setModel_Higgs_b2_phi(float); + + /// get model_Higgs_b2_E + float model_Higgs_b2_E() const; + /// set model_Higgs_b2_E + void setModel_Higgs_b2_E(float); + + /// get model_Higgs_b2_jetIndex + unsigned int model_Higgs_b2_jetIndex() const; + /// set model_Higgs_b2_jetIndex + void setModel_Higgs_b2_jetIndex(unsigned int); + + /// get model_lep_pt + float model_lep_pt() const; + /// set model_lep_pt + void setModel_lep_pt(float); + + /// get model_lep_eta + float model_lep_eta() const; + /// set model_lep_eta + void setModel_lep_eta(float); + + /// get model_lep_phi + float model_lep_phi() const; + /// set model_lep_phi + void setModel_lep_phi(float); + + /// get model_lep_E + float model_lep_E() const; + /// set model_lep_E + void setModel_lep_E(float); + + /// get model_lep_index + unsigned int model_lep_index() const; + /// set model_lep_index + void setModel_lep_index(unsigned int); + + /// get model_lep_pt + float model_lepZ1_pt() const; + /// set model_lepZ1_pt + void setModel_lepZ1_pt(float); + + /// get model_lepZ1_eta + float model_lepZ1_eta() const; + /// set model_lepZ1_eta + void setModel_lepZ1_eta(float); + + /// get model_lepZ1_phi + float model_lepZ1_phi() const; + /// set model_lepZ1_phi + void setModel_lepZ1_phi(float); + + /// get model_lepZ1_E + float model_lepZ1_E() const; + /// set model_lepZ1_E + void setModel_lepZ1_E(float); + + /// get model_lepZ1_index + unsigned int model_lepZ1_index() const; + /// set model_lepZ1_index + void setModel_lepZ1_index(unsigned int); + + /// get model_lepZ2_pt + float model_lepZ2_pt() const; + /// set model_lepZ2_pt + void setModel_lepZ2_pt(float); + + /// get model_lepZ2_eta + float model_lepZ2_eta() const; + /// set model_lepZ2_eta + void setModel_lepZ2_eta(float); + + /// get model_lepZ2_phi + float model_lepZ2_phi() const; + /// set model_lepZ2_phi + void setModel_lepZ2_phi(float); + + /// get model_lepZ2_E + float model_lepZ2_E() const; + /// set model_lepZ2_E + void setModel_lepZ2_E(float); + + /// get model_lepZ2_index + unsigned int model_lepZ2_index() const; + /// set model_lepZ2_index + void setModel_lepZ2_index(unsigned int); + + /// get model_nu_pt + float model_nu_pt() const; + /// set model_nu_pt + void setModel_nu_pt(float); + + /// get model_nu_eta + float model_nu_eta() const; + /// set model_nu_eta + void setModel_nu_eta(float); + + /// get model_nu_phi + float model_nu_phi() const; + /// set model_nu_phi + void setModel_nu_phi(float); + + /// get model_nu_E + float model_nu_E() const; + /// set model_nu_E + void setModel_nu_E(float); + + /// get model_b_from_top1_pt + float model_b_from_top1_pt() const; + /// set model_b_from_top1_pt + void setModel_b_from_top1_pt(float); + + /// get model_b_from_top1_eta + float model_b_from_top1_eta() const; + /// set model_b_from_top1_eta + void setModel_b_from_top1_eta(float); + + /// get model_b_from_top1_phi + float model_b_from_top1_phi() const; + /// set model_b_from_top1_phi + void setModel_b_from_top1_phi(float); + + /// get model_b_from_top1_E + float model_b_from_top1_E() const; + /// set model_b_from_top1_E + void setModel_b_from_top1_E(float); + + /// get model_b_from_top1_jetIndex + unsigned int model_b_from_top1_jetIndex() const; + /// set model_b_from_top1_jetIndex + void setModel_b_from_top1_jetIndex(unsigned int); + + /// get model_b_from_top2_pt + float model_b_from_top2_pt() const; + /// set model_b_from_top2_pt + void setModel_b_from_top2_pt(float); + + /// get model_b_from_top2_eta + float model_b_from_top2_eta() const; + /// set model_b_from_top2_eta + void setModel_b_from_top2_eta(float); + + /// get model_b_from_top2_phi + float model_b_from_top2_phi() const; + /// set model_b_from_top2_phi + void setModel_b_from_top2_phi(float); + + /// get model_b_from_top2_E + float model_b_from_top2_E() const; + /// set model_b_from_top2_E + void setModel_b_from_top2_E(float); + + /// get model_b_from_top2_jetIndex + unsigned int model_b_from_top2_jetIndex() const; + /// set model_b_from_top2_jetIndex + void setModel_b_from_top2_jetIndex(unsigned int); + + /// get model_lj1_from_top1_pt + float model_lj1_from_top1_pt() const; + /// set model_lj1_from_top1_pt + void setModel_lj1_from_top1_pt(float); + + /// get model_lj1_from_top1_eta + float model_lj1_from_top1_eta() const; + /// set model_lj1_from_top1_eta + void setModel_lj1_from_top1_eta(float); + + /// get model_lj1_from_top1_phi + float model_lj1_from_top1_phi() const; + /// set model_lj1_from_top1_phi + void setModel_lj1_from_top1_phi(float); + + /// get model_lj1_from_top1_E + float model_lj1_from_top1_E() const; + /// set model_lj1_from_top1_E + void setModel_lj1_from_top1_E(float); + + /// get model_lj1_from_top1_jetIndex + unsigned int model_lj1_from_top1_jetIndex() const; + /// set model_lj1_from_top1_jetIndex + void setModel_lj1_from_top1_jetIndex(unsigned int); + + /// get model_lj2_from_top1_pt + float model_lj2_from_top1_pt() const; + /// set model_lj2_from_top1_pt + void setModel_lj2_from_top1_pt(float); + + /// get model_lj2_from_top1_eta + float model_lj2_from_top1_eta() const; + /// set model_lj2_from_top1_eta + void setModel_lj2_from_top1_eta(float); + + /// get model_lj2_from_top1_phi + float model_lj2_from_top1_phi() const; + /// set model_lj2_from_top1_phi + void setModel_lj2_from_top1_phi(float); + + /// get model_lj2_from_top1_E + float model_lj2_from_top1_E() const; + /// set model_lj2_from_top1_E + void setModel_lj2_from_top1_E(float); + + /// get model_lj2_from_top1_jetIndex + unsigned int model_lj2_from_top1_jetIndex() const; + /// set model_lj2_from_top1_jetIndex + void setModel_lj2_from_top1_jetIndex(unsigned int); + + /// get model_lj1_from_top2_pt + float model_lj1_from_top2_pt() const; + /// set model_lj1_from_top2_pt + void setModel_lj1_from_top2_pt(float); + + /// get model_lj1_from_top2_eta + float model_lj1_from_top2_eta() const; + /// set model_lj1_from_top2_eta + void setModel_lj1_from_top2_eta(float); + + /// get model_lj1_from_top2_phi + float model_lj1_from_top2_phi() const; + /// set model_lj1_from_top2_phi + void setModel_lj1_from_top2_phi(float); + + /// get model_lj1_from_top2_E + float model_lj1_from_top2_E() const; + /// set model_lj1_from_top2_E + void setModel_lj1_from_top2_E(float); + + /// get model_lj1_from_top2_jetIndex + unsigned int model_lj1_from_top2_jetIndex() const; + /// set model_lj1_from_top2_jetIndex + void setModel_lj1_from_top2_jetIndex(unsigned int); + + /// get model_lj2_from_top2_pt + float model_lj2_from_top2_pt() const; + /// set model_lj2_from_top2_pt + void setModel_lj2_from_top2_pt(float); + + /// get model_lj2_from_top2_eta + float model_lj2_from_top2_eta() const; + /// set model_lj2_from_top2_eta + void setModel_lj2_from_top2_eta(float); + + /// get model_lj2_from_top2_phi + float model_lj2_from_top2_phi() const; + /// set model_lj2_from_top2_phi + void setModel_lj2_from_top2_phi(float); + + /// get model_lj2_from_top2_E + float model_lj2_from_top2_E() const; + /// set model_lj2_from_top2_E + void setModel_lj2_from_top2_E(float); + + /// get model_lj2_from_top2_jetIndex + unsigned int model_lj2_from_top2_jetIndex() const; + /// set model_lj2_from_top2_jetIndex + void setModel_lj2_from_top2_jetIndex(unsigned int); }; - + typedef DataVector< xAOD::KLFitterResult > KLFitterResultContainer; } // Dictonaries -CLASS_DEF( xAOD::KLFitterResult , 103465656 , 1 ) -CLASS_DEF( xAOD::KLFitterResultContainer , 1116647492 , 1 ) -CLASS_DEF( xAOD::KLFitterResultAuxContainer , 1292529835 , 1 ) +CLASS_DEF(xAOD::KLFitterResult, 103465656, 1) +CLASS_DEF(xAOD::KLFitterResultContainer, 1116647492, 1) +CLASS_DEF(xAOD::KLFitterResultAuxContainer, 1292529835, 1) #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/PseudoTopResult.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/PseudoTopResult.h index a30b730c83b0e38607510d9a780b8fdf690cb3c0..79fa86f0c3190588ba6edb00f84a7ac06453e53c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/PseudoTopResult.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/PseudoTopResult.h @@ -1,13 +1,13 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPEVENT_PSEUDOTOPRESULT_H #define ANALYSISTOP_TOPEVENT_PSEUDOTOPRESULT_H /** - * @author Andrea Knue <aknue@cern.ch> - **/ + * @author Andrea Knue <aknue@cern.ch> + **/ // EDM include(s): #include "AthContainers/DataVector.h" @@ -16,32 +16,30 @@ #include "xAODCore/CLASS_DEF.h" #include <vector> -namespace xAOD{ - - /// Aux Container - class PseudoTopResultAuxContainer : public AuxContainerBase { - public: - /// Default constructor - PseudoTopResultAuxContainer(); +namespace xAOD { + /// Aux Container + class PseudoTopResultAuxContainer: public AuxContainerBase { + public: + /// Default constructor + PseudoTopResultAuxContainer(); }; // end Aux container - + /// Interface class - class PseudoTopResult : public SG::AuxElement { - public: - /// Default constructor - PseudoTopResult(); - /// Default desturctor - virtual ~PseudoTopResult(){} - - void IniVar(bool); - - }; - typedef DataVector < xAOD::PseudoTopResult > PseudoTopResultContainer; + class PseudoTopResult: public SG::AuxElement { + public: + /// Default constructor + PseudoTopResult(); + /// Default desturctor + virtual ~PseudoTopResult() {} + + void IniVar(bool); + }; + typedef DataVector < xAOD::PseudoTopResult > PseudoTopResultContainer; } // Dictonaries -CLASS_DEF( xAOD::PseudoTopResult , 135846343 , 1 ) -CLASS_DEF( xAOD::PseudoTopResultContainer , 1219079565 , 1 ) -CLASS_DEF( xAOD::PseudoTopResultAuxContainer , 1244378748 , 1 ) +CLASS_DEF(xAOD::PseudoTopResult, 135846343, 1) +CLASS_DEF(xAOD::PseudoTopResultContainer, 1219079565, 1) +CLASS_DEF(xAOD::PseudoTopResultAuxContainer, 1244378748, 1) #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/RCJetMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/RCJetMC15.h new file mode 100644 index 0000000000000000000000000000000000000000..9b8ad48823aa419926f3664a6243d21d195015dd --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/RCJetMC15.h @@ -0,0 +1,161 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef RCJETMC15_H_ +#define RCJETMC15_H_ + +#include "TopEvent/Event.h" +#include "TopEvent/EventTools.h" +#include "TopEvent/TopEventMaker.h" +#include "TopEvent/SystematicEvent.h" +#include "TopConfiguration/ConfigurationSettings.h" + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "xAODRootAccess/TEvent.h" +#include "xAODRootAccess/TStore.h" +#include "xAODRootAccess/TActiveStore.h" +#include "xAODCore/ShallowCopy.h" +#include "xAODJet/JetContainer.h" +#include "xAODJet/JetAuxContainer.h" + +#include "JetReclustering/JetReclusteringTool.h" +#include <unordered_map> +#include <unordered_set> +#include <memory> +#include <set> +#include <list> +#include <vector> + +// Forward declaration(s): +namespace xAOD { + class SystematicEvent; +} + +namespace top { + class TopConfig; + class Event; +} + +namespace fastjet { + class JetDefinition; + namespace contrib { + class Nsubjettiness; + class EnergyCorrelator; + } +} + +namespace JetSubStructureUtils { + class KtSplittingScale; + class Qw; + class EnergyCorrelatorGeneralized; +} + +class RCJetMC15 final: public asg::AsgTool { +public: + //Default - so root can load based on a name + explicit RCJetMC15(const std::string& name); + + //Default - so we can clean up + ~RCJetMC15(); + + // Delete Standard constructors + RCJetMC15(const RCJetMC15& rhs) = delete; + RCJetMC15(RCJetMC15&& rhs) = delete; + RCJetMC15& operator = (const RCJetMC15& rhs) = delete; + + //Run once at the start of the job + StatusCode initialize(); + + //Run for every event (in every systematic) that needs saving + StatusCode execute(const top::Event& event); + + //Clean-up remaining things + StatusCode finalize(); + + //Check if systematic needs a unique container + bool isUniqueSyst(std::string syst_name); + + //Access all of the container names from the Event Saver + std::string inputContainerName(std::size_t hash_value, bool isLooseEvent); + std::string rcjetContainerName(std::size_t hash_value, bool isLooseEvent); + + bool passSelection(const xAOD::Jet& jet) const; + + void getEMTopoClusters(std::vector<fastjet::PseudoJet>& clusters, const xAOD::Jet* rcjet); + void getLCTopoClusters(std::vector<fastjet::PseudoJet>& clusters, const xAOD::Jet* rcjet); + + void getPflowConstituent(std::vector<fastjet::PseudoJet>& clusters, const xAOD::Jet* rcjet, const top::Event& event); +private: + std::string m_name; + + std::shared_ptr<top::TopConfig> m_config; + bool m_VarRCjets; + std::string m_VarRCjets_rho; + std::string m_VarRCjets_mass_scale; + float m_ptcut; // in GeV + float m_etamax; + float m_inputJetPtMin; + float m_inputJetEtaMax; + float m_trim; + float m_radius; + float m_minradius; + float m_massscale; + bool m_useJSS; + bool m_useAdditionalJSS; + + std::string m_egamma; + std::string m_jetsyst; + std::string m_muonsyst; + std::string m_tracksyst; + + std::string m_InJetContainerBase; + std::string m_OutJetContainerBase; + std::string m_InputJetContainer; + std::string m_OutputJetContainer; + int m_loose_hashValue; + + //Substructure tool definitions + std::shared_ptr<fastjet::JetDefinition> m_jet_def_rebuild; + std::shared_ptr<fastjet::contrib::Nsubjettiness> m_nSub1_beta1; + std::shared_ptr<fastjet::contrib::Nsubjettiness> m_nSub2_beta1; + std::shared_ptr<fastjet::contrib::Nsubjettiness> m_nSub3_beta1; + std::shared_ptr<fastjet::contrib::EnergyCorrelator> m_ECF1; + std::shared_ptr<fastjet::contrib::EnergyCorrelator> m_ECF2; + std::shared_ptr<fastjet::contrib::EnergyCorrelator> m_ECF3; + std::shared_ptr<JetSubStructureUtils::KtSplittingScale> m_split12; + std::shared_ptr<JetSubStructureUtils::KtSplittingScale> m_split23; + std::shared_ptr<JetSubStructureUtils::Qw> m_qw; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF332; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF461; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF322; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF331; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF422; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF441; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF212; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF321; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF311; + + bool m_unique_syst; + + typedef std::map<std::size_t, std::string>::iterator m_iterator; + std::map<std::size_t, std::string> m_inputContainerNames; + std::map<std::size_t, std::string> m_outputContainerNames; + + std::map<std::string, float> mass_scales = { + {"m_t", 172500.}, + {"m_w", 80385.}, + {"m_z", 91188.}, + {"m_h", 125090.} + }; + + //re-clustered jets + // -> need unordered map for systematics + std::unordered_map<std::size_t, std::shared_ptr<JetReclusteringTool> > m_jetReclusteringTool; + typedef std::unordered_map<std::size_t, std::shared_ptr<JetReclusteringTool> >::iterator m_tool_iterator; + + ClassDef(RCJetMC15, 0); +}; + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/SystematicEvent.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/SystematicEvent.h index 63e466eb1191d5d6ad7db752884e8fa0a9e9d541..62128b5cb9fc3c2e16210d8dbd7397a196d93289 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/SystematicEvent.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/SystematicEvent.h @@ -1,26 +1,26 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: SystematicEvent.h 692539 2015-09-02 00:20:52Z morrisj $ #ifndef ANALYSISTOP_TOPEVENT_SYSTEMATICEVENT_H #define ANALYSISTOP_TOPEVENT_SYSTEMATICEVENT_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief SystematicEvent - * A simple xAOD class which we can persist into a mini-xAOD - * The xAOD EDM is way too complex, so let's simplify it - * It's not like ROOT can do schema evolution...... - * - * This class contains only vectors of unsigned int's - * It is very light weight and is used to make top::Event objects - * - * $Revision: 692539 $ - * $Date: 2015-09-02 02:20:52 +0200 (Wed, 02 Sep 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief SystematicEvent + * A simple xAOD class which we can persist into a mini-xAOD + * The xAOD EDM is way too complex, so let's simplify it + * It's not like ROOT can do schema evolution...... + * + * This class contains only vectors of unsigned int's + * It is very light weight and is used to make top::Event objects + * + * $Revision: 692539 $ + * $Date: 2015-09-02 01:20:52 +0100 (Wed, 02 Sep 2015) $ + * + **/ // EDM include(s): #include "AthContainers/DataVector.h" @@ -30,92 +30,109 @@ #include <vector> #include <stdint.h> -namespace xAOD{ - - /// Aux Container - class SystematicEventAuxContainer : public AuxContainerBase { - public: - /// Default constructor - SystematicEventAuxContainer(); - private: - - std::vector<std::size_t> hashValue; - std::vector<unsigned int> ttreeIndex; - std::vector<char> isLooseEvent; - - std::vector<std::vector<unsigned int>> goodPhotons; - std::vector<std::vector<unsigned int>> goodElectrons; - std::vector<std::vector<unsigned int>> goodMuons; - std::vector<std::vector<unsigned int>> goodTaus; - std::vector<std::vector<unsigned int>> goodJets; - std::vector<std::vector<unsigned int>> goodLargeRJets; - std::vector<std::vector<unsigned int>> goodTrackJets; +namespace xAOD { + /// Aux Container + class SystematicEventAuxContainer: public AuxContainerBase { + public: + /// Default constructor + SystematicEventAuxContainer(); + private: + std::vector<std::size_t> hashValue; + std::vector<unsigned int> ttreeIndex; + std::vector<char> isLooseEvent; + + std::vector<std::vector<unsigned int> > goodPhotons; + std::vector<std::vector<unsigned int> > goodElectrons; + std::vector<std::vector<unsigned int> > goodFwdElectrons; + std::vector<std::vector<unsigned int> > goodMuons; + std::vector<std::vector<unsigned int> > goodSoftMuons; + std::vector<std::vector<unsigned int> > goodTaus; + std::vector<std::vector<unsigned int> > goodJets; + std::vector<std::vector<unsigned int> > goodLargeRJets; + std::vector<std::vector<unsigned int> > goodTrackJets; + std::vector<std::vector<unsigned int> > goodTracks; }; - + /// Interface class - class SystematicEvent : public SG::AuxElement { - public: - /// Default constructor - SystematicEvent(); - /// Default destructor - virtual ~SystematicEvent(){} - - /// get hash value - std::size_t hashValue() const; - /// set hash value - void setHashValue(std::size_t); - - /// get ttreeIndex - unsigned int ttreeIndex() const; - /// set ttreeIndex - void setTtreeIndex(unsigned int); - - /// get isLooseEvent - char isLooseEvent() const; - /// set isLooseEvent - void setIsLooseEvent(char); - - /// get Photons - const std::vector<unsigned int>& goodPhotons() const; - /// set Photons - void setGoodPhotons(const std::vector<unsigned int>&); - - /// get Electrons - const std::vector<unsigned int>& goodElectrons() const; - /// set Electrons - void setGoodElectrons(const std::vector<unsigned int>&); - - /// get Muons - const std::vector<unsigned int>& goodMuons() const; - /// set Muons - void setGoodMuons(const std::vector<unsigned int>&); - - /// get Taus - const std::vector<unsigned int>& goodTaus() const; - /// set Taus - void setGoodTaus(const std::vector<unsigned int>&); - - /// get Jets - const std::vector<unsigned int>& goodJets() const; - /// set Jets - void setGoodJets(const std::vector<unsigned int>&); - - /// get LargeRJets - const std::vector<unsigned int>& goodLargeRJets() const; - /// set LargeRJets - void setGoodLargeRJets(const std::vector<unsigned int>&); - - /// get TrackJets - const std::vector<unsigned int>& goodTrackJets() const; - /// set TrackJets - void setGoodTrackJets(const std::vector<unsigned int>&); + class SystematicEvent: public SG::AuxElement { + public: + /// Default constructor + SystematicEvent(); + /// Default destructor + virtual ~SystematicEvent() {} + + /// get hash value + std::size_t hashValue() const; + /// set hash value + void setHashValue(std::size_t); + + /// get ttreeIndex + unsigned int ttreeIndex() const; + /// set ttreeIndex + void setTtreeIndex(unsigned int); + + /// get isLooseEvent + char isLooseEvent() const; + /// set isLooseEvent + void setIsLooseEvent(char); + + /// get Photons + const std::vector<unsigned int>& goodPhotons() const; + /// set Photons + void setGoodPhotons(const std::vector<unsigned int>&); + + /// get Electrons + const std::vector<unsigned int>& goodElectrons() const; + /// set Electrons + void setGoodElectrons(const std::vector<unsigned int>&); + + /// get FWD Electrons + const std::vector<unsigned int>& goodFwdElectrons() const; + /// set FWD Electrons + void setGoodFwdElectrons(const std::vector<unsigned int>&); + + /// get Muons + const std::vector<unsigned int>& goodMuons() const; + /// set Muons + void setGoodMuons(const std::vector<unsigned int>&); + + /// get Soft Muons + const std::vector<unsigned int>& goodSoftMuons() const; + /// set Soft Muons + void setGoodSoftMuons(const std::vector<unsigned int>&); + + /// get Taus + const std::vector<unsigned int>& goodTaus() const; + /// set Taus + void setGoodTaus(const std::vector<unsigned int>&); + + /// get Jets + const std::vector<unsigned int>& goodJets() const; + /// set Jets + void setGoodJets(const std::vector<unsigned int>&); + + /// get LargeRJets + const std::vector<unsigned int>& goodLargeRJets() const; + /// set LargeRJets + void setGoodLargeRJets(const std::vector<unsigned int>&); + + /// get TrackJets + const std::vector<unsigned int>& goodTrackJets() const; + /// set TrackJets + void setGoodTrackJets(const std::vector<unsigned int>&); + + /// get Tracks + const std::vector<unsigned int>& goodTracks() const; + /// set Tracks + void setGoodTracks(const std::vector<unsigned int>&); + }; - + typedef DataVector< xAOD::SystematicEvent > SystematicEventContainer; } // Dictonaries -CLASS_DEF( xAOD::SystematicEvent , 173054021 , 1 ) -CLASS_DEF( xAOD::SystematicEventContainer , 1133646307 , 1 ) -CLASS_DEF( xAOD::SystematicEventAuxContainer , 1283481454 , 1 ) +CLASS_DEF(xAOD::SystematicEvent, 173054021, 1) +CLASS_DEF(xAOD::SystematicEventContainer, 1133646307, 1) +CLASS_DEF(xAOD::SystematicEventAuxContainer, 1283481454, 1) #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/TopEventMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/TopEventMaker.h index 1f56a1dc51d1ec8aed6c4c443a5ec60023932d63..25c46a20029ca0264f5d25340123b8314acdeac7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/TopEventMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEvent/TopEvent/TopEventMaker.h @@ -1,22 +1,22 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: TopEventMaker.h 661108 2015-04-17 00:01:16Z morrisj $ #ifndef ANALYSISTOP_TOPEVENT_TOPEVENTMAKER_H #define ANALYSISTOP_TOPEVENT_TOPEVENTMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief TopEventMaker - * produce top::Event objects from xAOD::SystematicEvent objects - * - * - * $Revision: 661108 $ - * $Date: 2015-04-17 02:01:16 +0200 (Fri, 17 Apr 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief TopEventMaker + * produce top::Event objects from xAOD::SystematicEvent objects + * + * + * $Revision: 661108 $ + * $Date: 2015-04-17 01:01:16 +0100 (Fri, 17 Apr 2015) $ + * + **/ // system include(s): #include <memory> @@ -27,45 +27,59 @@ #include "TopEvent/Event.h" #include "TopEvent/SystematicEvent.h" +#include "TopEvent/RCJetMC15.h" -namespace top { +class RCJetMC15; + +namespace top { class TopConfig; - class TopEventMaker final : public asg::AsgTool { - public: - explicit TopEventMaker( const std::string& name ); - virtual ~TopEventMaker(){} - - // Delete Standard constructors - TopEventMaker(const TopEventMaker& rhs) = delete; - TopEventMaker(TopEventMaker&& rhs) = delete; - TopEventMaker& operator=(const TopEventMaker& rhs) = delete; - /** - * @brief Make a top::Event from a xAOD::SystematicEvent - * - * A SingleSystEvent contains only access to calibrated/systematic - * StoreGate keys and vectors telling it which objects in a collection - * are good - * - * You want to do physics on a top::Event - * - * @param systEvent Essentially this make an analysis friendly version of - * the information in systEvent - * - * @return A top::Event that you can do analysis on containing the good - * objects, which you can then perform selection based on event-level info - * with. Such as object multiplicity. Fun times are ahead. - */ - top::Event makeTopEvent(const xAOD::SystematicEvent& currentSystematic); - - /// As top-xaod isn't an asg::AsgTool, it doesn't have access to all the information - /// Very annoying - const xAOD::SystematicEventContainer* systematicEvents(const std::string& sgKey) const; + class TopEventMaker final: public asg::AsgTool { + public: + explicit TopEventMaker(const std::string& name); + virtual ~TopEventMaker() {} + StatusCode initialize(); + + // Delete Standard constructors + TopEventMaker(const TopEventMaker& rhs) = delete; + TopEventMaker(TopEventMaker&& rhs) = delete; + TopEventMaker& operator = (const TopEventMaker& rhs) = delete; + + /** + * @brief Make a top::Event from a xAOD::SystematicEvent + * + * A SingleSystEvent contains only access to calibrated/systematic + * StoreGate keys and vectors telling it which objects in a collection + * are good + * + * You want to do physics on a top::Event + * + * @param systEvent Essentially this make an analysis friendly version of + * the information in systEvent + * + * @return A top::Event that you can do analysis on containing the good + * objects, which you can then perform selection based on event-level info + * with. Such as object multiplicity. Fun times are ahead. + */ + top::Event makeTopEvent(const xAOD::SystematicEvent* currentSystematic); + + /// As top-xaod isn't an asg::AsgTool, it doesn't have access to all the information + /// Very annoying + const xAOD::SystematicEventContainer* systematicEvents(const std::string& sgKey) const; + private: + + void decorateTopEvent(top::Event &event); + void decorateTopEventSoftMuons(top::Event &event); + + std::shared_ptr<top::TopConfig> m_config; + std::unique_ptr<RCJetMC15> m_rc; + std::map<std::string, std::unique_ptr<RCJetMC15> > m_VarRC; + std::vector<std::string> m_VarRCJetRho; + std::vector<std::string> m_VarRCJetMassScale; - private: - std::shared_ptr<top::TopConfig> m_config; + static bool s_hasTruthEvent; // one-time check at first event we loop over }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/CMakeLists.txt index c3017dfafd18d6d416f218ceb7866598f4c05b81..8eb186314d2ca1c9a3917b38a2695efba667647e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopEventReconstructionTools ) @@ -20,9 +19,8 @@ find_package( KLFitter ) # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopEventReconstructionTools _cintDictSource - ROOT_HEADERS TopEventReconstructionTools/TopEventReconstructionToolsLoader.h - Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopEventReconstructionTools Root/*.cxx Root/*.h Root/*.icc @@ -41,18 +39,3 @@ atlas_add_library( TopEventReconstructionTools Root/*.cxx Root/*.h Root/*.icc # Install data files from the package: atlas_install_data( share/* ) - -# Build the executables of the package: -atlas_add_executable( topreco_test_mt2 - util/topreco_test_mt2.cxx - LINK_LIBRARIES xAODCore - AthContainers - AsgTools - TopEvent - TopEventSelectionTools - TopAnalysis - ${KLFITTER_LIBRARIES} - ${ROOT_LIBRARIES} - TopEventReconstructionTools - INCLUDE_DIRS ${KLFITTER_INCLUDE_DIRS} ) - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Chi2LJets.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Chi2LJets.cxx index c19f4c80636a683ad329f6725d23c3c62c887495..803f7518b8e092fe986abe7881dac22f8d9bbbf3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Chi2LJets.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Chi2LJets.cxx @@ -1,37 +1,34 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/Chi2LJets.h" #include "TMinuit.h" namespace top { + const double Chi2LJets::input_topmass = 172500; + const double Chi2LJets::input_wmass = 80300; -const double Chi2LJets::input_topmass = 172500; -const double Chi2LJets::input_wmass = 80300; + const double Chi2LJets::input_topsigma = 13000; + const double Chi2LJets::input_wsigma = 7000; -const double Chi2LJets::input_topsigma = 13000; -const double Chi2LJets::input_wsigma = 7000; - -Chi2LJets::Chi2LJets() { + Chi2LJets::Chi2LJets() { min = new TMinuit(2); min->SetPrintLevel(-1); min->SetObjectFit(¶ms); min->SetFCN(fcn); -} + } -Chi2LJets::~Chi2LJets() { + Chi2LJets::~Chi2LJets() { delete min; -} + } -bool Chi2LJets::apply(const top::Event& event) const { + bool Chi2LJets::apply(const top::Event& event) const { //set lepton - if (event.m_electrons.size() == 1) - params.lepton = event.m_electrons.at(0)->p4(); + if (event.m_electrons.size() == 1) params.lepton = event.m_electrons.at(0)->p4(); - if (event.m_muons.size() == 1) - params.lepton = event.m_muons.at(0)->p4(); + if (event.m_muons.size() == 1) params.lepton = event.m_muons.at(0)->p4(); //and met params.neutrino_px = event.m_met->mpx(); @@ -44,52 +41,49 @@ bool Chi2LJets::apply(const top::Event& event) const { //First loop is for the leptonic b quark for (xAOD::JetContainer::const_iterator j1 = event.m_jets.begin(); j1 != event.m_jets.end(); ++j1) { - params.leptonic_b = (*j1)->p4(); - - //Second loop is for one of the jets that makes a W - for (xAOD::JetContainer::const_iterator j2 = event.m_jets.begin(); j2 != event.m_jets.end(); ++j2) { - if (j1 == j2) - continue; - - ///The other jet in the W - for (xAOD::JetContainer::const_iterator j3 = event.m_jets.begin(); j3 != event.m_jets.end(); ++j3) { - if (j1 == j3 || j2 == j3) - continue; - - params.hadronic_w_mass = ((*j2)->p4() + (*j3)->p4()).M(); - - ///The hadronic b quark - for (xAOD::JetContainer::const_iterator j4 = event.m_jets.begin(); j4 != event.m_jets.end(); ++j4) { - if (j1 == j4 || j2 == j4 || j3 == j4) - continue; - - params.hadronic_t_mass = ((*j1)->p4() + (*j2)->p4() + (*j3)->p4()).M(); - - //Set input parameters to something reasonable (a guess) - min->DefineParameter(0, "top_mass", 172500., 10000., 0, 500000); //starting guess, step, min, max - min->DefineParameter(1, "neutrino_pz", 10000, 10000, -1000000, 1000000); - - //Perform the minimisation - int status = min->Migrad(); - - double chi2 = 0; - double edm = 0; - double errdef = 0; - int nvpar = 0; - int nparx = 0; - int icstat = 0; - - min->mnstat(chi2, edm, errdef, nvpar, nparx, icstat); - - if (status == 0 && chi2 < chi2min) { - double error = 0; - chi2min = chi2; - min->GetParameter(0, topmass, error); - //wmass = params.hadronic_w_mass; - } //min chi2 - } //j4 = hadronic b - } //j3 = j3 + j2 = hadronic W - } //j2 + params.leptonic_b = (*j1)->p4(); + + //Second loop is for one of the jets that makes a W + for (xAOD::JetContainer::const_iterator j2 = event.m_jets.begin(); j2 != event.m_jets.end(); ++j2) { + if (j1 == j2) continue; + + ///The other jet in the W + for (xAOD::JetContainer::const_iterator j3 = event.m_jets.begin(); j3 != event.m_jets.end(); ++j3) { + if (j1 == j3 || j2 == j3) continue; + + params.hadronic_w_mass = ((*j2)->p4() + (*j3)->p4()).M(); + + ///The hadronic b quark + for (xAOD::JetContainer::const_iterator j4 = event.m_jets.begin(); j4 != event.m_jets.end(); ++j4) { + if (j1 == j4 || j2 == j4 || j3 == j4) continue; + + params.hadronic_t_mass = ((*j1)->p4() + (*j2)->p4() + (*j3)->p4()).M(); + + //Set input parameters to something reasonable (a guess) + min->DefineParameter(0, "top_mass", 172500., 10000., 0, 500000); //starting guess, step, min, max + min->DefineParameter(1, "neutrino_pz", 10000, 10000, -1000000, 1000000); + + //Perform the minimisation + int status = min->Migrad(); + + double chi2 = 0; + double edm = 0; + double errdef = 0; + int nvpar = 0; + int nparx = 0; + int icstat = 0; + + min->mnstat(chi2, edm, errdef, nvpar, nparx, icstat); + + if (status == 0 && chi2 < chi2min) { + double error = 0; + chi2min = chi2; + min->GetParameter(0, topmass, error); + //wmass = params.hadronic_w_mass; + } //min chi2 + } //j4 = hadronic b + } //j3 = j3 + j2 = hadronic W + } //j2 } //j1 = leptonic b @@ -98,7 +92,8 @@ bool Chi2LJets::apply(const top::Event& event) const { // // 577 MiniElectronContainer electrons = event.electrons(); // 578 if (electrons.size() == 1) - // 579 params.lepton.SetPtEtaPhiE(electrons[0]->pt(), electrons[0]->eta(), electrons[0]->phi(), electrons[0]->E()); + // 579 params.lepton.SetPtEtaPhiE(electrons[0]->pt(), electrons[0]->eta(), electrons[0]->phi(), + // electrons[0]->E()); // 580 // 581 MiniMuonContainer muons = event.muons(); // 582 if (muons.size() == 1) @@ -157,7 +152,8 @@ bool Chi2LJets::apply(const top::Event& event) const { // 635 params.hadronic_t_mass = (a + b + c).M(); // 636 // 637 //Set input parameters to something reasonable (a guess) - // 638 min->DefineParameter(0, "top_mass", 172500., 10000., 0, 500000); //starting guess, step, min, max + // 638 min->DefineParameter(0, "top_mass", 172500., 10000., 0, 500000); //starting + // guess, step, min, max // 639 min->DefineParameter(1, "neutrino_pz", 10000, 10000, -1000000, 1000000); // 640 // 641 //Perform the minimisation @@ -177,32 +173,35 @@ bool Chi2LJets::apply(const top::Event& event) const { // 655 } //j1 = leptonic b return true; -} - + } } - /** - * @brief this is where we write out chi2 - */ +/** + * @brief this is where we write out chi2 + */ void fcn(int& /*npar*/, double* /*deriv*/, double& result, double par[], int /*flag*/) { - const top::FitInfo* params = (top::FitInfo*) gMinuit->GetObjectFit(); + const top::FitInfo* params = (top::FitInfo*) gMinuit->GetObjectFit(); - double mytopmass = par[0]; - double pz = par[1]; + double mytopmass = par[0]; + double pz = par[1]; - TLorentzVector neutrino(params->neutrino_px, params->neutrino_py, pz, sqrt(params->neutrino_px * params->neutrino_px + params->neutrino_py * params->neutrino_py + pz * pz)); - double w_lep_term = ((params->lepton + neutrino).M() - top::Chi2LJets::input_wmass) / top::Chi2LJets::input_wsigma; - double t_lep_term = ((params->lepton + neutrino + params->leptonic_b).M() - mytopmass) / top::Chi2LJets::input_topsigma; + TLorentzVector neutrino(params->neutrino_px, params->neutrino_py, pz, sqrt( + params->neutrino_px* params->neutrino_px + params->neutrino_py* params->neutrino_py + + pz* pz)); + double w_lep_term = ((params->lepton + neutrino).M() - top::Chi2LJets::input_wmass) / top::Chi2LJets::input_wsigma; + double t_lep_term = ((params->lepton + neutrino + params->leptonic_b).M() - mytopmass) / + top::Chi2LJets::input_topsigma; - double w_term = (params->hadronic_w_mass - top::Chi2LJets::input_wmass) / top::Chi2LJets::input_wsigma; - double t_term = (params->hadronic_t_mass - mytopmass) / top::Chi2LJets::input_topsigma; + double w_term = (params->hadronic_w_mass - top::Chi2LJets::input_wmass) / top::Chi2LJets::input_wsigma; + double t_term = (params->hadronic_t_mass - mytopmass) / top::Chi2LJets::input_topsigma; - result = w_lep_term * w_lep_term + - t_lep_term * t_lep_term + - w_term * w_term + - t_term * t_term; + result = w_lep_term * w_lep_term + + t_lep_term * t_lep_term + + w_term * w_term + + t_term * t_term; - // cout << "SJH fcn hadw " << fit->hadronicW << " " << TopWidth::input_wmass << " " << TopWidth::input_wsigma << endl; - // cout << "SJH fcn hadt " << fit->hadronicTop << " " << mytopmass << " " << TopWidth::input_topsigma << endl; + // cout << "SJH fcn hadw " << fit->hadronicW << " " << TopWidth::input_wmass << " " << TopWidth::input_wsigma << + // endl; + // cout << "SJH fcn hadt " << fit->hadronicTop << " " << mytopmass << " " << TopWidth::input_topsigma << endl; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterRun.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterRun.cxx index f93519feacd822f04497dff6ede31e556cfb0b89..c4a045b480525ca615c49218145ac8c6fe955e07 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterRun.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterRun.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/KLFitterRun.h" @@ -13,27 +13,32 @@ #include <cmath> #include <fstream> -namespace top{ - - KLFitterRun::KLFitterRun(const std::string& kLeptonType,std::shared_ptr<top::TopConfig> config) : - m_name("RECO::KLFitterRun_" + kLeptonType), - m_myFitter(nullptr) - { - - m_myFitter = std::unique_ptr<top::KLFitterTool> ( new top::KLFitterTool( m_name ) ); - top::check( m_myFitter->setProperty("config", config ), "Failed to setProperty of KLFitterTool" ); - top::check( m_myFitter->setProperty("LeptonType",kLeptonType), "Failed to setProperty of KLFitterTool" ); - top::check( m_myFitter->initialize() , "Failed to initialize KLFitterTool" ); +namespace top { + KLFitterRun::KLFitterRun(const std::string& kSelectionName, const std::string& kParameters, + std::shared_ptr<top::TopConfig> config) : + m_name(""), + m_myFitter(nullptr) { + std::string kLeptonType = ""; + std::string kCustomParameters = ""; + if (kParameters.find(" ") != std::string::npos) { + kLeptonType = kParameters.substr(0, kParameters.find(" ")); + kCustomParameters = kParameters.substr(kParameters.find(" ") + 1); + } else kLeptonType = kParameters; + m_name = "RECO::KLFitterRun_" + kLeptonType; + m_myFitter = std::unique_ptr<top::KLFitterTool> (new top::KLFitterTool(m_name)); + top::check(m_myFitter->setProperty("config", config), "Failed to setProperty of KLFitterTool"); + top::check(m_myFitter->setProperty("LeptonType", kLeptonType), "Failed to setProperty of KLFitterTool"); + top::check(m_myFitter->setProperty("CustomParameters", kCustomParameters), "Failed to setProperty of KLFitterTool"); + top::check(m_myFitter->setProperty("SelectionName", kSelectionName), "Failed to setProperty of KLFitterTool"); + top::check(m_myFitter->initialize(), "Failed to initialize KLFitterTool"); } - - bool KLFitterRun::apply(const top::Event& event) const - { - top::check( m_myFitter->execute(event) , "Failed to run KLFitterTool" ); + + bool KLFitterRun::apply(const top::Event& event) const { + top::check(m_myFitter->execute(event), "Failed to run KLFitterTool"); return true; } - + std::string KLFitterRun::name() const { return m_name; - } - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterTool.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterTool.cxx index 9d09da9de623298585e18df8683e464dcebc7a65..a607cbb6941c467960dd83ad861a5bdca784a7cd 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterTool.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/KLFitterTool.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ // $Id: KLFitterTool.cxx 790035 2016-12-15 19:47:38Z aknue $ @@ -14,194 +14,336 @@ #include <algorithm> -namespace top{ - - KLFitterTool::KLFitterTool( const std::string& name) : - asg::AsgTool( name ), +namespace top { + KLFitterTool::KLFitterTool(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - m_massTop(172.5), // This is the MC top mass in GeV - only change if you change the MC mass - m_bTagCutValue(9999.9), + m_massTop(172.5), // This is the MC top mass in GeV - only change if you change the MC mass + m_bTagCutValue(9999.9), + m_isWorkingPoint(false), m_transferFunctionsPathPrefix("SetMe"), m_transferFunctionsPath("SetMe"), + m_selectionName("SetMe"), m_leptonType("SetMe"), + m_customParameters("SetMe"), m_LHType("SetMe"), - m_myFitter(nullptr) - { - declareProperty( "config" , m_config , "Set the configuration" ); - declareProperty( "LeptonType", m_leptonType = "kUndefined" , "Define the lepton type" ); - declareProperty( "LHType", m_LHType = "kUndefined" , "Define the Likelihood type" ); + m_myFitter(nullptr) { + declareProperty("config", m_config, "Set the configuration"); + declareProperty("LeptonType", m_leptonType = "kUndefined", "Define the lepton type"); + declareProperty("CustomParameters", m_customParameters = "", "Define the custom parameters"); + declareProperty("SelectionName", m_selectionName = "kUndefined", "Define the name of the selection"); + declareProperty("LHType", m_LHType = "kUndefined", "Define the Likelihood type"); } - + /// Function initialising the tool - StatusCode KLFitterTool::initialize() - { + StatusCode KLFitterTool::initialize() { // Have you set the config?? if (m_config == nullptr) { ATH_MSG_ERROR("Please set the top::TopConfig"); return StatusCode::FAILURE; } + //Retrieving configuration from TopConfig m_config->setKLFitter(); - m_LHType = m_config -> KLFitterLH(); - + //Setting configuration, giving priority to the ones passed inside the selection + std::vector<std::string> custom_tokens; + tokenize(m_customParameters, custom_tokens, " "); + std::string temp_option = ""; + // Setting event topology + if (findOption(custom_tokens, "KLFitterLH", temp_option)) m_LHType = temp_option; + else m_LHType = m_config->KLFitterLH(); // Find KLFitter ATLAS transfer functions. As of May '18, stored in // AnalysisTop group data area on cvmfs. - m_transferFunctionsPathPrefix = PathResolverFindCalibDirectory( "dev/AnalysisTop/KLFitterTFs/" ); - m_transferFunctionsPath = m_config->KLFitterTransferFunctionsPath(); - + m_transferFunctionsPathPrefix = PathResolverFindCalibDirectory("dev/AnalysisTop/KLFitterTFs/"); + if (findOption(custom_tokens, "KLFitterTransferFunctionsPath", temp_option)) m_transferFunctionsPath = temp_option; + else m_transferFunctionsPath = m_config->KLFitterTransferFunctionsPath(); std::string transferFunctionAbsPath = m_transferFunctionsPathPrefix + m_transferFunctionsPath + "/"; - + // 1) create an instance of the fitter - m_myFitter = std::unique_ptr<KLFitter::Fitter>( new KLFitter::Fitter{} ); - + m_myFitter = std::unique_ptr<KLFitter::Fitter>(new KLFitter::Fitter {}); + // 2) create an instance of the detector, which holds the information on the resolutions (transfer functions); // it takes as an argument the folder which contains the parameter files for the transfer functions - KLFitter::DetectorBase * myDetector = new KLFitter::DetectorAtlas_8TeV( transferFunctionAbsPath ); - + m_myDetector = std::make_unique<KLFitter::DetectorAtlas_8TeV>(transferFunctionAbsPath); + // 3) tell the fitter which detector to use - if (!m_myFitter->SetDetector(myDetector)) { - ATH_MSG_ERROR( "ERROR setting detector to fitter" ); - return StatusCode::FAILURE; - } - + top::check(m_myFitter->SetDetector( + m_myDetector.get()), "KLFitterTool::initialize() ERROR setting detector to fitter"); + // 4) create an instance of the likelihood for ttbar->l+jets channel and customize it according to your needs - KLFitter::LikelihoodTopLeptonJets * myLikelihood = new KLFitter::LikelihoodTopLeptonJets{}; - + m_myLikelihood = std::make_unique<KLFitter::LikelihoodTopLeptonJets>(); + // 4) create an instance of the likelihood for ttH -> l+jets channel and customize it according to your needs - KLFitter::LikelihoodTTHLeptonJets * myLikelihood_TTH = new KLFitter::LikelihoodTTHLeptonJets{}; + m_myLikelihood_TTH = std::make_unique<KLFitter::LikelihoodTTHLeptonJets>(); + + // 4) create an instance of the likelihood for ttbar->l+jets channel using jet angles channel and customize it + // according to your needs + m_myLikelihood_JetAngles = std::make_unique<KLFitter::LikelihoodTopLeptonJets_JetAngles>(); + + // 4) create an instance of the likelihood for ttZ -> trilepton channel and customize it according to your needs + m_myLikelihood_TTZ = std::make_unique<KLFitter::LikelihoodTTZTrilepton>(); + + // 4) create an instance of the likelihood for ttbar -> allhadronic channel and customize it according to your needs + m_myLikelihood_AllHadronic = std::make_unique<KLFitter::LikelihoodTopAllHadronic>(); + + // 4) create an instance of the likelihood for ttbar -> boosted ljets and customize it according to your needs + m_myLikelihood_BoostedLJets = std::make_unique<KLFitter::BoostedLikelihoodTopLeptonJets>(); // 4.a) SetleptonType - if (m_leptonType == "kElectron") { - m_leptonTypeKLFitterEnum = KLFitter::LikelihoodTopLeptonJets::LeptonType::kElectron; - m_leptonTypeKLFitterEnum_TTH = KLFitter::LikelihoodTTHLeptonJets::LeptonType::kElectron; - } - else if (m_leptonType == "kMuon") { - m_leptonTypeKLFitterEnum = KLFitter::LikelihoodTopLeptonJets::LeptonType::kMuon; - m_leptonTypeKLFitterEnum_TTH = KLFitter::LikelihoodTTHLeptonJets::LeptonType::kMuon; - } - else { - ATH_MSG_ERROR(" Please supply a valid LeptonType : kElectron or kMuon"); - return StatusCode::FAILURE; - } - - myLikelihood -> SetLeptonType( m_leptonTypeKLFitterEnum ); - myLikelihood_TTH -> SetLeptonType( m_leptonTypeKLFitterEnum_TTH ); + if (m_LHType != "ttbar_AllHadronic") { // no lepton type for all hadronic + if (m_leptonType == "kElectron") { + m_leptonTypeKLFitterEnum = KLFitter::LikelihoodTopLeptonJets::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_TTH = KLFitter::LikelihoodTTHLeptonJets::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_JetAngles = KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_TTZ = KLFitter::LikelihoodTTZTrilepton::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_BoostedLJets = KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kElectron; + } else if (m_leptonType == "kMuon") { + m_leptonTypeKLFitterEnum = KLFitter::LikelihoodTopLeptonJets::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_TTH = KLFitter::LikelihoodTTHLeptonJets::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_JetAngles = KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_TTZ = KLFitter::LikelihoodTTZTrilepton::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_BoostedLJets = KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kMuon; + } else if (m_leptonType == "kTriElectron") { + if (m_LHType != "ttZTrilepton") { + ATH_MSG_ERROR(" LeptonType kTriElectron is only defined for the ttZTrilepton likelihood"); + return StatusCode::FAILURE; + } + m_leptonTypeKLFitterEnum = KLFitter::LikelihoodTopLeptonJets::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_TTH = KLFitter::LikelihoodTTHLeptonJets::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_JetAngles = KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_TTZ = KLFitter::LikelihoodTTZTrilepton::LeptonType::kElectron; + m_leptonTypeKLFitterEnum_BoostedLJets = KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kElectron; + } else if (m_leptonType == "kTriMuon") { + if (m_LHType != "ttZTrilepton") { + ATH_MSG_ERROR(" LeptonType kTriMuon is only defined for the ttZTrilepton likelihood"); + return StatusCode::FAILURE; + } + m_leptonTypeKLFitterEnum = KLFitter::LikelihoodTopLeptonJets::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_TTH = KLFitter::LikelihoodTTHLeptonJets::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_JetAngles = KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_TTZ = KLFitter::LikelihoodTTZTrilepton::LeptonType::kMuon; + m_leptonTypeKLFitterEnum_BoostedLJets = KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kMuon; + } else { + ATH_MSG_ERROR(" Please supply a valid LeptonType : kElectron or kMuon"); + return StatusCode::FAILURE; + } - // 4.b) Jet Selection Mode - if (m_config->KLFitterJetSelectionMode() == "kLeadingFour" ){ - m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingFour; - } - else if (m_config->KLFitterJetSelectionMode() == "kLeadingFive") { - m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingFive; - } - else if (m_config->KLFitterJetSelectionMode() == "kLeadingSix") { - m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingSix; - } - else if (m_config->KLFitterJetSelectionMode() == "kBtagPriorityFourJets") { - m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kBtagPriorityFourJets; - } - else if (m_config->KLFitterJetSelectionMode() == "kBtagPriorityFiveJets") { - m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kBtagPriorityFiveJets; - } - else if (m_config->KLFitterJetSelectionMode() == "kBtagPrioritySixJets") { - m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kBtagPrioritySixJets; + m_myLikelihood->SetLeptonType(m_leptonTypeKLFitterEnum); + m_myLikelihood_TTH->SetLeptonType(m_leptonTypeKLFitterEnum_TTH); + m_myLikelihood_JetAngles->SetLeptonType(m_leptonTypeKLFitterEnum_JetAngles); + m_myLikelihood_TTZ->SetLeptonType(m_leptonTypeKLFitterEnum_TTZ); + m_myLikelihood_BoostedLJets->SetLeptonType(m_leptonTypeKLFitterEnum_BoostedLJets); } + // 4.b) Jet Selection Mode + std::string JetSelectionMode = ""; + if (findOption(custom_tokens, "KLFitterJetSelectionMode", temp_option)) JetSelectionMode = temp_option; + else JetSelectionMode = m_config->KLFitterJetSelectionMode(); + + if (JetSelectionMode == "kLeadingThree") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingThree; + else if (JetSelectionMode == + "kLeadingFour") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingFour; + else if (JetSelectionMode == + "kLeadingFive") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingFive; + else if (JetSelectionMode == "kLeadingSix") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingSix; + + else if (JetSelectionMode == + "kLeadingSeven") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingSeven; + else if (JetSelectionMode == + "kLeadingEight") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kLeadingEight; + else if (JetSelectionMode == + "kBtagPriorityThreeJets") m_jetSelectionModeKLFitterEnum = + top::KLFitterJetSelection::kBtagPriorityThreeJets; + else if (JetSelectionMode == + "kBtagPriorityFourJets") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kBtagPriorityFourJets; + + else if (JetSelectionMode == + "kBtagPriorityFiveJets") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kBtagPriorityFiveJets; + + else if (JetSelectionMode == + "kBtagPrioritySixJets") m_jetSelectionModeKLFitterEnum = top::KLFitterJetSelection::kBtagPrioritySixJets; + else if (JetSelectionMode == + "kBtagPrioritySevenJets") m_jetSelectionModeKLFitterEnum = + top::KLFitterJetSelection::kBtagPrioritySevenJets; + else if (JetSelectionMode == + "kBtagPriorityEightJets") m_jetSelectionModeKLFitterEnum = + top::KLFitterJetSelection::kBtagPriorityEightJets; else { - ATH_MSG_ERROR("Please supply a valid JetSelectionMode : kLeadingFour , kLeadingFive , kLeadingSix, kBtagPriorityFourJets , kBtagPriorityFiveJets kBtagPrioritySixJets" ); - return StatusCode::FAILURE; + ATH_MSG_ERROR( + "Please supply a valid JetSelectionMode : kLeadingFour , kLeadingFive , kLeadingSix , kLeadingSeven , kLeadingEight , kBtagPriorityFourJets , kBtagPriorityFiveJets , kBtagPrioritySixJets , kBtagPrioritySevenJets , kBtagPriorityEightJets"); + return StatusCode::FAILURE; } - - if(m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kLeadingSix && m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kBtagPrioritySixJets){ - if(m_LHType == "ttH"){ - ATH_MSG_ERROR("You want to run the ttH Likelihood, you need to use either : kLeadingSix or kBtagPrioritySixJets" ); - return StatusCode::FAILURE; - + if (m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kLeadingSix && + m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kBtagPrioritySixJets && + m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kLeadingSeven && + m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kBtagPrioritySevenJets && + m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kLeadingEight && + m_jetSelectionModeKLFitterEnum != top::KLFitterJetSelection::kBtagPriorityEightJets) { + if (m_LHType == "ttH" || m_LHType == "ttbar_AllHadronic") { + ATH_MSG_ERROR( + "You want to run the ttH or ttbar_AllHadronic Likelihood, you need to use either : kLeadingSix , kBtagPrioritySixJets , kLeadingSeven , kBtagPrioritySevenJets , kLeadingEight , kBtagPriorityEightJets"); + return StatusCode::FAILURE; } - } + } // 4.c) SetBTagging method - if (m_config->KLFitterBTaggingMethod() == "kNotag") { - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kNotag; - } - else if (m_config->KLFitterBTaggingMethod() == "kVetoNoFit" ){ - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoNoFit; - } - else if (m_config->KLFitterBTaggingMethod() == "kVetoNoFitLight" ){ - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoNoFitLight; - } - else if (m_config->KLFitterBTaggingMethod() == "kVetoNoFitBoth" ){ - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoNoFitBoth; - } - else if (m_config->KLFitterBTaggingMethod() == "kWorkingPoint" ){ + std::string BTaggingMethod = ""; + if (findOption(custom_tokens, "KLFitterBTaggingMethod", temp_option)) BTaggingMethod = temp_option; + else BTaggingMethod = m_config->KLFitterBTaggingMethod(); + + if (BTaggingMethod == "kNotag") m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kNotag; + else if (BTaggingMethod == + "kVetoNoFit") m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoNoFit; + else if (BTaggingMethod == + "kVetoNoFitLight") m_bTaggingMethodKLFitterEnum = + KLFitter::LikelihoodBase::BtaggingMethod::kVetoNoFitLight; + else if (BTaggingMethod == + "kVetoNoFitBoth") m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoNoFitBoth; + else if (BTaggingMethod == + "kVetoHybridNoFit") m_bTaggingMethodKLFitterEnum = + KLFitter::LikelihoodBase::BtaggingMethod::kVetoHybridNoFit; + else if (BTaggingMethod == "kWorkingPoint") { m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kWorkingPoint; - } - else if (m_config->KLFitterBTaggingMethod() == "kVeto" ){ - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVeto; - } - else if (m_config->KLFitterBTaggingMethod() == "kVetoLight" ){ - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoLight; - } - else if (m_config->KLFitterBTaggingMethod() == "kVetoBoth" ){ - m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoBoth; - } + m_isWorkingPoint = true; + } else if (BTaggingMethod == + "kVeto") m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVeto; + else if (BTaggingMethod == + "kVetoLight") m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoLight; + else if (BTaggingMethod == + "kVetoBoth") m_bTaggingMethodKLFitterEnum = KLFitter::LikelihoodBase::BtaggingMethod::kVetoBoth; else { - ATH_MSG_ERROR("Please supply a valid BTaggingMethod : kNotag,kVetoNoFit,kVetoNoFitLight,kVetoNoFitBoth,kWorkingPoint,kVeto,kVetoLight or kVetoBoth" ); + ATH_MSG_ERROR( + "Please supply a valid BTaggingMethod : kNotag,kVetoNoFit,kVetoNoFitLight,kVetoNoFitBoth,kVetoHybridNoFit,kWorkingPoint,kVeto,kVetoLight or kVetoBoth"); return StatusCode::FAILURE; } - myLikelihood -> SetBTagging( m_bTaggingMethodKLFitterEnum ); - myLikelihood_TTH -> SetBTagging( m_bTaggingMethodKLFitterEnum ); + m_myLikelihood->SetBTagging(m_bTaggingMethodKLFitterEnum); + m_myLikelihood_TTH->SetBTagging(m_bTaggingMethodKLFitterEnum); + m_myLikelihood_JetAngles->SetBTagging(m_bTaggingMethodKLFitterEnum); + m_myLikelihood_TTZ->SetBTagging(m_bTaggingMethodKLFitterEnum); + m_myLikelihood_AllHadronic->SetBTagging(m_bTaggingMethodKLFitterEnum); + m_myLikelihood_BoostedLJets->SetBTagging(m_bTaggingMethodKLFitterEnum); // 4.d) SetTopMass - myLikelihood -> PhysicsConstants()->SetMassTop( m_massTop ); - myLikelihood_TTH -> PhysicsConstants()->SetMassTop( m_massTop ); + m_myLikelihood->PhysicsConstants()->SetMassTop(m_massTop); + m_myLikelihood_TTH->PhysicsConstants()->SetMassTop(m_massTop); + m_myLikelihood_JetAngles->PhysicsConstants()->SetMassTop(m_massTop); + m_myLikelihood_TTZ->PhysicsConstants()->SetMassTop(m_massTop); + m_myLikelihood_AllHadronic->PhysicsConstants()->SetMassTop(m_massTop); + m_myLikelihood_BoostedLJets->PhysicsConstants()->SetMassTop(m_massTop); // 4.e) TopMassFixed - myLikelihood -> SetFlagTopMassFixed( m_config->KLFitterTopMassFixed() ); - myLikelihood_TTH -> SetFlagTopMassFixed( m_config->KLFitterTopMassFixed() ); + bool FixTopMass = true; + if (findOption(custom_tokens, "KLFitterTopMassFixed", temp_option)) { + if (temp_option.compare("True") == 0) FixTopMass = true; + else if (temp_option.compare("False") == 0) FixTopMass = false; + else { + ATH_MSG_ERROR("Invalid KLFitterTopMassFixed custom option! Exiting."); + return StatusCode::FAILURE; + } + } else FixTopMass = m_config->KLFitterTopMassFixed(); + + m_myLikelihood->SetFlagTopMassFixed(FixTopMass); + m_myLikelihood_TTH->SetFlagTopMassFixed(FixTopMass); + m_myLikelihood_JetAngles->SetFlagTopMassFixed(FixTopMass); + m_myLikelihood_TTZ->SetFlagTopMassFixed(FixTopMass); + m_myLikelihood_AllHadronic->SetFlagTopMassFixed(FixTopMass); + m_myLikelihood_BoostedLJets->SetFlagTopMassFixed(FixTopMass); // 5) tell the fitter which likelihood to use - if(m_LHType == "ttbar") - m_myFitter->SetLikelihood(myLikelihood); - else if (m_LHType == "ttH") - m_myFitter->SetLikelihood(myLikelihood_TTH); - else{ + if (m_LHType == "ttbar") top::check(m_myFitter->SetLikelihood( + m_myLikelihood.get()), + "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); + else if (m_LHType == "ttH") top::check(m_myFitter->SetLikelihood( + m_myLikelihood_TTH.get()), + "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); + else if (m_LHType == "ttbar_JetAngles") top::check(m_myFitter->SetLikelihood( + m_myLikelihood_JetAngles.get()), + "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); - ATH_MSG_ERROR( "KLFitter: This likelihood is not defined..." ); + else if (m_LHType == "ttZTrilepton" && (m_leptonType == "kTriElectron" || m_leptonType == "kTriMuon")) { + // For ttZ->trilepton, we can have difficult combinations of leptons in the + // final state (3x same flavour, or mixed case). The latter is trivial, for + // which we can default back to the ljets likelihood. So we distinguish here: + // - kTriMuon, kTriElectron: dedicated TTZ->trilepton likelihood, + // - kMuon, kElectron: standard ttbar->l+jets likelihood. + top::check(m_myFitter->SetLikelihood( + m_myLikelihood_TTZ.get()), "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); + } else if (m_LHType == "ttZTrilepton") { + top::check(m_myFitter->SetLikelihood( + m_myLikelihood.get()), "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); + } else if (m_LHType == "ttbar_AllHadronic") { + top::check(m_myFitter->SetLikelihood( + m_myLikelihood_AllHadronic.get()), + "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); + } else if (m_LHType == "ttbar_BoostedLJets") { + top::check(m_myFitter->SetLikelihood( + m_myLikelihood_BoostedLJets.get()), + "KLFitterTool::initialize() ERROR setting likelihood for KLFitter"); + } else { + ATH_MSG_ERROR("KLFitter: This likelihood is not defined..."); return StatusCode::FAILURE; - } - + // 6) Figure out the b tagging working point // All the blame for this horrible code rests with the b-tagging people - if (m_config->bTagWP_available().size() != 1) { - ATH_MSG_INFO(m_config->bTagWP_available().size()<<" b-tagging WP - cannot pick b-jets. Please select only 1 WP if you are using KLFitter"); + std::string btagWP = ""; + if (findOption(custom_tokens, "KLFitterBTaggingWP", temp_option)) btagWP = temp_option; + else { + if (m_config->bTagWP_available().size() != 1) { + ATH_MSG_ERROR( + m_config->bTagWP_available().size() << + " b-tagging WP - cannot pick b-jets. Please select only 1 WP or specify the desired one in your selection!"); + return StatusCode::FAILURE; + } + btagWP = m_config->bTagWP_available()[0]; + } + if (btagWP.find("Continuous") != std::string::npos) { + ATH_MSG_ERROR( + "KLFitter is not able to run with (pseudo)continuous b-tagging! Please specify a different WP either in your configuration file or in your selection!"); + return StatusCode::FAILURE; } - - const auto btagWP = m_config->bTagWP_available()[0]; - m_btagging_eff_tool = "BTaggingEfficiencyTool_"+btagWP+"_"+m_config->sgKeyJets(); - top::check( m_btagging_eff_tool.retrieve(), "Failed to retrieve b-tagging Efficiency tool" ); - + + if (m_isWorkingPoint) { + m_btagging_eff_tool = "BTaggingEfficiencyTool_" + btagWP + "_" + m_config->sgKeyJets(); + top::check(m_btagging_eff_tool.retrieve(), "KLFitterTool:: Failed to retrieve b-tagging Efficiency tool"); + } + ATH_MSG_INFO("++++++++++++++++++++++++++++++"); - ATH_MSG_INFO("Configured KLFitter with name "<<name()); - ATH_MSG_INFO(" Using " << "BTaggingEfficiencyTool_"+btagWP+"_"+m_config->sgKeyJets()); + ATH_MSG_INFO("Configured KLFitter with name " << name()); + ATH_MSG_INFO(" For selection " << m_selectionName); + ATH_MSG_INFO(" Using " << m_btagging_eff_tool); ATH_MSG_INFO(" Using transfer functions with full path " << transferFunctionAbsPath); - ATH_MSG_INFO(" Using Lepton \t\t" << m_leptonType); - ATH_MSG_INFO(" Using JetSelectionMode \t" << m_config->KLFitterJetSelectionMode()); - ATH_MSG_INFO(" Using BTaggingMethod \t" << m_config->KLFitterBTaggingMethod()); - ATH_MSG_INFO(" Using TopMassFixed \t" << m_config->KLFitterTopMassFixed()); - - if (m_config->KLFitterSaveAllPermutations()) - ATH_MSG_INFO(" Saving All permutations"); - if (!m_config->KLFitterSaveAllPermutations()) - ATH_MSG_INFO(" Saving only the permutation with the highest event probability"); - ATH_MSG_INFO("++++++++++++++++++++++++++++++"); - + ATH_MSG_INFO(" Using Lepton \t\t" << m_leptonType); + ATH_MSG_INFO(" Using JetSelectionMode \t" << JetSelectionMode); + ATH_MSG_INFO(" Using BTaggingMethod \t" << BTaggingMethod); + ATH_MSG_INFO(" Using TopMassFixed \t" << FixTopMass); + + if (m_config->KLFitterSaveAllPermutations()) ATH_MSG_INFO(" Saving All permutations"); + else ATH_MSG_INFO(" Saving only the permutation with the highest event probability"); + ATH_MSG_INFO("++++++++++++++++++++++++++++++"); + /// Return gracefully: - return StatusCode::SUCCESS; + return StatusCode::SUCCESS; } - + + /// Config helpers + bool KLFitterTool::findOption(std::vector<std::string> full_options, std::string option, std::string& op_value) { + //Find option in full_options and put in op_value, then return true. Otherwise return false + for (unsigned int t = 0; t < full_options.size(); ++t) { + if (full_options.at(t).compare("") == 0) continue; //Skip void strings + top::check((full_options.at(t).find( + ":") != std::string::npos), + "KLFitterTool::findOption Error! You specified an invalid option: " + full_options.at( + t) + ". Expected format is A:a B:b C:c..."); + std::string key = full_options.at(t).substr(0, full_options.at(t).find(":")); + std::string value = full_options.at(t).substr(full_options.at(t).find(":") + 1); + if (key.compare(option) == 0) { + op_value = value; + return true; + } + } + return false; + } + /// Function executing the tool - StatusCode KLFitterTool::execute(const top::Event& event) - { - + StatusCode KLFitterTool::execute(const top::Event& event) { // run KLFitter // create an instance of the particles class filled with the particles to be fitted; // here, you need to make sure that @@ -219,390 +361,656 @@ namespace top{ // - index of the particle in your original collection (for convenience) // - for jets: // * bool isBtagged : mandatory only if you want to use b-tagging in the fit - - KLFitter::Particles * myParticles = new KLFitter::Particles{}; - if(m_LHType == "ttbar"){ +/* + FIXME: this may be useful to cache results, that's why I am not deleting this piece of commented code + maybe we could concatenate the full KLFitter selection and then calculate an hash... + if( (event.m_info->isAvailable< int >( "KLFitterHasRun" ) ) ) + if( ( event.m_info->auxdata< int >("KLFitterHasRun") )!=0 ) return StatusCode::SUCCESS; + */ + KLFitter::Particles* myParticles = new KLFitter::Particles {}; + if (m_LHType == "ttbar") { if (m_leptonTypeKLFitterEnum == KLFitter::LikelihoodTopLeptonJets::LeptonType::kElectron) { - TLorentzVector el; - el.SetPtEtaPhiE( event.m_electrons.at(0)->pt()/1.e3 , event.m_electrons.at(0)->eta() , event.m_electrons.at(0)->phi(), event.m_electrons.at(0)->e() / 1.e3); - myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2) , KLFitter::Particles::kElectron); + TLorentzVector el; + el.SetPtEtaPhiE(event.m_electrons.at(0)->pt() / 1.e3, event.m_electrons.at(0)->eta(), event.m_electrons.at( + 0)->phi(), event.m_electrons.at(0)->e() / 1.e3); + myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2), KLFitter::Particles::kElectron); } if (m_leptonTypeKLFitterEnum == KLFitter::LikelihoodTopLeptonJets::LeptonType::kMuon) { - TLorentzVector mu; - mu.SetPtEtaPhiE( event.m_muons.at(0)->pt()/1.e3 , event.m_muons.at(0)->eta() , event.m_muons.at(0)->phi(), event.m_muons.at(0)->e() / 1.e3); - myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon); + TLorentzVector mu; + mu.SetPtEtaPhiE(event.m_muons.at(0)->pt() / 1.e3, event.m_muons.at(0)->eta(), event.m_muons.at( + 0)->phi(), event.m_muons.at(0)->e() / 1.e3); + myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon); } } - if(m_LHType == "ttH"){ - + if (m_LHType == "ttH") { if (m_leptonTypeKLFitterEnum_TTH == KLFitter::LikelihoodTTHLeptonJets::LeptonType::kElectron) { TLorentzVector el; - el.SetPtEtaPhiE( event.m_electrons.at(0)->pt()/1.e3 , event.m_electrons.at(0)->eta() , event.m_electrons.at(0)->phi(), event.m_electrons.at(0)->e() / 1.e3); - myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2) , KLFitter::Particles::kElectron); + el.SetPtEtaPhiE(event.m_electrons.at(0)->pt() / 1.e3, event.m_electrons.at(0)->eta(), event.m_electrons.at( + 0)->phi(), event.m_electrons.at(0)->e() / 1.e3); + myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2), KLFitter::Particles::kElectron); } if (m_leptonTypeKLFitterEnum_TTH == KLFitter::LikelihoodTTHLeptonJets::LeptonType::kMuon) { TLorentzVector mu; - mu.SetPtEtaPhiE( event.m_muons.at(0)->pt()/1.e3 , event.m_muons.at(0)->eta() , event.m_muons.at(0)->phi(), event.m_muons.at(0)->e() / 1.e3); + mu.SetPtEtaPhiE(event.m_muons.at(0)->pt() / 1.e3, event.m_muons.at(0)->eta(), event.m_muons.at( + 0)->phi(), event.m_muons.at(0)->e() / 1.e3); + myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon); + } + } + if (m_LHType == "ttbar_JetAngles") { + if (m_leptonTypeKLFitterEnum_JetAngles == KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kElectron) { + TLorentzVector el; + el.SetPtEtaPhiE(event.m_electrons.at(0)->pt() / 1.e3, event.m_electrons.at(0)->eta(), event.m_electrons.at( + 0)->phi(), event.m_electrons.at(0)->e() / 1.e3); + myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2), KLFitter::Particles::kElectron); + } + if (m_leptonTypeKLFitterEnum_JetAngles == KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kMuon) { + TLorentzVector mu; + mu.SetPtEtaPhiE(event.m_muons.at(0)->pt() / 1.e3, event.m_muons.at(0)->eta(), event.m_muons.at( + 0)->phi(), event.m_muons.at(0)->e() / 1.e3); myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon); } } - + + if (m_LHType == "ttZTrilepton") { + if (m_leptonTypeKLFitterEnum_TTZ == KLFitter::LikelihoodTTZTrilepton::LeptonType::kElectron) { + if (m_leptonType == "kTriElectron") { + // This is the "true" trilepton case with three leptons of the same flavour. + if (event.m_electrons.size() < 3) { + ATH_MSG_ERROR("KLFitter: kTriElectron requires three electrons..."); + return StatusCode::FAILURE; + } + TLorentzVector el; + for (unsigned int i = 0; i < 3; ++i) { + const auto& electron = event.m_electrons.at(i); + el.SetPtEtaPhiE(electron->pt() / 1.e3, electron->eta(), electron->phi(), electron->e() / 1.e3); + myParticles->AddParticle(&el, electron->caloCluster()->etaBE(2), KLFitter::Particles::kElectron, "", i); + } + } else { + // Trivial case of mixed lepton flavours. Use ttbar->l+jets likelihood and only add the single lepton. + TLorentzVector el; + el.SetPtEtaPhiE(event.m_electrons.at(0)->pt() / 1.e3, event.m_electrons.at(0)->eta(), event.m_electrons.at( + 0)->phi(), event.m_electrons.at(0)->e() / 1.e3); + myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2), + KLFitter::Particles::kElectron); + } + } + + if (m_leptonTypeKLFitterEnum_TTZ == KLFitter::LikelihoodTTZTrilepton::LeptonType::kMuon) { + if (m_leptonType == "kTriMuon") { + // This is the "true" trilepton case with three leptons of the same flavour. + if (event.m_muons.size() < 3) { + ATH_MSG_ERROR("KLFitter: kTriMuon requires three muons..."); + return StatusCode::FAILURE; + } + TLorentzVector mu; + for (unsigned int i = 0; i < 3; ++i) { + const auto& muon = event.m_muons.at(i); + mu.SetPtEtaPhiE(muon->pt() / 1.e3, muon->eta(), muon->phi(), muon->e() / 1.e3); + myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon, "", i); + } + } else { + // Trivial case of mixed lepton flavours. Use ttbar->l+jets likelihood and only add the single lepton. + TLorentzVector mu; + mu.SetPtEtaPhiE(event.m_muons.at(0)->pt() / 1.e3, event.m_muons.at(0)->eta(), event.m_muons.at( + 0)->phi(), event.m_muons.at(0)->e() / 1.e3); + myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon); + } + } + } + if (m_LHType == "ttbar_BoostedLJets") { + if (m_leptonTypeKLFitterEnum_BoostedLJets == KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kElectron) { + TLorentzVector el; + el.SetPtEtaPhiE(event.m_electrons.at(0)->pt() / 1.e3, event.m_electrons.at(0)->eta(), event.m_electrons.at( + 0)->phi(), event.m_electrons.at(0)->e() / 1.e3); + myParticles->AddParticle(&el, event.m_electrons.at(0)->caloCluster()->etaBE(2), KLFitter::Particles::kElectron); + } + if (m_leptonTypeKLFitterEnum_BoostedLJets == KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kMuon) { + TLorentzVector mu; + mu.SetPtEtaPhiE(event.m_muons.at(0)->pt() / 1.e3, event.m_muons.at(0)->eta(), event.m_muons.at( + 0)->phi(), event.m_muons.at(0)->e() / 1.e3); + myParticles->AddParticle(&mu, mu.Eta(), KLFitter::Particles::kMuon); + } + } + // set the jets, depending on the Jet Selection Mode - setJets(event, myParticles); - + if (!setJets(event, myParticles)) { + ATH_MSG_INFO( + "KLFitterTool::execute: error at event " << event.m_info->eventNumber() << + ". It was not possible to properly fill the jets. Are you trying to use a KLeadingX Jet Selection mode with a signal region with less than X jets? Please check your configuration!"); + return StatusCode::FAILURE; + } + // add the particles to the fitter if (!m_myFitter->SetParticles(myParticles)) { - ATH_MSG_ERROR( "KLFitter: Error adding particles to fitter..." ); + ATH_MSG_ERROR("KLFitter: Error adding particles to fitter..."); return StatusCode::FAILURE; - } - + } + // add the MET x and y components as well as the SumET to the fitter const double met_ex = event.m_met->mpx() / 1.e3; const double met_ey = event.m_met->mpy() / 1.e3; const double met_sumet = event.m_met->sumet() / 1.e3; if (!m_myFitter->SetET_miss_XY_SumET(met_ex, met_ey, met_sumet)) { - ATH_MSG_ERROR( "KLFitter: Error adding MET to fitter..." ); + ATH_MSG_ERROR("KLFitter: Error adding MET to fitter..."); return StatusCode::FAILURE; - } - - // create the xAOD::KLFitterResultContainer - xAOD::KLFitterResultAuxContainer* resultAuxContainer = new xAOD::KLFitterResultAuxContainer{}; - xAOD::KLFitterResultContainer* resultContainer = new xAOD::KLFitterResultContainer{}; - resultContainer->setStore( resultAuxContainer ); - - + } + // define StoreGate names + std::string outputSGKey("SetMe"); + if (!event.m_isLoose) { + outputSGKey = m_config->sgKeyKLFitter(event.m_hashValue); + } + if (event.m_isLoose) { + outputSGKey = m_config->sgKeyKLFitterLoose(event.m_hashValue); + } + std::string outputSGKeyAux = outputSGKey + "Aux."; + // create or retrieve (if existent) the xAOD::KLFitterResultContainer + xAOD::KLFitterResultAuxContainer* resultAuxContainer = nullptr; + xAOD::KLFitterResultContainer* resultContainer = nullptr; + if ((!m_config->KLFitterSaveAllPermutations()) || + ((m_config->KLFitterSaveAllPermutations()) && + (!evtStore()->tds()->contains<xAOD::KLFitterResultContainer>(outputSGKey)))) { + resultAuxContainer = new xAOD::KLFitterResultAuxContainer {}; + resultContainer = new xAOD::KLFitterResultContainer {}; + resultContainer->setStore(resultAuxContainer); + } else top::check(evtStore()->tds()->retrieve(resultContainer, + outputSGKey), + "KLFitterTools::execute(): can not retrieve xAOD::KLFitterResultContainer from evtStore()"); + // loop over all permutations const int nperm = m_myFitter->Permutations()->NPermutations(); - for (int iperm = 0; iperm < nperm; ++iperm) { + for (int iperm = 0; iperm < nperm; ++iperm) { // Perform the fit - m_myFitter->Fit(iperm); - - // create a result - xAOD::KLFitterResult* result = new xAOD::KLFitterResult{}; - resultContainer->push_back( result ); - + m_myFitter->Fit(iperm); + // create a result + xAOD::KLFitterResult* result = new xAOD::KLFitterResult {}; + resultContainer->push_back(result); + + //Set name hash. This is because it seems std::string is not supported by AuxContainers... + std::hash<std::string> hash_string; + result->setSelectionCode(hash_string(m_selectionName)); + unsigned int ConvergenceStatusBitWord = m_myFitter->ConvergenceStatus(); bool MinuitDidNotConverge = (ConvergenceStatusBitWord & m_myFitter->MinuitDidNotConvergeMask) != 0; bool FitAbortedDueToNaN = (ConvergenceStatusBitWord & m_myFitter->FitAbortedDueToNaNMask) != 0; - bool AtLeastOneFitParameterAtItsLimit = (ConvergenceStatusBitWord & m_myFitter->AtLeastOneFitParameterAtItsLimitMask) != 0; - bool InvalidTransferFunctionAtConvergence = (ConvergenceStatusBitWord & m_myFitter->InvalidTransferFunctionAtConvergenceMask) != 0; - - result->setMinuitDidNotConverge( ((MinuitDidNotConverge) ? 1 : 0) ); - result->setFitAbortedDueToNaN( ((FitAbortedDueToNaN) ? 1 : 0) ); - result->setAtLeastOneFitParameterAtItsLimit( ((AtLeastOneFitParameterAtItsLimit) ? 1 : 0 ) ); - result->setInvalidTransferFunctionAtConvergence( ((InvalidTransferFunctionAtConvergence) ? 1 : 0) ); - - result->setLogLikelihood( m_myFitter->Likelihood()->LogLikelihood(m_myFitter->Likelihood()->GetBestFitParameters()) ); - result->setEventProbability( std::exp(m_myFitter->Likelihood()->LogEventProbability()) ); - result->setParameters( m_myFitter->Likelihood()->GetBestFitParameters() ); - result->setParameterErrors( m_myFitter->Likelihood()->GetBestFitParameterErrors() ); - - KLFitter::Particles * myModelParticles = m_myFitter->Likelihood()->ParticlesModel(); - KLFitter::Particles ** myPermutedParticles = m_myFitter->Likelihood()->PParticlesPermuted(); - - result->setModel_bhad_pt( myModelParticles->Parton(0)->Pt() ); - result->setModel_bhad_eta( myModelParticles->Parton(0)->Eta() ); - result->setModel_bhad_phi( myModelParticles->Parton(0)->Phi() ); - result->setModel_bhad_E( myModelParticles->Parton(0)->E() ); - result->setModel_bhad_jetIndex( (*myPermutedParticles)->JetIndex(0) ); - - result->setModel_blep_pt( myModelParticles->Parton(1)->Pt() ); - result->setModel_blep_eta( myModelParticles->Parton(1)->Eta() ); - result->setModel_blep_phi( myModelParticles->Parton(1)->Phi() ); - result->setModel_blep_E( myModelParticles->Parton(1)->E() ); - result->setModel_blep_jetIndex( (*myPermutedParticles)->JetIndex(1) ); - - result->setModel_lq1_pt( myModelParticles->Parton(2)->Pt() ); - result->setModel_lq1_eta( myModelParticles->Parton(2)->Eta() ); - result->setModel_lq1_phi( myModelParticles->Parton(2)->Phi() ); - result->setModel_lq1_E( myModelParticles->Parton(2)->E() ); - result->setModel_lq1_jetIndex( (*myPermutedParticles)->JetIndex(2) ); - - result->setModel_lq2_pt( myModelParticles->Parton(3)->Pt() ); - result->setModel_lq2_eta( myModelParticles->Parton(3)->Eta() ); - result->setModel_lq2_phi( myModelParticles->Parton(3)->Phi() ); - result->setModel_lq2_E( myModelParticles->Parton(3)->E() ); - result->setModel_lq2_jetIndex( (*myPermutedParticles)->JetIndex(3) ); - - if(m_LHType == "ttH"){ - - result->setModel_Higgs_b1_pt( myModelParticles->Parton(4)->Pt() ); - result->setModel_Higgs_b1_eta( myModelParticles->Parton(4)->Eta() ); - result->setModel_Higgs_b1_phi( myModelParticles->Parton(4)->Phi() ); - result->setModel_Higgs_b1_E( myModelParticles->Parton(4)->E() ); - result->setModel_Higgs_b1_jetIndex( (*myPermutedParticles)->JetIndex(4) ); - - result->setModel_Higgs_b2_pt( myModelParticles->Parton(5)->Pt() ); - result->setModel_Higgs_b2_eta( myModelParticles->Parton(5)->Eta() ); - result->setModel_Higgs_b2_phi( myModelParticles->Parton(5)->Phi() ); - result->setModel_Higgs_b2_E( myModelParticles->Parton(5)->E() ); - result->setModel_Higgs_b2_jetIndex( (*myPermutedParticles)->JetIndex(5) ); - - } - - if (m_leptonTypeKLFitterEnum == KLFitter::LikelihoodTopLeptonJets::LeptonType::kElectron || m_leptonTypeKLFitterEnum_TTH == KLFitter::LikelihoodTTHLeptonJets::LeptonType::kElectron) { - result->setModel_lep_pt( myModelParticles->Electron(0)->Pt() ); - result->setModel_lep_eta( myModelParticles->Electron(0)->Eta() ); - result->setModel_lep_phi( myModelParticles->Electron(0)->Phi() ); - result->setModel_lep_E( myModelParticles->Electron(0)->E() ); - } - - if (m_leptonTypeKLFitterEnum == KLFitter::LikelihoodTopLeptonJets::LeptonType::kMuon || m_leptonTypeKLFitterEnum_TTH == KLFitter::LikelihoodTTHLeptonJets::LeptonType::kMuon) { - result->setModel_lep_pt( myModelParticles->Muon(0)->Pt() ); - result->setModel_lep_eta( myModelParticles->Muon(0)->Eta() ); - result->setModel_lep_phi( myModelParticles->Muon(0)->Phi() ); - result->setModel_lep_E( myModelParticles->Muon(0)->E() ); - } + bool AtLeastOneFitParameterAtItsLimit = + (ConvergenceStatusBitWord & m_myFitter->AtLeastOneFitParameterAtItsLimitMask) != 0; + bool InvalidTransferFunctionAtConvergence = + (ConvergenceStatusBitWord & m_myFitter->InvalidTransferFunctionAtConvergenceMask) != 0; + + result->setMinuitDidNotConverge(((MinuitDidNotConverge) ? 1 : 0)); + result->setFitAbortedDueToNaN(((FitAbortedDueToNaN) ? 1 : 0)); + result->setAtLeastOneFitParameterAtItsLimit(((AtLeastOneFitParameterAtItsLimit) ? 1 : 0)); + result->setInvalidTransferFunctionAtConvergence(((InvalidTransferFunctionAtConvergence) ? 1 : 0)); + + result->setLogLikelihood(m_myFitter->Likelihood()->LogLikelihood(m_myFitter->Likelihood()->GetBestFitParameters())); + result->setEventProbability(std::exp(m_myFitter->Likelihood()->LogEventProbability())); + result->setParameters(m_myFitter->Likelihood()->GetBestFitParameters()); + result->setParameterErrors(m_myFitter->Likelihood()->GetBestFitParameterErrors()); + + KLFitter::Particles* myModelParticles = m_myFitter->Likelihood()->ParticlesModel(); + KLFitter::Particles** myPermutedParticles = m_myFitter->Likelihood()->PParticlesPermuted(); + + + if (m_LHType == "ttbar" || m_LHType == "ttH" || m_LHType == "ttbar_JetAngles" || m_LHType == "ttZTrilepton" || + m_LHType == "ttbar_BoostedLJets") { + result->setModel_bhad_pt(myModelParticles->Parton(0)->Pt()); + result->setModel_bhad_eta(myModelParticles->Parton(0)->Eta()); + result->setModel_bhad_phi(myModelParticles->Parton(0)->Phi()); + result->setModel_bhad_E(myModelParticles->Parton(0)->E()); + result->setModel_bhad_jetIndex((*myPermutedParticles)->JetIndex(0)); + + result->setModel_blep_pt(myModelParticles->Parton(1)->Pt()); + result->setModel_blep_eta(myModelParticles->Parton(1)->Eta()); + result->setModel_blep_phi(myModelParticles->Parton(1)->Phi()); + result->setModel_blep_E(myModelParticles->Parton(1)->E()); + result->setModel_blep_jetIndex((*myPermutedParticles)->JetIndex(1)); + + result->setModel_lq1_pt(myModelParticles->Parton(2)->Pt()); + result->setModel_lq1_eta(myModelParticles->Parton(2)->Eta()); + result->setModel_lq1_phi(myModelParticles->Parton(2)->Phi()); + result->setModel_lq1_E(myModelParticles->Parton(2)->E()); + result->setModel_lq1_jetIndex((*myPermutedParticles)->JetIndex(2)); + + // boosted likelihood has only one light jet + if (m_LHType != "ttbar_BoostedLJets") { + result->setModel_lq2_pt(myModelParticles->Parton(3)->Pt()); + result->setModel_lq2_eta(myModelParticles->Parton(3)->Eta()); + result->setModel_lq2_phi(myModelParticles->Parton(3)->Phi()); + result->setModel_lq2_E(myModelParticles->Parton(3)->E()); + result->setModel_lq2_jetIndex((*myPermutedParticles)->JetIndex(3)); - result->setModel_nu_pt( myModelParticles->Neutrino(0)->Pt() ); - result->setModel_nu_eta( myModelParticles->Neutrino(0)->Eta() ); - result->setModel_nu_phi( myModelParticles->Neutrino(0)->Phi() ); - result->setModel_nu_E( myModelParticles->Neutrino(0)->E() ); - - + if (m_LHType == "ttH") { + result->setModel_Higgs_b1_pt(myModelParticles->Parton(4)->Pt()); + result->setModel_Higgs_b1_eta(myModelParticles->Parton(4)->Eta()); + result->setModel_Higgs_b1_phi(myModelParticles->Parton(4)->Phi()); + result->setModel_Higgs_b1_E(myModelParticles->Parton(4)->E()); + result->setModel_Higgs_b1_jetIndex((*myPermutedParticles)->JetIndex(4)); + + result->setModel_Higgs_b2_pt(myModelParticles->Parton(5)->Pt()); + result->setModel_Higgs_b2_eta(myModelParticles->Parton(5)->Eta()); + result->setModel_Higgs_b2_phi(myModelParticles->Parton(5)->Phi()); + result->setModel_Higgs_b2_E(myModelParticles->Parton(5)->E()); + result->setModel_Higgs_b2_jetIndex((*myPermutedParticles)->JetIndex(5)); + } + } + + if (m_leptonTypeKLFitterEnum == KLFitter::LikelihoodTopLeptonJets::LeptonType::kElectron || + m_leptonTypeKLFitterEnum_TTH == KLFitter::LikelihoodTTHLeptonJets::LeptonType::kElectron || + m_leptonTypeKLFitterEnum_TTZ == KLFitter::LikelihoodTTZTrilepton::LeptonType::kElectron || + m_leptonTypeKLFitterEnum_BoostedLJets == KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kElectron || + m_leptonTypeKLFitterEnum_JetAngles == KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kElectron) { + result->setModel_lep_pt(myModelParticles->Electron(0)->Pt()); + result->setModel_lep_eta(myModelParticles->Electron(0)->Eta()); + result->setModel_lep_phi(myModelParticles->Electron(0)->Phi()); + result->setModel_lep_E(myModelParticles->Electron(0)->E()); + + if (m_leptonType == "kTriElectron") { + result->setModel_lep_index((*myPermutedParticles)->ElectronIndex(0)); + + result->setModel_lepZ1_pt(myModelParticles->Electron(1)->Pt()); + result->setModel_lepZ1_eta(myModelParticles->Electron(1)->Eta()); + result->setModel_lepZ1_phi(myModelParticles->Electron(1)->Phi()); + result->setModel_lepZ1_E(myModelParticles->Electron(1)->E()); + result->setModel_lepZ1_index((*myPermutedParticles)->ElectronIndex(1)); + + result->setModel_lepZ2_pt(myModelParticles->Electron(2)->Pt()); + result->setModel_lepZ2_eta(myModelParticles->Electron(2)->Eta()); + result->setModel_lepZ2_phi(myModelParticles->Electron(2)->Phi()); + result->setModel_lepZ2_E(myModelParticles->Electron(2)->E()); + result->setModel_lepZ2_index((*myPermutedParticles)->ElectronIndex(2)); + } + } + + if (m_leptonTypeKLFitterEnum == KLFitter::LikelihoodTopLeptonJets::LeptonType::kMuon || + m_leptonTypeKLFitterEnum_TTH == KLFitter::LikelihoodTTHLeptonJets::LeptonType::kMuon || + m_leptonTypeKLFitterEnum_TTZ == KLFitter::LikelihoodTTZTrilepton::LeptonType::kMuon || + m_leptonTypeKLFitterEnum_BoostedLJets == KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType::kMuon || + m_leptonTypeKLFitterEnum_JetAngles == KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType::kMuon) { + result->setModel_lep_pt(myModelParticles->Muon(0)->Pt()); + result->setModel_lep_eta(myModelParticles->Muon(0)->Eta()); + result->setModel_lep_phi(myModelParticles->Muon(0)->Phi()); + result->setModel_lep_E(myModelParticles->Muon(0)->E()); + + if (m_leptonType == "kTriMuon") { + result->setModel_lep_index((*myPermutedParticles)->MuonIndex(0)); + + result->setModel_lepZ1_pt(myModelParticles->Muon(1)->Pt()); + result->setModel_lepZ1_eta(myModelParticles->Muon(1)->Eta()); + result->setModel_lepZ1_phi(myModelParticles->Muon(1)->Phi()); + result->setModel_lepZ1_E(myModelParticles->Muon(1)->E()); + result->setModel_lepZ1_index((*myPermutedParticles)->MuonIndex(1)); + + result->setModel_lepZ2_pt(myModelParticles->Muon(2)->Pt()); + result->setModel_lepZ2_eta(myModelParticles->Muon(2)->Eta()); + result->setModel_lepZ2_phi(myModelParticles->Muon(2)->Phi()); + result->setModel_lepZ2_E(myModelParticles->Muon(2)->E()); + result->setModel_lepZ2_index((*myPermutedParticles)->MuonIndex(2)); + } + } + + result->setModel_nu_pt(myModelParticles->Neutrino(0)->Pt()); + result->setModel_nu_eta(myModelParticles->Neutrino(0)->Eta()); + result->setModel_nu_phi(myModelParticles->Neutrino(0)->Phi()); + result->setModel_nu_E(myModelParticles->Neutrino(0)->E()); + } else if (m_LHType == "ttbar_AllHadronic") { + result->setModel_b_from_top1_pt(myModelParticles->Parton(0)->Pt()); + result->setModel_b_from_top1_eta(myModelParticles->Parton(0)->Eta()); + result->setModel_b_from_top1_phi(myModelParticles->Parton(0)->Phi()); + result->setModel_b_from_top1_E(myModelParticles->Parton(0)->E()); + result->setModel_b_from_top1_jetIndex((*myPermutedParticles)->JetIndex(0)); + + result->setModel_b_from_top2_pt(myModelParticles->Parton(1)->Pt()); + result->setModel_b_from_top2_eta(myModelParticles->Parton(1)->Eta()); + result->setModel_b_from_top2_phi(myModelParticles->Parton(1)->Phi()); + result->setModel_b_from_top2_E(myModelParticles->Parton(1)->E()); + result->setModel_b_from_top2_jetIndex((*myPermutedParticles)->JetIndex(1)); + + result->setModel_lj1_from_top1_pt(myModelParticles->Parton(2)->Pt()); + result->setModel_lj1_from_top1_eta(myModelParticles->Parton(2)->Eta()); + result->setModel_lj1_from_top1_phi(myModelParticles->Parton(2)->Phi()); + result->setModel_lj1_from_top1_E(myModelParticles->Parton(2)->E()); + result->setModel_lj1_from_top1_jetIndex((*myPermutedParticles)->JetIndex(2)); + + result->setModel_lj2_from_top1_pt(myModelParticles->Parton(3)->Pt()); + result->setModel_lj2_from_top1_eta(myModelParticles->Parton(3)->Eta()); + result->setModel_lj2_from_top1_phi(myModelParticles->Parton(3)->Phi()); + result->setModel_lj2_from_top1_E(myModelParticles->Parton(3)->E()); + result->setModel_lj2_from_top1_jetIndex((*myPermutedParticles)->JetIndex(3)); + + result->setModel_lj1_from_top2_pt(myModelParticles->Parton(4)->Pt()); + result->setModel_lj1_from_top2_eta(myModelParticles->Parton(4)->Eta()); + result->setModel_lj1_from_top2_phi(myModelParticles->Parton(4)->Phi()); + result->setModel_lj1_from_top2_E(myModelParticles->Parton(4)->E()); + result->setModel_lj1_from_top2_jetIndex((*myPermutedParticles)->JetIndex(4)); + + result->setModel_lj2_from_top2_pt(myModelParticles->Parton(5)->Pt()); + result->setModel_lj2_from_top2_eta(myModelParticles->Parton(5)->Eta()); + result->setModel_lj2_from_top2_phi(myModelParticles->Parton(5)->Phi()); + result->setModel_lj2_from_top2_E(myModelParticles->Parton(5)->E()); + result->setModel_lj2_from_top2_jetIndex((*myPermutedParticles)->JetIndex(5)); + } } // Loop over permutations - + // Normalize event probability to unity // work out best permutation - float sumEventProbability(0.),bestEventProbability(0.); - unsigned int bestPermutation(999),iPerm(0); - + float sumEventProbability(0.), bestEventProbability(0.); + unsigned int bestPermutation(999), iPerm(0); + // First loop for (auto x : *resultContainer) { float prob = x->eventProbability(); + short minuitDidNotConverge = x->minuitDidNotConverge(); + short fitAbortedDueToNaN = x->fitAbortedDueToNaN(); + short atLeastOneFitParameterAtItsLimit = x->atLeastOneFitParameterAtItsLimit(); + short invalidTransferFunctionAtConvergence = x->invalidTransferFunctionAtConvergence(); sumEventProbability += prob; - + ++iPerm; + + // check if the best value has the highest event probability AND converged + if (minuitDidNotConverge) continue; + if (fitAbortedDueToNaN) continue; + if (atLeastOneFitParameterAtItsLimit) continue; + if (invalidTransferFunctionAtConvergence) continue; + if (prob > bestEventProbability) { bestEventProbability = prob; - bestPermutation = iPerm; + // Using iPerm -1 because it has already been incremented before + bestPermutation = iPerm - 1; } - ++iPerm; } - + // Second loop iPerm = 0; for (auto x : *resultContainer) { - x->setEventProbability( x->eventProbability() / sumEventProbability ); + x->setEventProbability(x->eventProbability() / sumEventProbability); if (iPerm == bestPermutation) { x->setBestPermutation(1); - } - else{ + } else { x->setBestPermutation(0); } ++iPerm; } - - // Save to StoreGate / TStore - std::string outputSGKey("SetMe"); - if (!event.m_isLoose) { - outputSGKey = m_config->sgKeyKLFitter( event.m_hashValue ); - } - if (event.m_isLoose) { - outputSGKey = m_config->sgKeyKLFitterLoose( event.m_hashValue ); - } - - std::string outputSGKeyAux = outputSGKey + "Aux."; - + // Save all permutations or only the highest event probability? - + // Save all - if (m_config->KLFitterSaveAllPermutations()) { - xAOD::TReturnCode save = evtStore()->tds()->record( resultContainer ,outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( resultAuxContainer , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } + if (m_config->KLFitterSaveAllPermutations()) { + if (!evtStore()->tds()->contains<xAOD::KLFitterResultContainer>(outputSGKey)) { + top::check(evtStore()->tds()->record(resultContainer, + outputSGKey), + "KLFitterTools: ERROR! Was not able to write KLFitterResultContainer"); + top::check(evtStore()->tds()->record(resultAuxContainer, + outputSGKeyAux), + "KLFitterTools: ERROR! Was not able to write KLFitterResultAuxContainer"); + } } - // Save only the best - if (!m_config->KLFitterSaveAllPermutations()) { - // create the xAOD::KLFitterResultContainer - xAOD::KLFitterResultAuxContainer* bestAuxContainer = new xAOD::KLFitterResultAuxContainer{}; - xAOD::KLFitterResultContainer* bestContainer = new xAOD::KLFitterResultContainer{}; - bestContainer->setStore( bestAuxContainer ); - + else { + // create ore retrieve the xAOD::KLFitterResultContainer + xAOD::KLFitterResultAuxContainer* bestAuxContainer = nullptr; + xAOD::KLFitterResultContainer* bestContainer = nullptr; + if (!evtStore()->tds()->contains<xAOD::KLFitterResultContainer>(outputSGKey)) { + bestAuxContainer = new xAOD::KLFitterResultAuxContainer {}; + bestContainer = new xAOD::KLFitterResultContainer {}; + bestContainer->setStore(bestAuxContainer); + } else top::check(evtStore()->tds()->retrieve(bestContainer, + outputSGKey), + "KLFitterTools::execute(): can not retrieve xAOD::KLFitterResultContainer from evtStore()"); + for (auto x : *resultContainer) { if (x->bestPermutation() == 1) { - xAOD::KLFitterResult* result = new xAOD::KLFitterResult{}; - result->makePrivateStore( *x ); - bestContainer->push_back( result ); + xAOD::KLFitterResult* result = new xAOD::KLFitterResult {}; + result->makePrivateStore(*x); + bestContainer->push_back(result); } } - - xAOD::TReturnCode save = evtStore()->tds()->record( bestContainer ,outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( bestAuxContainer , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } - + if (!evtStore()->tds()->contains<xAOD::KLFitterResultContainer>(outputSGKey)) { + top::check(evtStore()->tds()->record(bestContainer, + outputSGKey), + "KLFitterTools: ERROR! Was not able to write KLFitterResultContainer with best permutation"); + top::check(evtStore()->tds()->record(bestAuxContainer, + outputSGKeyAux), + "KLFitterTools: ERROR! Was not able to write KLFitterResultAuxContainer with best permutation"); + } // watch out for memory leaks! // raw pointers have not been put into a DataVector // we still actually own them - // AnalysisTop will actually do some memory management (which is very wierd and we don't like it) + // AnalysisTop will actually do some memory management (which is very wierd and we don't like it) delete resultContainer; delete resultAuxContainer; } - + // Pull the const result back out of StoreGate and attach to top::Event - top::check(evtStore()->retrieve(event.m_KLFitterResults,outputSGKey),"Failed to add KLFitterResults to top::Event"); + top::check(evtStore()->retrieve(event.m_KLFitterResults, outputSGKey), + "Failed to add KLFitterResults to top::Event"); delete myParticles; - + /// Return gracefully: - return StatusCode::SUCCESS; + return StatusCode::SUCCESS; } - + bool KLFitterTool::HasTag(const xAOD::Jet& jet, double& weight) const { weight = -99.; - const auto& btag_object = jet.btagging(); - const auto& tagger_name = m_btagging_eff_tool->getTaggerName(); - if (!btag_object || !btag_object->MVx_discriminant(tagger_name, weight)) { - ATH_MSG_ERROR("Failed to retrieve "+tagger_name+" weight!"); - } - for(const auto& tagWP : m_config->bTagWP_available()){ - if(!jet.isAvailable<char>("isbtagged_"+tagWP)) { - ATH_MSG_ERROR("Failed to retrieve jet decoration isbtagged_"+tagWP); + for (const auto& tagWP : m_config->bTagWP_available()) { + if (tagWP == "DL1_Continuous") continue; + if (!jet.isAvailable<char>("isbtagged_" + tagWP)) { + ATH_MSG_ERROR("Failed to retrieve jet decoration isbtagged_" + tagWP); break; } - return jet.auxdataConst<char>("isbtagged_"+tagWP); + return jet.auxdataConst<char>("isbtagged_" + tagWP); } return false; } - - + void KLFitterTool::retrieveEfficiencies(const xAOD::Jet& jet, float* efficiency, float* inefficiency) { *efficiency = .7725; // dummy values - *inefficiency = 1./125.93; // dummy values - - auto pretend_to_be_b = new xAOD::Jet(jet); - auto pretend_to_be_light = new xAOD::Jet(jet); - - pretend_to_be_b->setAttribute("HadronConeExclTruthLabelID", 5); - pretend_to_be_light->setAttribute("HadronConeExclTruthLabelID", 0); - - top::check(m_btagging_eff_tool->getMCEfficiency(*pretend_to_be_b, *efficiency), + *inefficiency = 1. / 125.93; // dummy values + //copy jet + xAOD::JetContainer jets; + xAOD::JetAuxContainer jetsAux; + jets.setStore(&jetsAux); + xAOD::Jet* jet_copy = new xAOD::Jet(); + jets.push_back(jet_copy); + *jet_copy = jet; + jet_copy->setJetP4(jet.jetP4()); + //treat jet as b-tagged + jet_copy->setAttribute("HadronConeExclTruthLabelID", 5); + top::check(m_btagging_eff_tool->getMCEfficiency(*jet_copy, *efficiency), "Could not retrieve tagging efficiency for b-jet"); - top::check(m_btagging_eff_tool->getMCEfficiency(*pretend_to_be_light, *inefficiency), + //treat jet as light + jet_copy->setAttribute("HadronConeExclTruthLabelID", 0); + top::check(m_btagging_eff_tool->getMCEfficiency(*jet_copy, *inefficiency), "Could not retrieve tagging efficiency for light jet"); + } - delete pretend_to_be_b; - delete pretend_to_be_light; + bool KLFitterTool::setJets(const top::Event& event, KLFitter::Particles* inputParticles) { + if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingThree) return setJetskLeadingThree(event, + inputParticles); - } + if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingFour) return setJetskLeadingFour(event, + inputParticles); + + + + if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingFive) return setJetskLeadingFive(event, + inputParticles); - void KLFitterTool::setJets(const top::Event& event,KLFitter::Particles* inputParticles) - { - if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingFour) { - setJetskLeadingFour( event , inputParticles ); - } - if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingFive) { - setJetskLeadingFive( event , inputParticles ); - } - if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingSix) { - setJetskLeadingSix( event , inputParticles ); - } - if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kBtagPriorityFourJets) { - setJetskBtagPriorityFourJets( event , inputParticles ); - } - if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kBtagPriorityFiveJets) { - setJetskBtagPriorityFiveJets( event , inputParticles ); - } - if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kBtagPrioritySixJets) { - setJetskBtagPrioritySixJets( event , inputParticles ); - } + if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingSix) return setJetskLeadingSix(event, + inputParticles); + + + + if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingSeven) return setJetskLeadingSeven(event, + inputParticles); + + + + if (m_jetSelectionModeKLFitterEnum == top::KLFitterJetSelection::kLeadingEight) return setJetskLeadingEight(event, + inputParticles); + + + + if (m_jetSelectionModeKLFitterEnum == + top::KLFitterJetSelection::kBtagPriorityThreeJets) return setJetskBtagPriorityThreeJets(event, inputParticles); + + if (m_jetSelectionModeKLFitterEnum == + top::KLFitterJetSelection::kBtagPriorityFourJets) return setJetskBtagPriorityFourJets(event, inputParticles); + + if (m_jetSelectionModeKLFitterEnum == + top::KLFitterJetSelection::kBtagPriorityFiveJets) return setJetskBtagPriorityFiveJets(event, inputParticles); + + if (m_jetSelectionModeKLFitterEnum == + top::KLFitterJetSelection::kBtagPrioritySixJets) return setJetskBtagPrioritySixJets(event, inputParticles); + + if (m_jetSelectionModeKLFitterEnum == + top::KLFitterJetSelection::kBtagPrioritySevenJets) return setJetskBtagPrioritySevenJets(event, inputParticles); + + if (m_jetSelectionModeKLFitterEnum == + top::KLFitterJetSelection::kBtagPriorityEightJets) return setJetskBtagPriorityEightJets(event, inputParticles); + + return false; + } + + bool KLFitterTool::setJetskLeadingThree(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskLeadingX(event, inputParticles, 3); + } + + bool KLFitterTool::setJetskLeadingFour(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskLeadingX(event, inputParticles, 4); + } + + bool KLFitterTool::setJetskLeadingFive(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskLeadingX(event, inputParticles, 5); } - - void KLFitterTool::setJetskLeadingFour(const top::Event& event,KLFitter::Particles* inputParticles) - { - setJetskLeadingX(event, inputParticles, 4); + + bool KLFitterTool::setJetskLeadingSix(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskLeadingX(event, inputParticles, 6); } - void KLFitterTool::setJetskLeadingFive(const top::Event& event,KLFitter::Particles* inputParticles) - { - setJetskLeadingX(event, inputParticles, 5); + bool KLFitterTool::setJetskLeadingSeven(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskLeadingX(event, inputParticles, 7); } - void KLFitterTool::setJetskLeadingSix(const top::Event& event,KLFitter::Particles* inputParticles) - { - setJetskLeadingX(event, inputParticles, 6); + bool KLFitterTool::setJetskLeadingEight(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskLeadingX(event, inputParticles, 8); } - void KLFitterTool::setJetskLeadingX(const top::Event& event,KLFitter::Particles* inputParticles, int njets) - { - int index(0); + bool KLFitterTool::setJetskLeadingX(const top::Event& event, KLFitter::Particles* inputParticles, + const unsigned int njets) { + unsigned int index(0); + + //If container has less jets than required, raise error + if (m_config->KLFitterFailOnLessThanXJets()) { + if (event.m_jets.size() < njets) { + ATH_MSG_INFO( + "KLFitterTool::setJetskLeadingX: You required " << njets << " jets. Event has " << event.m_jets.size() << + " jets!"); + return false; + } + } for (const auto& jet : event.m_jets) { - if (index > njets-1) break; + if (index > njets - 1) break; TLorentzVector jet_p4; jet_p4.SetPtEtaPhiE(jet->pt() / 1.e3, jet->eta(), jet->phi(), jet->e() / 1.e3); double weight(-99.); + float eff(0), ineff(0); + const bool isTagged = HasTag(*jet, weight); - float eff(0), ineff(0); - retrieveEfficiencies(*jet, &eff, &ineff); + if (m_isWorkingPoint) { + retrieveEfficiencies(*jet, &eff, &ineff); - inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, - isTagged, eff, 1./ineff, KLFitter::Particles::kNone, weight); + inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, + isTagged, eff, 1. / ineff, KLFitter::Particles::kNone, weight); + } else { + inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, isTagged); + } ++index; } + return true; + } + + bool KLFitterTool::setJetskBtagPriorityThreeJets(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskBtagPriority(event, inputParticles, 3); } - - void KLFitterTool::setJetskBtagPriorityFourJets(const top::Event& event,KLFitter::Particles* inputParticles) - { - setJetskBtagPriority( event , inputParticles , 4 ); + bool KLFitterTool::setJetskBtagPriorityFourJets(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskBtagPriority(event, inputParticles, 4); } - - void KLFitterTool::setJetskBtagPriorityFiveJets(const top::Event& event,KLFitter::Particles* inputParticles) - { - setJetskBtagPriority( event , inputParticles , 5 ); - } - - void KLFitterTool::setJetskBtagPrioritySixJets(const top::Event& event,KLFitter::Particles* inputParticles) - { - setJetskBtagPriority( event , inputParticles , 6 ); + + bool KLFitterTool::setJetskBtagPriorityFiveJets(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskBtagPriority(event, inputParticles, 5); + } + + bool KLFitterTool::setJetskBtagPrioritySixJets(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskBtagPriority(event, inputParticles, 6); + } + + bool KLFitterTool::setJetskBtagPrioritySevenJets(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskBtagPriority(event, inputParticles, 7); + } + + bool KLFitterTool::setJetskBtagPriorityEightJets(const top::Event& event, KLFitter::Particles* inputParticles) { + return setJetskBtagPriority(event, inputParticles, 8); } - - void KLFitterTool::setJetskBtagPriority(const top::Event& event,KLFitter::Particles* inputParticles,const unsigned int maxJets) - { - // kBtagPriority mode first adds the b jets, then the light jets - // If your 6th or 7th jet is a b jet, then you probably want this option + + bool KLFitterTool::setJetskBtagPriority(const top::Event& event, KLFitter::Particles* inputParticles, + const unsigned int maxJets) { + // kBtagPriority mode first adds the b jets, then the light jets + // If your 6th or 7th jet is a b jet, then you probably want this option + + //If container has less jets than required, raise error + if (m_config->KLFitterFailOnLessThanXJets()) { + if (event.m_jets.size() < maxJets) { + ATH_MSG_INFO( + "KLFitterTool::setJetskBtagPriority: You required " << maxJets << " jets. Event has " << event.m_jets.size() << + " jets!"); + return false; + } + } unsigned int totalJets(0); - // First find the b-jets + // First find the b-jets unsigned int index(0); double weight(0); for (const auto& jet : event.m_jets) { if (totalJets >= maxJets) break; if (HasTag(*jet, weight)) { - TLorentzVector jet_p4; + TLorentzVector jet_p4; jet_p4.SetPtEtaPhiE(jet->pt() / 1.e3, jet->eta(), jet->phi(), jet->e() / 1.e3); - float eff(0), ineff(0); - retrieveEfficiencies(*jet, &eff, &ineff); + if (m_isWorkingPoint) { + float eff(0), ineff(0); + retrieveEfficiencies(*jet, &eff, &ineff); - inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, - true, eff, 1./ineff, KLFitter::Particles::kNone, weight); + inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, + true, eff, 1. / ineff, KLFitter::Particles::kNone, weight); + } else { + inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, + true); + } ++totalJets; - } // HasTag - + } // HasTag + ++index; - } // for (jet) - + } // for (jet) + - // Second, find the light jets + // Second, find the light jets index = 0; for (const auto& jet : event.m_jets) { if (totalJets >= maxJets) break; @@ -610,24 +1018,27 @@ namespace top{ TLorentzVector jet_p4; jet_p4.SetPtEtaPhiE(jet->pt() / 1.e3, jet->eta(), jet->phi(), jet->e() / 1.e3); - float eff(0), ineff(0); - retrieveEfficiencies(*jet, &eff, &ineff); + if (m_isWorkingPoint) { + float eff(0), ineff(0); + retrieveEfficiencies(*jet, &eff, &ineff); - inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, - false, eff, 1./ineff, KLFitter::Particles::kNone, weight); + inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, + false, eff, 1. / ineff, KLFitter::Particles::kNone, weight); + } else { + inputParticles->AddParticle(&jet_p4, jet_p4.Eta(), KLFitter::Particles::kParton, "", index, + false); + } ++totalJets; - } // !HasTag - + } // !HasTag + ++index; - } // for (jet) - + } // for (jet) + return true; } - /// Function finalizing the tool - StatusCode KLFitterTool::finalize() - { + StatusCode KLFitterTool::finalize() { /// Return gracefully: - return StatusCode::SUCCESS; + return StatusCode::SUCCESS; } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/LinkDef.h index dbc94fd06e17016ff0ab7bea737a0911ede05941..a81a3c2f51e385bb4148866fbac2e694197ac744 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/LinkDef.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/TopEventReconstructionToolsLoader.h" diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/MT2Reco.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/MT2Reco.cxx index dcbe8c0e0001fff90af4d23323f04f08271043a0..7aa6718b2e14b8ead7d9cf93019c678864e99626 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/MT2Reco.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/MT2Reco.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/MT2Reco.h" @@ -9,17 +9,15 @@ #ifdef ROOTCORE_PACKAGE_Oxbridgekinetics namespace top { + MT2Reco::MT2Reco() { + } -MT2Reco::MT2Reco() { -} - -MT2Reco::~MT2Reco() { -} + MT2Reco::~MT2Reco() { + } -bool MT2Reco::apply(const top::Event& /*event*/) const { + bool MT2Reco::apply(const top::Event& /*event*/) const { return true; -} - + } } #endif //ROOTCORE_PACKAGE_Oxbridgekinetics diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/NeutrinoWeighting.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/NeutrinoWeighting.cxx index f0807169e4d99aa4c2bf69be48712fabf58e457d..54a50b4e490bf50fae54881c8895f594cdba5a5f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/NeutrinoWeighting.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/NeutrinoWeighting.cxx @@ -1,37 +1,39 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/NeutrinoWeighting.h" #include "TopEvent/Event.h" -namespace top { +#include <cmath> -NeutrinoWeighting::NeutrinoWeighting() : sigmax(10), sigmay(10) { +namespace top { + NeutrinoWeighting::NeutrinoWeighting() : sigmax(10), sigmay(10) { double etaStep = 0.2; //construct the array of eta values to use (cosh and sinh them) int index = 0; + for (double eta = -5.0; eta < 5.0001; eta += etaStep) { - neutrinos[index][0] = eta; - neutrinos[index][1] = sinh(eta); - neutrinos[index][2] = cosh(eta); - ++index; + neutrinos[index][0] = eta; + neutrinos[index][1] = std::sinh(eta); + neutrinos[index][2] = std::cosh(eta); + ++index; } etaSize = index; if (etaSize > 2000) { - std::cout << "ERROR TOO MANY SAMPLING POINT FOR neutrinos ARRAY" << std::endl; - exit(1); + std::cout << "ERROR TOO MANY SAMPLING POINT FOR neutrinos ARRAY" << std::endl; + exit(1); } -} + } -NeutrinoWeighting::~NeutrinoWeighting() { -} + NeutrinoWeighting::~NeutrinoWeighting() { + } -bool NeutrinoWeighting::apply(const top::Event& event) const { + bool NeutrinoWeighting::apply(const top::Event& event) const { TLorentzVector l1; TLorentzVector l2; TLorentzVector b1; @@ -42,41 +44,42 @@ bool NeutrinoWeighting::apply(const top::Event& event) const { const double met_ey = event.m_met->mpy(); for (int i = 0; i < etaSize; ++i) { - for (int j = 0; j < etaSize; ++j) { - NWSolution ans1 = solveForNeutrinoEta(l1, b1, topMass, i); - NWSolution ans2 = solveForNeutrinoEta(l2, b2, topMass, j); - - if (ans1.getNumSolutions() > 0 && ans2.getNumSolutions() > 0) { - const double sol1 = neutrino_weight(ans1.getv1(), ans2.getv1(), met_ex, met_ey); - const double sol2 = neutrino_weight(ans1.getv1(), ans2.getv2(), met_ex, met_ey); - const double sol3 = neutrino_weight(ans1.getv2(), ans2.getv1(), met_ex, met_ey); - const double sol4 = neutrino_weight(ans1.getv2(), ans2.getv2(), met_ex, met_ey); - - if (isnan(sol1) || isnan(sol2) || isnan(sol3) || isnan(sol4)) - std::cout << "One of the quadratic ans is NaN!" << std::endl; - } - - ans1 = solveForNeutrinoEta(l1, b2, topMass, i); - ans2 = solveForNeutrinoEta(l2, b1, topMass, j); - - if (ans1.getNumSolutions() > 0 && ans2.getNumSolutions() > 0) { - const double sol1 = neutrino_weight(ans1.getv1(), ans2.getv1(), met_ex, met_ey); - const double sol2 = neutrino_weight(ans1.getv1(), ans2.getv2(), met_ex, met_ey); - const double sol3 = neutrino_weight(ans1.getv2(), ans2.getv1(), met_ex, met_ey); - const double sol4 = neutrino_weight(ans1.getv2(), ans2.getv2(), met_ex, met_ey); - - if (isnan(sol1) || isnan(sol2) || isnan(sol3) || isnan(sol4)) - std::cout << "One of the quadratic ans is NaN!" << std::endl; - } - } - } + for (int j = 0; j < etaSize; ++j) { + NWSolution ans1 = solveForNeutrinoEta(l1, b1, topMass, i); + NWSolution ans2 = solveForNeutrinoEta(l2, b2, topMass, j); + + if (ans1.getNumSolutions() > 0 && ans2.getNumSolutions() > 0) { + const double sol1 = neutrino_weight(ans1.getv1(), ans2.getv1(), met_ex, met_ey); + const double sol2 = neutrino_weight(ans1.getv1(), ans2.getv2(), met_ex, met_ey); + const double sol3 = neutrino_weight(ans1.getv2(), ans2.getv1(), met_ex, met_ey); + const double sol4 = neutrino_weight(ans1.getv2(), ans2.getv2(), met_ex, met_ey); + + if (std::isnan(sol1) || std::isnan(sol2) || std::isnan(sol3) || + std::isnan(sol4)) std::cout << "One of the quadratic ans is NaN!" << std::endl; + } + + ans1 = solveForNeutrinoEta(l1, b2, topMass, i); + ans2 = solveForNeutrinoEta(l2, b1, topMass, j); + + if (ans1.getNumSolutions() > 0 && ans2.getNumSolutions() > 0) { + const double sol1 = neutrino_weight(ans1.getv1(), ans2.getv1(), met_ex, met_ey); + const double sol2 = neutrino_weight(ans1.getv1(), ans2.getv2(), met_ex, met_ey); + const double sol3 = neutrino_weight(ans1.getv2(), ans2.getv1(), met_ex, met_ey); + const double sol4 = neutrino_weight(ans1.getv2(), ans2.getv2(), met_ex, met_ey); + + if (std::isnan(sol1) || std::isnan(sol2) || std::isnan(sol3) || + std::isnan(sol4)) std::cout << "One of the quadratic ans is NaN!" << std::endl; + } + } + } //normalise? return true; -} + } -NWSolution NeutrinoWeighting::solveForNeutrinoEta(const TLorentzVector& lepton, const TLorentzVector& bJet, double topMass, int index) const { + NWSolution NeutrinoWeighting::solveForNeutrinoEta(const TLorentzVector& lepton, const TLorentzVector& bJet, + double topMass, int index) const { double Wmass2 = m_wmass * m_wmass; double bmass = m_bmass; @@ -84,7 +87,8 @@ NWSolution NeutrinoWeighting::solveForNeutrinoEta(const TLorentzVector& lepton, double Ebprime = bJet.E() * neutrinos[index][2] - bJet.Pz() * neutrinos[index][1]; double A = (lepton.Py() * Ebprime - bJet.Py() * Elprime) / (bJet.Px() * Elprime - lepton.Px() * Ebprime); - double B = (Elprime * (topMass * topMass - Wmass2 - bmass * bmass - 2. * lepton * bJet) - Ebprime * Wmass2) / (2. * (lepton.Px() * Ebprime - bJet.Px() * Elprime)); + double B = (Elprime * (topMass * topMass - Wmass2 - bmass * bmass - 2. * lepton * bJet) - Ebprime * Wmass2) / + (2. * (lepton.Px() * Ebprime - bJet.Px() * Elprime)); double par1 = (lepton.Px() * A + lepton.Py()) / Elprime; double C = A * A + 1. - par1 * par1; @@ -94,33 +98,34 @@ NWSolution NeutrinoWeighting::solveForNeutrinoEta(const TLorentzVector& lepton, double det = D * D - 4. * C * F; NWSolution sol; + sol.setSolutions(0); if (det > 0.) { - double tmp = sqrt(det) / (2. * C); - double py1 = -D / (2. * C) + tmp; - double py2 = -D / (2. * C) - tmp; - double px1 = A * py1 + B; - double px2 = A * py2 + B; - double pT2_1 = px1 * px1 + py1 * py1; - double pT2_2 = px2 * px2 + py2 * py2; - double pz1 = sqrt(pT2_1) * neutrinos[index][1]; - double pz2 = sqrt(pT2_2) * neutrinos[index][1]; - - TLorentzVector a1(px1, py1, pz1, sqrt(pT2_1 + pz1 * pz1)); - TLorentzVector a2(px2, py2, pz2, sqrt(pT2_2 + pz2 * pz2)); - - sol.setSolutions(2, a1, a2); + double tmp = std::sqrt(det) / (2. * C); + double py1 = -D / (2. * C) + tmp; + double py2 = -D / (2. * C) - tmp; + double px1 = A * py1 + B; + double px2 = A * py2 + B; + double pT2_1 = px1 * px1 + py1 * py1; + double pT2_2 = px2 * px2 + py2 * py2; + double pz1 = std::sqrt(pT2_1) * neutrinos[index][1]; + double pz2 = std::sqrt(pT2_2) * neutrinos[index][1]; + + TLorentzVector a1(px1, py1, pz1, sqrt(pT2_1 + pz1* pz1)); + TLorentzVector a2(px2, py2, pz2, sqrt(pT2_2 + pz2* pz2)); + + sol.setSolutions(2, a1, a2); } return sol; -} + } -double NeutrinoWeighting::neutrino_weight(const TLorentzVector& neutrino1, const TLorentzVector& neutrino2, double met_ex, double met_ey) const { + double NeutrinoWeighting::neutrino_weight(const TLorentzVector& neutrino1, const TLorentzVector& neutrino2, + double met_ex, double met_ey) const { const double dx = met_ex - neutrino1.Px() - neutrino2.Px(); const double dy = met_ey - neutrino1.Py() - neutrino2.Py(); - return exp(- dx * dx / (2. * sigmax * sigmax) - dy * dy / (2. * sigmay * sigmay)); -} - + return exp(-dx * dx / (2. * sigmax * sigmax) - dy * dy / (2. * sigmay * sigmay)); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PTMaxReco.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PTMaxReco.cxx index 9fc9fd90a0168e621bbdc586a71c4072d6045b3f..466683dfce36c8f3937223f301f7de4aa25523d3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PTMaxReco.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PTMaxReco.cxx @@ -1,20 +1,19 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/PTMaxReco.h" #include "TopEvent/Event.h" namespace top { + PTMaxReco::PTMaxReco() : m_wmass(80400.), m_topmass(172500.) { + } -PTMaxReco::PTMaxReco() : m_wmass(80400.), m_topmass(172500.) { -} - -PTMaxReco::~PTMaxReco() { -} + PTMaxReco::~PTMaxReco() { + } -bool PTMaxReco::apply(const top::Event& event) const { + bool PTMaxReco::apply(const top::Event& event) const { //get the hadronic top //jets that make-up the hadronic top quark @@ -23,93 +22,87 @@ bool PTMaxReco::apply(const top::Event& event) const { const xAOD::Jet* jet3 = nullptr; double maxptsq = 0.; + for (xAOD::JetContainer::const_iterator j1 = event.m_jets.begin(); j1 != event.m_jets.end(); ++j1) { - for (xAOD::JetContainer::const_iterator j2 = j1 + 1; j2 != event.m_jets.end(); ++j2) { - for (xAOD::JetContainer::const_iterator j3 = j2 + 1; j3 != event.m_jets.end(); ++j3) { - const double px = (*j1)->px() + (*j2)->px() + (*j3)->px(); - const double py = (*j1)->py() + (*j2)->py() + (*j3)->py(); - - //pt2 to avoid the slow sqrt - const double ptsq = px * px + py * py; - - if (ptsq > maxptsq) { - jet1 = (*j1); - jet2 = (*j2); - jet3 = (*j3); - } - } + for (xAOD::JetContainer::const_iterator j2 = j1 + 1; j2 != event.m_jets.end(); ++j2) { + for (xAOD::JetContainer::const_iterator j3 = j2 + 1; j3 != event.m_jets.end(); ++j3) { + const double px = (*j1)->px() + (*j2)->px() + (*j3)->px(); + const double py = (*j1)->py() + (*j2)->py() + (*j3)->py(); + + //pt2 to avoid the slow sqrt + const double ptsq = px * px + py * py; + + if (ptsq > maxptsq) { + jet1 = (*j1); + jet2 = (*j2); + jet3 = (*j3); + } } + } } //get the leptonic top //e+jets TLorentzVector lepton; - if (event.m_electrons.size() == 1) - lepton = event.m_electrons.at(0)->p4(); + if (event.m_electrons.size() == 1) lepton = event.m_electrons.at(0)->p4(); //mu+jets - if (event.m_muons.size() == 1) - lepton = event.m_muons.at(0)->p4(); + if (event.m_muons.size() == 1) lepton = event.m_muons.at(0)->p4(); TLorentzVector nu = neutrinoCandidate(lepton, *event.m_met, true); const xAOD::Jet* lepb = nullptr; double topdiff = 1000000.; for (xAOD::JetContainer::const_iterator j1 = event.m_jets.begin(); j1 != event.m_jets.end(); ++j1) { - //ignore the three jets that make-up the hadronic top quark - if (*j1 == jet1 || *j1 == jet2 || *j1 == jet3) - continue; + //ignore the three jets that make-up the hadronic top quark + if (*j1 == jet1 || *j1 == jet2 || *j1 == jet3) continue; - //pick the jet which makes a leptonic top closest to the true top mass - const double tempdiff = fabs((lepton + nu + (*j1)->p4()).M()); + //pick the jet which makes a leptonic top closest to the true top mass + const double tempdiff = fabs((lepton + nu + (*j1)->p4()).M()); - if ((tempdiff - m_topmass) < topdiff) { - lepb = *j1; - topdiff = tempdiff; - } + if ((tempdiff - m_topmass) < topdiff) { + lepb = *j1; + topdiff = tempdiff; + } } std::cout << lepb->pt() << std::endl; return true; -} + } -TLorentzVector PTMaxReco::neutrinoCandidate(const TLorentzVector& lep, const xAOD::MissingET& met, bool dealWithNegative_nu) const { + TLorentzVector PTMaxReco::neutrinoCandidate(const TLorentzVector& lep, const xAOD::MissingET& met, + bool dealWithNegative_nu) const { const double px = met.mpx(); const double py = met.mpy(); // solve quadratic to find neutrino four vector - double alpha = pow(m_wmass,2) + pow((px+lep.Px()),2)+pow((py+lep.Py()),2) -pow(lep.E(),2); - double beta = 0.5 * ( alpha-pow(met.met(),2) + pow(lep.Pz(), 2) ); - double gamma = -( beta*beta - ( pow(lep.E(),2)*pow(met.met(), 2) ) ) / ( pow(lep.E(),2)-pow(lep.Pz(), 2) ); - double lambda = 2. * beta * lep.Pz() / (pow(lep.E(), 2)-pow(lep.Pz(), 2)); - double delta = pow(lambda,2) - 4 * gamma; + double alpha = pow(m_wmass, 2) + pow((px + lep.Px()), 2) + pow((py + lep.Py()), 2) - pow(lep.E(), 2); + double beta = 0.5 * (alpha - pow(met.met(), 2) + pow(lep.Pz(), 2)); + double gamma = -(beta * beta - (pow(lep.E(), 2) * pow(met.met(), 2))) / (pow(lep.E(), 2) - pow(lep.Pz(), 2)); + double lambda = 2. * beta * lep.Pz() / (pow(lep.E(), 2) - pow(lep.Pz(), 2)); + double delta = pow(lambda, 2) - 4 * gamma; if (delta < 0) { // ignore non real solutions - if (dealWithNegative_nu) - delta = 0; - else - return TLorentzVector(); + if (dealWithNegative_nu) delta = 0; + else return TLorentzVector(); } delta = sqrt(delta); - double pz_pos = (lambda+delta) / 2.; - double pz_neg = (lambda-delta) / 2.; + double pz_pos = (lambda + delta) / 2.; + double pz_neg = (lambda - delta) / 2.; double pz = 0.0; - if (fabs(pz_pos) > fabs(pz_neg)) - pz = pz_neg; - else - pz = pz_pos; + if (fabs(pz_pos) > fabs(pz_neg)) pz = pz_neg; + else pz = pz_pos; - double e = sqrt(px*px + py*py + pz*pz); + double e = sqrt(px * px + py * py + pz * pz); TLorentzVector neutrino; neutrino.SetPxPyPzE(px, py, pz, e); return neutrino; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopReco.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopReco.cxx index d3895c0fd436e0e656ae23c789aaa2ad9ba30aeb..7545b624d716e5f6f3b269f434ff40551455a97b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopReco.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopReco.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // definitions taken from the MAMbo code here: https://twiki.cern.ch/twiki/bin/view/Main/MAMbo @@ -13,21 +13,18 @@ #include <algorithm> -namespace top{ - - PseudoTopReco::PseudoTopReco( const std::string& name) : - asg::AsgTool( name ), +namespace top { + PseudoTopReco::PseudoTopReco(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - m_bTagCutValue(9999.9), - m_leptonType("SetMe") - { - declareProperty( "config" , m_config , "Set the configuration" ); - declareProperty( "LeptonType", m_leptonType = "kUndefined" , "Define the lepton type" ); + m_bTagCutValue(9999.9), + m_leptonType("SetMe") { + declareProperty("config", m_config, "Set the configuration"); + declareProperty("LeptonType", m_leptonType = "kUndefined", "Define the lepton type"); } - + /// Function initialising the tool - StatusCode PseudoTopReco::initialize() - { + StatusCode PseudoTopReco::initialize() { // Have you set the config?? if (m_config == nullptr) { ATH_MSG_ERROR("Please set the top::TopConfig"); @@ -35,354 +32,324 @@ namespace top{ } m_config->setPseudoTop(); - + // Figure out the b tagging working point if (m_config->bTagWP_available().size() != 1) { - ATH_MSG_INFO(m_config->bTagWP_available().size()<<" b-tagging WP - cannot pick b-jets. Please select only 1 WP if you want to use the PseudoTop reconstruction"); + ATH_MSG_INFO( + m_config->bTagWP_available().size() << + " b-tagging WP - cannot pick b-jets. Please select only 1 WP if you want to use the PseudoTop reconstruction"); } - - + + ATH_MSG_INFO("++++++++++++++++++++++++++++++"); ATH_MSG_INFO(" Using Lepton \t" << m_leptonType); - ATH_MSG_INFO("++++++++++++++++++++++++++++++"); - + ATH_MSG_INFO("++++++++++++++++++++++++++++++"); + /// Return gracefully: - return StatusCode::SUCCESS; + return StatusCode::SUCCESS; } - + /// Function executing the tool - StatusCode PseudoTopReco::execute(const top::Event& event) - { + StatusCode PseudoTopReco::execute(const top::Event& event) { + if ((!event.m_isLoose && + evtStore()->contains<xAOD::PseudoTopResultContainer>(m_config->sgKeyPseudoTop(event.m_hashValue))) || + (event.m_isLoose && + evtStore()->contains<xAOD::PseudoTopResultContainer>(m_config->sgKeyPseudoTopLoose(event.m_hashValue)))) { + return StatusCode::SUCCESS; + } - // Create the partonHistory xAOD object - xAOD::PseudoTopResultAuxContainer* pseudoTopAuxCont = new xAOD::PseudoTopResultAuxContainer{}; - xAOD::PseudoTopResultContainer* pseudoTop = new xAOD::PseudoTopResultContainer{}; - pseudoTop->setStore( pseudoTopAuxCont ); + // Create the partonHistory xAOD object + xAOD::PseudoTopResultAuxContainer* pseudoTopAuxCont = new xAOD::PseudoTopResultAuxContainer {}; + xAOD::PseudoTopResultContainer* pseudoTop = new xAOD::PseudoTopResultContainer {}; + pseudoTop->setStore(pseudoTopAuxCont); - xAOD::PseudoTopResult* PseudoTopResult = new xAOD::PseudoTopResult{}; - pseudoTop -> push_back( PseudoTopResult ); + xAOD::PseudoTopResult* PseudoTopResult = new xAOD::PseudoTopResult {}; + pseudoTop->push_back(PseudoTopResult); - PseudoTopResult -> IniVar(true); + PseudoTopResult->IniVar(true); // fill either reco particles or truth particles into four vectors // store them in GeV // check if particle/jet is b-tagged // check if electron or muon channel // store output so that it can be written later to the event saver - + m_bJets.clear(); m_lightJets.clear(); - + // get the MET x and y components for the reconstruction - m_nu_px = event.m_met->mpx() / 1.e3; - m_nu_py = event.m_met->mpy() / 1.e3; - m_met_et = sqrt(m_nu_px*m_nu_px + m_nu_py*m_nu_py); + m_nu_px = event.m_met->mpx() / 1.e3; + m_nu_py = event.m_met->mpy() / 1.e3; + m_met_et = sqrt(m_nu_px * m_nu_px + m_nu_py * m_nu_py); SetJetInfo(event); SetChargedLeptonInfo(event); - if(m_bJets.size() == 2 && m_lightJets.size() >= 2){ - + if (m_bJets.size() == 2 && m_lightJets.size() >= 2) { ReconstructLeptonicW(); RunReconstruction(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_lep_pt" ) = m_top_lep.Pt(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_lep_eta" ) = m_top_lep.Eta(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_lep_phi" ) = m_top_lep.Phi(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_lep_m" ) = m_top_lep.M(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_lep_pt") = m_top_lep.Pt(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_lep_eta") = m_top_lep.Eta(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_lep_phi") = m_top_lep.Phi(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_lep_m") = m_top_lep.M(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_had_pt" ) = m_top_had.Pt(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_had_eta" ) = m_top_had.Eta(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_had_phi" ) = m_top_had.Phi(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_top_had_m" ) = m_top_had.M(); - - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_ttbar_pt" ) = m_ttbar.Pt(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_ttbar_eta" ) = m_ttbar.Eta(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_ttbar_phi" ) = m_ttbar.Phi(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Reco_ttbar_m" ) = m_ttbar.M(); - - } - else{ + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_had_pt") = m_top_had.Pt(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_had_eta") = m_top_had.Eta(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_had_phi") = m_top_had.Phi(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_top_had_m") = m_top_had.M(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_ttbar_pt") = m_ttbar.Pt(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_ttbar_eta") = m_ttbar.Eta(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_ttbar_phi") = m_ttbar.Phi(); + PseudoTopResult->auxdecor< float >("PseudoTop_Reco_ttbar_m") = m_ttbar.M(); + } else { // std::cout<< "NOT ENOUGH BJETS!!!" << std::endl; - } - // Save to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyPseudoTop(event.m_hashValue); + // Save to StoreGate / TStore + std::string outputSGKey("SetMe"); + if (!event.m_isLoose) { + outputSGKey = m_config->sgKeyPseudoTop(event.m_hashValue); + } else { + outputSGKey = m_config->sgKeyPseudoTopLoose(event.m_hashValue); + } std::string outputSGKeyAux = outputSGKey + "Aux."; - xAOD::TReturnCode save = evtStore()->tds()->record( pseudoTop , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( pseudoTopAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ + xAOD::TReturnCode save = evtStore()->tds()->record(pseudoTop, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(pseudoTopAuxCont, outputSGKeyAux); + if (!save || !saveAux) { return StatusCode::FAILURE; - } - + } + /// Return gracefully: - return StatusCode::SUCCESS; + return StatusCode::SUCCESS; } - StatusCode PseudoTopReco::execute(const top::ParticleLevelEvent& plEvent) - { + StatusCode PseudoTopReco::execute(const top::ParticleLevelEvent& plEvent) { + if (evtStore()->contains<xAOD::PseudoTopResultContainer>(m_config->sgKeyPseudoTop(0))) { + return StatusCode::SUCCESS; + } - // Create the pseudoTopHistory xAOD object - xAOD::PseudoTopResultAuxContainer* pseudoTopAuxCont = new xAOD::PseudoTopResultAuxContainer{}; - xAOD::PseudoTopResultContainer* pseudoTop = new xAOD::PseudoTopResultContainer{}; - pseudoTop->setStore( pseudoTopAuxCont ); + // Create the pseudoTopHistory xAOD object + xAOD::PseudoTopResultAuxContainer* pseudoTopAuxCont = new xAOD::PseudoTopResultAuxContainer {}; + xAOD::PseudoTopResultContainer* pseudoTop = new xAOD::PseudoTopResultContainer {}; + pseudoTop->setStore(pseudoTopAuxCont); - xAOD::PseudoTopResult* PseudoTopResult = new xAOD::PseudoTopResult{}; - pseudoTop->push_back( PseudoTopResult ); + xAOD::PseudoTopResult* PseudoTopResult = new xAOD::PseudoTopResult {}; + pseudoTop->push_back(PseudoTopResult); - PseudoTopResult -> IniVar(false); + PseudoTopResult->IniVar(false); m_bJets.clear(); m_lightJets.clear(); - // get the MET x and y components for the reconstruction - m_nu_px = plEvent.m_met->mpx() / 1.e3; - m_nu_py = plEvent.m_met->mpy() / 1.e3; - m_met_et = sqrt(m_nu_px*m_nu_px + m_nu_py*m_nu_py); - + // get the MET x and y components for the reconstruction + m_nu_px = plEvent.m_met->mpx() / 1.e3; + m_nu_py = plEvent.m_met->mpy() / 1.e3; + m_met_et = sqrt(m_nu_px * m_nu_px + m_nu_py * m_nu_py); + SetJetInfo(plEvent); SetChargedLeptonInfo(plEvent); - if(m_bJets.size() == 2 && m_lightJets.size() >= 2){ - + if (m_bJets.size() == 2 && m_lightJets.size() >= 2) { ReconstructLeptonicW(); RunReconstruction(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_lep_pt" ) = m_top_lep.Pt(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_lep_eta" ) = m_top_lep.Eta(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_lep_phi" ) = m_top_lep.Phi(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_lep_m" ) = m_top_lep.M(); - - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_had_pt" ) = m_top_had.Pt(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_had_eta" ) = m_top_had.Eta(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_had_phi" ) = m_top_had.Phi(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_top_had_m" ) = m_top_had.M(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_lep_pt") = m_top_lep.Pt(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_lep_eta") = m_top_lep.Eta(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_lep_phi") = m_top_lep.Phi(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_lep_m") = m_top_lep.M(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_ttbar_pt" ) = m_ttbar.Pt(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_ttbar_eta" ) = m_ttbar.Eta(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_ttbar_phi" ) = m_ttbar.Phi(); - PseudoTopResult->auxdecor< float >( "PseudoTop_Particle_ttbar_m" ) = m_ttbar.M(); - - - - } - else{ + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_had_pt") = m_top_had.Pt(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_had_eta") = m_top_had.Eta(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_had_phi") = m_top_had.Phi(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_top_had_m") = m_top_had.M(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_ttbar_pt") = m_ttbar.Pt(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_ttbar_eta") = m_ttbar.Eta(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_ttbar_phi") = m_ttbar.Phi(); + PseudoTopResult->auxdecor< float >("PseudoTop_Particle_ttbar_m") = m_ttbar.M(); + } else { // std::cout << "NOT ENOUGH BJETS!!!" << std::endl; - } - // Save to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyPseudoTop(0); + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyPseudoTop(0); std::string outputSGKeyAux = outputSGKey + "Aux."; - xAOD::TReturnCode save = evtStore()->tds()->record( pseudoTop , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( pseudoTopAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ + xAOD::TReturnCode save = evtStore()->tds()->record(pseudoTop, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(pseudoTopAuxCont, outputSGKeyAux); + if (!save || !saveAux) { return StatusCode::FAILURE; } - /// Return gracefully: + /// Return gracefully: return StatusCode::SUCCESS; } - - - bool PseudoTopReco::SetChargedLeptonInfo(const top::Event& event){ + bool PseudoTopReco::SetChargedLeptonInfo(const top::Event& event) { if (m_leptonType == "kElectron") { - m_lepton.SetPtEtaPhiE(event.m_electrons.at(0)->pt()/1.e3 , event.m_electrons.at(0)->eta(), event.m_electrons.at(0)->phi(), event.m_electrons.at(0) ->e() / 1.e3 ); - } - else if (m_leptonType == "kMuon") { - m_lepton.SetPtEtaPhiE( event.m_muons.at(0)->pt()/1.e3 , event.m_muons.at(0)->eta() , event.m_muons.at(0)->phi(), event.m_muons.at(0)->e() / 1.e3); - } - else { + m_lepton.SetPtEtaPhiE(event.m_electrons.at(0)->pt() / 1.e3, event.m_electrons.at(0)->eta(), event.m_electrons.at( + 0)->phi(), event.m_electrons.at(0)->e() / 1.e3); + } else if (m_leptonType == "kMuon") { + m_lepton.SetPtEtaPhiE(event.m_muons.at(0)->pt() / 1.e3, event.m_muons.at(0)->eta(), event.m_muons.at( + 0)->phi(), event.m_muons.at(0)->e() / 1.e3); + } else { ATH_MSG_ERROR(" Please supply a valid LeptonType : kElectron or kMuon"); return false; } return true; - } - bool PseudoTopReco::SetChargedLeptonInfo(const top::ParticleLevelEvent& plEvent){ - + bool PseudoTopReco::SetChargedLeptonInfo(const top::ParticleLevelEvent& plEvent) { if (m_leptonType == "kElectron") { - m_lepton.SetPtEtaPhiE( plEvent.m_electrons->at(0)->pt()/1.e3 , plEvent.m_electrons->at(0)->eta(), plEvent.m_electrons->at(0)->phi(), plEvent.m_electrons->at(0)->e() / 1.e3 ); - } - else if (m_leptonType == "kMuon") { - m_lepton.SetPtEtaPhiE( plEvent.m_muons->at(0)->pt()/1.e3 , plEvent.m_muons->at(0)->eta(), plEvent.m_muons->at(0)->phi(), plEvent.m_muons->at(0)->e() / 1.e3 ); - } - else { + m_lepton.SetPtEtaPhiE(plEvent.m_electrons->at(0)->pt() / 1.e3, plEvent.m_electrons->at( + 0)->eta(), plEvent.m_electrons->at(0)->phi(), plEvent.m_electrons->at(0)->e() / 1.e3); + } else if (m_leptonType == "kMuon") { + m_lepton.SetPtEtaPhiE(plEvent.m_muons->at(0)->pt() / 1.e3, plEvent.m_muons->at(0)->eta(), plEvent.m_muons->at( + 0)->phi(), plEvent.m_muons->at(0)->e() / 1.e3); + } else { ATH_MSG_ERROR(" Please supply a valid LeptonType : kElectron or kMuon"); return false; } - + return true; - } - - bool PseudoTopReco::SetJetInfo(const top::Event& event){ - + bool PseudoTopReco::SetJetInfo(const top::Event& event) { int bCounter = 0; for (const auto* const jetPtr : event.m_jets) { - TLorentzVector helpVec(0, 0, 0, 0); - helpVec.SetPtEtaPhiE( jetPtr->pt() / 1.e3 , jetPtr->eta() , jetPtr->phi() , jetPtr->e() / 1.e3); - + helpVec.SetPtEtaPhiE(jetPtr->pt() / 1.e3, jetPtr->eta(), jetPtr->phi(), jetPtr->e() / 1.e3); + // if more than two b-jets are available, consider third leading b-tagged jet as light jet! std::string out = m_config->bTagWP_available()[0]; - const bool hasbTagFlag = jetPtr->isAvailable<char>("isbtagged_"+out); + const bool hasbTagFlag = jetPtr->isAvailable<char>("isbtagged_" + out); if (hasbTagFlag) { - if (jetPtr->auxdataConst<char>("isbtagged_"+out) && bCounter < 2) { - m_bJets.push_back(helpVec); - - bCounter++; - } - else{ - m_lightJets.push_back(helpVec); - } + if (jetPtr->auxdataConst<char>("isbtagged_" + out) && bCounter < 2) { + m_bJets.push_back(helpVec); + + bCounter++; + } else { + m_lightJets.push_back(helpVec); + } } } // end loop over jets - + return true; - } - - - bool PseudoTopReco::SetJetInfo(const top::ParticleLevelEvent& plEvent){ - + + bool PseudoTopReco::SetJetInfo(const top::ParticleLevelEvent& plEvent) { // if more than two b-jets are available, consider third leading b-tagged jet as light jet! int bCounter = 0; - for (const auto & jetPtr : * plEvent.m_jets) { - + for (const auto& jetPtr : *plEvent.m_jets) { TLorentzVector helpVec(0, 0, 0, 0); - helpVec.SetPtEtaPhiE( jetPtr->pt() / 1.e3 , jetPtr->eta() , jetPtr->phi() , jetPtr->e() / 1.e3); - - int nGhosts = jetPtr->auxdata<int>( "GhostBHadronsFinalCount" ); - - if(nGhosts >= 1 && bCounter < 2){ - m_bJets.push_back(helpVec); - bCounter++; - } - else - m_lightJets.push_back(helpVec); + helpVec.SetPtEtaPhiE(jetPtr->pt() / 1.e3, jetPtr->eta(), jetPtr->phi(), jetPtr->e() / 1.e3); + + int nGhosts = jetPtr->auxdata<int>("GhostBHadronsFinalCount"); + + if (nGhosts >= 1 && bCounter < 2) { + m_bJets.push_back(helpVec); + bCounter++; + } else m_lightJets.push_back(helpVec); } - + return true; - } - - bool PseudoTopReco::RunReconstruction(){ - + bool PseudoTopReco::RunReconstruction() { double bestwmass = 999.e9; TLorentzVector Whelp(0, 0, 0, 0); // get first the b-jet closest to the lepton in dR // define this as TLorentzVector m_b_lep; - // take now remaining b-jet as m_b_had + // take now remaining b-jet as m_b_had double dRb1 = m_bJets[0].DeltaR(m_lepton); double dRb2 = m_bJets[1].DeltaR(m_lepton); - if(dRb1 < dRb2){ + if (dRb1 < dRb2) { m_b_lep = m_bJets[0]; m_b_had = m_bJets[1]; - } - else{ + } else { m_b_lep = m_bJets[1]; m_b_had = m_bJets[0]; } - // then loop over all light jets - // take combination which is closest to mW (PDG) - for(unsigned int iJet = 0; iJet < m_lightJets.size(); ++iJet){ - for(unsigned int kJet = 0; kJet < m_lightJets.size(); ++kJet){ - - if(iJet == kJet) - continue; - - Whelp = m_lightJets[iJet] + m_lightJets[kJet]; - - if(fabs(mWPDG - Whelp.M()) < fabs(mWPDG - bestwmass)){ - - m_W_had = Whelp; - bestwmass = Whelp.M(); - - } + // then loop over all light jets + // take combination which is closest to mW (PDG) + for (unsigned int iJet = 0; iJet < m_lightJets.size(); ++iJet) { + for (unsigned int kJet = 0; kJet < m_lightJets.size(); ++kJet) { + if (iJet == kJet) continue; + Whelp = m_lightJets[iJet] + m_lightJets[kJet]; + + if (fabs(mWPDG - Whelp.M()) < fabs(mWPDG - bestwmass)) { + m_W_had = Whelp; + bestwmass = Whelp.M(); + } } - } - + } + // define now the top and ttbar four-vectors m_top_lep = m_W_lep + m_b_lep; m_top_had = m_W_had + m_b_had; - m_ttbar = m_top_lep + m_top_had; - + m_ttbar = m_top_lep + m_top_had; + return true; - } - - bool PseudoTopReco::ReconstructLeptonicW() - { - double v_pz = -KinemEdge; + bool PseudoTopReco::ReconstructLeptonicW() { + double v_pz = -KinemEdge; double delta = -KinemEdge; - - // lepton already made by reco or particle levels: - double l_px = m_lepton.Px(); double l_py = m_lepton.Py(); double l_pz = m_lepton.Pz(); - double l_m = m_lepton.M(); double l_E = m_lepton.E(); - double mdiff = 0.5 * ( mWPDG*mWPDG - l_m*l_m ); - double pT_vl = m_nu_px*l_px + m_nu_py*l_py; + // lepton already made by reco or particle levels: + double l_px = m_lepton.Px(); + double l_py = m_lepton.Py(); + double l_pz = m_lepton.Pz(); + double l_m = m_lepton.M(); + double l_E = m_lepton.E(); - double a = l_E*l_E - l_pz*l_pz; - double b = -2. * l_pz * ( mdiff + pT_vl ); - double c = m_met_et*m_met_et*l_E*l_E - mdiff*mdiff - pT_vl*pT_vl - 2.*mdiff*pT_vl; + double mdiff = 0.5 * (mWPDG * mWPDG - l_m * l_m); + double pT_vl = m_nu_px * l_px + m_nu_py * l_py; - delta = b*b - 4.*a*c; + double a = l_E * l_E - l_pz * l_pz; + double b = -2. * l_pz * (mdiff + pT_vl); + double c = m_met_et * m_met_et * l_E * l_E - mdiff * mdiff - pT_vl * pT_vl - 2. * mdiff * pT_vl; - if( delta <= 0. ) { + delta = b * b - 4. * a * c; + + if (delta <= 0.) { // take only the real part - v_pz = -0.5*b/a; + v_pz = -0.5 * b / a; } else { - double v_pz_1 = 0.5 * ( -b - sqrt(delta) ) / a; - double v_pz_2 = 0.5 * ( -b + sqrt(delta) ) / a; - - v_pz = ( fabs(v_pz_1) > fabs(v_pz_2) ) ? v_pz_2 : v_pz_1; - + double v_pz_1 = 0.5 * (-b - sqrt(delta)) / a; + double v_pz_2 = 0.5 * (-b + sqrt(delta)) / a; + + v_pz = (fabs(v_pz_1) > fabs(v_pz_2)) ? v_pz_2 : v_pz_1; } - - double v_E = sqrt( m_met_et*m_met_et + v_pz*v_pz ); - m_neutrino.SetPxPyPzE( m_nu_px, m_nu_py, v_pz, v_E ); - + double v_E = sqrt(m_met_et * m_met_et + v_pz * v_pz); + + m_neutrino.SetPxPyPzE(m_nu_px, m_nu_py, v_pz, v_E); + m_W_lep = m_neutrino + m_lepton; return true; - } - /// Function finalizing the tool - StatusCode PseudoTopReco::finalize() - { + StatusCode PseudoTopReco::finalize() { /// Return gracefully: - return StatusCode::SUCCESS; + return StatusCode::SUCCESS; } - - - - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopRecoRun.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopRecoRun.cxx index f12493ee40f03363026cca298b860d54ec7941a2..9155eda8cabcb85f3f9ca866de2dcac8c1a53f05 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopRecoRun.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/PseudoTopRecoRun.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/PseudoTopRecoRun.h" @@ -13,35 +13,28 @@ #include <cmath> #include <fstream> -namespace top{ - +namespace top { PseudoTopRecoRun::PseudoTopRecoRun(const std::string& kLeptonType, std::shared_ptr<top::TopConfig> config) : m_name("RECO::PseudoTopRecoRun_" + kLeptonType), - m_PseudoTopReco(nullptr) - { - - m_PseudoTopReco = std::unique_ptr<top::PseudoTopReco> ( new top::PseudoTopReco( m_name ) ); - top::check( m_PseudoTopReco->setProperty("config", config ), "Failed to setProperty of PseudoTopReco" ); - top::check( m_PseudoTopReco->setProperty("LeptonType", kLeptonType), "Failed to setProperty of PseudoTopReco" ); + m_PseudoTopReco(nullptr) { + m_PseudoTopReco = std::unique_ptr<top::PseudoTopReco> (new top::PseudoTopReco(m_name)); + top::check(m_PseudoTopReco->setProperty("config", config), "Failed to setProperty of PseudoTopReco"); + top::check(m_PseudoTopReco->setProperty("LeptonType", kLeptonType), "Failed to setProperty of PseudoTopReco"); //top::check( m_PseudoTopReco->setProperty("RecoType", kRecoType), "Failed to setProperty of PseudoTopReco" ); - top::check( m_PseudoTopReco->initialize() , "Failed to initialize PseudoTopRecoTool" ); - + top::check(m_PseudoTopReco->initialize(), "Failed to initialize PseudoTopRecoTool"); } - - bool PseudoTopRecoRun::apply(const top::Event& event) const - { - top::check( m_PseudoTopReco->execute(event) , "Failed to run PseudoTopReco" ); + + bool PseudoTopRecoRun::apply(const top::Event& event) const { + top::check(m_PseudoTopReco->execute(event), "Failed to run PseudoTopReco"); return true; } - bool PseudoTopRecoRun::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const - { - top::check( m_PseudoTopReco->execute(plEvent) , "Failed to run PseudoTopReco" ); + bool PseudoTopRecoRun::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const { + top::check(m_PseudoTopReco->execute(plEvent), "Failed to run PseudoTopReco"); return true; } - + std::string PseudoTopRecoRun::name() const { return m_name; - } - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Sonnenschein.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Sonnenschein.cxx index 2c774ba9c53c18d69d69c1680860b3f48b562cd2..783e9ba33c65d559fff843728cc32a66e54a3ab9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Sonnenschein.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/Sonnenschein.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/Sonnenschein.h" #include "TopEvent/Event.h" @@ -11,63 +11,64 @@ #include <iostream> namespace top { + Sonnenschein::Sonnenschein() { + } -Sonnenschein::Sonnenschein() { -} - -Sonnenschein::~Sonnenschein() { -} + Sonnenschein::~Sonnenschein() { + } -bool Sonnenschein::tWb(const top::Event& event, int start, TLorentzVector& t, TLorentzVector& W, TLorentzVector& b, TLorentzVector& l, TLorentzVector& nu) const { + bool Sonnenschein::tWb(const top::Event& event, int start, TLorentzVector& t, TLorentzVector& W, TLorentzVector& b, + TLorentzVector& l, TLorentzVector& nu) const { bool hasT = false; bool hasB = false; bool hasL = false; bool hasNu = false; for (const xAOD::TruthParticle* particle : *event.m_truth) { - if (particle->pdgId() == start) { - //std::cout << *particle << std::endl; - t = particle->p4(); - hasT = true; - - if (particle->hasDecayVtx()) { - const xAOD::TruthVertex* vtx = particle->decayVtx(); - for (size_t i = 0; i < vtx->nOutgoingParticles(); ++i) { - const xAOD::TruthParticle* tDecayProduct = vtx->outgoingParticle(i); - //std::cout << " " << *tDecayProduct << std::endl; - - if (abs(tDecayProduct->pdgId()) == 24 && tDecayProduct->hasDecayVtx()) { - W = tDecayProduct->p4(); - - const xAOD::TruthVertex* wDecayVtx = tDecayProduct->decayVtx(); - for (size_t j = 0; j < wDecayVtx->nOutgoingParticles(); ++j) { - const xAOD::TruthParticle* wDecayProduct = wDecayVtx->outgoingParticle(j); - //std::cout << " " << *wDecayProduct << std::endl; - - if (abs(wDecayProduct->pdgId()) == 11 || abs(wDecayProduct->pdgId()) == 13 || abs(wDecayProduct->pdgId()) == 15) { - l = wDecayProduct->p4(); - hasL = true; - } - - if (abs(wDecayProduct->pdgId()) == 12 || abs(wDecayProduct->pdgId()) == 14 || abs(wDecayProduct->pdgId()) == 16) { - nu = wDecayProduct->p4(); - hasNu = true; - } - - } - } else if (abs(tDecayProduct->pdgId()) == 5) { - b = tDecayProduct->p4(); - hasB = true; - } + if (particle->pdgId() == start) { + //std::cout << *particle << std::endl; + t = particle->p4(); + hasT = true; + + if (particle->hasDecayVtx()) { + const xAOD::TruthVertex* vtx = particle->decayVtx(); + for (size_t i = 0; i < vtx->nOutgoingParticles(); ++i) { + const xAOD::TruthParticle* tDecayProduct = vtx->outgoingParticle(i); + //std::cout << " " << *tDecayProduct << std::endl; + + if (abs(tDecayProduct->pdgId()) == 24 && tDecayProduct->hasDecayVtx()) { + W = tDecayProduct->p4(); + + const xAOD::TruthVertex* wDecayVtx = tDecayProduct->decayVtx(); + for (size_t j = 0; j < wDecayVtx->nOutgoingParticles(); ++j) { + const xAOD::TruthParticle* wDecayProduct = wDecayVtx->outgoingParticle(j); + //std::cout << " " << *wDecayProduct << std::endl; + + if (abs(wDecayProduct->pdgId()) == 11 || abs(wDecayProduct->pdgId()) == 13 || + abs(wDecayProduct->pdgId()) == 15) { + l = wDecayProduct->p4(); + hasL = true; + } + + if (abs(wDecayProduct->pdgId()) == 12 || abs(wDecayProduct->pdgId()) == 14 || + abs(wDecayProduct->pdgId()) == 16) { + nu = wDecayProduct->p4(); + hasNu = true; } + } + } else if (abs(tDecayProduct->pdgId()) == 5) { + b = tDecayProduct->p4(); + hasB = true; } + } } + } } return hasT && hasB && hasL && hasNu; -} + } -bool Sonnenschein::apply(const top::Event& event) const { + bool Sonnenschein::apply(const top::Event& event) const { TLorentzVector t; TLorentzVector Wp; TLorentzVector b; @@ -83,25 +84,26 @@ bool Sonnenschein::apply(const top::Event& event) const { bool cando2 = tWb(event, -6, tbar, Wm, bbar, lm, nubar); //isn't dilepton at truth level, so return - if (!cando1 || !cando2) - return true; + if (!cando1 || !cando2) return true; const double met_ex = nu.Px() + nubar.Px(); const double met_ey = nu.Py() + nubar.Py(); //solve - std::vector<std::pair<TLorentzVector, TLorentzVector>> allSolutions = m_sonn.solve(lp, b, t.M(), Wp.M(), lm, bbar, tbar.M(), Wm.M(), met_ex, met_ey); + std::vector<std::pair<TLorentzVector, TLorentzVector> > allSolutions = m_sonn.solve(lp, b, t.M(), + Wp.M(), lm, bbar, + tbar.M(), Wm.M(), met_ex, + met_ey); std::cout << "EVENT" << std::endl; unsigned int counter = 0; for (const auto& possible : allSolutions) { - std::cout << "Possible solution number " << counter << "\n"; - std::cout << " first neutrino : " << possible.first << "\n"; - std::cout << " second neutrino: " << possible.second << "\n"; - ++counter; + std::cout << "Possible solution number " << counter << "\n"; + std::cout << " first neutrino : " << possible.first << "\n"; + std::cout << " second neutrino: " << possible.second << "\n"; + ++counter; } return true; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/SonnenscheinEngine.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/SonnenscheinEngine.cxx index aaa2683543a2c5d3b4ecc9e90c7440171e5fcc29..7bc789d0bec0685a1963a65352fd68984554a5e4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/SonnenscheinEngine.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/SonnenscheinEngine.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/SonnenscheinEngine.h" @@ -11,28 +11,34 @@ #include <cmath> namespace top { - -SonnenscheinEngine::SonnenscheinEngine() : m_debug(false) { -} - -SonnenscheinEngine::~SonnenscheinEngine() { -} - -std::vector<std::pair<TLorentzVector, TLorentzVector> > SonnenscheinEngine::solve(const TLorentzVector& me_t_lp, const TLorentzVector& me_t_b, double mass_t, double mass_wp, const TLorentzVector& me_tbar_lm, const TLorentzVector& me_tbar_bbar, double mass_tbar, double mass_wm, double me_mex, double me_mey) const { + SonnenscheinEngine::SonnenscheinEngine() : m_debug(false) { + } + + SonnenscheinEngine::~SonnenscheinEngine() { + } + + std::vector<std::pair<TLorentzVector, TLorentzVector> > SonnenscheinEngine::solve(const TLorentzVector& me_t_lp, + const TLorentzVector& me_t_b, + double mass_t, double mass_wp, + const TLorentzVector& me_tbar_lm, + const TLorentzVector& me_tbar_bbar, + double mass_tbar, double mass_wm, + double me_mex, + double me_mey) const { std::vector<std::pair<TLorentzVector, TLorentzVector> > lvs; if (m_debug) { - std::cout << "Starting SOLVE\n"; - std::cout << "lp " << me_t_lp << "\n"; - std::cout << "lm " << me_tbar_lm << "\n"; - std::cout << "b " << me_t_b << "\n"; - std::cout << "bbar " << me_tbar_bbar << "\n"; - std::cout << "met_ex " << me_mex << "\n"; - std::cout << "met_ey " << me_mey << "\n"; - std::cout << "mt " << mass_t << "\n"; - std::cout << "mtbar " << mass_tbar << "\n"; - std::cout << "mWp " << mass_wp << "\n"; - std::cout << "mWm " << mass_wm << "\n"; + std::cout << "Starting SOLVE\n"; + std::cout << "lp " << me_t_lp << "\n"; + std::cout << "lm " << me_tbar_lm << "\n"; + std::cout << "b " << me_t_b << "\n"; + std::cout << "bbar " << me_tbar_bbar << "\n"; + std::cout << "met_ex " << me_mex << "\n"; + std::cout << "met_ey " << me_mey << "\n"; + std::cout << "mt " << mass_t << "\n"; + std::cout << "mtbar " << mass_tbar << "\n"; + std::cout << "mWp " << mass_wp << "\n"; + std::cout << "mWm " << mass_wm << "\n"; } const double Elp = me_t_lp.E(); @@ -65,85 +71,85 @@ std::vector<std::pair<TLorentzVector, TLorentzVector> > SonnenscheinEngine::solv const TVector3 pbbar = me_tbar_bbar.Vect(); if (m_debug) { - std::cout << "mex and mey " << me_mex << " " << me_mey << "\n"; - std::cout << "Starting Calculation\n"; - std::cout << "Calculating a\n"; + std::cout << "mex and mey " << me_mex << " " << me_mey << "\n"; + std::cout << "Starting Calculation\n"; + std::cout << "Calculating a\n"; } - double a1 = (Eb + Elp)*(mass_wp * mass_wp - mlp * mlp) - - Elp * (mass_t * mass_t - mb * mb - mlp * mlp) - + 2 * Eb * Elp * Elp - 2 * Elp * pb * plp; + double a1 = (Eb + Elp) * (mass_wp * mass_wp - mlp * mlp) + - Elp * (mass_t * mass_t - mb * mb - mlp * mlp) + + 2 * Eb * Elp * Elp - 2 * Elp * pb * plp; double a2 = 2 * (Eb * plpx - Elp * pbx); double a3 = 2 * (Eb * plpy - Elp * pby); double a4 = 2 * (Eb * plpz - Elp * pbz); if (m_debug) { - std::cout << "a1 : " << a1 << "\n"; - std::cout << "a2 : " << a2 << "\n"; - std::cout << "a3 : " << a3 << "\n"; - std::cout << "a4 : " << a4 << "\n"; - - //double pvx = nu->Px() ; - //double pvy = nu->Py() ; - //double pvz = nu->Pz() ; - //std::cout << a1 + a2 * pvx + a3 * pvy + a4 * pvz << "\n"; + std::cout << "a1 : " << a1 << "\n"; + std::cout << "a2 : " << a2 << "\n"; + std::cout << "a3 : " << a3 << "\n"; + std::cout << "a4 : " << a4 << "\n"; + + //double pvx = nu->Px() ; + //double pvy = nu->Py() ; + //double pvz = nu->Pz() ; + //std::cout << a1 + a2 * pvx + a3 * pvy + a4 * pvz << "\n"; } - double b1 = (Ebbar + Elm)*(mass_wm * mass_wm - mlm * mlm) - - Elm * (mass_tbar * mass_tbar - mbbar * mbbar - mlm * mlm) - + 2 * Ebbar * Elm * Elm - 2 * Elm * pbbar * plm; + double b1 = (Ebbar + Elm) * (mass_wm * mass_wm - mlm * mlm) + - Elm * (mass_tbar * mass_tbar - mbbar * mbbar - mlm * mlm) + + 2 * Ebbar * Elm * Elm - 2 * Elm * pbbar * plm; double b2 = 2 * (Ebbar * plmx - Elm * pbbarx); double b3 = 2 * (Ebbar * plmy - Elm * pbbary); double b4 = 2 * (Ebbar * plmz - Elm * pbbarz); if (m_debug) { - std::cout << "Calculating b\n"; - std::cout << "b1 : " << b1 << "\n"; - std::cout << "b2 : " << b2 << "\n"; - std::cout << "b3 : " << b3 << "\n"; - std::cout << "b4 : " << b4 << "\n"; + std::cout << "Calculating b\n"; + std::cout << "b1 : " << b1 << "\n"; + std::cout << "b2 : " << b2 << "\n"; + std::cout << "b3 : " << b3 << "\n"; + std::cout << "b4 : " << b4 << "\n"; - //std::cout << "Checking b" << "\n"; + //std::cout << "Checking b" << "\n"; - //double pvbarx = nu2->Px() ; - //double pvbary = nu2->Py() ; - //double pvbarz = nu2->Pz() ; + //double pvbarx = nu2->Px() ; + //double pvbary = nu2->Py() ; + //double pvbarz = nu2->Pz() ; - //std::cout << b1 + b2 * pvbarx + b3 * pvbary + b4 * pvbarz << "\n"; + //std::cout << b1 + b2 * pvbarx + b3 * pvbary + b4 * pvbarz << "\n"; - std::cout << "Calculating c\n"; + std::cout << "Calculating c\n"; } double c22 = (mass_wp * mass_wp - mlp * mlp) * (mass_wp * mass_wp - mlp * mlp) - -4 * (Elp * Elp - plpz * plpz) * (a1 / a4) * (a1 / a4) - -4 * (mass_wp * mass_wp - mlp * mlp) * plpz * a1 / a4; + - 4 * (Elp * Elp - plpz * plpz) * (a1 / a4) * (a1 / a4) + - 4 * (mass_wp * mass_wp - mlp * mlp) * plpz * a1 / a4; - double c21 = 4 * (mass_wp * mass_wp - mlp * mlp) * (plpx - plpz * a2 / a4) //? - -8 * (Elp * Elp - plpz * plpz) * a1 * a2 / (a4 * a4) - -8 * plpx * plpz * a1 / a4; + double c21 = 4 * (mass_wp * mass_wp - mlp * mlp) * (plpx - plpz * a2 / a4) //? + - 8 * (Elp * Elp - plpz * plpz) * a1 * a2 / (a4 * a4) + - 8 * plpx * plpz * a1 / a4; double c20 = -4 * (Elp * Elp - plpx * plpx) - -4 * (Elp * Elp - plpz * plpz)*(a2 / a4)*(a2 / a4) - -8 * plpx * plpz * a2 / a4; + - 4 * (Elp * Elp - plpz * plpz) * (a2 / a4) * (a2 / a4) + - 8 * plpx * plpz * a2 / a4; - double c11 = 4 * (mass_wp * mass_wp - mlp * mlp) * (plpy - plpz * a3 / a4) - -8 * (Elp * Elp - plpz * plpz) * a1 * a3 / (a4 * a4) - -8 * plpy * plpz * a1 / a4; + double c11 = 4 * (mass_wp * mass_wp - mlp * mlp) * (plpy - plpz * a3 / a4) + - 8 * (Elp * Elp - plpz * plpz) * a1 * a3 / (a4 * a4) + - 8 * plpy * plpz * a1 / a4; double c10 = -8 * (Elp * Elp - plpz * plpz) * a2 * a3 / (a4 * a4) - +8 * plpx * plpy - -8 * plpx * plpz * a3 / a4 - -8 * plpy * plpz * a2 / a4; + + 8 * plpx * plpy + - 8 * plpx * plpz * a3 / a4 + - 8 * plpy * plpz * a2 / a4; double c00 = -4 * (Elp * Elp - plpy * plpy) - -4 * (Elp * Elp - plpz * plpz) * (a3 / a4) * (a3 / a4) - -8 * plpy * plpz * a3 / a4; + - 4 * (Elp * Elp - plpz * plpz) * (a3 / a4) * (a3 / a4) + - 8 * plpy * plpz * a3 / a4; /* - for cross check - the original paper used these definitions. - similar for dp. + for cross check - the original paper used these definitions. + similar for dp. */ c22 = a4 * a4 * c22; c21 = a4 * a4 * c21; @@ -153,49 +159,49 @@ std::vector<std::pair<TLorentzVector, TLorentzVector> > SonnenscheinEngine::solv c00 = a4 * a4 * c00; if (m_debug) { - std::cout << "c22 : " << c22 << "\n"; - std::cout << "c21 : " << c21 << "\n"; - std::cout << "c20 : " << c20 << "\n"; - std::cout << "c11 : " << c11 << "\n"; - std::cout << "c10 : " << c10 << "\n"; - std::cout << "c00 : " << c00 << "\n"; - - //std::cout "c=0? " << - //c22 - //+ c21 * pvx - //+ c11 * pvy - //+ c20 * pvx * pvx - //+ c10 * pvx * pvy - //+ c00 * pvy * pvy - //<<"\n"; - - std::cout << "Calculating d'\n"; + std::cout << "c22 : " << c22 << "\n"; + std::cout << "c21 : " << c21 << "\n"; + std::cout << "c20 : " << c20 << "\n"; + std::cout << "c11 : " << c11 << "\n"; + std::cout << "c10 : " << c10 << "\n"; + std::cout << "c00 : " << c00 << "\n"; + + //std::cout "c=0? " << + //c22 + //+ c21 * pvx + //+ c11 * pvy + //+ c20 * pvx * pvx + //+ c10 * pvx * pvy + //+ c00 * pvy * pvy + //<<"\n"; + + std::cout << "Calculating d'\n"; } - double dp22 = pow( mass_wm * mass_wm - mlm * mlm, 2) - -4 * (Elm * Elm - plmz * plmz) * (b1 / b4) * (b1 / b4) - -4 * (mass_wm * mass_wm - mlm * mlm) * plmz * b1 / b4; + double dp22 = pow(mass_wm * mass_wm - mlm * mlm, 2) + - 4 * (Elm * Elm - plmz * plmz) * (b1 / b4) * (b1 / b4) + - 4 * (mass_wm * mass_wm - mlm * mlm) * plmz * b1 / b4; - double dp21 = 4 * (mass_wm * mass_wm - mlm * mlm) * (plmx - plmz * b2 / b4) - -8 * (Elm * Elm - plmz * plmz) * b1 * b2 / (b4 * b4) - -8 * plmx * plmz * b1 / b4; + double dp21 = 4 * (mass_wm * mass_wm - mlm * mlm) * (plmx - plmz * b2 / b4) + - 8 * (Elm * Elm - plmz * plmz) * b1 * b2 / (b4 * b4) + - 8 * plmx * plmz * b1 / b4; double dp20 = -4 * (Elm * Elm - plmx * plmx) - -4 * (Elm * Elm - plmz * plmz)*(b2 / b4)*(b2 / b4) - -8 * plmx * plmz * b2 / b4; + - 4 * (Elm * Elm - plmz * plmz) * (b2 / b4) * (b2 / b4) + - 8 * plmx * plmz * b2 / b4; - double dp11 = 4 * (mass_wm * mass_wm - mlm * mlm) * (plmy - plmz * b3 / b4) - -8 * (Elm * Elm - plmz * plmz) * b1 * b3 / (b4 * b4) - -8 * plmy * plmz * b1 / b4; + double dp11 = 4 * (mass_wm * mass_wm - mlm * mlm) * (plmy - plmz * b3 / b4) + - 8 * (Elm * Elm - plmz * plmz) * b1 * b3 / (b4 * b4) + - 8 * plmy * plmz * b1 / b4; double dp10 = -8 * (Elm * Elm - plmz * plmz) * b2 * b3 / (b4 * b4) - +8 * plmx * plmy - -8 * plmx * plmz * b3 / b4 - -8 * plmy * plmz * b2 / b4; + + 8 * plmx * plmy + - 8 * plmx * plmz * b3 / b4 + - 8 * plmy * plmz * b2 / b4; double dp00 = -4 * (Elm * Elm - plmy * plmy) - -4 * (Elm * Elm - plmz * plmz) * (b3 / b4) * (b3 / b4) - -8 * plmy * plmz * b3 / b4; + - 4 * (Elm * Elm - plmz * plmz) * (b3 / b4) * (b3 / b4) + - 8 * plmy * plmz * b3 / b4; dp22 = b4 * b4 * dp22; dp21 = b4 * b4 * dp21; @@ -205,195 +211,193 @@ std::vector<std::pair<TLorentzVector, TLorentzVector> > SonnenscheinEngine::solv dp00 = b4 * b4 * dp00; if (m_debug) { - std::cout << "dp22 : " << dp22 << "\n"; - std::cout << "dp21 : " << dp21 << "\n"; - std::cout << "dp20 : " << dp20 << "\n"; - std::cout << "dp11 : " << dp11 << "\n"; - std::cout << "dp10 : " << dp10 << "\n"; - std::cout << "dp00 : " << dp00 << "\n"; - - //in the paper for c and dp c21 appears twice. is this right? - //std::cout << "dp=0? " << - //dp22 - //+ dp21 * pvbarx - //+ dp11 * pvbary - //+ dp20 * pvbarx * pvbarx - //+ dp10 * pvbarx * pvbary - //+ dp00 * pvbary * pvbary - //<<"\n"; - - std::cout << "Calculating d\n"; + std::cout << "dp22 : " << dp22 << "\n"; + std::cout << "dp21 : " << dp21 << "\n"; + std::cout << "dp20 : " << dp20 << "\n"; + std::cout << "dp11 : " << dp11 << "\n"; + std::cout << "dp10 : " << dp10 << "\n"; + std::cout << "dp00 : " << dp00 << "\n"; + + //in the paper for c and dp c21 appears twice. is this right? + //std::cout << "dp=0? " << + //dp22 + //+ dp21 * pvbarx + //+ dp11 * pvbary + //+ dp20 * pvbarx * pvbarx + //+ dp10 * pvbarx * pvbary + //+ dp00 * pvbary * pvbary + //<<"\n"; + + std::cout << "Calculating d\n"; } const double d22 = dp22 - + me_mex * me_mex * dp20 - + me_mey * me_mey * dp00 - + me_mex * me_mey * dp10 - + me_mex * dp21 - + me_mey * dp11; + + me_mex * me_mex * dp20 + + me_mey * me_mey * dp00 + + me_mex * me_mey * dp10 + + me_mex * dp21 + + me_mey * dp11; const double d21 = -1 * dp21 - -2 * me_mex * dp20 - - me_mey * dp10; + - 2 * me_mex * dp20 + - me_mey * dp10; const double d20 = dp20; const double d11 = -1 * dp11 - - 2 * me_mey * dp00 - - me_mex * dp10; + - 2 * me_mey * dp00 + - me_mex * dp10; const double d10 = dp10; const double d00 = dp00; if (m_debug) { - std::cout << "d22 : " << d22 << "\n"; - std::cout << "d21 : " << d21 << "\n"; - std::cout << "d20 : " << d20 << "\n"; - std::cout << "d11 : " << d11 << "\n"; - std::cout << "d10 : " << d10 << "\n"; - std::cout << "d00 : " << d00 << "\n"; - - //std::cout << "d " << - //d22 - //+d21 * pvx - //+d11 * pvy - //+d20 * pvx * pvx - //+d10 * pvx * pvy - //+d00 * pvy * pvy - //<< "\n"; - - std::cout << "Calculating h\n"; + std::cout << "d22 : " << d22 << "\n"; + std::cout << "d21 : " << d21 << "\n"; + std::cout << "d20 : " << d20 << "\n"; + std::cout << "d11 : " << d11 << "\n"; + std::cout << "d10 : " << d10 << "\n"; + std::cout << "d00 : " << d00 << "\n"; + + //std::cout << "d " << + //d22 + //+d21 * pvx + //+d11 * pvy + //+d20 * pvx * pvx + //+d10 * pvx * pvy + //+d00 * pvy * pvy + //<< "\n"; + + std::cout << "Calculating h\n"; } const double h4 = c00 * c00 * d22 * d22 - + c11 * d22 * (c11 * d00 - c00 * d11) - + c00 * c22 * (d11 * d11 - 2 * d00 * d22) - + c22 * d00 * (c22 * d00 - c11 * d11); + + c11 * d22 * (c11 * d00 - c00 * d11) + + c00 * c22 * (d11 * d11 - 2 * d00 * d22) + + c22 * d00 * (c22 * d00 - c11 * d11); const double h3 = c00 * d21 * (2 * c00 * d22 - c11 * d11) - + c00 * d11 * (2 * c22 * d10 + c21 * d11) - + c22 * d00 * (2 * c21 * d00 - c11 * d10) - - c00 * d22 * (c11 * d10 + c10 * d11) - -2 * c00 * d00 *(c22 * d21 + c21 * d22) - - d00 * d11 * (c11 * c21 + c10 * c22) - + c11 * d00 * (c11 * d21 + 2 * c10 * d22); + + c00 * d11 * (2 * c22 * d10 + c21 * d11) + + c22 * d00 * (2 * c21 * d00 - c11 * d10) + - c00 * d22 * (c11 * d10 + c10 * d11) + - 2 * c00 * d00 * (c22 * d21 + c21 * d22) + - d00 * d11 * (c11 * c21 + c10 * c22) + + c11 * d00 * (c11 * d21 + 2 * c10 * d22); const double h2 = c00 * c00 * (2 * d22 * d20 + d21 * d21) - - c00 * d21 * (c11 * d10 + c10 * d11) - + c11 * d20 * (c11 * d00 - c00 * d11) - + c00 * d10 * (c22 * d10 - c10 * d22) - + c00 * d11 * (2 * c21 * d10 + c20 * d11) - + (2 * c22 * c20 + c21 * c21) * d00 * d00 - - 2 * c00 * d00 * (c22 * d20 + c21 * d21 + c20 * d22) - + c10 * d00 * (2 * c11 * d21 + c10 * d22) - - d00 * d10 * (c11 * c21 + c10 * c22) - - d00 * d11 * (c11 * c20 + c10 * c21); + - c00 * d21 * (c11 * d10 + c10 * d11) + + c11 * d20 * (c11 * d00 - c00 * d11) + + c00 * d10 * (c22 * d10 - c10 * d22) + + c00 * d11 * (2 * c21 * d10 + c20 * d11) + + (2 * c22 * c20 + c21 * c21) * d00 * d00 + - 2 * c00 * d00 * (c22 * d20 + c21 * d21 + c20 * d22) + + c10 * d00 * (2 * c11 * d21 + c10 * d22) + - d00 * d10 * (c11 * c21 + c10 * c22) + - d00 * d11 * (c11 * c20 + c10 * c21); /* * leave! */ /* - double h1 = c00 * d21 * (2 * c00 * d20 - c10 * d10) - - c00 * d20 * (c11 * d10 + c10 * d11) - + c00 * d10 * (c21 * d10 + 2 * c20 * d11) - -2 * c00 * d00 * (c21 * d20 + c20 * d21) - + c10 * d00 * (2 * c11 * d20 + c10 * d21) - - c20 * d00 * (2 * c21 * d00 - c10 * d11) - - d00 * d10 * (c11 * c20 + c10 * c21); + double h1 = c00 * d21 * (2 * c00 * d20 - c10 * d10) + - c00 * d20 * (c11 * d10 + c10 * d11) + + c00 * d10 * (c21 * d10 + 2 * c20 * d11) + -2 * c00 * d00 * (c21 * d20 + c20 * d21) + + c10 * d00 * (2 * c11 * d20 + c10 * d21) + - c20 * d00 * (2 * c21 * d00 - c10 * d11) + - d00 * d10 * (c11 * c20 + c10 * c21); */ const double h1 = c00 * d21 * (2 * c00 * d20 - c10 * d10) - - c00 * d20 * (c11 * d10 + c10 * d11) - + c00 * d10 * (c21 * d10 + 2 * c20 * d11) - -2 * c00 * d00 * (c21 * d20 + c20 * d21) - + c10 * d00 * (2 * c11 * d20 + c10 * d21) - + c20 * d00 * (2 * c21 * d00 - c10 * d11) - - d00 * d10 * (c11 * c20 + c10 * c21); + - c00 * d20 * (c11 * d10 + c10 * d11) + + c00 * d10 * (c21 * d10 + 2 * c20 * d11) + - 2 * c00 * d00 * (c21 * d20 + c20 * d21) + + c10 * d00 * (2 * c11 * d20 + c10 * d21) + + c20 * d00 * (2 * c21 * d00 - c10 * d11) + - d00 * d10 * (c11 * c20 + c10 * c21); const double h0 = c00 * c00 * d20 * d20 - + c10 * d20 * (c10 * d00 - c00 * d10) - + c20 * d10 * (c00 * d10 - c10 * d00) - + c20 * d00 * (c20 * d00 - 2 * c00 * d20); + + c10 * d20 * (c10 * d00 - c00 * d10) + + c20 * d10 * (c00 * d10 - c10 * d00) + + c20 * d00 * (c20 * d00 - 2 * c00 * d20); if (m_debug) { - std::cout << "h4 : " << h4 << "\n"; - std::cout << "h3 : " << h3 << "\n"; - std::cout << "h2 : " << h2 << "\n"; - std::cout << "h1 : " << h1 << "\n"; - std::cout << "h0 : " << h0 << "\n"; + std::cout << "h4 : " << h4 << "\n"; + std::cout << "h3 : " << h3 << "\n"; + std::cout << "h2 : " << h2 << "\n"; + std::cout << "h1 : " << h1 << "\n"; + std::cout << "h0 : " << h0 << "\n"; - std::cout << "Messy Calculate Over\n"; + std::cout << "Messy Calculate Over\n"; - //function is h0 pvx ^4 + h1 pvx ^3 + h2 pvx ^2 + h3 pvx + h4 + //function is h0 pvx ^4 + h1 pvx ^3 + h2 pvx ^2 + h3 pvx + h4 - std::cout << "gnuplot command\n"; + std::cout << "gnuplot command\n"; - std::stringstream s; - s << h0/h0 << "*x*x*x*x + " << - h1/h0 << "*x*x*x + " << - h2/h0<< "*x*x + " << - h3/h0 << "*x + " << h4/h0; + std::stringstream s; + s << h0 / h0 << "*x*x*x*x + " << + h1 / h0 << "*x*x*x + " << + h2 / h0 << "*x*x + " << + h3 / h0 << "*x + " << h4 / h0; - std::string fn = s.str(); + std::string fn = s.str(); - std::cout << "plot " << fn << "\n"; + std::cout << "plot " << fn << "\n"; } std::vector<double> pvxs = solveQuartic(h0, h1, h2, h3, h4); if (m_debug) { - std::cout << "--------------------------\n"; - std::cout << "Kinematic Solutions\n"; + std::cout << "--------------------------\n"; + std::cout << "Kinematic Solutions\n"; } int num = 0; for (std::vector<double>::const_iterator it = pvxs.begin(); it != pvxs.end(); ++it, ++num) { - double pvx = *it; + double pvx = *it; - double pvbarx = me_mex - *it; + double pvbarx = me_mex - *it; - double c0 = c00; - double d0 = d00; + double c0 = c00; + double d0 = d00; - double c1 = c10 * pvx + c11; - double c2 = c20 * pvx * pvx + c21 * pvx + c22; + double c1 = c10 * pvx + c11; + double c2 = c20 * pvx * pvx + c21 * pvx + c22; - double d1 = d10 * pvx + d11; - double d2 = d20 * pvx * pvx + d21 * pvx + d22; + double d1 = d10 * pvx + d11; + double d2 = d20 * pvx * pvx + d21 * pvx + d22; - double pvy = (c0 * d2 - c2 * d0) / (c1 * d0 - c0 * d1); - double pvbary = me_mey - pvy; + double pvy = (c0 * d2 - c2 * d0) / (c1 * d0 - c0 * d1); + double pvbary = me_mey - pvy; - double pvz = (a1 + a2 * pvx + a3 * pvy) / (-a4); - double pvbarz = (b1 + b2 * pvbarx + b3 * pvbary) / (-b4); + double pvz = (a1 + a2 * pvx + a3 * pvy) / (-a4); + double pvbarz = (b1 + b2 * pvbarx + b3 * pvbary) / (-b4); - double pvE = sqrt(pvx*pvx + pvy*pvy + pvz*pvz); - double pvbarE = sqrt(pvbarx*pvbarx + pvbary*pvbary + pvbarz*pvbarz); + double pvE = sqrt(pvx * pvx + pvy * pvy + pvz * pvz); + double pvbarE = sqrt(pvbarx * pvbarx + pvbary * pvbary + pvbarz * pvbarz); - TLorentzVector tlv1(pvx,pvy,pvz,pvE); - TLorentzVector tlv2(pvbarx,pvbary,pvbarz,pvbarE); + TLorentzVector tlv1(pvx, pvy, pvz, pvE); + TLorentzVector tlv2(pvbarx, pvbary, pvbarz, pvbarE); - if (m_debug) { - std::cout << "Solution " << num << "\n"; - std::cout << tlv1 << std::endl; - std::cout << tlv2 << std::endl; - std::cout << "----------" << "\n"; - } + if (m_debug) { + std::cout << "Solution " << num << "\n"; + std::cout << tlv1 << std::endl; + std::cout << tlv2 << std::endl; + std::cout << "----------" << "\n"; + } - std::pair<TLorentzVector, TLorentzVector> p(tlv1,tlv2); + std::pair<TLorentzVector, TLorentzVector> p(tlv1, tlv2); - lvs.push_back(p); + lvs.push_back(p); } - if (m_debug) - std::cout << "Finished Kinematic Solution" << "\n"; + if (m_debug) std::cout << "Finished Kinematic Solution" << "\n"; return lvs; -} + } -std::vector<double> SonnenscheinEngine::solveQuartic(double h0, double h1, double h2, double h3, double h4) const { - if (m_debug) - std::cout << "Solve Quartic\n"; + std::vector<double> SonnenscheinEngine::solveQuartic(double h0, double h1, double h2, double h3, double h4) const { + if (m_debug) std::cout << "Solve Quartic\n"; //normalise to coefficient of highest order. const double nh1 = h1 / h0; @@ -407,130 +411,120 @@ std::vector<double> SonnenscheinEngine::solveQuartic(double h0, double h1, doubl const double k3 = nh4 - 3 * pow(nh1, 4) / 256. + nh1 * nh1 * nh2 / 16. - nh1 * nh3 / 4.; if (m_debug) { - std::cout << "e " << k1 << "\n"; - std::cout << "f " << k2 << "\n"; - std::cout << "g " << k3 << "\n"; + std::cout << "e " << k1 << "\n"; + std::cout << "f " << k2 << "\n"; + std::cout << "g " << k3 << "\n"; } - std::vector<double> sols = solveCubic(2. * k1, k1 * k1 -4. * k3, -k2 * k2); + std::vector<double> sols = solveCubic(2. * k1, k1 * k1 - 4. * k3, -k2 * k2); //using the solutions from above... double t1 = -1.; for (std::vector<double>::const_iterator it = sols.begin(); it != sols.end(); ++it) { - if (*it > 0.) - t1 = sqrt(*it); + if (*it > 0.) t1 = sqrt(*it); } //we just need one positive root to get the other roots... double t2 = (k1 + t1 * t1 - k2 / t1) / 2.; - if (m_debug) - std::cout << "first quadratic\n"; + if (m_debug) std::cout << "first quadratic\n"; std::vector<double> s1 = solveQuadratic(1., t1, t2); std::vector<double> pvxs; for (std::vector<double>::const_iterator it = s1.begin(); it != s1.end(); ++it) { + if (m_debug) std::cout << "pvx " << *it - nh1 / 4. << "\n"; - if (m_debug) - std::cout << "pvx " << *it - nh1 / 4. << "\n"; - - pvxs.push_back(*it - nh1 / 4.); + pvxs.push_back(*it - nh1 / 4.); } //now use the other quadratic - if (m_debug) - std::cout << "second quadratic\n"; + if (m_debug) std::cout << "second quadratic\n"; std::vector<double> s2 = solveQuadratic(1., -t1, k3 / t2); for (std::vector<double>::const_iterator it = s2.begin(); it != s2.end(); ++it) { - if (m_debug) - std::cout << "pvx " << *it - nh1 / 4. << "\n"; + if (m_debug) std::cout << "pvx " << *it - nh1 / 4. << "\n"; - pvxs.push_back(*it - nh1 / 4.); + pvxs.push_back(*it - nh1 / 4.); } return pvxs; -} + } -std::vector<double> SonnenscheinEngine::solveCubic(double s1, double s2, double s3) const { + std::vector<double> SonnenscheinEngine::solveCubic(double s1, double s2, double s3) const { std::vector<double> sols; const double q = (s1 * s1 - 3 * s2) / 9.; const double r = (2 * s1 * s1 * s1 - 9 * s1 * s2 + 27 * s3) / 54.; if (m_debug) { - std::cout << "Solve Cubic\n"; - std::cout << "q " << q << "\n"; - std::cout << "r " << r << "\n"; + std::cout << "Solve Cubic\n"; + std::cout << "q " << q << "\n"; + std::cout << "r " << r << "\n"; } - if (r*r < q*q*q) { - const double theta = acos(r / sqrt(q*q*q) ); - const double z1_1 = -2 * sqrt(q) * cos(theta / 3.) - s1 / 3.; - const double z1_2 = -2 * sqrt(q) * cos((theta + 2 * M_PI) / 3.) - s1 / 3.; - const double z1_3 = -2 * sqrt(q) * cos((theta - 2 * M_PI) / 3.) - s1 / 3.; - - if (m_debug) { - std::cout << "r^2 < q^3 -> 3 solutions\n"; - std::cout << "z1_1 " << z1_1 << "\n"; - std::cout << "z1_2 " << z1_2 << "\n"; - std::cout << "z1_3 " << z1_3 << "\n"; - } - - sols.push_back(z1_1); - sols.push_back(z1_2); - sols.push_back(z1_3); + if (r * r < q * q * q) { + const double theta = acos(r / sqrt(q * q * q)); + const double z1_1 = -2 * sqrt(q) * cos(theta / 3.) - s1 / 3.; + const double z1_2 = -2 * sqrt(q) * cos((theta + 2 * M_PI) / 3.) - s1 / 3.; + const double z1_3 = -2 * sqrt(q) * cos((theta - 2 * M_PI) / 3.) - s1 / 3.; + + if (m_debug) { + std::cout << "r^2 < q^3 -> 3 solutions\n"; + std::cout << "z1_1 " << z1_1 << "\n"; + std::cout << "z1_2 " << z1_2 << "\n"; + std::cout << "z1_3 " << z1_3 << "\n"; + } + + sols.push_back(z1_1); + sols.push_back(z1_2); + sols.push_back(z1_3); } else { - if (m_debug) - std::cout << "r^2 >= q^3 -> 1 solution" << "\n"; + if (m_debug) std::cout << "r^2 >= q^3 -> 1 solution" << "\n"; - const double radicant = -r + sqrt( r * r - q * q * q); - const double powthrd = pow( fabs(radicant), 1./3.); - const double a = sign(radicant) * powthrd; //sign?? - //double b = (a!=0.) ? q/a : 0.; - const double b = q / a; + const double radicant = -r + sqrt(r * r - q * q * q); + const double powthrd = pow(fabs(radicant), 1. / 3.); + const double a = sign(radicant) * powthrd; //sign?? + //double b = (a!=0.) ? q/a : 0.; + const double b = q / a; - const double z1_1 = a + b - s1 /3.; - //std::cout << "z1_1 " << z1_1 << "\n"; + const double z1_1 = a + b - s1 / 3.; + //std::cout << "z1_1 " << z1_1 << "\n"; - sols.push_back(z1_1); + sols.push_back(z1_1); } return sols; -} + } -std::vector<double> SonnenscheinEngine::solveQuadratic(double a, double b, double c) const { + std::vector<double> SonnenscheinEngine::solveQuadratic(double a, double b, double c) const { std::vector<double> sols; - if (m_debug) - std::cout << "Solve Quadratic\n"; + if (m_debug) std::cout << "Solve Quadratic\n"; const double b2m4ac = b * b - 4. * a * c; if (b2m4ac > 0.) { - const double sol1 = (-b + sqrt(b2m4ac)) / 2. * a; - const double sol2 = (-b - sqrt(b2m4ac)) / 2. * a; + const double sol1 = (-b + sqrt(b2m4ac)) / 2. * a; + const double sol2 = (-b - sqrt(b2m4ac)) / 2. * a; - if (m_debug) { - std::cout << "Quadratic sol1 : " << sol1 << "\n"; - std::cout << "Quadratic sol2 : " << sol2 << "\n"; - } + if (m_debug) { + std::cout << "Quadratic sol1 : " << sol1 << "\n"; + std::cout << "Quadratic sol2 : " << sol2 << "\n"; + } - sols.push_back(sol1); - sols.push_back(sol2); - } else if (m_debug) - std::cout << "Quadratic has no solutions\n"; + sols.push_back(sol1); + sols.push_back(sol2); + } else if (m_debug) std::cout << "Quadratic has no solutions\n"; return sols; -} + } -double SonnenscheinEngine::sign(double a) const { + double SonnenscheinEngine::sign(double a) const { return (a < 0) ? -1 : (a > 0) ? 1 : 0; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TopEventReconstructionToolsLoader.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TopEventReconstructionToolsLoader.cxx index 62a25e3470fff31cebf598b018a4627e05542df4..808d0a1c4b12aa67d3d5c40808d125b44925c8b4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TopEventReconstructionToolsLoader.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TopEventReconstructionToolsLoader.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventReconstructionTools/TopEventReconstructionToolsLoader.h" #include "TopEventReconstructionTools/Sonnenschein.h" @@ -11,8 +11,10 @@ #include "TopAnalysis/Tools.h" //for the loadLibraries function namespace top { - -top::EventSelectorBase* TopEventReconstructionToolsLoader::initTool(const std::string& /*name*/, const std::string& line, TFile* /*outputFile*/,std::shared_ptr<top::TopConfig> config, EL::Worker* /*wk*/) { + top::EventSelectorBase* TopEventReconstructionToolsLoader::initTool(const std::string& name, const std::string& line, + TFile* /*outputFile*/, + std::shared_ptr<top::TopConfig> config, + EL::Worker* /*wk*/) { //get the first bit of the string and store it in toolname std::istringstream iss(line); std::string toolname; @@ -20,23 +22,18 @@ top::EventSelectorBase* TopEventReconstructionToolsLoader::initTool(const std::s //any parameters? std::string param; - if (line.size() > toolname.size()) - param = line.substr(toolname.size() + 1); + if (line.size() > toolname.size()) param = line.substr(toolname.size() + 1); - if (toolname == "RECO::SONNENSCHEIN") - return new top::Sonnenschein(); + if (toolname == "RECO::SONNENSCHEIN") return new top::Sonnenschein(); else if (toolname == "RECO::KLFITTERRUN") { loadLibraries("libKLFitter"); - return new top::KLFitterRun(param,config); - } - - else if (toolname == "RECO::PSEUDOTOP"){ + return new top::KLFitterRun(name, param, config); + } else if (toolname == "RECO::PSEUDOTOP") { return new top::PseudoTopRecoRun(param, config); } return nullptr; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresChi2.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresChi2.cxx index e991d93320abb44c07a62e3bcc03b99d4627cf91..41af802ea11dde2f2af81e22603aedb650418e66 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresChi2.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresChi2.cxx @@ -1,164 +1,164 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ /* ********************************************************************** - * Class : TTBarLeptonJetsBuilder_chi2 - * Author : LPC-ClermontFerrand team - ************************************************************************/ +* Class : TTBarLeptonJetsBuilder_chi2 +* Author : LPC-ClermontFerrand team +************************************************************************/ #include "TopEventReconstructionTools/TtresChi2.h" #include "TopEventReconstructionTools/TtresNeutrinoBuilder.h" //_________________________________________________________________________________________________ -TtresChi2::TtresChi2(std::string units){ +TtresChi2::TtresChi2(std::string units) { m_debug = 0; m_WReco = ROTATION; - if (units=="MeV")m_Units = 1000.; - else if(units=="GeV")m_Units = 1.; + if (units == "MeV") m_Units = 1000.; + else if (units == "GeV") m_Units = 1.; else std::cerr << "WARNING in TtresChi2: units different from GeV or MeV" << std::endl; m_UsePtDiff = PTDIFF; m_Btag = AFFECTBTAG; m_RunMode = RUNDEFAULT; m_NeutrinoBuilder = new TtresNeutrinoBuilder(units); Init(DATA2012SUMMER2013PT100); - res_chi2All = -1.; - res_chi2WH = -1.; + res_chi2All = -1.; + res_chi2WH = -1.; res_chi2TopH = -1.; res_chi2TopL = -1.; - res_Mtl = -1.; - res_Mwh = -1.; - res_Mth = -1.; - res_Mtt = -1.; - m_WhChi2Value = -1; - m_ThWhChi2Value = -1; - m_TlChi2Value = -1; + res_Mtl = -1.; + res_Mwh = -1.; + res_Mth = -1.; + res_Mtt = -1.; + m_WhChi2Value = -1; + m_ThWhChi2Value = -1; + m_TlChi2Value = -1; m_PtDiffChi2Value = -1; - m_category = -1; + m_category = -1; } //_________________________________________________________________________________________________ -TtresChi2::~TtresChi2(){ - if(m_debug>0) std::cout << "in destructor " << std::endl; +TtresChi2::~TtresChi2() { + if (m_debug > 0) std::cout << "in destructor " << std::endl; if (m_NeutrinoBuilder) delete m_NeutrinoBuilder; } //_________________________________________________________________________________________________ void TtresChi2::Init(Chi2Version version, double highJetMass) { - m_highJetMass = highJetMass; - switch (version){ - - case DATA2012SUMMER2013PT100: - //Rel17.2: values obtained for Z' 0.5TeV-2 TeV including njets>=5 events - // LC jets + Jet Area correction - // Applying a cut at 100 GeV on the pT of the leading jet - MjjP=82.74*m_Units; - SMjjP=9.524*m_Units; - - m_TopMinusW_had_mean=89.99*m_Units; - m_TopMinusW_had_sigma=13.91*m_Units; - - m_Top_lep_mean=166.6*m_Units; - m_Top_lep_sigma=17.34*m_Units; - - m_PtDiff_mean=-1.903*m_Units; - m_PtDiff_sigma=47.24*m_Units; - - m_PtDiffRel_mean=0.002678; - m_PtDiffRel_sigma=0.07662; - - m_PtDiffRelMass_mean=0.001315; - m_PtDiffRelMass_sigma=0.05092; - - MTHJJ=171.8*m_Units; - STHJJ=16.04*m_Units; - break; - - case DATA2012SUMMER2013: - //Rel17.2: values obtained for Z' 0.5TeV-2 TeV including njets>=5 events - // LC jets + Jet Area correction - MjjP=82.41*m_Units; - SMjjP=9.553*m_Units; - - m_TopMinusW_had_mean=89.01*m_Units; - m_TopMinusW_had_sigma=15.67*m_Units; - - m_Top_lep_mean=166*m_Units; - m_Top_lep_sigma=17.48*m_Units; - - m_PtDiff_mean=0.4305*m_Units; - m_PtDiff_sigma=46.07*m_Units; - - m_PtDiffRel_mean=0.00144; - m_PtDiffRel_sigma=0.07837; - - m_PtDiffRelMass_mean=0.0004532; - m_PtDiffRelMass_sigma=0.05112; - - MTHJJ=171.8*m_Units; - STHJJ=16.04*m_Units; - break; - case DATA2012AUTOMN2012: - //Rel17.2: values obtained for Z' 0.5TeV-2 TeV including njets>=5 events - // LC jets - MjjP=83.93*m_Units; - SMjjP=10.76*m_Units; - - m_TopMinusW_had_mean=91.05*m_Units; - m_TopMinusW_had_sigma=14.23*m_Units; - - m_Top_lep_mean=168.2*m_Units; - m_Top_lep_sigma=20.57*m_Units; - - m_PtDiff_mean=-8.709*m_Units; - m_PtDiff_sigma=55.*m_Units; - - MTHJJ=173.5*m_Units; - STHJJ=16.25*m_Units; - break; - - case DATA2011SUMMER2012: - //Rel17.0: values obtained for Z' 1TeV-2 TeV including njets>=5 events - // EM+JES jets - MjjP=83.18*m_Units; - SMjjP=10.67*m_Units; - - m_TopMinusW_had_mean=90.87*m_Units; - m_TopMinusW_had_sigma=12.78*m_Units; - - m_Top_lep_mean=167.6*m_Units; - m_Top_lep_sigma=20.53*m_Units; - - m_PtDiff_mean=-7.381*m_Units; - m_PtDiff_sigma=63.96*m_Units; - - MTHJJ=172.2*m_Units; - STHJJ=16.8*m_Units; - break; - default: - std::cerr << "TtresChi2::Init chi2 is not defined!!" << std::endl; - break; + switch (version) { + case DATA2012SUMMER2013PT100: + //Rel17.2: values obtained for Z' 0.5TeV-2 TeV including njets>=5 events + // LC jets + Jet Area correction + // Applying a cut at 100 GeV on the pT of the leading jet + MjjP = 82.74 * m_Units; + SMjjP = 9.524 * m_Units; + + m_TopMinusW_had_mean = 89.99 * m_Units; + m_TopMinusW_had_sigma = 13.91 * m_Units; + + m_Top_lep_mean = 166.6 * m_Units; + m_Top_lep_sigma = 17.34 * m_Units; + + m_PtDiff_mean = -1.903 * m_Units; + m_PtDiff_sigma = 47.24 * m_Units; + + m_PtDiffRel_mean = 0.002678; + m_PtDiffRel_sigma = 0.07662; + + m_PtDiffRelMass_mean = 0.001315; + m_PtDiffRelMass_sigma = 0.05092; + + MTHJJ = 171.8 * m_Units; + STHJJ = 16.04 * m_Units; + break; + + case DATA2012SUMMER2013: + //Rel17.2: values obtained for Z' 0.5TeV-2 TeV including njets>=5 events + // LC jets + Jet Area correction + MjjP = 82.41 * m_Units; + SMjjP = 9.553 * m_Units; + + m_TopMinusW_had_mean = 89.01 * m_Units; + m_TopMinusW_had_sigma = 15.67 * m_Units; + + m_Top_lep_mean = 166 * m_Units; + m_Top_lep_sigma = 17.48 * m_Units; + + m_PtDiff_mean = 0.4305 * m_Units; + m_PtDiff_sigma = 46.07 * m_Units; + + m_PtDiffRel_mean = 0.00144; + m_PtDiffRel_sigma = 0.07837; + + m_PtDiffRelMass_mean = 0.0004532; + m_PtDiffRelMass_sigma = 0.05112; + + MTHJJ = 171.8 * m_Units; + STHJJ = 16.04 * m_Units; + break; + + case DATA2012AUTOMN2012: + //Rel17.2: values obtained for Z' 0.5TeV-2 TeV including njets>=5 events + // LC jets + MjjP = 83.93 * m_Units; + SMjjP = 10.76 * m_Units; + + m_TopMinusW_had_mean = 91.05 * m_Units; + m_TopMinusW_had_sigma = 14.23 * m_Units; + + m_Top_lep_mean = 168.2 * m_Units; + m_Top_lep_sigma = 20.57 * m_Units; + + m_PtDiff_mean = -8.709 * m_Units; + m_PtDiff_sigma = 55. * m_Units; + + MTHJJ = 173.5 * m_Units; + STHJJ = 16.25 * m_Units; + break; + + case DATA2011SUMMER2012: + //Rel17.0: values obtained for Z' 1TeV-2 TeV including njets>=5 events + // EM+JES jets + MjjP = 83.18 * m_Units; + SMjjP = 10.67 * m_Units; + + m_TopMinusW_had_mean = 90.87 * m_Units; + m_TopMinusW_had_sigma = 12.78 * m_Units; + + m_Top_lep_mean = 167.6 * m_Units; + m_Top_lep_sigma = 20.53 * m_Units; + + m_PtDiff_mean = -7.381 * m_Units; + m_PtDiff_sigma = 63.96 * m_Units; + + MTHJJ = 172.2 * m_Units; + STHJJ = 16.8 * m_Units; + break; + + default: + std::cerr << "TtresChi2::Init chi2 is not defined!!" << std::endl; + break; } return; } //_________________________________________________________________________________________________ -void TtresChi2::Reset(){ - res_chi2All = -1.; - res_chi2WH = -1.; +void TtresChi2::Reset() { + res_chi2All = -1.; + res_chi2WH = -1.; res_chi2TopH = -1.; res_chi2TopL = -1.; - res_Mwh = -1.; - res_Mth = -1.; - res_Mtl = -1.; - res_Mtt = -1.; - m_WhChi2Value = -1; - m_ThWhChi2Value = -1; - m_TlChi2Value = -1; + res_Mwh = -1.; + res_Mth = -1.; + res_Mtl = -1.; + res_Mtt = -1.; + m_WhChi2Value = -1; + m_ThWhChi2Value = -1; + m_TlChi2Value = -1; m_PtDiffChi2Value = -1; - m_category = -1; + m_category = -1; m_nChi2Values = 0; m_chi2Values.clear(); m_chi2Wh_Values.clear(); @@ -175,7 +175,7 @@ void TtresChi2::Reset(){ m_Wh_Values.clear(); m_ThWh_Values.clear(); m_Th_Values.clear(); - m_Tl_Values.clear(); + m_Tl_Values.clear(); m_chi2Values.reserve(10000); m_chi2Wh_Values.reserve(10000); m_chi2Th_Values.reserve(10000); @@ -191,541 +191,564 @@ void TtresChi2::Reset(){ m_Wh_Values.reserve(10000); m_ThWh_Values.reserve(10000); m_Th_Values.reserve(10000); - m_Tl_Values.reserve(10000); + m_Tl_Values.reserve(10000); return; } //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresChi2::GetNeutrinos(TLorentzVector* L, TLorentzVector*MET){ +std::vector<TLorentzVector*> TtresChi2::GetNeutrinos(TLorentzVector* L, TLorentzVector* MET) { std::vector<TLorentzVector*> neutrinoVector; - if (m_WReco==ROTATION) neutrinoVector = m_NeutrinoBuilder->candidatesFromWMass_Rotation(L, MET, false /*m_useSmallestPz*/); - else if (m_WReco==REALPART)neutrinoVector = m_NeutrinoBuilder->candidatesFromWMass_RealPart(L, MET, false /*m_useSmallestPz*/); - else if (m_WReco==DECREASING) neutrinoVector = m_NeutrinoBuilder->candidatesFromWMass_Scaling(L, MET); + if (m_WReco == + ROTATION) neutrinoVector = m_NeutrinoBuilder->candidatesFromWMass_Rotation(L, MET, false /*m_useSmallestPz*/); + else if (m_WReco == + REALPART) neutrinoVector = + m_NeutrinoBuilder->candidatesFromWMass_RealPart(L, MET, false /*m_useSmallestPz*/); + else if (m_WReco == DECREASING) neutrinoVector = m_NeutrinoBuilder->candidatesFromWMass_Scaling(L, MET); return neutrinoVector; } //_________________________________________________________________________________________________ -bool TtresChi2::findMinChiSquare_HMelseLM(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L){ - if(m_debug>0) std::cout << "entering TtresChi2::findMinChiSquare_HMelseLM()" << std::endl; +bool TtresChi2::findMinChiSquare_HMelseLM(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, + const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, + int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, + double& chi2ming1H, double& chi2ming1L) { + if (m_debug > 0) std::cout << "entering TtresChi2::findMinChiSquare_HMelseLM()" << std::endl; bool status = false; - status = this->findMinChiSquare_HighMass(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); - - if (status && TMath::Log10(chi2ming1)<0.9) return status; // have found a good combination for HM - + status = this->findMinChiSquare_HighMass(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_lep, ign1, chi2ming1, + chi2ming1H, chi2ming1L); + + if (status && TMath::Log10(chi2ming1) < 0.9) return status; // have found a good combination for HM + // Otherwise try the LM chi2 - status = this->findMinChiSquare (L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_had, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); + status = this->findMinChiSquare(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_had, i_b_lep, ign1, chi2ming1, + chi2ming1H, chi2ming1L); return status; } - //_________________________________________________________________________________________________ -bool TtresChi2::findMinChiSquare_LMelseHM(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L){ - if(m_debug>0) std::cout << "entering TtresChi2::findMinChiSquare_LMelseHM()" << std::endl; +bool TtresChi2::findMinChiSquare_LMelseHM(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, + const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, + int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, + double& chi2ming1H, double& chi2ming1L) { + if (m_debug > 0) std::cout << "entering TtresChi2::findMinChiSquare_LMelseHM()" << std::endl; bool status = false; - status = this->findMinChiSquare (L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_had, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); - - if (status && TMath::Log10(chi2ming1)<0.9) return status; // have found a good combination for LM - + status = this->findMinChiSquare(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_had, i_b_lep, ign1, chi2ming1, + chi2ming1H, chi2ming1L); + + if (status && TMath::Log10(chi2ming1) < 0.9) return status; // have found a good combination for LM + // Otherwise try the HM chi2 - status = this->findMinChiSquare_HighMass(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); + status = this->findMinChiSquare_HighMass(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_lep, ign1, chi2ming1, + chi2ming1H, chi2ming1L); return status; } - //_________________________________________________________________________________________________ -bool TtresChi2::findMinChiSquare_AllRanges(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L){ - if(m_debug>0) std::cout << "entering TtresChi2::findMinChiSquare_AllRanges()" << std::endl; +bool TtresChi2::findMinChiSquare_AllRanges(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, + const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, + int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, + double& chi2ming1H, double& chi2ming1L) { + if (m_debug > 0) std::cout << "entering TtresChi2::findMinChiSquare_AllRanges()" << std::endl; bool status = false; float massMax = 0.; - for (unsigned int i=0; i<jetVector->size(); ++i) if(jetVector->at(i)->M()>massMax)massMax= jetVector->at(i)->M(); + for (unsigned int i = 0; i < jetVector->size(); + ++i) if (jetVector->at(i)->M() > massMax) massMax = jetVector->at(i)->M(); - if(massMax>=m_highJetMass*m_Units)status = this->findMinChiSquare_HighMass(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); - else status = this->findMinChiSquare (L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_had, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); + if (massMax >= m_highJetMass * m_Units) status = this->findMinChiSquare_HighMass(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); + else status = this->findMinChiSquare(L, jetVector, isJetBtagged, MET, i_q1_W, i_q2_W, i_b_had, i_b_lep, ign1, chi2ming1, chi2ming1H, chi2ming1L); return status; } //_________________________________________________________________________________________________ -bool TtresChi2::findMinChiSquare(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L){ - if(m_debug>0) std::cout << "entering TtresChi2::findMinChiSquare()" << std::endl; +bool TtresChi2::findMinChiSquare(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_had, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L) { + if (m_debug > 0) std::cout << "entering TtresChi2::findMinChiSquare()" << std::endl; //_________________________________________________________________________________________________ - i_q1_W=-1; - i_q2_W=-1; - i_b_had=-1; - i_b_lep=-1; - ign1=-1; - chi2ming1 =1e7; - chi2ming1H=1e7; - chi2ming1L=1e7; - double chi2ming1WH=1e7; + i_q1_W = -1; + i_q2_W = -1; + i_b_had = -1; + i_b_lep = -1; + ign1 = -1; + chi2ming1 = 1e7; + chi2ming1H = 1e7; + chi2ming1L = 1e7; + double chi2ming1WH = 1e7; int n_jets = jetVector->size(); int n_bjets = 0; - + this->Reset(); if (L == NULL) { - std::cerr << "ERROR : TtresChi2::findMinChiSquare: Lepton is NULL" << std::endl; - return false; + std::cerr << "ERROR : TtresChi2::findMinChiSquare: Lepton is NULL" << std::endl; + return false; } - - if(m_Btag==AFFECTBTAG){ - for(unsigned int ib = 0; ib<(unsigned int)isJetBtagged->size(); ++ib){ - if(isJetBtagged->at(ib)) n_bjets++; - } + + if (m_Btag == AFFECTBTAG) { + for (unsigned int ib = 0; ib < (unsigned int) isJetBtagged->size(); ++ib) { + if (isJetBtagged->at(ib)) n_bjets++; + } } - + //_________________________________________________________________________________________________ std::vector<TLorentzVector*> neutrinoVector = GetNeutrinos(L, MET); //_________________________________________________________________________________________________ - for (unsigned int i=0; i<(unsigned int)n_jets; i++){ + for (unsigned int i = 0; i < (unsigned int) n_jets; i++) { const TLorentzVector* I = jetVector->at(i); - for (unsigned int j=i+1; j<(unsigned int)n_jets; j++){ + for (unsigned int j = i + 1; j < (unsigned int) n_jets; j++) { const TLorentzVector* J = jetVector->at(j); - for (unsigned int k=0; k< (unsigned int)n_jets; k++){ - if ( k!=i && k!=j) { - const TLorentzVector* K = jetVector->at(k); - TLorentzVector TopH = (*I) + (*J) + (*K); - TLorentzVector Whad = (*I) + (*J); - for (unsigned int n=0; n< neutrinoVector.size(); n++){ - - TLorentzVector* N = neutrinoVector[n]; - - TLorentzVector Wlv = (*N) + (*L); - for (unsigned int m=0; m< (unsigned int)n_jets; m++){ - if (m!=i && m!=j && m!=k) { - const TLorentzVector* M = jetVector->at(m); - TLorentzVector Tlv = Wlv + (*M); - TLorentzVector Tt = Tlv + TopH; - double chi2WH = pow((Whad.M()-MjjP)/SMjjP,2); - double chi2H = chi2WH + pow((TopH.M()-Whad.M()-m_TopMinusW_had_mean)/m_TopMinusW_had_sigma,2); - double chi2L = pow((Tlv.M()-m_Top_lep_mean)/m_Top_lep_sigma,2); - - double chi2tempg1 = chi2H+chi2L; - if (m_UsePtDiff==PTDIFF){ - double chi2Diff = pow((TopH.Pt()-Tlv.Pt()-m_PtDiff_mean)/m_PtDiff_sigma,2); - chi2tempg1+=chi2Diff; - }else if (m_UsePtDiff==PTDIFFREL){ - double chi2DiffRel = pow(((TopH.Pt()-Tlv.Pt())/(TopH.Pt()+Tlv.Pt())-m_PtDiffRel_mean)/m_PtDiffRel_sigma,2); - chi2tempg1+=chi2DiffRel; - }else if (m_UsePtDiff==PTDIFFMASS){ - double chi2DiffRelMass = pow(((TopH.Pt()-Tlv.Pt())/(Tt.M())-m_PtDiffRelMass_mean)/m_PtDiffRelMass_sigma,2); - chi2tempg1+=chi2DiffRelMass; - } - - // does this combination contain a b - // k -> hadronic b - // m -> leptonic b - int n_bJetsComb = 0; - if (isJetBtagged->at(k)){ - n_bJetsComb++; - } - // second b - if (isJetBtagged->at(m)){ - n_bJetsComb++; - } - - bool passBtag = false; - if(m_Btag==STDBTAG || m_Btag==NO_BTAGHM){ - if(n_bJetsComb>0){ - passBtag = true; - } - }else if(m_Btag==AFFECTBTAG){ - if(n_bjets==0){ - passBtag = true; - }else if(n_bjets==1){ - if(n_bJetsComb==1){ passBtag = true; } - }else if(n_bjets>=2){ - if(n_bJetsComb==2){ passBtag = true; } - } - }else if(m_Btag==NO_BTAG){ - passBtag = true; - } - - if(passBtag && m_RunMode==RUNSTUDY){ - m_chi2Values.push_back(chi2tempg1); - m_chi2Wh_Values.push_back(chi2WH); - m_chi2ThWh_Values.push_back(chi2H - chi2WH); - m_chi2Tl_Values.push_back(chi2L); - m_chi2PtDiff_Values.push_back(chi2tempg1 - chi2H - chi2L); - m_i_Wq1.push_back(i); - m_i_Wq2.push_back(j); - m_i_Thb.push_back(k); - m_i_Tlb.push_back(m); - m_i_n.push_back(n); - if(m_UsePtDiff==PTDIFF) m_PtDiff_Values.push_back((TopH.Pt()-Tlv.Pt())/m_Units); - else if(m_UsePtDiff==PTDIFFMASS) m_PtDiff_Values.push_back((TopH.Pt()-Tlv.Pt())/(Tt.M())); - m_Wh_Values.push_back(Whad.M()/m_Units); - m_ThWh_Values.push_back((TopH.M()-Whad.M())/m_Units); - m_Tl_Values.push_back((Tlv.M())/m_Units); - m_nChi2Values++; - } - - //################# - //Original chi2 method - //################# - if (chi2tempg1<chi2ming1){ - - if(passBtag){ - chi2ming1 = chi2tempg1; - chi2ming1H = chi2H; - chi2ming1L = chi2L; - m_WhChi2Value = chi2WH; - m_ThWhChi2Value = chi2H - chi2WH; - m_TlChi2Value = chi2L; - m_PtDiffChi2Value = chi2tempg1 - chi2H - chi2L; - - i_q1_W=i; - i_q2_W=j; - i_b_had=k; - i_b_lep=m; - ign1=n; - res_Mtl=Tlv.M(); - res_Mwh=Whad.M(); - res_Mth=TopH.M(); - res_Mtt=Tt.M(); - res_Tt = Tt; - - //============================ - // bjet category splitting - //============================ - if(n_bjets==0){ - m_category = 0; - }else if(n_bjets==1){ - if(isJetBtagged->at(k)){//b-jet on the hadronic side - m_category = 2; - }else if(isJetBtagged->at(m)){//b-jet on the leptonic side - m_category = 3; - }else{ - std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; - } - }else if(n_bjets>=2){ - if(isJetBtagged->at(k)){//b-jet on the hadronic side - if(isJetBtagged->at(m)){//b-jet on the leptonic side too - m_category = 1; - }else{//b-jet only on the hadronic side - m_category = 2; - } - }else if(isJetBtagged->at(m)){ - m_category = 3; - }else{ - std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; - } - } - } - } // end of case a minimal chisquare was found - } // end of case unique combination - } //end of loop over jets - } // end of loop over all neutrino solutions - } // end of case this is the electron channel + for (unsigned int k = 0; k < (unsigned int) n_jets; k++) { + if (k != i && k != j) { + const TLorentzVector* K = jetVector->at(k); + TLorentzVector TopH = (*I) + (*J) + (*K); + TLorentzVector Whad = (*I) + (*J); + for (unsigned int n = 0; n < neutrinoVector.size(); n++) { + TLorentzVector* N = neutrinoVector[n]; + + TLorentzVector Wlv = (*N) + (*L); + for (unsigned int m = 0; m < (unsigned int) n_jets; m++) { + if (m != i && m != j && m != k) { + const TLorentzVector* M = jetVector->at(m); + TLorentzVector Tlv = Wlv + (*M); + TLorentzVector Tt = Tlv + TopH; + double chi2WH = pow((Whad.M() - MjjP) / SMjjP, 2); + double chi2H = chi2WH + pow((TopH.M() - Whad.M() - m_TopMinusW_had_mean) / m_TopMinusW_had_sigma, 2); + double chi2L = pow((Tlv.M() - m_Top_lep_mean) / m_Top_lep_sigma, 2); + + double chi2tempg1 = chi2H + chi2L; + if (m_UsePtDiff == PTDIFF) { + double chi2Diff = pow((TopH.Pt() - Tlv.Pt() - m_PtDiff_mean) / m_PtDiff_sigma, 2); + chi2tempg1 += chi2Diff; + } else if (m_UsePtDiff == PTDIFFREL) { + double chi2DiffRel = pow(((TopH.Pt() - Tlv.Pt()) / (TopH.Pt() + Tlv.Pt()) - m_PtDiffRel_mean) / m_PtDiffRel_sigma, 2); + chi2tempg1 += chi2DiffRel; + } else if (m_UsePtDiff == PTDIFFMASS) { + double chi2DiffRelMass = pow(((TopH.Pt() - Tlv.Pt()) / (Tt.M()) - m_PtDiffRelMass_mean) / m_PtDiffRelMass_sigma, 2); + chi2tempg1 += chi2DiffRelMass; + } + + // does this combination contain a b + // k -> hadronic b + // m -> leptonic b + int n_bJetsComb = 0; + if (isJetBtagged->at(k)) { + n_bJetsComb++; + } + // second b + if (isJetBtagged->at(m)) { + n_bJetsComb++; + } + + bool passBtag = false; + if (m_Btag == STDBTAG || m_Btag == NO_BTAGHM) { + if (n_bJetsComb > 0) { + passBtag = true; + } + } else if (m_Btag == AFFECTBTAG) { + if (n_bjets == 0) { + passBtag = true; + } else if (n_bjets == 1) { + if (n_bJetsComb == 1) { + passBtag = true; + } + } else if (n_bjets >= 2) { + if (n_bJetsComb == 2) { + passBtag = true; + } + } + } else if (m_Btag == NO_BTAG) { + passBtag = true; + } + + if (passBtag && m_RunMode == RUNSTUDY) { + m_chi2Values.push_back(chi2tempg1); + m_chi2Wh_Values.push_back(chi2WH); + m_chi2ThWh_Values.push_back(chi2H - chi2WH); + m_chi2Tl_Values.push_back(chi2L); + m_chi2PtDiff_Values.push_back(chi2tempg1 - chi2H - chi2L); + m_i_Wq1.push_back(i); + m_i_Wq2.push_back(j); + m_i_Thb.push_back(k); + m_i_Tlb.push_back(m); + m_i_n.push_back(n); + if (m_UsePtDiff == PTDIFF) m_PtDiff_Values.push_back((TopH.Pt() - Tlv.Pt()) / m_Units); + else if (m_UsePtDiff == PTDIFFMASS) m_PtDiff_Values.push_back((TopH.Pt() - Tlv.Pt()) / (Tt.M())); + m_Wh_Values.push_back(Whad.M() / m_Units); + m_ThWh_Values.push_back((TopH.M() - Whad.M()) / m_Units); + m_Tl_Values.push_back((Tlv.M()) / m_Units); + m_nChi2Values++; + } + + //################# + //Original chi2 method + //################# + if (chi2tempg1 < chi2ming1) { + if (passBtag) { + chi2ming1 = chi2tempg1; + chi2ming1H = chi2H; + chi2ming1L = chi2L; + m_WhChi2Value = chi2WH; + m_ThWhChi2Value = chi2H - chi2WH; + m_TlChi2Value = chi2L; + m_PtDiffChi2Value = chi2tempg1 - chi2H - chi2L; + + i_q1_W = i; + i_q2_W = j; + i_b_had = k; + i_b_lep = m; + ign1 = n; + res_Mtl = Tlv.M(); + res_Mwh = Whad.M(); + res_Mth = TopH.M(); + res_Mtt = Tt.M(); + res_Tt = Tt; + + //============================ + // bjet category splitting + //============================ + if (n_bjets == 0) { + m_category = 0; + } else if (n_bjets == 1) { + if (isJetBtagged->at(k)) {//b-jet on the hadronic side + m_category = 2; + } else if (isJetBtagged->at(m)) {//b-jet on the leptonic side + m_category = 3; + } else { + std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; + } + } else if (n_bjets >= 2) { + if (isJetBtagged->at(k)) {//b-jet on the hadronic side + if (isJetBtagged->at(m)) {//b-jet on the leptonic side too + m_category = 1; + } else {//b-jet only on the hadronic side + m_category = 2; + } + } else if (isJetBtagged->at(m)) { + m_category = 3; + } else { + std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; + } + } + } + } // end of case a minimal chisquare was found + } // end of case unique combination + } //end of loop over jets + } // end of loop over all neutrino solutions + } // end of case this is the electron channel } // end of loop over jets k } // end of loop over jets } // end of loop over jets - bool status=false; - if ( i_q1_W != -1 && i_q2_W != -1 && i_b_had != -1 && i_b_lep != -1 && ign1 != -1){ + bool status = false; + if (i_q1_W != -1 && i_q2_W != -1 && i_b_had != -1 && i_b_lep != -1 && ign1 != -1) { status = true; } - res_chi2All = chi2ming1; - res_chi2WH = chi2ming1WH; + res_chi2All = chi2ming1; + res_chi2WH = chi2ming1WH; res_chi2TopH = chi2ming1H; res_chi2TopL = chi2ming1L; - for (unsigned int i =0; i< neutrinoVector.size(); i++)delete neutrinoVector[i]; neutrinoVector.clear(); + for (unsigned int i = 0; i < neutrinoVector.size(); i++) { + delete neutrinoVector[i]; + } + neutrinoVector.clear(); return status; } - //_________________________________________________________________________________________________ -bool TtresChi2::findMinChiSquare_HighMass(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_lep, int& ign1, double& chi2ming1, double& -chi2ming1H, double& chi2ming1L){ - if(m_debug>0) std::cout << "entering TtresChi2::findMinChiSquare_HighMass()" << std::endl; +bool TtresChi2::findMinChiSquare_HighMass(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q1_W, int& i_q2_W, int& i_b_lep, int& ign1, double& chi2ming1, double& + chi2ming1H, double& chi2ming1L) { + if (m_debug > 0) std::cout << "entering TtresChi2::findMinChiSquare_HighMass()" << std::endl; //_________________________________________________________________________________________________ - i_q1_W=-1; - i_q2_W=-1; - i_b_lep=-1; - ign1=-1; - chi2ming1 =1e7; - chi2ming1H=1e7; - chi2ming1L=1e7; + i_q1_W = -1; + i_q2_W = -1; + i_b_lep = -1; + ign1 = -1; + chi2ming1 = 1e7; + chi2ming1H = 1e7; + chi2ming1L = 1e7; double HMtop = -1e6; int n_jets = jetVector->size(); int n_bjets = 0; - + this->Reset(); if (L == NULL) { - std::cerr << "ERROR : TtresChi2::findMinChiSquare: Lepton is NULL" << std::endl; - return false; + std::cerr << "ERROR : TtresChi2::findMinChiSquare: Lepton is NULL" << std::endl; + return false; } - - if(m_Btag==AFFECTBTAG){ - for(unsigned int ib = 0; ib<(unsigned int)isJetBtagged->size(); ++ib){ - if(isJetBtagged->at(ib)) n_bjets++; - } + + if (m_Btag == AFFECTBTAG) { + for (unsigned int ib = 0; ib < (unsigned int) isJetBtagged->size(); ++ib) { + if (isJetBtagged->at(ib)) n_bjets++; + } } - + //_________________________________________________________________________________________________ - std::vector<TLorentzVector*> neutrinoVector= GetNeutrinos(L, MET); + std::vector<TLorentzVector*> neutrinoVector = GetNeutrinos(L, MET); //_________________________________________________________________________________________________ - for (unsigned int i=0; i<(unsigned int)n_jets; i++){ + for (unsigned int i = 0; i < (unsigned int) n_jets; i++) { const TLorentzVector* I = jetVector->at(i); - for (unsigned int j=i+1; j<(unsigned int)n_jets; j++){ + for (unsigned int j = i + 1; j < (unsigned int) n_jets; j++) { const TLorentzVector* J = jetVector->at(j); - if ( I->M()>m_highJetMass*m_Units || J->M()>m_highJetMass*m_Units ) { - TLorentzVector TopH = (*I) + (*J); - - for (unsigned int n=0; n< neutrinoVector.size(); n++){ - - TLorentzVector* N = neutrinoVector[n]; - - TLorentzVector Wlv = (*N) + (*L); - for (unsigned int m=0; m<(unsigned int) n_jets; m++){ - if (m!=i && m!=j) { - const TLorentzVector* M = jetVector->at(m); - TLorentzVector Tlv = Wlv + (*M); - TLorentzVector Tt = Tlv + TopH; - - double HMtoptemp = I->M(); - double chi2H = pow((TopH.M()-MTHJJ)/STHJJ,2); - double chi2L = pow((Tlv.M()-m_Top_lep_mean)/m_Top_lep_sigma,2); - - double chi2tempg1 = chi2H+chi2L; - if (m_UsePtDiff==PTDIFF){ - double chi2Diff = pow((TopH.Pt()-Tlv.Pt()-m_PtDiff_mean)/m_PtDiff_sigma,2); - chi2tempg1+=chi2Diff; - }else if (m_UsePtDiff==PTDIFFREL){ - double chi2DiffRel = pow(((TopH.Pt()-Tlv.Pt())/(TopH.Pt()+Tlv.Pt())-m_PtDiffRel_mean)/m_PtDiffRel_sigma,2); - chi2tempg1+=chi2DiffRel; - }else if (m_UsePtDiff==PTDIFFMASS){ - double chi2DiffRelMass = pow(((TopH.Pt()-Tlv.Pt())/(Tt.M())-m_PtDiffRelMass_mean)/m_PtDiffRelMass_sigma,2); - chi2tempg1+=chi2DiffRelMass; - } - - // does this combination contain a b - // k -> hadronic b - // m -> leptonic b - int n_bJetsComb = 0; - // check whether one of the taggers is passed - // first b - if (isJetBtagged->at(i) || isJetBtagged->at(j)){ - n_bJetsComb++; - } - // second b - if (isJetBtagged->at(m)){ - n_bJetsComb++; - } - - bool passBtag = false; - if(m_Btag==STDBTAG){ - if(n_bJetsComb>0){ - passBtag = true; - } - }else if(m_Btag==AFFECTBTAG){ - if(n_bjets==0){ - passBtag = true; - }else if(n_bjets==1){ - if(n_bJetsComb==1){ passBtag = true; } - }else if(n_bjets>=2){ - if(n_bJetsComb==2){ passBtag = true; } - } - }else if(m_Btag==NO_BTAGHM || m_Btag==NO_BTAG){ - passBtag = true; - } - - if(passBtag && m_RunMode==RUNSTUDY){ - m_chi2Values.push_back(chi2tempg1); - m_chi2Th_Values.push_back(chi2H); - m_chi2Tl_Values.push_back(chi2L); - m_chi2PtDiff_Values.push_back(chi2tempg1 - chi2H - chi2L); - m_i_Wq1.push_back(i); - m_i_Wq2.push_back(j); - m_i_Tlb.push_back(m); - m_i_n.push_back(n); - if(m_UsePtDiff==PTDIFF) m_PtDiff_Values.push_back((TopH.Pt()-Tlv.Pt())/m_Units); - else if(m_UsePtDiff==PTDIFFMASS) m_PtDiff_Values.push_back((TopH.Pt()-Tlv.Pt())/(Tt.M())); - m_Th_Values.push_back((TopH.M())/m_Units); - m_Tl_Values.push_back((Tlv.M())/m_Units); - m_nChi2Values++; - } - - //################# - //Original chi2 method - //################# - if (chi2tempg1<chi2ming1 && HMtoptemp>=HMtop){ - if(passBtag){ - HMtop=HMtoptemp; - chi2ming1=chi2tempg1; - chi2ming1H=chi2H; - chi2ming1L=chi2L; - m_ThWhChi2Value = chi2H; - m_TlChi2Value = chi2L; - m_PtDiffChi2Value = chi2tempg1 - chi2H - chi2L; - - i_q1_W=i; - i_q2_W=j; - i_b_lep=m; - ign1=n; - res_Mtl=Tlv.M(); - //res_Mwh is not defined here - res_Mth=TopH.M(); - res_Mtt=Tt.M(); - res_Tt = Tt; - - //============================ - // bjet category splitting - //============================ - if(n_bjets==0){ - m_category = 0; - }else if(n_bjets==1){ - if(isJetBtagged->at(i) || isJetBtagged->at(j)){//b-jet on the hadronic side - m_category = 2; - }else if(isJetBtagged->at(m)){//b-jet on the leptonic side - m_category = 3; - }else{ - std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; - } - }else if(n_bjets>=2){ - if(isJetBtagged->at(i) || isJetBtagged->at(m)){//b-jet on the hadronic side - if(isJetBtagged->at(m)){//b-jet on the leptonic side too - m_category = 1; - }else{//b-jet only on the hadronic side - m_category = 2; - } - }else if(isJetBtagged->at(m)){ - m_category = 3; - }else{ - std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; - } - } - - } //end of btag requirement - } // end of case a minimal chisquare was found - } // end of case unique combination - } //end of loop over jets - } // end of loop over all neutrino solutions + if (I->M() > m_highJetMass * m_Units || J->M() > m_highJetMass * m_Units) { + TLorentzVector TopH = (*I) + (*J); + + for (unsigned int n = 0; n < neutrinoVector.size(); n++) { + TLorentzVector* N = neutrinoVector[n]; + + TLorentzVector Wlv = (*N) + (*L); + for (unsigned int m = 0; m < (unsigned int) n_jets; m++) { + if (m != i && m != j) { + const TLorentzVector* M = jetVector->at(m); + TLorentzVector Tlv = Wlv + (*M); + TLorentzVector Tt = Tlv + TopH; + + double HMtoptemp = I->M(); + double chi2H = pow((TopH.M() - MTHJJ) / STHJJ, 2); + double chi2L = pow((Tlv.M() - m_Top_lep_mean) / m_Top_lep_sigma, 2); + + double chi2tempg1 = chi2H + chi2L; + if (m_UsePtDiff == PTDIFF) { + double chi2Diff = pow((TopH.Pt() - Tlv.Pt() - m_PtDiff_mean) / m_PtDiff_sigma, 2); + chi2tempg1 += chi2Diff; + } else if (m_UsePtDiff == PTDIFFREL) { + double chi2DiffRel = pow(((TopH.Pt() - Tlv.Pt()) / (TopH.Pt() + Tlv.Pt()) - m_PtDiffRel_mean) / m_PtDiffRel_sigma, 2); + chi2tempg1 += chi2DiffRel; + } else if (m_UsePtDiff == PTDIFFMASS) { + double chi2DiffRelMass = pow(((TopH.Pt() - Tlv.Pt()) / (Tt.M()) - m_PtDiffRelMass_mean) / m_PtDiffRelMass_sigma, 2); + chi2tempg1 += chi2DiffRelMass; + } + + // does this combination contain a b + // k -> hadronic b + // m -> leptonic b + int n_bJetsComb = 0; + // check whether one of the taggers is passed + // first b + if (isJetBtagged->at(i) || isJetBtagged->at(j)) { + n_bJetsComb++; + } + // second b + if (isJetBtagged->at(m)) { + n_bJetsComb++; + } + + bool passBtag = false; + if (m_Btag == STDBTAG) { + if (n_bJetsComb > 0) { + passBtag = true; + } + } else if (m_Btag == AFFECTBTAG) { + if (n_bjets == 0) { + passBtag = true; + } else if (n_bjets == 1) { + if (n_bJetsComb == 1) { + passBtag = true; + } + } else if (n_bjets >= 2) { + if (n_bJetsComb == 2) { + passBtag = true; + } + } + } else if (m_Btag == NO_BTAGHM || m_Btag == NO_BTAG) { + passBtag = true; + } + + if (passBtag && m_RunMode == RUNSTUDY) { + m_chi2Values.push_back(chi2tempg1); + m_chi2Th_Values.push_back(chi2H); + m_chi2Tl_Values.push_back(chi2L); + m_chi2PtDiff_Values.push_back(chi2tempg1 - chi2H - chi2L); + m_i_Wq1.push_back(i); + m_i_Wq2.push_back(j); + m_i_Tlb.push_back(m); + m_i_n.push_back(n); + if (m_UsePtDiff == PTDIFF) m_PtDiff_Values.push_back((TopH.Pt() - Tlv.Pt()) / m_Units); + else if (m_UsePtDiff == PTDIFFMASS) m_PtDiff_Values.push_back((TopH.Pt() - Tlv.Pt()) / (Tt.M())); + m_Th_Values.push_back((TopH.M()) / m_Units); + m_Tl_Values.push_back((Tlv.M()) / m_Units); + m_nChi2Values++; + } + + //################# + //Original chi2 method + //################# + if (chi2tempg1 < chi2ming1 && HMtoptemp >= HMtop) { + if (passBtag) { + HMtop = HMtoptemp; + chi2ming1 = chi2tempg1; + chi2ming1H = chi2H; + chi2ming1L = chi2L; + m_ThWhChi2Value = chi2H; + m_TlChi2Value = chi2L; + m_PtDiffChi2Value = chi2tempg1 - chi2H - chi2L; + + i_q1_W = i; + i_q2_W = j; + i_b_lep = m; + ign1 = n; + res_Mtl = Tlv.M(); + //res_Mwh is not defined here + res_Mth = TopH.M(); + res_Mtt = Tt.M(); + res_Tt = Tt; + + //============================ + // bjet category splitting + //============================ + if (n_bjets == 0) { + m_category = 0; + } else if (n_bjets == 1) { + if (isJetBtagged->at(i) || isJetBtagged->at(j)) {//b-jet on the hadronic side + m_category = 2; + } else if (isJetBtagged->at(m)) {//b-jet on the leptonic side + m_category = 3; + } else { + std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; + } + } else if (n_bjets >= 2) { + if (isJetBtagged->at(i) || isJetBtagged->at(m)) {//b-jet on the hadronic side + if (isJetBtagged->at(m)) {//b-jet on the leptonic side too + m_category = 1; + } else {//b-jet only on the hadronic side + m_category = 2; + } + } else if (isJetBtagged->at(m)) { + m_category = 3; + } else { + std::cerr << "<!> In TtresChi2::findMinChiSquare : cannot find the corresponding category." << std::endl; + } + } + } //end of btag requirement + } // end of case a minimal chisquare was found + } // end of case unique combination + } //end of loop over jets + } // end of loop over all neutrino solutions } // end of case this is the electron channel } // end of loop over jets } // end of loop over jets - bool status=false; - if ( i_q1_W != -1 && i_q2_W != -1 && i_b_lep != -1 && ign1 != -1){ + bool status = false; + if (i_q1_W != -1 && i_q2_W != -1 && i_b_lep != -1 && ign1 != -1) { status = true; } - res_chi2All = chi2ming1; + res_chi2All = chi2ming1; res_chi2TopH = chi2ming1H; res_chi2TopL = chi2ming1L; - for (unsigned int i =0; i< neutrinoVector.size(); i++)delete neutrinoVector[i]; neutrinoVector.clear(); + for (unsigned int i = 0; i < neutrinoVector.size(); i++) { + delete neutrinoVector[i]; + } + neutrinoVector.clear(); return status; } //_________________________________________________________________________________________________ -bool TtresChi2::findMinChiSquare_VeryHighMass(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q2_W, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L){ - if(m_debug>0) std::cout << "entering TtresChi2::findMinChiSquare_VeryHighMass() " << std::endl; +bool TtresChi2::findMinChiSquare_VeryHighMass(TLorentzVector* L, const std::vector<TLorentzVector*>* jetVector, const std::vector<bool>* isJetBtagged, TLorentzVector* MET, int& i_q2_W, int& i_b_lep, int& ign1, double& chi2ming1, double& chi2ming1H, double& chi2ming1L) { + if (m_debug > 0) std::cout << "entering TtresChi2::findMinChiSquare_VeryHighMass() " << std::endl; //_________________________________________________________________________________________________ - i_q2_W=-1; - i_b_lep=-1; - ign1=-1; - chi2ming1 =1e7; - chi2ming1H=1e7; - chi2ming1L=1e7; + i_q2_W = -1; + i_b_lep = -1; + ign1 = -1; + chi2ming1 = 1e7; + chi2ming1H = 1e7; + chi2ming1L = 1e7; double HMtop = -1e6; int n_jets = jetVector->size(); this->Reset(); if (L == NULL) { - std::cerr << "ERROR : TtresChi2::findMinChiSquare: Lepton is NULL" << std::endl; - return false; + std::cerr << "ERROR : TtresChi2::findMinChiSquare: Lepton is NULL" << std::endl; + return false; } - std::vector<TLorentzVector*> neutrinoVector= GetNeutrinos(L, MET); + std::vector<TLorentzVector*> neutrinoVector = GetNeutrinos(L, MET); //_________________________________________________________________________________________________ - for (unsigned int i=0; i<(unsigned int)n_jets; i++){ + for (unsigned int i = 0; i < (unsigned int) n_jets; i++) { const TLorentzVector* I = jetVector->at(i); TLorentzVector TopH = (*I); - if (I->M()>150.*m_Units){ - for (unsigned int n=0; n< neutrinoVector.size(); n++){ - - TLorentzVector* N = neutrinoVector[n]; - - TLorentzVector Wlv = (*N) + (*L); - for (unsigned int m=0; m< (unsigned int)n_jets; m++){ - if (m!=i) { - const TLorentzVector* M = jetVector->at(m); - TLorentzVector Tlv = Wlv + (*M); - TLorentzVector Tt = Tlv + TopH; - - double HMtoptemp = I->M(); - double chi2H = 1.; - double chi2L = pow((Tlv.M()-m_Top_lep_mean)/m_Top_lep_sigma,2); - double chi2Diff = pow((TopH.Pt()-Tlv.Pt()-m_PtDiff_mean)/m_PtDiff_sigma,2); - double chi2tempg1 = chi2L; - - if (m_UsePtDiff) chi2tempg1+=chi2Diff; - - //################# - //Original chi2 method - //################# - if (chi2tempg1<chi2ming1 && HMtoptemp>=HMtop){ - - // does this combination contain a b - // k -> hadronic b - // m -> leptonic b - int n_bJets = 0; - // check whether one of the taggers is passed - // first b - if (isJetBtagged->at(i)){ - n_bJets++; - } - // second b - if (isJetBtagged->at(m)){ - n_bJets++; - } - - if (n_bJets >= 1){ - HMtop=HMtoptemp; - chi2ming1=chi2tempg1; - chi2ming1H=chi2H; - chi2ming1L=chi2L; - i_q2_W=i; - i_b_lep=m; - ign1=n; - res_Mtl=Tlv.M(); - //res_Mwh is not defined here - res_Mth=TopH.M(); - res_Mtt=Tt.M(); - res_Tt = Tt; - } - } // end of case a minimal chisquare was found - } // end of case unique combination - } //end of loop over jets + if (I->M() > 150. * m_Units) { + for (unsigned int n = 0; n < neutrinoVector.size(); n++) { + TLorentzVector* N = neutrinoVector[n]; + + TLorentzVector Wlv = (*N) + (*L); + for (unsigned int m = 0; m < (unsigned int) n_jets; m++) { + if (m != i) { + const TLorentzVector* M = jetVector->at(m); + TLorentzVector Tlv = Wlv + (*M); + TLorentzVector Tt = Tlv + TopH; + + double HMtoptemp = I->M(); + double chi2H = 1.; + double chi2L = pow((Tlv.M() - m_Top_lep_mean) / m_Top_lep_sigma, 2); + double chi2Diff = pow((TopH.Pt() - Tlv.Pt() - m_PtDiff_mean) / m_PtDiff_sigma, 2); + double chi2tempg1 = chi2L; + + if (m_UsePtDiff) chi2tempg1 += chi2Diff; + + //################# + //Original chi2 method + //################# + if (chi2tempg1 < chi2ming1 && HMtoptemp >= HMtop) { + // does this combination contain a b + // k -> hadronic b + // m -> leptonic b + int n_bJets = 0; + // check whether one of the taggers is passed + // first b + if (isJetBtagged->at(i)) { + n_bJets++; + } + // second b + if (isJetBtagged->at(m)) { + n_bJets++; + } + + if (n_bJets >= 1) { + HMtop = HMtoptemp; + chi2ming1 = chi2tempg1; + chi2ming1H = chi2H; + chi2ming1L = chi2L; + i_q2_W = i; + i_b_lep = m; + ign1 = n; + res_Mtl = Tlv.M(); + //res_Mwh is not defined here + res_Mth = TopH.M(); + res_Mtt = Tt.M(); + res_Tt = Tt; + } + } // end of case a minimal chisquare was found + } // end of case unique combination + } //end of loop over jets } // end of loop over all neutrino solutions } // end of high mass } // end of loop over jets bool status = false; - if ( i_q2_W != -1 && i_b_lep != -1 && ign1 != -1){ + if (i_q2_W != -1 && i_b_lep != -1 && ign1 != -1) { status = true; } - res_chi2All = chi2ming1; + res_chi2All = chi2ming1; res_chi2TopH = chi2ming1H; res_chi2TopL = chi2ming1L; - for (unsigned int i =0; i< neutrinoVector.size(); i++)delete neutrinoVector[i]; neutrinoVector.clear(); + for (unsigned int i = 0; i < neutrinoVector.size(); i++) { + delete neutrinoVector[i]; + } + neutrinoVector.clear(); return status; } - - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresNeutrinoBuilder.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresNeutrinoBuilder.cxx index f177f65c3f0dfb3f071dc9cafe8c55408c40eaf3..41a6e140176afad6333f65fb210b60cac64ad2c0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresNeutrinoBuilder.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresNeutrinoBuilder.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include <TMinuit.h> #include "TopEventReconstructionTools/TtresNeutrinoBuilder.h" @@ -9,26 +9,26 @@ void delta2_fcn(Int_t&, Double_t*, Double_t&, Double_t*, Int_t); //_________________________________________________________________________________________________ -TtresNeutrinoBuilder::TtresNeutrinoBuilder(std::string units){ +TtresNeutrinoBuilder::TtresNeutrinoBuilder(std::string units) { m_debug = 0; - if (units=="MeV")m_Units = 1000.; - else if(units=="GeV")m_Units = 1.; + if (units == "MeV") m_Units = 1000.; + else if (units == "GeV") m_Units = 1.; else std::cerr << "WARNING in NeutrinoBuilder: units different from GeV or MeV" << std::endl; } //_________________________________________________________________________________________________ -TtresNeutrinoBuilder::~TtresNeutrinoBuilder(){ - if(m_debug>0) std::cout << "in destructor " << std::endl; +TtresNeutrinoBuilder::~TtresNeutrinoBuilder() { + if (m_debug > 0) std::cout << "in destructor " << std::endl; } -//_________________________________________________________________________________________________ -TtresNeutrinoBuilder::TtresNeutrinoBuilder(const TtresNeutrinoBuilder& other) { +//_________________________________________________________________________________________________ +TtresNeutrinoBuilder::TtresNeutrinoBuilder(const TtresNeutrinoBuilder& other) { m_debug = other.m_debug; } -//_________________________________________________________________________________________________ -TtresNeutrinoBuilder& TtresNeutrinoBuilder::operator=(const TtresNeutrinoBuilder& other) { - if(this != &other) { +//_________________________________________________________________________________________________ +TtresNeutrinoBuilder& TtresNeutrinoBuilder::operator = (const TtresNeutrinoBuilder& other) { + if (this != &other) { m_debug = other.m_debug; } return *this; @@ -36,8 +36,7 @@ TtresNeutrinoBuilder& TtresNeutrinoBuilder::operator=(const TtresNeutrinoBuilder //_________________________________________________________________________________________________ // JDM - fix compiler warnings -void delta2_fcn(Int_t& /*npar*/, Double_t* /*grad*/, Double_t& f, Double_t* par, Int_t /*iflag*/){ - +void delta2_fcn(Int_t& /*npar*/, Double_t* /*grad*/, Double_t& f, Double_t* par, Int_t /*iflag*/) { Double_t delta2 = 0; Double_t alpha = par[0]; Double_t r = par[1]; @@ -46,14 +45,16 @@ void delta2_fcn(Int_t& /*npar*/, Double_t* /*grad*/, Double_t& f, Double_t* par, Double_t l_m = par[4]; Double_t n_px = par[5]; Double_t n_py = par[6]; + r /= sqrt(l_pt * l_pt + l_m * l_m) - l_pt * cos(dphi + alpha); - TLorentzVector *neut = new TLorentzVector(n_px, n_py, 0., 0.); + TLorentzVector* neut = new TLorentzVector(n_px, n_py, 0., 0.); neut->SetE(neut->P()); - - TLorentzVector *neut_new = new TLorentzVector(r * neut->P() * cos(neut->Phi() + alpha), r * neut->P() * sin(neut->Phi() + alpha), 0., 0.); + + TLorentzVector* neut_new = + new TLorentzVector(r * neut->P() * cos(neut->Phi() + alpha), r * neut->P() * sin(neut->Phi() + alpha), 0., 0.); neut_new->SetE(neut_new->P()); - - delta2 = pow((neut_new->Px() - neut->Px()), 2) + pow((neut_new->Py() - neut->Py()), 2); + + delta2 = pow((neut_new->Px() - neut->Px()), 2) + pow((neut_new->Py() - neut->Py()), 2); r *= sqrt(l_pt * l_pt + l_m * l_m) - l_pt * cos(dphi + alpha); delete neut; delete neut_new; @@ -61,29 +62,41 @@ void delta2_fcn(Int_t& /*npar*/, Double_t* /*grad*/, Double_t& f, Double_t* par, } //_________________________________________________________________________________________________ -double TtresNeutrinoBuilder::fitAlpha(const TLorentzVector* L, const Double_t met, const Double_t metphi){ - +double TtresNeutrinoBuilder::fitAlpha(const TLorentzVector* L, const Double_t met, const Double_t metphi) { // initialize double m_mWpdg = 80.4 * m_Units; Double_t pxNu = met * cos(metphi); Double_t pyNu = met * sin(metphi); Double_t ptNu = met; - - TMinuit *fit = new TMinuit(7); + + TMinuit* fit = new TMinuit(7); + fit->SetFCN(delta2_fcn); int ierr = 0; - double arglist[1] = {-1}; - fit->mnexcm("SET PRIN",arglist,1,ierr); + double arglist[1] = { + -1 + }; + fit->mnexcm("SET PRIN", arglist, 1, ierr); // Initialise the parameters - std::string par_name[7] = {"alpha", "r", "dphi", "l_pt", "l_m", "n_px", "n_py"}; - Double_t par_ival[7] = {0., (m_mWpdg * m_mWpdg - L->M() * L->M()) / (2 * ptNu), metphi - L->Phi(), L->Pt(), L->M(), pxNu, pyNu}; - Double_t par_step[7] = {0.1, 0., 0., 0., 0., 0., 0.}; - Double_t par_min[7] = {-3.15, 0., -3.15, 0., 0., -10000., -10000.}; - Double_t par_max[7] = {3.15, 1., 3.15, 10000., 80., 10000., 10000.}; - for (Int_t i = 0; i < 7; i++){ - fit->DefineParameter(i,par_name[i].c_str(),par_ival[i],par_step[i],par_min[i],par_max[i]); - if (i != 0){ + std::string par_name[7] = { + "alpha", "r", "dphi", "l_pt", "l_m", "n_px", "n_py" + }; + Double_t par_ival[7] = { + 0., (m_mWpdg * m_mWpdg - L->M() * L->M()) / (2 * ptNu), metphi - L->Phi(), L->Pt(), L->M(), pxNu, pyNu + }; + Double_t par_step[7] = { + 0.1, 0., 0., 0., 0., 0., 0. + }; + Double_t par_min[7] = { + -3.15, 0., -3.15, 0., 0., -10000., -10000. + }; + Double_t par_max[7] = { + 3.15, 1., 3.15, 10000., 80., 10000., 10000. + }; + for (Int_t i = 0; i < 7; i++) { + fit->DefineParameter(i, par_name[i].c_str(), par_ival[i], par_step[i], par_min[i], par_max[i]); + if (i != 0) { fit->FixParameter(i); } } @@ -92,27 +105,27 @@ double TtresNeutrinoBuilder::fitAlpha(const TLorentzVector* L, const Double_t me Double_t a, e_a; Int_t ret = fit->GetParameter(0, a, e_a); delete fit; - if (ret > 0){ + if (ret > 0) { return a; - } - else { + } else { std::cout << "Error in fit of alpha for met correction" << std::endl; return 0.; } - } - // In case of negative discriminant, decrease the MET //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, const TLorentzVector* MET){ -return this->candidatesFromWMass_Scaling(L, MET->Px(), MET->Py()); +std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, + const TLorentzVector* MET) { + return this->candidatesFromWMass_Scaling(L, MET->Px(), MET->Py()); } // In case of negative discriminant, decrease the MET //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, const double met_etx, const double met_ety){ - if(m_debug>0) std::cout << "entering NeutrinoBuilder::candidatesFromWMass_Scaling()" << std::endl; +std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, + const double met_etx, + const double met_ety) { + if (m_debug > 0) std::cout << "entering NeutrinoBuilder::candidatesFromWMass_Scaling()" << std::endl; std::vector<TLorentzVector*> NC; this->candidatesFromWMass_Scaling(L, met_etx, met_ety, NC); return NC; @@ -120,9 +133,9 @@ std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Scaling(c // In case of negative discriminant, decrease the MET //_________________________________________________________________________________________________ -bool TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, const double met_etx, const double met_ety, std::vector<TLorentzVector*>& NC){ - - if(m_debug>0) std::cout << "entering NeutrinoBuilder::candidatesFromWMass_Scaling()" << std::endl; +bool TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, const double met_etx, + const double met_ety, std::vector<TLorentzVector*>& NC) { + if (m_debug > 0) std::cout << "entering NeutrinoBuilder::candidatesFromWMass_Scaling()" << std::endl; // initialize double delta; double lambda; @@ -132,218 +145,220 @@ bool TtresNeutrinoBuilder::candidatesFromWMass_Scaling(const TLorentzVector* L, double alpha; double beta; double gamma; - double m_mWpdg=80.4 * m_Units; + double m_mWpdg = 80.4 * m_Units; int count = 0; - + pxNu = met_etx; pyNu = met_ety; do { // solve the quadratic equation ++count; - ptNu = sqrt (pxNu*pxNu + pyNu*pyNu); - alpha = pow(m_mWpdg,2)+pow((pxNu+L->Px()),2)+pow((pyNu+L->Py()),2)-pow(L->E(),2); - - beta = 0.5 * ( alpha-pow(ptNu,2)+pow(L->Pz(),2) ); - gamma = -( beta*beta - ( pow(L->E(),2)*pow(ptNu,2) ) ) / ( pow(L->E(),2)-pow(L->Pz(),2) ); - lambda = 2*beta*L->Pz() / (pow(L->E(),2)-pow(L->Pz(),2)); - delta = pow(lambda,2)-4*gamma; - if(m_debug>1) std::cout << "count = " << count << "\tptNu = " << ptNu << "\tdelta = " << delta << "\tm_mWpdg = " << m_mWpdg << std::endl; + ptNu = sqrt(pxNu * pxNu + pyNu * pyNu); + alpha = pow(m_mWpdg, 2) + pow((pxNu + L->Px()), 2) + pow((pyNu + L->Py()), 2) - pow(L->E(), 2); + + beta = 0.5 * (alpha - pow(ptNu, 2) + pow(L->Pz(), 2)); + gamma = -(beta * beta - (pow(L->E(), 2) * pow(ptNu, 2))) / (pow(L->E(), 2) - pow(L->Pz(), 2)); + lambda = 2 * beta * L->Pz() / (pow(L->E(), 2) - pow(L->Pz(), 2)); + delta = pow(lambda, 2) - 4 * gamma; + if (m_debug > + 1) std::cout << "count = " << count << "\tptNu = " << ptNu << "\tdelta = " << delta << "\tm_mWpdg = " << + m_mWpdg << + std::endl; // if no real solution, reduce Pt by 0.1 GeV and recompute pxNu & pyNu // in consequence - if (delta < 0){ - if(ptNu > 100. ){ - double Ptmiss = ptNu; - ptNu -= 100. ; - pxNu *= ptNu/Ptmiss; - pyNu *= ptNu/Ptmiss; - } + if (delta < 0) { + if (ptNu > 100.) { + double Ptmiss = ptNu; + ptNu -= 100.; + pxNu *= ptNu / Ptmiss; + pyNu *= ptNu / Ptmiss; + } } // end of case delta is negatively defined - - } while( (delta < 0) && (count < 10000) && ( ptNu > 20 *1000)); - if (delta < 0){ - if(m_debug>0) std::cout << "no solution delta still<0" << std::endl; return false; + } while ((delta < 0) && (count < 10000) && (ptNu > 20 * 1000)); + if (delta < 0) { + if (m_debug > 0) std::cout << "no solution delta still<0" << std::endl; + return false; } delta = sqrt(delta); // instantiate Neutrino - double pz = (lambda-delta)/2.0; - double e = sqrt(pxNu*pxNu+pyNu*pyNu+pz*pz); - TLorentzVector *nu1 = new TLorentzVector(pxNu,pyNu,pz,e); - pz = (lambda+delta)/2.0; - e = sqrt(pxNu*pxNu+pyNu*pyNu+pz*pz); - TLorentzVector *nu2 = new TLorentzVector(pxNu,pyNu,pz,e); + double pz = (lambda - delta) / 2.0; + double e = sqrt(pxNu * pxNu + pyNu * pyNu + pz * pz); + TLorentzVector* nu1 = new TLorentzVector(pxNu, pyNu, pz, e); + pz = (lambda + delta) / 2.0; + e = sqrt(pxNu * pxNu + pyNu * pyNu + pz * pz); + TLorentzVector* nu2 = new TLorentzVector(pxNu, pyNu, pz, e); NC.push_back(nu1); NC.push_back(nu2); - if(m_debug>0) std::cout << "quitting NeutrinoBuilder::candidatesFromWMass_Scaling()" << std::endl; + if (m_debug > 0) std::cout << "quitting NeutrinoBuilder::candidatesFromWMass_Scaling()" << std::endl; return true; } - - - - // In case of negative discriminant, decrese the MET //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Rotation(const TLorentzVector* L, const TLorentzVector* MET, const bool useSmallestPz){ - return this->candidatesFromWMass_Rotation(L, MET->Pt(), MET->Phi(), useSmallestPz); +std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Rotation(const TLorentzVector* L, + const TLorentzVector* MET, + const bool useSmallestPz) { + return this->candidatesFromWMass_Rotation(L, MET->Pt(), MET->Phi(), useSmallestPz); } // In case of negative discriminant, decrese the MET //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Rotation(const TLorentzVector* L, const Double_t met, const Double_t metphi, const bool useSmallestPz){ - if(m_debug>0) std::cout << "entering candidatesFromWMassRotation()" << std::endl; - - // initialize - Double_t m_mWpdg = 80.4 * m_Units; - Double_t pxNu = met * cos(metphi); - Double_t pyNu = met * sin(metphi); - Double_t pzNu = -1000000; - Double_t ptNu = met; - Double_t eNu; - - std::vector<TLorentzVector*> NC; - - Double_t c1 = m_mWpdg * m_mWpdg - L->M() * L->M() + 2 * (L->Px() * pxNu + L->Py() * pyNu); - Double_t b1 = 2 * L->Pz(); - - Double_t A = 4 * pow(L->E(), 2) - b1 * b1; - Double_t B = -2 * c1 * b1; - Double_t C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; - Double_t discr = B*B - 4*A*C; - Double_t r = 1; - - Double_t sol1, sol2; - if (discr > 0){ - sol1 = (-B + sqrt(discr)) / (2*A); - sol2 = (-B - sqrt(discr)) / (2*A); - } - else { - Double_t alpha = fitAlpha(L, met, metphi); - Double_t dphi = metphi - L->Phi(); - r = ( pow(m_mWpdg,2) - pow(L->M(),2) ) / (2 * ptNu * (sqrt(pow(L->Pt(),2) + pow(L->M(),2)) - L->Pt() * cos(dphi + alpha))); - - Double_t old_p = ptNu; - Double_t old_phi = metphi; - pxNu = r * old_p * cos(old_phi + alpha); - pyNu = r * old_p * sin(old_phi + alpha); - ptNu = sqrt (pxNu*pxNu + pyNu*pyNu); - - c1 = m_mWpdg * m_mWpdg - pow(L->M(),2) + 2 * (L->Px() * pxNu + L->Py() * pyNu); - B = -2 * c1 * b1; - C = 4 * pow(L->E(),2) * ptNu * ptNu - c1 * c1; - discr = B*B - 4*A*C; - - sol1 = -B / (2*A); - sol2 = -B / (2*A); - } - - if (useSmallestPz){ - - pzNu = (fabs(sol1) > fabs(sol2)) ? sol2 : sol1; - - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu1 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - NC.push_back(nu1); - - }else{ - - pzNu = sol1; - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu1 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - pzNu = sol2; - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu2 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - NC.push_back(nu1); - NC.push_back(nu2); - - } +std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_Rotation(const TLorentzVector* L, + const Double_t met, + const Double_t metphi, + const bool useSmallestPz) { + if (m_debug > 0) std::cout << "entering candidatesFromWMassRotation()" << std::endl; - if(m_debug>0) std::cout << "quitting NeutrinoBuilder::candidatesFromWMassRotation() : " << NC.size() << std::endl; - return NC; + // initialize + Double_t m_mWpdg = 80.4 * m_Units; + Double_t pxNu = met * cos(metphi); + Double_t pyNu = met * sin(metphi); + Double_t pzNu = -1000000; + Double_t ptNu = met; + Double_t eNu; + + std::vector<TLorentzVector*> NC; + + Double_t c1 = m_mWpdg * m_mWpdg - L->M() * L->M() + 2 * (L->Px() * pxNu + L->Py() * pyNu); + Double_t b1 = 2 * L->Pz(); + + Double_t A = 4 * pow(L->E(), 2) - b1 * b1; + Double_t B = -2 * c1 * b1; + Double_t C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; + Double_t discr = B * B - 4 * A * C; + Double_t r = 1; + + Double_t sol1, sol2; + if (discr > 0) { + sol1 = (-B + sqrt(discr)) / (2 * A); + sol2 = (-B - sqrt(discr)) / (2 * A); + } else { + Double_t alpha = fitAlpha(L, met, metphi); + Double_t dphi = metphi - L->Phi(); + r = + (pow(m_mWpdg, + 2) - pow(L->M(), 2)) / (2 * ptNu * (sqrt(pow(L->Pt(), 2) + pow(L->M(), 2)) - L->Pt() * cos(dphi + alpha))); + + Double_t old_p = ptNu; + Double_t old_phi = metphi; + pxNu = r * old_p * cos(old_phi + alpha); + pyNu = r * old_p * sin(old_phi + alpha); + ptNu = sqrt(pxNu * pxNu + pyNu * pyNu); + + c1 = m_mWpdg * m_mWpdg - pow(L->M(), 2) + 2 * (L->Px() * pxNu + L->Py() * pyNu); + B = -2 * c1 * b1; + C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; + discr = B * B - 4 * A * C; + + sol1 = -B / (2 * A); + sol2 = -B / (2 * A); + } + + if (useSmallestPz) { + pzNu = (fabs(sol1) > fabs(sol2)) ? sol2 : sol1; + + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu1 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + NC.push_back(nu1); + } else { + pzNu = sol1; + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu1 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + pzNu = sol2; + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu2 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + NC.push_back(nu1); + NC.push_back(nu2); + } + + if (m_debug > 0) std::cout << "quitting NeutrinoBuilder::candidatesFromWMassRotation() : " << NC.size() << std::endl; + return NC; } // In case of negative discriminant, use the real part //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_RealPart(const TLorentzVector* L, const TLorentzVector* MET, const bool useSmallestPz){ - return this->candidatesFromWMass_RealPart(L, MET->Pt(), MET->Phi(), useSmallestPz); +std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_RealPart(const TLorentzVector* L, + const TLorentzVector* MET, + const bool useSmallestPz) { + return this->candidatesFromWMass_RealPart(L, MET->Pt(), MET->Phi(), useSmallestPz); } + // In case of negative discriminant, use the real part //_________________________________________________________________________________________________ -std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_RealPart(const TLorentzVector* L, Double_t met, Double_t metphi, const bool useSmallestPz){ - if(m_debug>0) std::cout << "entering candidatesFromWMass_RealPart()" << std::endl; - - // initialize - Double_t m_mWpdg = 80.4 * m_Units; - Double_t pxNu = met * cos(metphi); - Double_t pyNu = met * sin(metphi); - Double_t pzNu = -1000000; - Double_t ptNu = met; - Double_t eNu; - - std::vector<TLorentzVector*> NC; - - Double_t c1 = m_mWpdg * m_mWpdg - L->M() * L->M() + 2 * (L->Px() * pxNu + L->Py() * pyNu); - Double_t b1 = 2 * L->Pz(); - - Double_t A = 4 * pow(L->E(), 2) - b1 * b1; - Double_t B = -2 * c1 * b1; - Double_t C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; - Double_t discr = B*B - 4*A*C; - - Double_t sol1, sol2; - if (discr > 0){ - sol1 = (-B + sqrt(discr)) / (2*A); - sol2 = (-B - sqrt(discr)) / (2*A); - } - //if discr<0 - else { - pzNu = -B / (2*A); - - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu1 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - NC.push_back(nu1); - return NC; - } - - if (useSmallestPz){ - - pzNu = (fabs(sol1) > fabs(sol2)) ? sol2 : sol1; - - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu1 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - NC.push_back(nu1); - - }else{ - - pzNu = sol1; - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu1 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - pzNu = sol2; - eNu = sqrt(pxNu*pxNu + pyNu*pyNu + pzNu*pzNu); - TLorentzVector *nu2 = new TLorentzVector(pxNu,pyNu,pzNu,eNu); - NC.push_back(nu1); - NC.push_back(nu2); - - } +std::vector<TLorentzVector*> TtresNeutrinoBuilder::candidatesFromWMass_RealPart(const TLorentzVector* L, Double_t met, + Double_t metphi, + const bool useSmallestPz) { + if (m_debug > 0) std::cout << "entering candidatesFromWMass_RealPart()" << std::endl; + + // initialize + Double_t m_mWpdg = 80.4 * m_Units; + Double_t pxNu = met * cos(metphi); + Double_t pyNu = met * sin(metphi); + Double_t pzNu = -1000000; + Double_t ptNu = met; + Double_t eNu; + + std::vector<TLorentzVector*> NC; + + Double_t c1 = m_mWpdg * m_mWpdg - L->M() * L->M() + 2 * (L->Px() * pxNu + L->Py() * pyNu); + Double_t b1 = 2 * L->Pz(); + + Double_t A = 4 * pow(L->E(), 2) - b1 * b1; + Double_t B = -2 * c1 * b1; + Double_t C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; + Double_t discr = B * B - 4 * A * C; + + Double_t sol1, sol2; + if (discr > 0) { + sol1 = (-B + sqrt(discr)) / (2 * A); + sol2 = (-B - sqrt(discr)) / (2 * A); + } + //if discr<0 + else { + pzNu = -B / (2 * A); - if(m_debug>0) std::cout << "quitting NeutrinoBuilder::candidatesFromWMass_RealPart() : " << NC.size() << std::endl; + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu1 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + NC.push_back(nu1); return NC; -} + } + + if (useSmallestPz) { + pzNu = (fabs(sol1) > fabs(sol2)) ? sol2 : sol1; -Double_t TtresNeutrinoBuilder::getDiscriminant(const TLorentzVector* L, Double_t met, Double_t metphi){ - - // initialize - Double_t m_mWpdg = 80.4 * m_Units; - Double_t pxNu = met * cos(metphi); - Double_t pyNu = met * sin(metphi); - Double_t ptNu = met; - - Double_t c1 = m_mWpdg * m_mWpdg - L->M() * L->M() + 2 * (L->Px() * pxNu + L->Py() * pyNu); - Double_t b1 = 2 * L->Pz(); - - Double_t A = 4 * pow(L->E(), 2) - b1 * b1; - Double_t B = -2 * c1 * b1; - Double_t C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; - Double_t discr = B*B - 4*A*C; - return discr; + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu1 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + NC.push_back(nu1); + } else { + pzNu = sol1; + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu1 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + pzNu = sol2; + eNu = sqrt(pxNu * pxNu + pyNu * pyNu + pzNu * pzNu); + TLorentzVector* nu2 = new TLorentzVector(pxNu, pyNu, pzNu, eNu); + NC.push_back(nu1); + NC.push_back(nu2); + } + + if (m_debug > 0) std::cout << "quitting NeutrinoBuilder::candidatesFromWMass_RealPart() : " << NC.size() << std::endl; + + return NC; } +Double_t TtresNeutrinoBuilder::getDiscriminant(const TLorentzVector* L, Double_t met, Double_t metphi) { + // initialize + Double_t m_mWpdg = 80.4 * m_Units; + Double_t pxNu = met * cos(metphi); + Double_t pyNu = met * sin(metphi); + Double_t ptNu = met; + + Double_t c1 = m_mWpdg * m_mWpdg - L->M() * L->M() + 2 * (L->Px() * pxNu + L->Py() * pyNu); + Double_t b1 = 2 * L->Pz(); + + Double_t A = 4 * pow(L->E(), 2) - b1 * b1; + Double_t B = -2 * c1 * b1; + Double_t C = 4 * pow(L->E(), 2) * ptNu * ptNu - c1 * c1; + Double_t discr = B * B - 4 * A * C; + + return discr; +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresdRmin.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresdRmin.cxx index 551fa4518b1375a1138db4c4dbc6b0b246d113a8..80c542ae0bbe35f6ef3008d09935f0b9a8a696a4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresdRmin.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/Root/TtresdRmin.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ /////////////////////////////////////////////////////////////////////////////////// // // @@ -33,54 +33,50 @@ // Class constructor // TtresdRmin::TtresdRmin(TString units, bool verbose) { - m_init = false; m_verbose = verbose; - if(units == "MeV") { + if (units == "MeV") { m_Units = 1000.0; - } else if(units == "GeV") { + } else if (units == "GeV") { m_Units = 1.0; } else { - cout << " ERROR in in TtresdRmin :: Unit setting '" << units << "' doest not match pattern of GeV or MeV" << endl; + cout << " ERROR in in TtresdRmin :: Unit setting '" << units << "' doest not match pattern of GeV or MeV" << endl; } } - //========================================================================================================== // Initialize parameters for tool // void TtresdRmin::Init(double highJetMass, double minJetPt, double dRCutOffset, double dRCutMassFactor) { //Set parameters - m_highM = highJetMass; - m_minJetPt = minJetPt; - m_dRCutOffset = dRCutOffset; + m_highM = highJetMass; + m_minJetPt = minJetPt; + m_dRCutOffset = dRCutOffset; m_dRCutMassFactor = dRCutMassFactor; //Reset m_jet_indices.clear(); m_highMassJetIndex = -1; - m_highestJetMass = 0.0; + m_highestJetMass = 0.0; //Initialization status m_init = true; } - //========================================================================================================== // Setup event with kinematic objects // -bool TtresdRmin::SetupEvent(vector<TLorentzVector*> &jets, TLorentzVector &lepton, TLorentzVector &neutrino) { - - if(!m_init) { +bool TtresdRmin::SetupEvent(vector<TLorentzVector*>& jets, TLorentzVector& lepton, TLorentzVector& neutrino) { + if (!m_init) { cout << " ERROR in TtresdRmin :: Tool not initialized! Initialize tool before usage!!!" << endl; return false; } //Set objects - m_jets = jets; - m_lepton = lepton; - m_neutrino = neutrino; + m_jets = jets; + m_lepton = lepton; + m_neutrino = neutrino; m_Wleptonic = lepton + neutrino; //Reset @@ -90,24 +86,23 @@ bool TtresdRmin::SetupEvent(vector<TLorentzVector*> &jets, TLorentzVector &lepto //===== Search for high mass jet ===== - int highMJetIdx = -1; //Index of jet with highest mass above threshold - double highM = m_highM*m_Units; //Threshold for high mass jet - double minJetPt = m_minJetPt*m_Units; //Threshold for jet pT + int highMJetIdx = -1; //Index of jet with highest mass above threshold + double highM = m_highM * m_Units; //Threshold for high mass jet + double minJetPt = m_minJetPt * m_Units; //Threshold for jet pT //Loop jets - for(int ijet = 0; ijet < (int)jets.size(); ijet++) { - + for (int ijet = 0; ijet < (int) jets.size(); ijet++) { //pT requirmenet - if(jets.at(ijet)->Pt() <= minJetPt) continue; //next jet + if (jets.at(ijet)->Pt() <= minJetPt) continue; //next jet //high mass requirement - if(jets.at(ijet)->M() <= highM) continue; //next jet + if (jets.at(ijet)->M() <= highM) continue; //next jet highMJetIdx = ijet; highM = jets.at(ijet)->M(); }//end of jet loop - if(highMJetIdx >= 0) { + if (highMJetIdx >= 0) { m_highMassJetIndex = highMJetIdx; m_highestJetMass = highM; FindJetIndices_HM(); @@ -118,17 +113,15 @@ bool TtresdRmin::SetupEvent(vector<TLorentzVector*> &jets, TLorentzVector &lepto return true; } - //========================================================================================================== // Get invariant ttbar mass // double TtresdRmin::GetMttdRmin() { - double mtt_dRmin = 0.0; - if(m_jet_indices.size() > 0) { - TLorentzVector dRsumJet(0,0,0,0); - for(unsigned int ijet = 0; ijet < m_jet_indices.size(); ijet++) { + if (m_jet_indices.size() > 0) { + TLorentzVector dRsumJet(0, 0, 0, 0); + for (unsigned int ijet = 0; ijet < m_jet_indices.size(); ijet++) { dRsumJet += *(m_jets.at(m_jet_indices.at(ijet))); } mtt_dRmin = (dRsumJet + m_Wleptonic).M(); @@ -141,12 +134,11 @@ double TtresdRmin::GetMttdRmin() { // Get ttbar system TLorentzVector // TLorentzVector TtresdRmin::GetTlvdRmin() { + TLorentzVector tt_dRmin(0, 0, 0, 0); - TLorentzVector tt_dRmin(0,0,0,0); - - if(m_jet_indices.size() > 0) { - TLorentzVector dRsumJet(0,0,0,0); - for(unsigned int ijet = 0; ijet < (unsigned int)m_jet_indices.size(); ijet++) { + if (m_jet_indices.size() > 0) { + TLorentzVector dRsumJet(0, 0, 0, 0); + for (unsigned int ijet = 0; ijet < (unsigned int) m_jet_indices.size(); ijet++) { dRsumJet += *(m_jets.at(m_jet_indices.at(ijet))); } tt_dRmin = dRsumJet + m_Wleptonic; @@ -155,21 +147,19 @@ TLorentzVector TtresdRmin::GetTlvdRmin() { return tt_dRmin; } - //========================================================================================================== // Find jet indices for reconstruction for events with a high mass jet // bool TtresdRmin::FindJetIndices_HM() { - //===== Find closest jet to high mass jet ===== double dR_had = 999.9; int closest_jetIdx_had = -1; //Loop m_jets - for(int ijet = 0; ijet < (int)m_jets.size(); ijet++) { - if(ijet == m_highMassJetIndex) continue; //next jet + for (int ijet = 0; ijet < (int) m_jets.size(); ijet++) { + if (ijet == m_highMassJetIndex) continue; //next jet double dR = m_jets.at(m_highMassJetIndex)->DeltaR(*(m_jets.at(ijet))); - if(dR < dR_had) { + if (dR < dR_had) { closest_jetIdx_had = ijet; dR_had = dR; } @@ -181,11 +171,11 @@ bool TtresdRmin::FindJetIndices_HM() { int closest_jetIdx_lep = -1; //Loop jets - for(int ijet = 0; ijet < (int)m_jets.size(); ijet++) { - if(ijet == m_highMassJetIndex) continue; //next jet - if(ijet == closest_jetIdx_had) continue; //next jet + for (int ijet = 0; ijet < (int) m_jets.size(); ijet++) { + if (ijet == m_highMassJetIndex) continue; //next jet + if (ijet == closest_jetIdx_had) continue; //next jet double dR = m_Wleptonic.DeltaR(*(m_jets.at(ijet))); - if(dR < dR_lep) { + if (dR < dR_lep) { closest_jetIdx_lep = ijet; dR_lep = dR; } @@ -194,35 +184,33 @@ bool TtresdRmin::FindJetIndices_HM() { //===== Save jet indices used for reconstruction ===== m_jet_indices.push_back(m_highMassJetIndex); - if(closest_jetIdx_had >= 0){ + if (closest_jetIdx_had >= 0) { m_jet_indices.push_back(closest_jetIdx_had); } else { - if(m_verbose) cout << " WARNING in TtresdRmin :: Can not find jet close to high mass jet" << endl; + if (m_verbose) cout << " WARNING in TtresdRmin :: Can not find jet close to high mass jet" << endl; } - if(closest_jetIdx_lep >= 0) { + if (closest_jetIdx_lep >= 0) { m_jet_indices.push_back(closest_jetIdx_lep); } else { - if(m_verbose) cout << " WARNING in TtresdRmin :: Can not find jet close to leptonic W-boson" << endl; + if (m_verbose) cout << " WARNING in TtresdRmin :: Can not find jet close to leptonic W-boson" << endl; } return true; } - //========================================================================================================== // Find jet indices for reconstruction for events without a high mass jet // bool TtresdRmin::FindJetIndices_LM() { - //jetflag vector to flag jets rejected by dRmin method vector<bool> jetflags(m_jets.size(), true); //do dRmin procedure if at least 4 jets are available - bool repeat_dRmin = ((int)m_jets.size() > 3); + bool repeat_dRmin = ((int) m_jets.size() > 3); //Loop dRmin method - while(repeat_dRmin) { + while (repeat_dRmin) { repeat_dRmin = false; double dR_max = 0.0; //Maximum dR passing dRmin cut requirement @@ -232,12 +220,11 @@ bool TtresdRmin::FindJetIndices_LM() { int nijet = 0; //Outer jet loop - for(int ijet = 0; ijet < (int)m_jets.size(); ijet++) { - - if(!jetflags.at(ijet)) continue; //next outer jet + for (int ijet = 0; ijet < (int) m_jets.size(); ijet++) { + if (!jetflags.at(ijet)) continue; //next outer jet //Use maximum of 4 goodflagged jets - if(nijet > 3) break; + if (nijet > 3) break; nijet++; double dR_min = 999.9; @@ -249,45 +236,44 @@ bool TtresdRmin::FindJetIndices_LM() { int njjet = 0; //Inner jet loop - for(int jjet = 0; jjet < (int)m_jets.size(); jjet++) { + for (int jjet = 0; jjet < (int) m_jets.size(); jjet++) { + if (!jetflags.at(jjet)) continue; //next inner jet - if(!jetflags.at(jjet)) continue; //next inner jet + //Use maximum of 4 goodflagged jets + if (njjet > 3) break; + njjet++; - //Use maximum of 4 goodflagged jets - if(njjet > 3) break; - njjet++; + if (jjet == ijet) continue; //next inner jet - if(jjet == ijet) continue; //next inner jet - - double dR_jet = m_jets.at(ijet)->DeltaR(*(m_jets.at(jjet))); - if(dR_jet < dR_min){ - dR_min = dR_jet; - } + double dR_jet = m_jets.at(ijet)->DeltaR(*(m_jets.at(jjet))); + if (dR_jet < dR_min) { + dR_min = dR_jet; + } } //end of inner jet loop - if(dR_min > dR_max) { - //dRmin specific cut (defined for GeV, needs m_Units correction on mass) - double dR_cut = m_dRCutOffset - m_dRCutMassFactor * m_jets.at(ijet)->M()/m_Units; - if(dR_min > dR_cut) { - dR_max = dR_min; - index_max = ijet; - } + if (dR_min > dR_max) { + //dRmin specific cut (defined for GeV, needs m_Units correction on mass) + double dR_cut = m_dRCutOffset - m_dRCutMassFactor * m_jets.at(ijet)->M() / m_Units; + if (dR_min > dR_cut) { + dR_max = dR_min; + index_max = ijet; + } } }//end of outer jet loop - if(index_max >= 0) { + if (index_max >= 0) { jetflags.at(index_max) = false; - if(count(jetflags.begin(), jetflags.end(), true) > 3) repeat_dRmin = true; + if (count(jetflags.begin(), jetflags.end(), true) > 3) repeat_dRmin = true; } }//end of while(repeat) int nijet = 0; //Save selected jet indices - for(int ijet = 0; ijet < (int)m_jets.size(); ijet++) { - if(!jetflags.at(ijet)) continue; //next jet + for (int ijet = 0; ijet < (int) m_jets.size(); ijet++) { + if (!jetflags.at(ijet)) continue; //next jet //Use maximum of 4 goodflagged jets - if(nijet > 3) break; + if (nijet > 3) break; nijet++; m_jet_indices.push_back(ijet); @@ -295,4 +281,3 @@ bool TtresdRmin::FindJetIndices_LM() { return true; } - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Chi2LJets.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Chi2LJets.h index def6b3cce0d9b3d175e8827ced03dc2ea6a2b21d..c377b6ab9c591e829b8d6e5f6a9f0c5d1d819893 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Chi2LJets.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Chi2LJets.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef CHI2LJETS_H_ #define CHI2LJETS_H_ @@ -12,13 +12,13 @@ class TMinuit; namespace top { -class Event; + class Event; /** * @brief Hold the information that is required for the chi^2 minimisation */ -class FitInfo : public TObject { -public: + class FitInfo: public TObject { + public: ///Mass of the hadronic W (j+j) double hadronic_w_mass; @@ -36,28 +36,27 @@ public: ///Four vector of the jet that we think is the leptonic b quark TLorentzVector leptonic_b; -}; + }; /** * @brief Not complete. Work in progress */ -class Chi2LJets : public EventSelectorBase { -public: + class Chi2LJets: public EventSelectorBase { + public: Chi2LJets(); virtual ~Chi2LJets(); virtual bool apply(const top::Event&) const override; - std::string name() const { return "RECO:CHI2LJETS"; } - -private: + std::string name() const override {return "RECO:CHI2LJETS";} + private: ///So we can do a minimisation TMinuit* min; mutable FitInfo params; //so the fcn function can see them -public: + public: ///The top mass that we're using as the baseline - used in chi2 function. static const double input_topmass; @@ -69,8 +68,7 @@ public: ///The W resolution that we're using as the baseline - used in chi2 function. static const double input_wsigma; -}; - + }; } void fcn(int& npar, double* deriv, double& result, double par[], int flag); diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterRun.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterRun.h index f11c5c2821944b898e713fb82186ec5818c88092..d2c1ddc0d7273c017a0acda029cf8f45c9d9c26a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterRun.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterRun.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: KLFitterRun.h 688037 2015-08-07 01:24:06Z morrisj $ #ifndef ANALYSISTOP_TOPEVENTRECONSTRCUTIONTOOLS_KLFITTERRUN_H @@ -9,23 +9,22 @@ #include "TopEventSelectionTools/EventSelectorBase.h" #include "TopEventReconstructionTools/KLFitterTool.h" -namespace top{ +namespace top { class Event; class TopConfig; - - class KLFitterRun : public EventSelectorBase { - public: - KLFitterRun(const std::string& kLeptonType,std::shared_ptr<top::TopConfig> config); - virtual ~KLFitterRun(){} - - virtual bool apply(const top::Event&) const override; - std::string name() const; - - private: - std::string m_name; - std::unique_ptr<top::KLFitterTool> m_myFitter; - + class KLFitterRun: public EventSelectorBase { + public: + KLFitterRun(const std::string& kSelectionName, const std::string& kParameters, + std::shared_ptr<top::TopConfig> config); + virtual ~KLFitterRun() {} + + virtual bool apply(const top::Event&) const override; + std::string name() const override; + private: + std::string m_name; + + std::unique_ptr<top::KLFitterTool> m_myFitter; }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterTool.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterTool.h index 8d28f4c22a68f7a826e89e56aff3eb70e0e0537f..ad8e92cec34c279e33c6ad66df341f8a33cab7d0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterTool.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/KLFitterTool.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ // $Id: KLFitterTool.h 788027 2016-12-04 18:30:45Z aknue $ #ifndef ANALYSISTOP_TOPEVENTRECONSTRCUTIONTOOLS_KLFITTERTOOL_H @@ -8,13 +8,20 @@ // Framework include(s): #include "AsgTools/AsgTool.h" -#include "xAODBTaggingEfficiency/IBTaggingEfficiencyTool.h" +#include "FTagAnalysisInterfaces/IBTaggingEfficiencyTool.h" +#include "xAODJet/JetContainer.h" +#include "xAODJet/JetAuxContainer.h" +#include "TopConfiguration/Tokenize.h" // KLFitter include(s): #include "KLFitter/Fitter.h" #include "KLFitter/LikelihoodTopLeptonJets.h" #include "KLFitter/LikelihoodTTHLeptonJets.h" +#include "KLFitter/LikelihoodTopLeptonJets_JetAngles.h" +#include "KLFitter/LikelihoodTTZTrilepton.h" +#include "KLFitter/LikelihoodTopAllHadronic.h" +#include "KLFitter/BoostedLikelihoodTopLeptonJets.h" #include "KLFitter/PhysicsConstants.h" #include "KLFitter/LikelihoodBase.h" #include "KLFitter/DetectorAtlas_8TeV.h" @@ -28,86 +35,110 @@ #include <memory> - /// - /// @author John Morris <john.morris@cern.ch> - /// - /// $Revision: 788027 $ - /// $Date: 2016-12-04 19:30:45 +0100 (Sun, 04 Dec 2016) $ - /// - /// @brief Interface to KLFitter - /// - +/// +/// @author John Morris <john.morris@cern.ch> +/// +/// $Revision: 788027 $ +/// $Date: 2016-12-04 18:30:45 +0000 (Sun, 04 Dec 2016) $ +/// +/// @brief Interface to KLFitter +/// + // Forware declare -namespace KLFitter{ +namespace KLFitter { class Particles; } -namespace top{ +namespace top { class Event; class TopConfig; - + /// Some additional enums - namespace KLFitterJetSelection{ - enum JetSelectionMode{ kLeadingFour , kLeadingFive , kLeadingSix, kBtagPriorityFourJets , kBtagPriorityFiveJets , kBtagPrioritySixJets}; + namespace KLFitterJetSelection { + enum JetSelectionMode { + kLeadingThree, kLeadingFour, kLeadingFive, kLeadingSix, + kLeadingSeven, kLeadingEight, kBtagPriorityThreeJets, + kBtagPriorityFourJets, kBtagPriorityFiveJets, kBtagPrioritySixJets, + kBtagPrioritySevenJets, kBtagPriorityEightJets + }; } - - - class KLFitterTool final : public asg::AsgTool { - - public: - /// Constructor - explicit KLFitterTool( const std::string& name ); - /// Destructor - virtual ~KLFitterTool(){} - - /// Function initialising the tool - virtual StatusCode initialize(); - /// Function executing the tool - virtual StatusCode execute(const top::Event&); - /// Function finalizing the tool - virtual StatusCode finalize(); - - private: - - // set jets depending on selection mode - void setJets(const top::Event&,KLFitter::Particles* inputParticles); - void setJetskLeadingFour(const top::Event&,KLFitter::Particles* inputParticles); - void setJetskLeadingFive(const top::Event&,KLFitter::Particles* inputParticles); - void setJetskLeadingSix(const top::Event&,KLFitter::Particles* inputParticles); - - void setJetskLeadingX(const top::Event& event,KLFitter::Particles* inputParticles, int); - - - void setJetskBtagPriorityFourJets(const top::Event&,KLFitter::Particles* inputParticles); - void setJetskBtagPriorityFiveJets(const top::Event&,KLFitter::Particles* inputParticles); - void setJetskBtagPrioritySixJets(const top::Event&,KLFitter::Particles* inputParticles); - - void setJetskBtagPriority(const top::Event&,KLFitter::Particles* inputParticles,const unsigned int maxJets); - - // configuration - std::shared_ptr<top::TopConfig> m_config; - float m_massTop; - float m_bTagCutValue; - - // Tools and functions for btagging - ToolHandle<IBTaggingEfficiencyTool> m_btagging_eff_tool; - bool HasTag(const xAOD::Jet& jet, double& weight) const; - void retrieveEfficiencies(const xAOD::Jet& jet, float* efficiency, float* inefficiency); - - /// KLFitter parameters, to be set by input file - std::string m_transferFunctionsPathPrefix; - std::string m_transferFunctionsPath; - - std::string m_leptonType; - std::string m_LHType; - KLFitter::LikelihoodTopLeptonJets::LeptonType m_leptonTypeKLFitterEnum; - KLFitter::LikelihoodTTHLeptonJets::LeptonType m_leptonTypeKLFitterEnum_TTH; - top::KLFitterJetSelection::JetSelectionMode m_jetSelectionModeKLFitterEnum; - KLFitter::LikelihoodBase::BtaggingMethod m_bTaggingMethodKLFitterEnum; - - /// The KLFitter - std::unique_ptr<KLFitter::Fitter> m_myFitter; - + + + class KLFitterTool final: public asg::AsgTool { + public: + /// Constructor + explicit KLFitterTool(const std::string& name); + /// Destructor + virtual ~KLFitterTool() {} + + /// Function initialising the tool + virtual StatusCode initialize(); + /// Function executing the tool + virtual StatusCode execute(const top::Event&); + /// Function finalizing the tool + virtual StatusCode finalize(); + private: + // set jets depending on selection mode + bool setJets(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskLeadingThree(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskLeadingFour(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskLeadingFive(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskLeadingSix(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskLeadingSeven(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskLeadingEight(const top::Event&, KLFitter::Particles* inputParticles); + + bool setJetskLeadingX(const top::Event& event, KLFitter::Particles* inputParticles, const unsigned int); + + + bool setJetskBtagPriorityThreeJets(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskBtagPriorityFourJets(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskBtagPriorityFiveJets(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskBtagPrioritySixJets(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskBtagPrioritySevenJets(const top::Event&, KLFitter::Particles* inputParticles); + bool setJetskBtagPriorityEightJets(const top::Event&, KLFitter::Particles* inputParticles); + + bool setJetskBtagPriority(const top::Event&, KLFitter::Particles* inputParticles, const unsigned int maxJets); + + // configuration + std::shared_ptr<top::TopConfig> m_config; + float m_massTop; + float m_bTagCutValue; + bool m_isWorkingPoint; + bool findOption(std::vector<std::string> full_options, std::string option, std::string& op_value); + + // Tools and functions for btagging + ToolHandle<IBTaggingEfficiencyTool> m_btagging_eff_tool; + bool HasTag(const xAOD::Jet& jet, double& weight) const; + void retrieveEfficiencies(const xAOD::Jet& jet, float* efficiency, float* inefficiency); + + /// KLFitter parameters, to be set by input file + std::string m_transferFunctionsPathPrefix; + std::string m_transferFunctionsPath; + + std::string m_selectionName; + std::string m_leptonType; + std::string m_customParameters; + std::string m_LHType; + KLFitter::LikelihoodTopLeptonJets::LeptonType m_leptonTypeKLFitterEnum; + KLFitter::LikelihoodTTHLeptonJets::LeptonType m_leptonTypeKLFitterEnum_TTH; + KLFitter::LikelihoodTopLeptonJets_JetAngles::LeptonType m_leptonTypeKLFitterEnum_JetAngles; + KLFitter::LikelihoodTTZTrilepton::LeptonType m_leptonTypeKLFitterEnum_TTZ; + KLFitter::BoostedLikelihoodTopLeptonJets::LeptonType m_leptonTypeKLFitterEnum_BoostedLJets; + + std::unique_ptr<KLFitter::LikelihoodTopLeptonJets> m_myLikelihood; + std::unique_ptr<KLFitter::LikelihoodTTHLeptonJets> m_myLikelihood_TTH; + std::unique_ptr<KLFitter::LikelihoodTopLeptonJets_JetAngles> m_myLikelihood_JetAngles; + std::unique_ptr<KLFitter::LikelihoodTTZTrilepton> m_myLikelihood_TTZ; + std::unique_ptr<KLFitter::LikelihoodTopAllHadronic> m_myLikelihood_AllHadronic; + std::unique_ptr<KLFitter::BoostedLikelihoodTopLeptonJets> m_myLikelihood_BoostedLJets; + + std::unique_ptr<KLFitter::DetectorAtlas_8TeV> m_myDetector; + + top::KLFitterJetSelection::JetSelectionMode m_jetSelectionModeKLFitterEnum; + KLFitter::LikelihoodBase::BtaggingMethod m_bTaggingMethodKLFitterEnum; + + /// The KLFitter + std::unique_ptr<KLFitter::Fitter> m_myFitter; }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/MT2Reco.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/MT2Reco.h index 21730795c365110ec26673a6b3201e386bee33b5..314c63949211e13bc1080df08c71c4cf35a9cbaf 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/MT2Reco.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/MT2Reco.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MT2RECO_H_ #define MT2RECO_H_ @@ -10,21 +10,20 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { -class Event; + class Event; /** * @brief Not complete. Work in progress */ -class MT2Reco : public EventSelectorBase { -public: + class MT2Reco: public EventSelectorBase { + public: MT2Reco(); virtual ~MT2Reco(); virtual bool apply(const top::Event&) const override; - std::string name() const { return "RECO:MT2"; } -}; - + std::string name() const {return "RECO:MT2";} + }; } #endif //ROOTCORE_PACKAGE_Oxbridgekinetics diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/NeutrinoWeighting.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/NeutrinoWeighting.h index 1a4a6ea63d93ce64f040f681f8cfbfb06e805c8a..1cf81a31c528d7143008430e0dad3cc19749518b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/NeutrinoWeighting.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/NeutrinoWeighting.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NEUTRINOWEIGHTING_H_ #define NEUTRINOWEIGHTING_H_ @@ -8,7 +8,7 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { -class Event; + class Event; /** * @brief Holds the two solutions from the quadratic equation as TLorentVectors. @@ -16,31 +16,31 @@ class Event; * Filled when solving the quadratic equation to calculate the 4 Vectors for * the two neutrinos in the event. */ -class NWSolution { -public: + class NWSolution { + public: void setSolutions(int num, const TLorentzVector& a, const TLorentzVector& b) { - m_v1 = a; - m_v2 = b; - m_solutions = num; + m_v1 = a; + m_v2 = b; + m_solutions = num; } void setSolutions(int num) { - m_solutions = num; + m_solutions = num; } int getNumSolutions() const { - return m_solutions; + return m_solutions; } TLorentzVector getv1() const { - return m_v1; + return m_v1; } TLorentzVector getv2() const { - return m_v2; + return m_v2; } -private: + private: ///Number of solutions. 0 or 2, one solution isn't possible due to the use of floats. int m_solutions; @@ -49,28 +49,28 @@ private: ///Second solution from the quadratic, check m_solutions is 2 first. TLorentzVector m_v2; -}; + }; /** * @brief Not complete. Work in progress */ -class NeutrinoWeighting : public EventSelectorBase { -public: + class NeutrinoWeighting: public EventSelectorBase { + public: NeutrinoWeighting(); virtual ~NeutrinoWeighting(); bool apply(const top::Event&) const override; - std::string name() const { return "RECO:NEUTRINOWEIGHTING"; } - -private: + std::string name() const override {return "RECO:NEUTRINOWEIGHTING";} + private: /** * @param lepton The lepton 4 vector. * @param bJet The b jet 4 vector. * @param topMass The top mass is a constraint in the spin correlation calculation. * @param index Gives the position in the neutrino eta array of this neutrino. */ - NWSolution solveForNeutrinoEta(const TLorentzVector& lepton, const TLorentzVector& bJet, double topMass, int index) const; + NWSolution solveForNeutrinoEta(const TLorentzVector& lepton, const TLorentzVector& bJet, double topMass, + int index) const; /** * @brief Calculate the weight for this combination of particles by comparing with Met. @@ -106,9 +106,7 @@ private: //For weighter. double sigmay; - -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PTMaxReco.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PTMaxReco.h index 7d701f9871b914afa5ef595750ca54740e96bf5a..b4b0239c7e945e49607d134021a1b92a4c553a08 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PTMaxReco.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PTMaxReco.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef PTMAXRECO_H_ #define PTMAXRECO_H_ @@ -10,27 +10,26 @@ #include "TLorentzVector.h" namespace top { -class Event; + class Event; /** * @brief Not complete. Work in progress */ -class PTMaxReco : public EventSelectorBase { -public: + class PTMaxReco: public EventSelectorBase { + public: PTMaxReco(); virtual ~PTMaxReco(); bool apply(const top::Event&) const override; - std::string name() const { return "RECO:PTMAX"; } - -private: - TLorentzVector neutrinoCandidate(const TLorentzVector& lep, const xAOD::MissingET& met, bool dealWithNegative_nu) const; + std::string name() const override {return "RECO:PTMAX";} + private: + TLorentzVector neutrinoCandidate(const TLorentzVector& lep, const xAOD::MissingET& met, + bool dealWithNegative_nu) const; double m_wmass; double m_topmass; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopReco.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopReco.h index 0b5ea4b5a0bb3b2ca1ae25d89c23eecb499f9429..f6b2636066fca533c4d485e158c1871d7fb035d0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopReco.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopReco.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPEVENTRECONSTRCUTIONTOOLS_PSEUDOTOPRECO_H @@ -19,77 +19,74 @@ #include <memory> - /// - /// @translated by A.Knue from MAMbo tool, Link: https://twiki.cern.ch/twiki/bin/view/Main/MAMbo - /// - /// @brief use PseudoTop definitions to reconstruct tttbar event - /// - -namespace PseudoTopReco{ +/// +/// @translated by A.Knue from MAMbo tool, Link: https://twiki.cern.ch/twiki/bin/view/Main/MAMbo +/// +/// @brief use PseudoTop definitions to reconstruct tttbar event +/// + +namespace PseudoTopReco { class Particles; } -namespace top{ +namespace top { class Event; class TopConfig; - - enum LeptonType{kElectron, kMuon}; - - class PseudoTopReco final : public asg::AsgTool { - - public: - /// Constructor - explicit PseudoTopReco( const std::string& name ); - /// Destructor - virtual ~PseudoTopReco(){} - - /// Function initialising the tool - virtual StatusCode initialize(); - /// Function executing the tool - virtual StatusCode execute(const top::Event&); - - virtual StatusCode execute(const top::ParticleLevelEvent& plEvent); - - /// Function finalizing the tool - virtual StatusCode finalize(); - - // fill first all four vectors to use for the reconstruction - bool SetChargedLeptonInfo(const top::Event& event); - bool SetJetInfo(const top::Event& event); - - bool SetChargedLeptonInfo(const top::ParticleLevelEvent& plEvent); - bool SetJetInfo(const top::ParticleLevelEvent& plEvent); - - bool RunReconstruction(); - - bool ReconstructLeptonicW(); - - private: - - // config file - std::shared_ptr<top::TopConfig> m_config; - float m_bTagCutValue; - - std::string m_leptonType; - - std::vector<TLorentzVector> m_bJets; - std::vector<TLorentzVector> m_lightJets; - TLorentzVector m_lepton; - TLorentzVector m_neutrino; - TLorentzVector m_W_lep; - TLorentzVector m_W_had; - TLorentzVector m_b_lep; - TLorentzVector m_b_had; - TLorentzVector m_top_lep; - TLorentzVector m_top_had; - TLorentzVector m_ttbar; - double m_nu_px, m_nu_py, m_nu_pz, m_met_et; - double m_ht,m_R_lb,m_R_Wb_had,m_R_Wb_lep; - - const double KinemEdge = 13.9e6; - const double mWPDG = 80.399; - - + + enum LeptonType { + kElectron, kMuon + }; + + class PseudoTopReco final: public asg::AsgTool { + public: + /// Constructor + explicit PseudoTopReco(const std::string& name); + /// Destructor + virtual ~PseudoTopReco() {} + + /// Function initialising the tool + virtual StatusCode initialize(); + /// Function executing the tool + virtual StatusCode execute(const top::Event&); + + virtual StatusCode execute(const top::ParticleLevelEvent& plEvent); + + /// Function finalizing the tool + virtual StatusCode finalize(); + + // fill first all four vectors to use for the reconstruction + bool SetChargedLeptonInfo(const top::Event& event); + bool SetJetInfo(const top::Event& event); + + bool SetChargedLeptonInfo(const top::ParticleLevelEvent& plEvent); + bool SetJetInfo(const top::ParticleLevelEvent& plEvent); + + bool RunReconstruction(); + + bool ReconstructLeptonicW(); + private: + // config file + std::shared_ptr<top::TopConfig> m_config; + float m_bTagCutValue; + + std::string m_leptonType; + + std::vector<TLorentzVector> m_bJets; + std::vector<TLorentzVector> m_lightJets; + TLorentzVector m_lepton; + TLorentzVector m_neutrino; + TLorentzVector m_W_lep; + TLorentzVector m_W_had; + TLorentzVector m_b_lep; + TLorentzVector m_b_had; + TLorentzVector m_top_lep; + TLorentzVector m_top_had; + TLorentzVector m_ttbar; + double m_nu_px, m_nu_py, m_nu_pz, m_met_et; + double m_ht, m_R_lb, m_R_Wb_had, m_R_Wb_lep; + + const double KinemEdge = 13.9e6; + const double mWPDG = 80.399; }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopRecoRun.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopRecoRun.h index b5c11a73f0b3f3d9f7836e87db47c61d870f967c..b04ddec6572d7d26001f99166c6fc346543d2ab0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopRecoRun.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/PseudoTopRecoRun.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPEVENTRECONSTRCUTIONTOOLS_PSEUDOTOPRECORUN_H #define ANALYSISTOP_TOPEVENTRECONSTRCUTIONTOOLS_PSEUDOTOPRECORUN_H @@ -8,26 +8,24 @@ #include "TopEventSelectionTools/EventSelectorBase.h" #include "TopEventReconstructionTools/PseudoTopReco.h" -namespace top{ +namespace top { class Event; class TopConfig; - - class PseudoTopRecoRun : public EventSelectorBase { - public: + + class PseudoTopRecoRun: public EventSelectorBase { + public: PseudoTopRecoRun(const std::string& kLeptonType, std::shared_ptr<top::TopConfig> config); - virtual ~PseudoTopRecoRun(){} - + virtual ~PseudoTopRecoRun() {} + virtual bool apply(const top::Event&) const override; virtual bool applyParticleLevel(const top::ParticleLevelEvent& plEvent) const override; - std::string name() const; - + std::string name() const override; private: std::string m_name; - + std::unique_ptr<top::PseudoTopReco> m_PseudoTopReco; - }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Sonnenschein.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Sonnenschein.h index d9882e2d94b0259a6941e2270a222ab43672749a..c56e663b3336d3ac0aebd702e98ec91aefbee6c3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Sonnenschein.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/Sonnenschein.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SONNENSCHEIN_H_ #define SONNENSCHEIN_H_ @@ -11,27 +11,26 @@ #include "TLorentzVector.h" namespace top { -class Event; + class Event; /** * @brief An AnalysisTop friendly wrapper for the Sonnenschein reconstruction * that is implemented in SonnenscheinEngine. */ -class Sonnenschein : public EventSelectorBase { -public: + class Sonnenschein: public EventSelectorBase { + public: Sonnenschein(); virtual ~Sonnenschein(); virtual bool apply(const top::Event&) const override; - std::string name() const { return "RECO:SONNENSCHEIN"; } - -private: - bool tWb(const top::Event& event, int start, TLorentzVector& t, TLorentzVector& W, TLorentzVector& b, TLorentzVector& l, TLorentzVector& nu) const; + std::string name() const override {return "RECO:SONNENSCHEIN";} + private: + bool tWb(const top::Event& event, int start, TLorentzVector& t, TLorentzVector& W, TLorentzVector& b, + TLorentzVector& l, TLorentzVector& nu) const; top::SonnenscheinEngine m_sonn; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/SonnenscheinEngine.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/SonnenscheinEngine.h index 564bc251970186df96ff14649d9f34dc612405c5..537c36abef0bb19b15d39636ae71c7452833e598 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/SonnenscheinEngine.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/SonnenscheinEngine.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SONNENSCEINENGINE_H_ #define SONNENSCEINENGINE_H_ @@ -12,7 +12,6 @@ #include "TLorentzVector.h" namespace top { - /** * @brief Rewrite the top and anti-top decays as a quartic polynomial using top * and W mass constraints. And solve. @@ -22,8 +21,8 @@ namespace top { * and returns the neutrino Lorentz vectors for both neutrinos in the event. * */ -class SonnenscheinEngine { -public: + class SonnenscheinEngine { + public: /** * @brief Does nothing except sets the default flag to false. */ @@ -46,9 +45,12 @@ public: * function you assumed a lepton-b pairing, so if you want to try the other * one you'll have to call it again with the b and bbar swapped or something. */ - std::vector<std::pair<TLorentzVector, TLorentzVector> > solve(const TLorentzVector& me_t_lp, const TLorentzVector& me_t_b, double mass_t, double mass_wp, const TLorentzVector& me_tbar_lm, const TLorentzVector& me_tbar_bbar, double mass_tbar, double mass_wm, double me_mex, double me_mey) const; - -private: + std::vector<std::pair<TLorentzVector, TLorentzVector> > solve(const TLorentzVector& me_t_lp, + const TLorentzVector& me_t_b, double mass_t, + double mass_wp, const TLorentzVector& me_tbar_lm, + const TLorentzVector& me_tbar_bbar, double mass_tbar, + double mass_wm, double me_mex, double me_mey) const; + private: /** * @brief Solve a quartic. * @@ -90,8 +92,7 @@ private: ///Print a load of debug information (probably not by default, right)? bool m_debug; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TopEventReconstructionToolsLoader.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TopEventReconstructionToolsLoader.h index 5f2dd1b0d6dd9bbc9db9fc6e35924472fd8695df..910e1d2b8bb9fa24eacec30e4f745df4043e09cb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TopEventReconstructionToolsLoader.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TopEventReconstructionToolsLoader.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef RECONSTRUCTIONTOOLLOADER_H_ #define RECONSTRUCTIONTOOLLOADER_H_ @@ -8,7 +8,6 @@ #include "TopEventSelectionTools/ToolLoaderBase.h" namespace top { - /** * @brief Load a ttbar event reconstruction code based on the same. * @@ -25,8 +24,8 @@ namespace top { * top::ToolLoaderBase. * */ -class TopEventReconstructionToolsLoader : public ToolLoaderBase { -public: + class TopEventReconstructionToolsLoader: public ToolLoaderBase { + public: /** * @brief Some sort of factory that can create the tool you need given a * string. @@ -38,11 +37,11 @@ public: * @param wk Not used, but needed by EventLoop for some of the selection tools. * @return A pointer to a fully initialised and ready to use tool. */ - top::EventSelectorBase* initTool(const std::string& name, const std::string& line, TFile* outputFile, std::shared_ptr<top::TopConfig> config,EL::Worker* wk = nullptr); + top::EventSelectorBase* initTool(const std::string& name, const std::string& line, TFile* outputFile, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk = nullptr); ClassDef(top::TopEventReconstructionToolsLoader, 0) -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresChi2.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresChi2.h index 1aee478fb6e3e776a36c15f6e0a64fc473970d0f..4ff97c91c0b1ed61b59cb2dd8f1f654e233ee30a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresChi2.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresChi2.h @@ -1,39 +1,49 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TtresChi2_H #define TtresChi2_H -#include<iostream> +#include <iostream> #include <string> #include <vector> #include "TLorentzVector.h" #include "TopEventReconstructionTools/TtresNeutrinoBuilder.h" -class TtresChi2{ - public: - TtresChi2(std::string units="GeV"); +class TtresChi2 { +public: + TtresChi2(std::string units = "GeV"); virtual ~TtresChi2(); - enum WReco {ROTATION, REALPART, DECREASING}; - enum Chi2Version {DATA2011SUMMER2012, DATA2012AUTOMN2012, DATA2012SUMMER2013, DATA2012SUMMER2013PT100}; - enum PtDiff {NOPTDIFF, PTDIFF, PTDIFFREL, PTDIFFMASS}; - enum Btag {STDBTAG, AFFECTBTAG, NO_BTAGHM, NO_BTAG}; - enum RunMode {RUNDEFAULT, RUNSTUDY}; - - private: + enum WReco { + ROTATION, REALPART, DECREASING + }; + enum Chi2Version { + DATA2011SUMMER2012, DATA2012AUTOMN2012, DATA2012SUMMER2013, DATA2012SUMMER2013PT100 + }; + enum PtDiff { + NOPTDIFF, PTDIFF, PTDIFFREL, PTDIFFMASS + }; + enum Btag { + STDBTAG, AFFECTBTAG, NO_BTAGHM, NO_BTAG + }; + enum RunMode { + RUNDEFAULT, RUNSTUDY + }; +private: TtresChi2(const TtresChi2&); - TtresChi2& operator=(const TtresChi2&); + TtresChi2& operator = (const TtresChi2&); std::vector<TLorentzVector*> GetNeutrinos(TLorentzVector*, TLorentzVector*); - double MjjP, SMjjP, m_TopMinusW_had_mean, m_TopMinusW_had_sigma, m_Top_lep_mean, m_Top_lep_sigma, m_PtDiff_mean, m_PtDiff_sigma, m_PtDiffRel_mean, m_PtDiffRel_sigma, m_PtDiffRelMass_mean, m_PtDiffRelMass_sigma, MTHJJ, STHJJ; - double m_WhChi2Value,m_ThWhChi2Value,m_TlChi2Value,m_PtDiffChi2Value; - int m_debug; + double MjjP, SMjjP, m_TopMinusW_had_mean, m_TopMinusW_had_sigma, m_Top_lep_mean, m_Top_lep_sigma, m_PtDiff_mean, + m_PtDiff_sigma, m_PtDiffRel_mean, m_PtDiffRel_sigma, m_PtDiffRelMass_mean, m_PtDiffRelMass_sigma, MTHJJ, STHJJ; + double m_WhChi2Value, m_ThWhChi2Value, m_TlChi2Value, m_PtDiffChi2Value; + int m_debug; PtDiff m_UsePtDiff; - Btag m_Btag; - WReco m_WReco; + Btag m_Btag; + WReco m_WReco; RunMode m_RunMode; double m_Units; TtresNeutrinoBuilder* m_NeutrinoBuilder; @@ -49,77 +59,81 @@ class TtresChi2{ std::vector < double > m_chi2ThWh_Values; std::vector < double > m_chi2Tl_Values; std::vector < double > m_chi2PtDiff_Values; - + std::vector < double > m_PtDiff_Values; std::vector < double > m_Wh_Values; std::vector < double > m_ThWh_Values; std::vector < double > m_Th_Values; std::vector < double > m_Tl_Values; - + std::vector < int > m_i_Wq1; std::vector < int > m_i_Wq2; std::vector < int > m_i_Thb; std::vector < int > m_i_Tlb; std::vector < int > m_i_n; - + int m_nChi2Values; - - public: +public: void Init(Chi2Version version = DATA2012SUMMER2013, double highJetMass = 60.0); void Reset(); - bool findMinChiSquare_HMelseLM(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); - bool findMinChiSquare_LMelseHM(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); + bool findMinChiSquare_HMelseLM(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, + TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); + bool findMinChiSquare_LMelseHM(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, + TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); - bool findMinChiSquare_AllRanges(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); + bool findMinChiSquare_AllRanges(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, + TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); - bool findMinChiSquare(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, int&, int&, int&, int&, int&, double&, double&, double&); + bool findMinChiSquare(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, + int&, int&, int&, int&, int&, double&, double&, double&); - bool findMinChiSquare_HighMass(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, int&, int&, int&, int&, double&, double&, double&); + bool findMinChiSquare_HighMass(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, + TLorentzVector*, int&, int&, int&, int&, double&, double&, double&); - bool findMinChiSquare_VeryHighMass(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, TLorentzVector*, int&, int&, int&, double&, double&, double&); + bool findMinChiSquare_VeryHighMass(TLorentzVector*, const std::vector<TLorentzVector*>*, const std::vector<bool>*, + TLorentzVector*, int&, int&, int&, double&, double&, double&); - inline void SetDebugMode(bool X){m_debug=X;if(m_debug>2)m_NeutrinoBuilder->setdebuglevel(m_debug);} - inline void SetWReconstruction(WReco X){m_WReco=X;} - inline void SetBtagHandeling(Btag X){m_Btag=X;} + inline void SetDebugMode(bool X) {m_debug = X; if (m_debug > 2) m_NeutrinoBuilder->setdebuglevel(m_debug); } + inline void SetWReconstruction(WReco X) {m_WReco = X;} + inline void SetBtagHandeling(Btag X) {m_Btag = X;} inline void SetHighMThreshold(double highJetMass) {m_highJetMass = highJetMass;} - inline void UsePtDiff(PtDiff X){m_UsePtDiff=X;} - inline void SetRunMode(RunMode X){m_RunMode=X;} - - inline double getResult_Chi2All() {return res_chi2All;} - inline double getResult_Chi2WH() {return res_chi2WH;} - inline double getResult_Chi2TopH() {return res_chi2TopH;} - inline double getResult_Chi2TopL() {return res_chi2TopL;} - inline double getResult_Mtl() {return res_Mtl;} - inline double getResult_Mwh() {return res_Mwh;} - inline double getResult_Mth() {return res_Mth;} - inline double getResult_Mtt() {return res_Mtt;} - - inline std::vector < double > getAllChi2Values() {return m_chi2Values; } - inline std::vector < double > getAllWh_Chi2Values() {return m_chi2Wh_Values; } - inline std::vector < double > getAllTh_Chi2Values() {return m_chi2Th_Values; } - inline std::vector < double > getAllThWh_Chi2Values() {return m_chi2ThWh_Values; } - inline std::vector < double > getAllTl_Chi2Values() {return m_chi2Tl_Values; } - inline std::vector < double > getAllPtDiff_Chi2Values() {return m_chi2PtDiff_Values;} - inline std::vector < int > getAllIndicesWq1() {return m_i_Wq1; } - inline std::vector < int > getAllIndicesWq2() {return m_i_Wq2; } - inline std::vector < int > getAllIndicesThb() {return m_i_Thb; } - inline std::vector < int > getAllIndicesTlb() {return m_i_Tlb; } - inline std::vector < int > getAllIndicesN() {return m_i_n; } - - inline std::vector < double > getAllPtDiff_Values() {return m_PtDiff_Values; } - inline std::vector < double > getAllWh_Values() {return m_Wh_Values; } - inline std::vector < double > getAllThWh_Values() {return m_ThWh_Values; } - inline std::vector < double > getAllTh_Values() {return m_Th_Values; } - inline std::vector < double > getAllTl_Values() {return m_Tl_Values; } - - inline double getWhChi2Value() {return m_WhChi2Value; } - inline double getThWhChi2Value() {return m_ThWhChi2Value;} - inline double getTlChi2Value() {return m_TlChi2Value; } - inline double getPtDiffChi2Value() {return m_PtDiffChi2Value;} - inline int getNChi2Values() {return m_nChi2Values; } - inline int getCategory() {return m_category; } - inline TLorentzVector getResult_Tlv() {return res_Tt; } - + inline void UsePtDiff(PtDiff X) {m_UsePtDiff = X;} + inline void SetRunMode(RunMode X) {m_RunMode = X;} + + inline double getResult_Chi2All() {return res_chi2All;} + inline double getResult_Chi2WH() {return res_chi2WH;} + inline double getResult_Chi2TopH() {return res_chi2TopH;} + inline double getResult_Chi2TopL() {return res_chi2TopL;} + inline double getResult_Mtl() {return res_Mtl;} + inline double getResult_Mwh() {return res_Mwh;} + inline double getResult_Mth() {return res_Mth;} + inline double getResult_Mtt() {return res_Mtt;} + + inline std::vector < double > getAllChi2Values() {return m_chi2Values;} + inline std::vector < double > getAllWh_Chi2Values() {return m_chi2Wh_Values;} + inline std::vector < double > getAllTh_Chi2Values() {return m_chi2Th_Values;} + inline std::vector < double > getAllThWh_Chi2Values() {return m_chi2ThWh_Values;} + inline std::vector < double > getAllTl_Chi2Values() {return m_chi2Tl_Values;} + inline std::vector < double > getAllPtDiff_Chi2Values() {return m_chi2PtDiff_Values;} + inline std::vector < int > getAllIndicesWq1() {return m_i_Wq1;} + inline std::vector < int > getAllIndicesWq2() {return m_i_Wq2;} + inline std::vector < int > getAllIndicesThb() {return m_i_Thb;} + inline std::vector < int > getAllIndicesTlb() {return m_i_Tlb;} + inline std::vector < int > getAllIndicesN() {return m_i_n;} + + inline std::vector < double > getAllPtDiff_Values() {return m_PtDiff_Values;} + inline std::vector < double > getAllWh_Values() {return m_Wh_Values;} + inline std::vector < double > getAllThWh_Values() {return m_ThWh_Values;} + inline std::vector < double > getAllTh_Values() {return m_Th_Values;} + inline std::vector < double > getAllTl_Values() {return m_Tl_Values;} + + inline double getWhChi2Value() {return m_WhChi2Value;} + inline double getThWhChi2Value() {return m_ThWhChi2Value;} + inline double getTlChi2Value() {return m_TlChi2Value;} + inline double getPtDiffChi2Value() {return m_PtDiffChi2Value;} + inline int getNChi2Values() {return m_nChi2Values;} + inline int getCategory() {return m_category;} + inline TLorentzVector getResult_Tlv() {return res_Tt;} }; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresNeutrinoBuilder.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresNeutrinoBuilder.h index bc6ddbec57b7aab422b4349a291a461a24d63793..a2e7cbd70fd4309b5c29014b79c572e3080195da 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresNeutrinoBuilder.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresNeutrinoBuilder.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TtresNeutrinoBuilder_H #define TtresNeutrinoBuilder_H 1 @@ -14,14 +14,13 @@ #include <TUUID.h> class TtresNeutrinoBuilder { - - public: +public: TtresNeutrinoBuilder(std::string units); virtual ~TtresNeutrinoBuilder(); TtresNeutrinoBuilder(const TtresNeutrinoBuilder&); - TtresNeutrinoBuilder& operator=(const TtresNeutrinoBuilder&); + TtresNeutrinoBuilder& operator = (const TtresNeutrinoBuilder&); - inline void setdebuglevel(int level){m_debug = level;}; + inline void setdebuglevel(int level) {m_debug = level;}; Double_t getDiscriminant(const TLorentzVector*, const Double_t, const Double_t); // In case of negative discriminant, decrease the MET @@ -29,17 +28,17 @@ class TtresNeutrinoBuilder { std::vector<TLorentzVector*> candidatesFromWMass_Scaling(const TLorentzVector*, const Double_t, const Double_t); std::vector<TLorentzVector*> candidatesFromWMass_Scaling(const TLorentzVector*, const TLorentzVector*); // In case of negative discriminant, rotate the MET - std::vector<TLorentzVector*> candidatesFromWMass_Rotation(const TLorentzVector*, const Double_t, const Double_t, const bool); - std::vector<TLorentzVector*> candidatesFromWMass_Rotation(const TLorentzVector*, const TLorentzVector*, const bool); + std::vector<TLorentzVector*> candidatesFromWMass_Rotation(const TLorentzVector*, const Double_t, const Double_t, + const bool); + std::vector<TLorentzVector*> candidatesFromWMass_Rotation(const TLorentzVector*, const TLorentzVector*, const bool); // In case of negative discriminant, use the real part - std::vector<TLorentzVector*> candidatesFromWMass_RealPart(const TLorentzVector*, const Double_t, const Double_t, const bool); - std::vector<TLorentzVector*> candidatesFromWMass_RealPart(const TLorentzVector*, const TLorentzVector*, const bool); - - protected: + std::vector<TLorentzVector*> candidatesFromWMass_RealPart(const TLorentzVector*, const Double_t, const Double_t, + const bool); + std::vector<TLorentzVector*> candidatesFromWMass_RealPart(const TLorentzVector*, const TLorentzVector*, const bool); +protected: double fitAlpha(const TLorentzVector*, const Double_t, const Double_t); int m_debug; double m_Units; - }; #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresdRmin.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresdRmin.h index 06bd7b2506ae6d4f5bbed953e977fa15dc6359d7..3014172d3c3ad113119669fe194d77170d7de315 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresdRmin.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/TopEventReconstructionTools/TtresdRmin.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TtresdRmin_H #define TtresdRmin_H @@ -13,14 +13,10 @@ using namespace std; class TtresdRmin { - - ///////////////////////////////////////////////////////////////////////////////////////////// // public ///////////////////////////////////////////////////////////////////////////////////////////// - - public: - +public: /** * Class constructor. Set unit used in four momentum vector calculations * @param units : Unit used for reconstruction, MeV or GeV @@ -44,7 +40,8 @@ class TtresdRmin { * @param dRCutMassFactor : Factor applied to jet mass in dRmin specific cut * @return void */ - void Init(double highJetMass = 60.0, double minJetPt = 25.0, double dRCutOffset = 2.5, double dRCutMassFactor = 0.015); + void Init(double highJetMass = 60.0, double minJetPt = 25.0, double dRCutOffset = 2.5, + double dRCutMassFactor = 0.015); /** @@ -55,35 +52,35 @@ class TtresdRmin { * @param neutrino : Reconstructed neutrino * @return bool : Success of setup */ - bool SetupEvent(vector<TLorentzVector*> &jets, TLorentzVector &lepton, TLorentzVector &neutrino); + bool SetupEvent(vector<TLorentzVector*>& jets, TLorentzVector& lepton, TLorentzVector& neutrino); /** * Get jet indicices identified by dRmin method, used for mtt reconstruction * @return vector<int> : Indices of identified jets in passed jet vector */ - inline vector<int> GetJetIndices() { return m_jet_indices; }; + inline vector<int> GetJetIndices() {return m_jet_indices;}; /** * Get index of jet with highest mass * @return int : jet index */ - inline int GetHighMassJetIndex() { return m_highMassJetIndex; }; + inline int GetHighMassJetIndex() {return m_highMassJetIndex;}; /** * Get highest jet mass found in jet vector * @return double : jet mass */ - inline double GetHighestJetMass() { return m_highestJetMass; }; + inline double GetHighestJetMass() {return m_highestJetMass;}; /** * Set threshold for highMass case * @param highJetMass threshold for the high jet mass case */ - inline void SetHighMThreshold(double highJetMass) { m_highM = highJetMass; }; + inline void SetHighMThreshold(double highJetMass) {m_highM = highJetMass;}; /** @@ -101,8 +98,7 @@ class TtresdRmin { ///////////////////////////////////////////////////////////////////////////////////////////// // private ///////////////////////////////////////////////////////////////////////////////////////////// - - private: +private: /** * Find the jet indices used for mtt reconstruction for events containing a high mass jet * @return bool : success of function @@ -116,16 +112,16 @@ class TtresdRmin { */ bool FindJetIndices_LM(); - bool m_init; ///< Flag of initialization status of tool - bool m_verbose; ///< Flag for verbosity level - double m_highM; ///< Jet mass threshold to identify it as a "high mass jet" - double m_Units; ///< Unit factor used, GeV = 1, MeV = 1000 - double m_minJetPt; ///< Minimum jet pT used for highM jet search - double m_dRCutOffset; ///< Offset of dRmin specific cut on jet_dR - double m_dRCutMassFactor; ///< Jet mass factor of dRmin specific cut on jet_dR + bool m_init; ///< Flag of initialization status of tool + bool m_verbose; ///< Flag for verbosity level + double m_highM; ///< Jet mass threshold to identify it as a "high mass jet" + double m_Units; ///< Unit factor used, GeV = 1, MeV = 1000 + double m_minJetPt; ///< Minimum jet pT used for highM jet search + double m_dRCutOffset; ///< Offset of dRmin specific cut on jet_dR + double m_dRCutMassFactor; ///< Jet mass factor of dRmin specific cut on jet_dR - int m_highMassJetIndex; ///< Index of highest mass jet for current event - double m_highestJetMass; ///< Highest jet mass found for current event + int m_highMassJetIndex; ///< Index of highest mass jet for current event + double m_highestJetMass; ///< Highest jet mass found for current event vector<TLorentzVector*> m_jets; ///< Input vector of jet objects TLorentzVector m_lepton; ///< Input lepton object @@ -133,7 +129,6 @@ class TtresdRmin { TLorentzVector m_Wleptonic; ///< leptonic W object reconstructed from lepton and neutrino vector<int> m_jet_indices; ///< Indices of jets used for reconstruction of invariant ttbar mass - }; #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/util/topreco_test_mt2.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/util/topreco_test_mt2.cxx index 55e00f281b2f84acb7f139c79402c327b14400ce..144400c36be3808f79750da0e0fdc348b02c9e78 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/util/topreco_test_mt2.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools/util/topreco_test_mt2.cxx @@ -1,10 +1,10 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include <iostream> -#include "RootCore/Packages.h" +//#include "RootCore/Packages.h" #ifdef ROOTCORE_PACKAGE_Oxbridgekinetics #include "Mt2/Basic_Mt2_332_Calculator.h" @@ -14,22 +14,21 @@ #endif int main() { - #ifndef ROOTCORE_PACKAGE_Oxbridgekinetics - std::cout << "Oxbridgekinetics library not found when compiling" << std::endl; + std::cout << "Oxbridgekinetics library not found when compiling" << std::endl; #else - std::cout << "Starting top mt2 test\n"; - Mt2::LorentzTransverseVector a; - Mt2::LorentzTransverseVector b; - Mt2::TwoVector c; - double d = 0.; + std::cout << "Starting top mt2 test\n"; + Mt2::LorentzTransverseVector a; + Mt2::LorentzTransverseVector b; + Mt2::TwoVector c; + double d = 0.; - Mt2::Basic_Mt2_332_Calculator mt2Calculator; - const double mt2 = mt2Calculator.mt2_332( a, b, c, d); + Mt2::Basic_Mt2_332_Calculator mt2Calculator; + const double mt2 = mt2Calculator.mt2_332(a, b, c, d); - std::cout << "mt2 " << mt2 << std::endl; - std::cout << "Ending\n"; + std::cout << "mt2 " << mt2 << std::endl; + std::cout << "Ending\n"; #endif - return 0; + return 0; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/CMakeLists.txt index 3413593ed74b58b021ca87770a9512e41aca9207..9c4ed1d2e3606c99f09b24cd74ecdc3addd88dc3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopEventSelectionTools ) @@ -10,16 +9,16 @@ atlas_depends_on_subdirs( PUBLIC TopEvent TopCorrections TopParticleLevel - MuonSelectorTools ) + TriggerAnalysisInterfaces + JetSelectorTools ) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopEventSelectionTools _cintDictSource - ROOT_HEADERS TopEventSelectionTools/ToolLoaderBase.h - TopEventSelectionTools/TopEventSelectionToolsLoader.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopEventSelectionTools Root/*.cxx Root/*.h Root/*.icc @@ -32,7 +31,7 @@ atlas_add_library( TopEventSelectionTools Root/*.cxx Root/*.h Root/*.icc TopEvent TopCorrections TopParticleLevel - MuonSelectorToolsLib + JetSelectorToolsLib ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ExamplePlots.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ExamplePlots.cxx index 6cabee37f80f876d3ef34c8d4dc861d4224d4dd1..4644e3108051a8dbc6891f0cf914d680eaa2dd9a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ExamplePlots.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ExamplePlots.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/ExamplePlots.h" @@ -19,14 +19,13 @@ #include "PATInterfaces/SystematicSet.h" namespace top { + const double ExamplePlots::toGeV = 0.001; -const double ExamplePlots::toGeV = 0.001; - - ExamplePlots::ExamplePlots(const std::string& name, TFile* outputFile, EL::Worker* wk, std::shared_ptr<top::TopConfig> config) : + ExamplePlots::ExamplePlots(const std::string& name, TFile* outputFile, EL::Worker* wk, + std::shared_ptr<top::TopConfig> config) : m_hists(name, outputFile, wk), m_nominalHashValue(0) { - m_config = config; - CP::SystematicSet nominal; + CP::SystematicSet nominal; m_nominalHashValue = nominal.hash(); m_hists.addHist("event_mu", ";<#mu>;Events", 25, 0., 50.); @@ -85,9 +84,8 @@ const double ExamplePlots::toGeV = 0.001; m_hists.addHist("jet_mv2c10", ";Jet mv2c10;Jets", 20, -1., 1.); if (m_config->isMC()) { m_hists.addHist("jet_truthflav", ";Jet truth flavor;Jets", 20, 0., 20.); - m_hists.addHist("jet_btagSF_77", ";Jet btag SF;Jets", 100, 0.5, 1.5); + m_hists.addHist("jet_btagSF_MV2c10_77", ";Jet btag SF;Jets", 100, 0.5, 1.5); } - m_hists.addHist("jet_isbtagged_77", ";Jet is b-tagged;Jets", 2, 0., 2.); m_hists.addHist("jet0_pt", ";Jet0 p_{T} / GeV; Events / 10 GeV", 25, 5, 505); m_hists.addHist("jet0_eta", ";Jet0 #eta; Jets", 25, -2.5, 2.5); @@ -96,9 +94,9 @@ const double ExamplePlots::toGeV = 0.001; m_hists.addHist("jet0_mv2c10", ";Jet0 mv2c10; Jets", 50, 0, 1); if (m_config->isMC()) { m_hists.addHist("jet0_truthflav", ";Jet0 truth flavor;Jets", 20, 0., 20.); - m_hists.addHist("jet0_btagSF_77", ";Jet0 btag SF;Jets", 100, 0.5, 1.5); + m_hists.addHist("jet0_btagSF_MV2c10_77", ";Jet0 btag SF;Jets", 100, 0.5, 1.5); } - m_hists.addHist("jet0_isbtagged_77", ";Jet is b-tagged;Jets", 2, 0., 2.); + m_hists.addHist("jet0_isbtagged_MV2c10_77", ";Jet is b-tagged;Jets", 2, 0., 2.); m_hists.addHist("jet1_pt", ";Jet1 p_{T} / GeV; Events / 10 GeV", 25, 5, 505); m_hists.addHist("jet1_eta", ";Jet1 #eta; Jets", 25, -2.5, 2.5); @@ -107,9 +105,9 @@ const double ExamplePlots::toGeV = 0.001; m_hists.addHist("jet1_mv2c10", ";Jet1 mv2c10; Jets", 50, 0, 1); if (m_config->isMC()) { m_hists.addHist("jet1_truthflav", ";Jet1 truth flavor;Jets", 20, 0., 20.); - m_hists.addHist("jet1_btagSF_77", ";Jet1 btag SF;Jets", 100, 0.5, 1.5); + m_hists.addHist("jet1_btagSF_MV2c10_77", ";Jet1 btag SF;Jets", 100, 0.5, 1.5); } - m_hists.addHist("jet1_isbtagged_77", ";Jet is b-tagged;Jets", 2, 0., 2.); + m_hists.addHist("jet1_isbtagged_MV2c10_77", ";Jet is b-tagged;Jets", 2, 0., 2.); m_hists.addHist("jet2_pt", ";Jet2 p_{T} / GeV; Events / 10 GeV", 25, 5, 505); m_hists.addHist("jet2_eta", ";Jet2 #eta; Jets", 25, -2.5, 2.5); @@ -118,9 +116,9 @@ const double ExamplePlots::toGeV = 0.001; m_hists.addHist("jet2_mv2c10", ";Jet2 mv2c10; Jets", 50, 0, 1); if (m_config->isMC()) { m_hists.addHist("jet2_truthflav", ";Jet2 truth flavor;Jets", 20, 0., 20.); - m_hists.addHist("jet2_btagSF_77", ";Jet2 btag SF;Jets", 100, 0.5, 1.5); + m_hists.addHist("jet2_btagSF_MV2c10_77", ";Jet2 btag SF;Jets", 100, 0.5, 1.5); } - m_hists.addHist("jet2_isbtagged_77", ";Jet is b-tagged;Jets", 2, 0., 2.); + m_hists.addHist("jet2_isbtagged_MV2c10_77", ";Jet is b-tagged;Jets", 2, 0., 2.); m_hists.addHist("jet3_pt", ";Jet3 p_{T} / GeV; Events / 10 GeV", 25, 5, 505); m_hists.addHist("jet3_eta", ";Jet3 #eta; Jets", 25, -2.5, 2.5); @@ -129,9 +127,9 @@ const double ExamplePlots::toGeV = 0.001; m_hists.addHist("jet3_mv2c10", ";Jet3 mv2c10; Jets", 50, 0, 1); if (m_config->isMC()) { m_hists.addHist("jet3_truthflav", ";Jet3 truth flavor;Jets", 20, 0., 20.); - m_hists.addHist("jet3_btagSF_77", ";Jet3 btag SF;Jets", 100, 0.5, 1.5); + m_hists.addHist("jet3_btagSF_MV2c10_77", ";Jet3 btag SF;Jets", 100, 0.5, 1.5); } - m_hists.addHist("jet3_isbtagged_77", ";Jet is b-tagged;Jets", 2, 0., 2.); + m_hists.addHist("jet3_isbtagged_MV2c10_77", ";Jet is b-tagged;Jets", 2, 0., 2.); //Large-R jet m_hists.addHist("ljet_n", ";Large-R Jet multiplicity; Jets ", 5, 0, 5); @@ -149,247 +147,231 @@ const double ExamplePlots::toGeV = 0.001; m_hists.addHist("event_met_et", ";MET / GeV;Events", 50, 0., 400.); m_hists.addHist("event_met_phi", ";MET #phi;Events", 20, -M_PI, M_PI); -} + } -bool ExamplePlots::apply(const top::Event& event) const { + bool ExamplePlots::apply(const top::Event& event) const { //only nominal - - if (event.m_hashValue != m_nominalHashValue) - return true; + + if (event.m_hashValue != m_nominalHashValue) return true; //only plot tight selection //before, we were plotting tight and loose together - if (event.m_isLoose) - return true; - - //std::cout << event << std::endl; + if (event.m_isLoose) return true; double eventWeight = 1.; - if (top::isSimulation(event)) -// eventWeight = event.m_info->mcEventWeight(); - eventWeight = event.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + if (top::isSimulation(event)) eventWeight = event.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); if (m_config->isMC()) { m_hists.hist("mc_weight")->Fill(eventWeight, eventWeight); m_hists.hist("jvt_SF")->Fill(event.m_jvtSF, eventWeight); //pileup weight needs pileup reweighting tool to have run - if (top::ScaleFactorRetriever::hasPileupSF(event)) - m_hists.hist("pileup_weight")->Fill(top::ScaleFactorRetriever::pileupSF(event), eventWeight); + if (top::ScaleFactorRetriever::hasPileupSF(event)) m_hists.hist("pileup_weight")->Fill(top::ScaleFactorRetriever::pileupSF( + event), eventWeight); } m_hists.hist("event_mu")->Fill(event.m_info->averageInteractionsPerCrossing(), eventWeight); m_hists.hist("el_n")->Fill(event.m_electrons.size(), eventWeight); for (const auto* const elPtr : event.m_electrons) { - m_hists.hist("el_pt") -> Fill(elPtr->pt() * toGeV, eventWeight); - m_hists.hist("el_eta") -> Fill(elPtr->eta(), eventWeight); - m_hists.hist("el_phi") -> Fill(elPtr->phi(), eventWeight); - m_hists.hist("el_charge") -> Fill(elPtr->charge(), eventWeight); + m_hists.hist("el_pt")->Fill(elPtr->pt() * toGeV, eventWeight); + m_hists.hist("el_eta")->Fill(elPtr->eta(), eventWeight); + m_hists.hist("el_phi")->Fill(elPtr->phi(), eventWeight); + m_hists.hist("el_charge")->Fill(elPtr->charge(), eventWeight); - //protection from the derivation framework - - //So far we keep tracks associated with "good" electrons. - //It could be you have a super-loose selection here (just for testing) - //so we need to check if the electron has a track associated with it - if (elPtr->trackParticle()) - m_hists.hist("el_trkpart_charge")->Fill(elPtr->trackParticle()->charge(), eventWeight); + //protection from the derivation framework - + //So far we keep tracks associated with "good" electrons. + //It could be you have a super-loose selection here (just for testing) + //so we need to check if the electron has a track associated with it + if (elPtr->trackParticle()) m_hists.hist("el_trkpart_charge")->Fill(elPtr->trackParticle()->charge(), + eventWeight); - //retrieve the truth-matching variables from MCTruthClassifier - if (m_config->isMC()) { - static SG::AuxElement::Accessor<int> typeel("truthType"); - if (typeel.isAvailable(*elPtr)) m_hists.hist("el_true_type")->Fill(typeel(*elPtr), eventWeight); - } + //retrieve the truth-matching variables from MCTruthClassifier + if (m_config->isMC()) { + static SG::AuxElement::Accessor<int> typeel("truthType"); + if (typeel.isAvailable(*elPtr)) m_hists.hist("el_true_type")->Fill(typeel(*elPtr), eventWeight); + } - //testing isolation in the derivation framework - float iso = 0; + //testing isolation in the derivation framework + float iso = 0; - if (elPtr->isolationValue(iso, xAOD::Iso::topoetcone20)) - m_hists.hist("el_topoetcone20")->Fill(iso * toGeV, eventWeight); + if (elPtr->isolationValue(iso, xAOD::Iso::topoetcone20)) m_hists.hist("el_topoetcone20")->Fill(iso * toGeV, + eventWeight); - if (elPtr->isolationValue(iso, xAOD::Iso::topoetcone30)) - m_hists.hist("el_topoetcone30")->Fill(iso * toGeV, eventWeight); + if (elPtr->isolationValue(iso, xAOD::Iso::topoetcone30)) m_hists.hist("el_topoetcone30")->Fill(iso * toGeV, + eventWeight); - if (elPtr->isolationValue(iso, xAOD::Iso::topoetcone40)) - m_hists.hist("el_topoetcone40")->Fill(iso * toGeV, eventWeight); + if (elPtr->isolationValue(iso, xAOD::Iso::topoetcone40)) m_hists.hist("el_topoetcone40")->Fill(iso * toGeV, + eventWeight); - if (elPtr->isolationValue(iso, xAOD::Iso::ptcone20)) - m_hists.hist("el_ptcone20")->Fill(iso * toGeV, eventWeight); + if (elPtr->isolationValue(iso, xAOD::Iso::ptcone20)) m_hists.hist("el_ptcone20")->Fill(iso * toGeV, eventWeight); - if (elPtr->isolationValue(iso, xAOD::Iso::ptcone30)) - m_hists.hist("el_ptcone30")->Fill(iso * toGeV, eventWeight); + if (elPtr->isolationValue(iso, xAOD::Iso::ptcone30)) m_hists.hist("el_ptcone30")->Fill(iso * toGeV, eventWeight); - if (elPtr->isolationValue(iso, xAOD::Iso::ptcone40)) - m_hists.hist("el_ptcone40")->Fill(iso * toGeV, eventWeight); + if (elPtr->isolationValue(iso, xAOD::Iso::ptcone40)) m_hists.hist("el_ptcone40")->Fill(iso * toGeV, eventWeight); - if (elPtr->isAvailable<float>("ptvarcone20")) { - float ptvarcone20 = elPtr->auxdataConst<float>("ptvarcone20"); - m_hists.hist("el_ptvarcone20")->Fill(ptvarcone20 * toGeV, eventWeight); - } + if (elPtr->isAvailable<float>("ptvarcone20")) { + float ptvarcone20 = elPtr->auxdataConst<float>("ptvarcone20"); + m_hists.hist("el_ptvarcone20")->Fill(ptvarcone20 * toGeV, eventWeight); + } - if (elPtr->isAvailable<float>("ptvarcone30")) { - float ptvarcone30 = elPtr->auxdataConst<float>("ptvarcone30"); - m_hists.hist("el_ptvarcone30")->Fill(ptvarcone30 * toGeV, eventWeight); - } + if (elPtr->isAvailable<float>("ptvarcone30")) { + float ptvarcone30 = elPtr->auxdataConst<float>("ptvarcone30"); + m_hists.hist("el_ptvarcone30")->Fill(ptvarcone30 * toGeV, eventWeight); + } - if (elPtr->isAvailable<float>("ptvarcone40")) { - float ptvarcone40 = elPtr->auxdataConst<float>("ptvarcone40"); - m_hists.hist("el_ptvarcone40")->Fill(ptvarcone40 * toGeV, eventWeight); - } + if (elPtr->isAvailable<float>("ptvarcone40")) { + float ptvarcone40 = elPtr->auxdataConst<float>("ptvarcone40"); + m_hists.hist("el_ptvarcone40")->Fill(ptvarcone40 * toGeV, eventWeight); + } } m_hists.hist("mu_n")->Fill(event.m_muons.size(), eventWeight); for (const auto* const muPtr : event.m_muons) { - m_hists.hist("mu_pt")->Fill(muPtr->pt() * toGeV, eventWeight); - m_hists.hist("mu_eta")->Fill(muPtr->eta(), eventWeight); - m_hists.hist("mu_phi")->Fill(muPtr->phi(), eventWeight); - - //protection from derivation framework removing tracks - const xAOD::TrackParticle* mutrack = muPtr->primaryTrackParticle(); - if (mutrack!=nullptr) { - m_hists.hist("mu_charge")->Fill(mutrack->charge(), eventWeight); - if (m_config->isMC()) { - static SG::AuxElement::Accessor<int> acc_mctt("truthType"); - if (acc_mctt.isAvailable(*mutrack)) m_hists.hist("mu_true_type")->Fill(acc_mctt(*mutrack), eventWeight); - } - } + m_hists.hist("mu_pt")->Fill(muPtr->pt() * toGeV, eventWeight); + m_hists.hist("mu_eta")->Fill(muPtr->eta(), eventWeight); + m_hists.hist("mu_phi")->Fill(muPtr->phi(), eventWeight); + + //protection from derivation framework removing tracks + const xAOD::TrackParticle* mutrack = muPtr->primaryTrackParticle(); + if (mutrack != nullptr) { + m_hists.hist("mu_charge")->Fill(mutrack->charge(), eventWeight); + if (m_config->isMC()) { + static SG::AuxElement::Accessor<int> acc_mctt("truthType"); + if (acc_mctt.isAvailable(*mutrack)) m_hists.hist("mu_true_type")->Fill(acc_mctt(*mutrack), eventWeight); + } + } - //testing isolation in the derivation framework - float iso = 0; + //testing isolation in the derivation framework + float iso = 0; - if (muPtr->isAvailable<float>("topoetcone20") && muPtr->isolation(iso, xAOD::Iso::topoetcone20)) - m_hists.hist("mu_topoetcone20")->Fill(iso * toGeV, eventWeight); + if (muPtr->isAvailable<float>("topoetcone20") && muPtr->isolation(iso, xAOD::Iso::topoetcone20)) m_hists.hist( + "mu_topoetcone20")->Fill(iso * toGeV, eventWeight); - if (muPtr->isAvailable<float>("topoetcone30") && muPtr->isolation(iso, xAOD::Iso::topoetcone30)) - m_hists.hist("mu_topoetcone30")->Fill(iso * toGeV, eventWeight); + if (muPtr->isAvailable<float>("topoetcone30") && muPtr->isolation(iso, xAOD::Iso::topoetcone30)) m_hists.hist( + "mu_topoetcone30")->Fill(iso * toGeV, eventWeight); - if (muPtr->isAvailable<float>("topoetcone40") && muPtr->isolation(iso, xAOD::Iso::topoetcone40)) - m_hists.hist("mu_topoetcone40")->Fill(iso * toGeV, eventWeight); + if (muPtr->isAvailable<float>("topoetcone40") && muPtr->isolation(iso, xAOD::Iso::topoetcone40)) m_hists.hist( + "mu_topoetcone40")->Fill(iso * toGeV, eventWeight); - if (muPtr->isolation(iso, xAOD::Iso::ptcone20)) - m_hists.hist("mu_ptcone20")->Fill(iso * toGeV, eventWeight); + if (muPtr->isolation(iso, xAOD::Iso::ptcone20)) m_hists.hist("mu_ptcone20")->Fill(iso * toGeV, eventWeight); - if (muPtr->isolation(iso, xAOD::Iso::ptcone30)) - m_hists.hist("mu_ptcone30")->Fill(iso * toGeV, eventWeight); + if (muPtr->isolation(iso, xAOD::Iso::ptcone30)) m_hists.hist("mu_ptcone30")->Fill(iso * toGeV, eventWeight); - if (muPtr->isolation(iso, xAOD::Iso::ptcone40)) - m_hists.hist("mu_ptcone40")->Fill(iso * toGeV, eventWeight); + if (muPtr->isolation(iso, xAOD::Iso::ptcone40)) m_hists.hist("mu_ptcone40")->Fill(iso * toGeV, eventWeight); - if (muPtr->isAvailable<float>("ptvarcone20")) { - float ptvarcone20 = muPtr->auxdataConst<float>("ptvarcone20"); - m_hists.hist("mu_ptvarcone20")->Fill(ptvarcone20 * toGeV, eventWeight); - } + if (muPtr->isAvailable<float>("ptvarcone20")) { + float ptvarcone20 = muPtr->auxdataConst<float>("ptvarcone20"); + m_hists.hist("mu_ptvarcone20")->Fill(ptvarcone20 * toGeV, eventWeight); + } - if (muPtr->isAvailable<float>("ptvarcone30")) { - float ptvarcone30 = muPtr->auxdataConst<float>("ptvarcone30"); - m_hists.hist("mu_ptvarcone30")->Fill(ptvarcone30 * toGeV, eventWeight); - } + if (muPtr->isAvailable<float>("ptvarcone30")) { + float ptvarcone30 = muPtr->auxdataConst<float>("ptvarcone30"); + m_hists.hist("mu_ptvarcone30")->Fill(ptvarcone30 * toGeV, eventWeight); + } - if (muPtr->isAvailable<float>("ptvarcone40")) { - float ptvarcone40 = muPtr->auxdataConst<float>("ptvarcone40"); - m_hists.hist("mu_ptvarcone40")->Fill(ptvarcone40 * toGeV, eventWeight); - } + if (muPtr->isAvailable<float>("ptvarcone40")) { + float ptvarcone40 = muPtr->auxdataConst<float>("ptvarcone40"); + m_hists.hist("mu_ptvarcone40")->Fill(ptvarcone40 * toGeV, eventWeight); + } } m_hists.hist("ph_n")->Fill(event.m_photons.size(), eventWeight); for (const auto* const phPtr : event.m_photons) { - m_hists.hist("ph_pt") -> Fill(phPtr->pt() * toGeV, eventWeight); - m_hists.hist("ph_eta") -> Fill(phPtr->eta(), eventWeight); - m_hists.hist("ph_phi") -> Fill(phPtr->phi(), eventWeight); - m_hists.hist("ph_e") -> Fill(phPtr->e() * toGeV, eventWeight); - if (phPtr->isAvailable<float>("ptvarcone20")) { - float ptvarcone20 = phPtr->auxdataConst<float>("ptvarcone20"); - m_hists.hist("ph_ptvarcone20")->Fill(ptvarcone20 * toGeV, eventWeight); - } + m_hists.hist("ph_pt")->Fill(phPtr->pt() * toGeV, eventWeight); + m_hists.hist("ph_eta")->Fill(phPtr->eta(), eventWeight); + m_hists.hist("ph_phi")->Fill(phPtr->phi(), eventWeight); + m_hists.hist("ph_e")->Fill(phPtr->e() * toGeV, eventWeight); + if (phPtr->isAvailable<float>("ptvarcone20")) { + float ptvarcone20 = phPtr->auxdataConst<float>("ptvarcone20"); + m_hists.hist("ph_ptvarcone20")->Fill(ptvarcone20 * toGeV, eventWeight); + } } m_hists.hist("jet_n")->Fill(event.m_jets.size(), eventWeight); unsigned int i = 0; - std::array<std::string, 4> numbers{ {"jet0", "jet1", "jet2", "jet3"} }; + std::array<std::string, 4> numbers {{ + "jet0", "jet1", "jet2", "jet3" + }}; + for (const auto* const jetPtr : event.m_jets) { - m_hists.hist("jet_pt") -> Fill(jetPtr->pt() * toGeV, eventWeight); - m_hists.hist("jet_eta") -> Fill(jetPtr->eta(), eventWeight); - m_hists.hist("jet_phi") -> Fill(jetPtr->phi(), eventWeight); - m_hists.hist("jet_e") -> Fill(jetPtr->e() * toGeV, eventWeight); - - double mv2c10_discriminant = 0.; - const bool hasmv2c10 = jetPtr->btagging()->MVx_discriminant("MV2c10", mv2c10_discriminant); - if (hasmv2c10){ - m_hists.hist("jet_mv2c10")->Fill(mv2c10_discriminant, eventWeight); - - } - - int jet_truthflav = -1; - if (m_config->isMC()) { - if(jetPtr->isAvailable<int>("HadronConeExclTruthLabelID")){ - jetPtr->getAttribute("HadronConeExclTruthLabelID", jet_truthflav); - m_hists.hist("jet_truthflav")->Fill(jet_truthflav, eventWeight); - } - } - - int isbtagged = 0; - bool hasBtag = false; - float btagSF = 1.; - bool hasBtagSF = false; - hasBtag = jetPtr->isAvailable<char>("isbtagged_FixedCutBEff_77"); - if(hasBtag) { - isbtagged = jetPtr->auxdataConst<char>("isbtagged_FixedCutBEff_77"); - m_hists.hist("jet_isbtagged_77")->Fill(isbtagged, eventWeight); - if (m_config->isMC()) { - if (jetPtr -> isAvailable<float>("btag_SF_FixedCutBEff_77_nom")) { - btagSF = jetPtr -> auxdataConst<float>("btag_SF_FixedCutBEff_77_nom"); - m_hists.hist("jet_btagSF_77")->Fill(btagSF, eventWeight); - hasBtagSF = true; - } + m_hists.hist("jet_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); + m_hists.hist("jet_eta")->Fill(jetPtr->eta(), eventWeight); + m_hists.hist("jet_phi")->Fill(jetPtr->phi(), eventWeight); + m_hists.hist("jet_e")->Fill(jetPtr->e() * toGeV, eventWeight); + + double mv2c10_discriminant = 0.; + int jet_truthflav = -1; + if (m_config->isMC()) { + if (jetPtr->isAvailable<int>("HadronConeExclTruthLabelID")) { + jetPtr->getAttribute("HadronConeExclTruthLabelID", jet_truthflav); + m_hists.hist("jet_truthflav")->Fill(jet_truthflav, eventWeight); + } + } + + int isbtagged = 0; + bool hasBtag = false; + float btagSF = 1.; + bool hasBtagSF = false; + hasBtag = jetPtr->isAvailable<char>("isbtagged_MV2c10_FixedCutBEff_77"); + if (hasBtag) { + isbtagged = jetPtr->auxdataConst<char>("isbtagged_MV2c10_FixedCutBEff_77"); + m_hists.hist("jet_isbtagged_MV2c10_77")->Fill(isbtagged, eventWeight); + if (m_config->isMC()) { + if (jetPtr->isAvailable<float>("btag_SF_MV2c10_FixedCutBEff_77_nom")) { + btagSF = jetPtr->auxdataConst<float>("btag_SF_MV2c10_FixedCutBEff_77_nom"); + m_hists.hist("jet_btagSF_MV2c10_77")->Fill(btagSF, eventWeight); + hasBtagSF = true; } } - - if (i < numbers.size()) { - m_hists.hist(numbers[i] + "_pt") -> Fill(jetPtr->pt() * toGeV, eventWeight); - m_hists.hist(numbers[i] + "_eta") -> Fill(jetPtr->eta(), eventWeight); - m_hists.hist(numbers[i] + "_phi") -> Fill(jetPtr->phi(), eventWeight); - m_hists.hist(numbers[i] + "_e") -> Fill(jetPtr->e() * toGeV, eventWeight); - m_hists.hist(numbers[i] + "_mv2c10") -> Fill(mv2c10_discriminant, eventWeight); - if(hasBtag) m_hists.hist(numbers[i] + "_isbtagged_77")->Fill(isbtagged, eventWeight); - if (m_config->isMC()) { - if (hasBtagSF) m_hists.hist(numbers[i] + "_btagSF_77")->Fill(btagSF, eventWeight); - m_hists.hist(numbers[i] + "_truthflav")->Fill(jet_truthflav, eventWeight); - } + } + + if (i < numbers.size()) { + m_hists.hist(numbers[i] + "_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); + m_hists.hist(numbers[i] + "_eta")->Fill(jetPtr->eta(), eventWeight); + m_hists.hist(numbers[i] + "_phi")->Fill(jetPtr->phi(), eventWeight); + m_hists.hist(numbers[i] + "_e")->Fill(jetPtr->e() * toGeV, eventWeight); + m_hists.hist(numbers[i] + "_mv2c10")->Fill(mv2c10_discriminant, eventWeight); + if (hasBtag) m_hists.hist(numbers[i] + "_isbtagged_MV2c10_77")->Fill(isbtagged, eventWeight); + if (m_config->isMC()) { + if (hasBtagSF) m_hists.hist(numbers[i] + "_btagSF_MV2c10_77")->Fill(btagSF, eventWeight); + m_hists.hist(numbers[i] + "_truthflav")->Fill(jet_truthflav, eventWeight); } + } - ++i; + + ++i; } - m_hists.hist("ljet_n") -> Fill(event.m_largeJets.size(), eventWeight); + m_hists.hist("ljet_n")->Fill(event.m_largeJets.size(), eventWeight); for (const auto* const jetPtr : event.m_largeJets) { - m_hists.hist("ljet_pt") -> Fill(jetPtr->pt() * toGeV, eventWeight); - m_hists.hist("ljet_eta") -> Fill(jetPtr->eta(), eventWeight); - m_hists.hist("ljet_phi") -> Fill(jetPtr->phi(), eventWeight); - m_hists.hist("ljet_m") -> Fill(jetPtr->m() * toGeV, eventWeight); - - float Split12 = 0; - jetPtr->getAttribute("Split12", Split12); - m_hists.hist("ljet_sd12") -> Fill(Split12 * toGeV, eventWeight); - + m_hists.hist("ljet_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); + m_hists.hist("ljet_eta")->Fill(jetPtr->eta(), eventWeight); + m_hists.hist("ljet_phi")->Fill(jetPtr->phi(), eventWeight); + m_hists.hist("ljet_m")->Fill(jetPtr->m() * toGeV, eventWeight); + + float Split12 = 0; + jetPtr->getAttribute("Split12", Split12); + m_hists.hist("ljet_sd12")->Fill(Split12 * toGeV, eventWeight); } m_hists.hist("taujet_n")->Fill(event.m_tauJets.size(), eventWeight); for (const auto* const tauPtr : event.m_tauJets) { - m_hists.hist("taujet_pt") -> Fill(tauPtr->pt() * toGeV, eventWeight); - m_hists.hist("taujet_eta") -> Fill(tauPtr->eta(), eventWeight); - m_hists.hist("taujet_phi") -> Fill(tauPtr->phi(), eventWeight); - m_hists.hist("taujet_charge") -> Fill(tauPtr->charge(), eventWeight); + m_hists.hist("taujet_pt")->Fill(tauPtr->pt() * toGeV, eventWeight); + m_hists.hist("taujet_eta")->Fill(tauPtr->eta(), eventWeight); + m_hists.hist("taujet_phi")->Fill(tauPtr->phi(), eventWeight); + m_hists.hist("taujet_charge")->Fill(tauPtr->charge(), eventWeight); } if (event.m_met != nullptr) { - m_hists.hist("event_met_et") -> Fill(event.m_met->met() * toGeV, eventWeight); - m_hists.hist("event_met_phi") -> Fill(event.m_met->phi(), eventWeight); + m_hists.hist("event_met_et")->Fill(event.m_met->met() * toGeV, eventWeight); + m_hists.hist("event_met_phi")->Fill(event.m_met->phi(), eventWeight); } return true; -} + } -std::string ExamplePlots::name() const { + std::string ExamplePlots::name() const { return "EXAMPLEPLOTS"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/FakesMMConfigs.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/FakesMMConfigs.cxx index d133f58b075114ec17c23ae1a46b249bbde3b48e..f47167d4067864516e02af5248305c480ce7515d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/FakesMMConfigs.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/FakesMMConfigs.cxx @@ -1,15 +1,14 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/FakesMMConfigs.h" namespace top { - FakesMMConfigs::FakesMMConfigs(const std::string& configs) { std::istringstream iss(configs); std::string config; - while (iss>>config) { + while (iss >> config) { m_configurations.push_back(config); } } @@ -21,5 +20,4 @@ namespace top { std::string FakesMMConfigs::name() const { return "FAKESMMCONFIGS"; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GRLSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GRLSelector.cxx index 91a261bed8ea8f1f69faaaf2458428823c835329..3b91c04c15baeeeb2ef9a5d4294b164167d0ecd7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GRLSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GRLSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/GRLSelector.h" @@ -9,13 +9,10 @@ #include "xAODEventInfo/EventInfo.h" namespace top { - - GRLSelector::GRLSelector() - { + GRLSelector::GRLSelector() { } - bool GRLSelector::apply(const top::Event& event) const - { + bool GRLSelector::apply(const top::Event& event) const { if (event.m_info->isAvailable<char>("AnalysisTop_GRL")) { if (event.m_info->auxdataConst<char>("AnalysisTop_GRL") == 1) { return true; @@ -24,9 +21,7 @@ namespace top { return false; } - std::string GRLSelector::name() const - { + std::string GRLSelector::name() const { return "GRL"; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GlobalTrigDecisionSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GlobalTrigDecisionSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..c91dea599d4d9667827810c20b2c5075a3efd272 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GlobalTrigDecisionSelector.cxx @@ -0,0 +1,33 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/GlobalTrigDecisionSelector.h" +#include "TopEvent/Event.h" +#include "TopEvent/EventTools.h" + +#include <vector> +#include <iostream> + + +namespace top { + GlobalTrigDecisionSelector::GlobalTrigDecisionSelector() + : m_globalTriggerSF("TrigGlobalEfficiencyCorrectionTool::TrigGlobal") + , m_globalTriggerSFLoose("TrigGlobalEfficiencyCorrectionTool::TrigGlobalLoose") { + } + + bool GlobalTrigDecisionSelector::apply(top::Event const& event) const { + //auto&& tool = (event.m_isLoose ? m_globalTriggerSFLoose : m_globalTriggerSF); + + std::vector<std::string> triggers; +// top::check(tool->getRelevantTriggers(triggers), "TrigGlobalEfficiencyCorrectionTool::getRelevantTriggers failed"); + for (std::string const& trigger : triggers) { + if (event.m_info->auxdataConst<char>("TRIGDEC_HLT_" + trigger) > 0) return true; + } + return false; + } + + std::string GlobalTrigDecisionSelector::name() const { + return "GTRIGDEC"; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GlobalTrigMatchSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GlobalTrigMatchSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..750fa58cf2da609f8b20e62390944858b2b4439c --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GlobalTrigMatchSelector.cxx @@ -0,0 +1,39 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/GlobalTrigMatchSelector.h" +#include "TopEvent/Event.h" +#include "TopEvent/EventTools.h" + +#include "xAODBase/IParticle.h" +#include "xAODEgamma/ElectronContainer.h" +#include "xAODMuon/MuonContainer.h" + +#include <iostream> +#include <vector> + + +namespace top { + GlobalTrigMatchSelector::GlobalTrigMatchSelector() + : m_globalTriggerSF("TrigGlobalEfficiencyCorrectionTool::TrigGlobal") + , m_globalTriggerSFLoose("TrigGlobalEfficiencyCorrectionTool::TrigGlobalLoose") { + } + + bool GlobalTrigMatchSelector::apply(top::Event const& event) const { +// auto&& tool = (event.m_isLoose ? m_globalTriggerSFLoose : m_globalTriggerSF); + bool result = false; + + std::vector<xAOD::IParticle const*> particles; + particles.insert(particles.end(), event.m_electrons.begin(), event.m_electrons.end()); + particles.insert(particles.end(), event.m_muons.begin(), event.m_muons.end()); +// top::check(tool->checkTriggerMatching(result, +// particles), +// "TrigGlobalEfficiencyCorrectionTool::checkTriggerMatching failed"); + return result; + } + + std::string GlobalTrigMatchSelector::name() const { + return "GTRIGMATCH"; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GoodCaloSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GoodCaloSelector.cxx index 43056052026318aa06e9d2a0bd4d37fc0572fcf2..e7d78ddd04a8066847a98e15f1a01c7ddc39eea2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GoodCaloSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/GoodCaloSelector.cxx @@ -1,18 +1,15 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/GoodCaloSelector.h" #include "TopEvent/EventTools.h" namespace top { - - GoodCaloSelector::GoodCaloSelector() - { + GoodCaloSelector::GoodCaloSelector() { } - bool GoodCaloSelector::apply(const top::Event& event) const - { + bool GoodCaloSelector::apply(const top::Event& event) const { if (event.m_info->isAvailable<char>("AnalysisTop_GOODCALO")) { if (event.m_info->auxdataConst<char>("AnalysisTop_GOODCALO") == 1) { return true; @@ -21,9 +18,7 @@ namespace top { return false; } - std::string GoodCaloSelector::name() const - { + std::string GoodCaloSelector::name() const { return "GOODCALO"; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/HTSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/HTSelector.cxx index 4627ce137a86d2da85c6f3ef2a53d3beed1b64cf..f850f464f9a6fa9cc56ed09914750aa06e90cc00 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/HTSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/HTSelector.cxx @@ -1,43 +1,42 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/HTSelector.h" #include "TopEvent/EventTools.h" namespace top { + HTSelector::HTSelector(const std::string& params) : + SignValueSelector("HT", params) { + } -HTSelector::HTSelector(const std::string& params) : - SignValueSelector("HT", params) { -} - -bool HTSelector::apply(const top::Event& event) const { + bool HTSelector::apply(const top::Event& event) const { const double ht = top::ht(event); + return checkFloat(ht, value()); -} + } -bool HTSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool HTSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons - or not event.m_jets ){ - return false; + if (not event.m_electrons + or not event.m_muons + or not event.m_jets) { + return false; } double sumHt = 0.0; - for (const auto el : * event.m_electrons) - sumHt += el->pt(); + for (const auto el : *event.m_electrons) + sumHt += el->pt(); - for (const auto mu : * event.m_muons) - sumHt += mu->pt(); + for (const auto mu : *event.m_muons) + sumHt += mu->pt(); - for (const auto jet : * event.m_jets) - sumHt += jet->pt(); + for (const auto jet : *event.m_jets) + sumHt += jet->pt(); return checkFloat(sumHt, value()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/IP3DSV1Selector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/IP3DSV1Selector.cxx deleted file mode 100644 index 997a6f6a719765f5df24f4c9c73738e5cc071cf8..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/IP3DSV1Selector.cxx +++ /dev/null @@ -1,22 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TopEventSelectionTools/IP3DSV1Selector.h" - -#include <algorithm> - -namespace top { - -IP3DSV1Selector::IP3DSV1Selector(const std::string& params) : - SignValueSelector("IP3DSV1_N", params, true) { - checkMultiplicityIsInteger(); -} - -bool IP3DSV1Selector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* const jetPtr) { return jetPtr->btagging()->SV1plusIP3D_discriminant() > value(); }; - auto count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); - return checkInt(count, multiplicity()); -} - -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/InitialSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/InitialSelector.cxx index 06599f35b9d7321002dcfbebb9b1d04752f1029f..2b638f0b514d4f1e18cf100d333595781fbec1ba 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/InitialSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/InitialSelector.cxx @@ -1,17 +1,15 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/InitialSelector.h" namespace top { - -bool InitialSelector::apply(const top::Event&) const { + bool InitialSelector::apply(const top::Event&) const { return true; -} + } -std::string InitialSelector::name() const { + std::string InitialSelector::name() const { return "INITIAL"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetCleaningSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetCleaningSelector.cxx index 8e2a2f9cc03a4ff786e4c3173f8c7966eb16b6a2..63d05d636eea8749c6e43adc8ab5510b5dd7eb2a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetCleaningSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetCleaningSelector.cxx @@ -1,65 +1,130 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/JetCleaningSelector.h" #include "TopEvent/EventTools.h" #include "xAODJet/JetContainer.h" #include "TopConfiguration/TopConfig.h" +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; namespace top { - JetCleaningSelector::JetCleaningSelector(const std::string& level, std::shared_ptr<top::TopConfig> config) : - m_jetCleaningToolLooseBad("JetCleaningToolLooseBad"), - m_jetCleaningToolTightBad("JetCleaningToolTightBad"), m_level(level), m_useLooseBad(true), - m_config(config) - { + m_config(config) { + if (!m_config->isTruthDxAOD()) { + m_jetCleaningToolLooseBad = ToolHandle<IJetSelector>("JetCleaningToolLooseBad"); + m_jetCleaningToolTightBad = ToolHandle<IJetSelector>("JetCleaningToolTightBad"); + m_jetEventCleaningToolLooseBad = ToolHandle<ECUtils::IEventCleaningTool>("JetEventCleaningToolLooseBad"); + m_jetEventCleaningToolTightBad = ToolHandle<ECUtils::IEventCleaningTool>("JetEventCleaningToolTightBad"); - if (m_level != "LooseBad" && m_level != "TightBad") { - std::cout << "JetCleaningSelector level not recognised - " << m_level << "\n"; - std::cout << "Should be LooseBad or TightBad\n"; - exit(1); - } - - if (m_level == "LooseBad") m_useLooseBad = true; - if (m_level == "TightBad") m_useLooseBad = false; - - // we can't yet use jet cleaning for particle-flow jets - if (!m_config->useParticleFlowJets()) { - if (m_useLooseBad) - top::check( m_jetCleaningToolLooseBad.retrieve() , "Failed to retrieve JetCleaningToolLooseBad" ); - if (!m_useLooseBad) - top::check( m_jetCleaningToolTightBad.retrieve() , "Failed to retrieve JetCleaningToolTightBad" ); + if (m_level != "LooseBad" && m_level != "TightBad") { + ATH_MSG_ERROR("JetCleaningSelector level not recognised - " << m_level << "\n" + << "Should be LooseBad or TightBad"); + throw std::runtime_error ("JetCleaningSelector: Cannot continue"); + } + + if (m_level == "LooseBad") m_useLooseBad = true; + if (m_level == "TightBad") m_useLooseBad = false; + + + m_useEventLevelJetCleaningTool = m_config->useEventLevelJetCleaningTool(); + + // Checking configuration for particle-flow jets: + if (m_config->useParticleFlowJets()) { + top::check(m_useLooseBad, + "JetCleaningSelector: This cleaning configuration is not available for particle-flow jets. The only available configuration is\n JETCLEAN LooseBad"); + } + + // We can't yet use jet cleaning or event cleaning tools for particle-flow jets + if (!m_config->useParticleFlowJets()) { + if (m_useEventLevelJetCleaningTool) { + if (m_useLooseBad) top::check( + m_jetEventCleaningToolLooseBad.retrieve(), "Failed to retrieve JetEventCleaningToolLooseBad"); + else top::check(m_jetEventCleaningToolTightBad.retrieve(), "Failed to retrieve JetEventCleaningToolTightBad"); + + } else { + if (m_useLooseBad) top::check( + m_jetCleaningToolLooseBad.retrieve(), "Failed to retrieve JetCleaningToolLooseBad"); + else top::check(m_jetCleaningToolTightBad.retrieve(), "Failed to retrieve JetCleaningToolTightBad"); + } + } // end (!m_config->useParticleFlowJets()) } } bool JetCleaningSelector::apply(const top::Event& event) const { - for (const auto* const jetPtr : event.m_jets){ - // we can't yet use jet cleaning for particle-flow jets, so do nothing in this case - if (m_config->useParticleFlowJets()) return true; - - if (m_useLooseBad) { - if (m_jetCleaningToolLooseBad->keep(*jetPtr) == 0) { - return false; - } + if (m_config->isTruthDxAOD()) return true; + + if (m_config->useParticleFlowJets()) { + top::check(event.m_info->isAvailable<char>( + "DFCommonJets_eventClean_LooseBad"), + "JetCleaningSelector: DFCommonJets_eventClean_LooseBad not available in EventInfo. Needed for particle-flow jets cleaning"); + bool result = event.m_info->auxdataConst<char>("DFCommonJets_eventClean_LooseBad"); + + if (result && m_config->useBadBatmanCleaning()) { + // passed the standard cleaning + // finally, check if the BadBatman cleaning should be applied + return JetCleaningSelector::checkBadBatman(event); } - - if (!m_useLooseBad) { - if (m_jetCleaningToolTightBad->keep(*jetPtr) == 0) { - return false; + return result; + } + + // There are two jet cleaning tools and we have a request to test the event level one + // These should be very close/ equivalent as we already handle the OR and JVT elsewhere + if (m_useEventLevelJetCleaningTool) { + // If we are to use the event object, we can just do acceptEvent + + if (m_useLooseBad) return m_jetEventCleaningToolLooseBad->acceptEvent(&event.m_jets); + else return m_jetEventCleaningToolTightBad->acceptEvent(&event.m_jets); + } + // This is the default/standard method for jet cleaning + else { + for (const auto* const jetPtr : event.m_jets) { + if (m_useLooseBad) { + if (m_jetCleaningToolLooseBad->keep(*jetPtr) == 0) { + return false; + } + } else { + if (m_jetCleaningToolTightBad->keep(*jetPtr) == 0) { + return false; + } } } - + } + + // passed the standard cleaning + // finally, check if the BadBatman cleaning should be applied + if (m_config->useBadBatmanCleaning()) { + return JetCleaningSelector::checkBadBatman(event); } return true; } - std::string JetCleaningSelector::name() const - { + std::string JetCleaningSelector::name() const { return "JETCLEAN " + m_level; } + bool JetCleaningSelector::checkBadBatman(const top::Event& event) const { + // we apply this only to Data + if (m_config->isMC()) { + return true; + } + // first check if the RunNUmber are within the specified range + const unsigned int runNumber = event.m_info->runNumber(); + + if ((m_config->badBatmanCleaningMin() >= runNumber) || (m_config->badBatmanCleaningMax() <= runNumber)) { + // is outside of the specified range + return true; + } + + top::check(event.m_info->isAvailable<char>( + "DFCommonJets_isBadBatman"), + "JetCleaningSelector: DFCommonJets_isBadBatman not available in EventInfo. Needed for BadBatman cleaning"); + const bool result = event.m_info->auxdataConst<char>("DFCommonJets_isBadBatman"); + // we need to return negation of the flag as it is true for problematic events + return !result; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFlavorPlots.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFlavorPlots.cxx index e7545d70af9b1df6a263747410467915dd4c7500..bd156abbb52f204dc007ab52393ad3f307e259b4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFlavorPlots.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFlavorPlots.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/JetFlavorPlots.h" @@ -9,6 +9,7 @@ #include <string> #include "TopEvent/EventTools.h" +#include "TopConfiguration/TopConfig.h" #include "TopCorrections/ScaleFactorRetriever.h" #include "TH1.h" @@ -18,59 +19,262 @@ // Systematic include(s): #include "PATInterfaces/SystematicSet.h" +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; + namespace top { + const double JetFlavorPlots::toGeV = 0.001; -const double JetFlavorPlots::toGeV = 0.001; -JetFlavorPlots::JetFlavorPlots(const std::string& name, - TFile* outputFile, EL::Worker* wk) : - m_hists(name, outputFile, wk), m_nominalHashValue(0) { + JetFlavorPlots::JetFlavorPlots(const std::string& name, + TFile* outputFile, const std::string& params, std::shared_ptr<top::TopConfig> config, + EL::Worker* wk) : + m_nominalHashValue(0), + m_detailed(false), + m_doNominal(false), + m_doRadHigh(false), + m_doRadLow(false), + // default pT and eta binning, and default max number of Jets + m_ptBins("15:20:30:45:60:80:110:160:210:260:310:400:500:600:800:1000:1200:1500:1800:2500"), + m_etaBins("0.:0.3:0.8:1.2:2.1:2.8:3.6:4.5"), + m_nJetsMax(15), + m_jetCollection(""), + m_config(config), + m_PMGTruthWeights(nullptr), + m_throwwarningPMG(true) { CP::SystematicSet nominal; m_nominalHashValue = nominal.hash(); - m_hists.addHist("gluon_jets", ";pT [GeV];Eta;Events", - 50, 0., 500., 10, 0, 5); - m_hists.addHist("quark_jets", ";pT [GeV];Eta;Events", - 50, 0., 500., 10, 0, 5); -} + // retrieve jet collection and remove the "Jets" at the end of it + m_jetCollection = m_config->sgKeyJets(); + int pos = m_jetCollection.find("Jets"); + m_jetCollection.erase(pos); + //FIXME: If no metadata is available, the PMGTool will crash. Providing here a "manual" workaround. + //FIXME PMG: comment from here + //retrieve PMGTruthWeights + const std::string truthWeightToolName = "PMGTruthWeightTool"; + if (asg::ToolStore::contains<PMGTools::PMGTruthWeightTool>(truthWeightToolName)) m_PMGTruthWeights = + asg::ToolStore::get<PMGTools::PMGTruthWeightTool>(truthWeightToolName); + else { + m_PMGTruthWeights = new PMGTools::PMGTruthWeightTool(truthWeightToolName); + top::check(m_PMGTruthWeights->initialize(), "Failed to initialize " + truthWeightToolName); + } + //FIXME PMG: comment till here + //decoding arguments + std::istringstream stream(params); + std::string s; + while (stream >> s) { + if (s == "detailed") m_detailed = true; + else if (s.substr(0, 3) == "pt:" || s.substr(0, 3) == "pT:") m_ptBins = s.substr(3, s.size() - 3); + else if (s.substr(0, 7) == "abseta:") m_etaBins = s.substr(7, s.size() - 7); + else if (s.substr(0, 9) == "nJetsMax:") m_nJetsMax = std::atoi(s.substr(9, s.size() - 9).c_str()); + else if (s == "nominal" || s == "NOMINAL" || s == "Nominal") m_doNominal = true; + else if (s == "radiationhigh" || s == "RADIATIONHIGH" || s == "RadiationHigh" || + s == "radiationHigh") m_doRadHigh = true; + else if (s == "radiationlow" || s == "RADIATIONLOW" || s == "RadiationLow" || + s == "radiationLow") m_doRadLow = true; + else { + throw std::runtime_error("ERROR: Can't understand argument " + s + "For JETFLAVORPLOTS"); + } + } + //If neither nominal or radiation has been selected, assume it's nominal + if ((m_doNominal + m_doRadHigh + m_doRadLow) == false) m_doNominal = true; + // create the JetFlavorPlots and JetFlavorPlots_Loose directories only if needed + if (m_config->doTightEvents()) { + if (m_doNominal) m_hists = std::make_shared<PlotManager>(name + "/JetFlavorPlots", outputFile, wk); + if (m_doRadHigh) m_hists_RadHigh = + std::make_shared<PlotManager>(name + "/JetFlavorPlots_RadHigh", outputFile, wk); + if (m_doRadLow) m_hists_RadLow = std::make_shared<PlotManager>(name + "/JetFlavorPlots_RadLow", outputFile, wk); + } + if (m_config->doLooseEvents()) { + if (m_doNominal) m_hists_Loose = std::make_shared<PlotManager>(name + "/JetFlavorPlots_Loose", outputFile, wk); + if (m_doRadHigh) m_hists_RadHigh_Loose = std::make_shared<PlotManager>(name + "/JetFlavorPlots_Loose_RadHigh", + outputFile, wk); + if (m_doRadLow) m_hists_RadLow_Loose = std::make_shared<PlotManager>(name + "/JetFlavorPlots_Loose_RadLow", + outputFile, wk); + } + //handle binning + std::vector<double> ptBinning; + std::vector<double> etaBinning; + formatBinning(m_ptBins, ptBinning); + formatBinning(m_etaBins, etaBinning); + std::ostream& msgInfo = msg(MSG::Level::INFO); + msgInfo << "Here is the binning used for JETFLAVORPLOTS in selection " << name << ":\n"; + msgInfo << "pt: "; + for (auto pt:ptBinning) msgInfo << pt << " "; + msgInfo << "\n"; + msgInfo << "abseta: "; + for (auto eta:etaBinning) msgInfo << eta << " "; + msgInfo << std::endl; + + if (m_config->doTightEvents()) { + if (m_doNominal) BookHistograms(m_hists, ptBinning, etaBinning); + if (m_doRadHigh) BookHistograms(m_hists_RadHigh, ptBinning, etaBinning); + if (m_doRadLow) BookHistograms(m_hists_RadLow, ptBinning, etaBinning); + } + if (m_config->doLooseEvents()) { + if (m_doNominal) BookHistograms(m_hists_Loose, ptBinning, etaBinning); + if (m_doRadHigh) BookHistograms(m_hists_RadHigh_Loose, ptBinning, etaBinning); + if (m_doRadLow) BookHistograms(m_hists_RadLow_Loose, ptBinning, etaBinning); + } + } + + void JetFlavorPlots::BookHistograms(std::shared_ptr<PlotManager> h_ptr, std::vector<double> ptBins, + std::vector<double> etaBins) { + if (m_detailed) { + for (std::string flavour:{"gluon", "lightquark", "cquark", "bquark", "other"}) { + // vs. nJets and flavour + for (int i = 0; i <= m_nJetsMax; ++i) { + h_ptr->addHist(flavour + "_jets_njet" + std::to_string( + i) + "_" + m_jetCollection, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + } + // vs. flavour only + h_ptr->addHist(flavour + "_jets_" + m_jetCollection, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + } + // if "detailed", also making the quark_jets one + h_ptr->addHist("quark_jets_" + m_jetCollection, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + } else { + // the simplest case, one for gluon, one for quarks + h_ptr->addHist("quark_jets_" + m_jetCollection, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + h_ptr->addHist("gluon_jets_" + m_jetCollection, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + } + } + + bool JetFlavorPlots::apply(const top::Event& event) const { + //only MC + if (!top::isSimulation(event)) return true; -bool JetFlavorPlots::apply(const top::Event& event) const { // only nominal - if (event.m_hashValue != m_nominalHashValue) - return true; + if (event.m_hashValue != m_nominalHashValue) return true; + + // do loose or tight events only if requested + if (event.m_isLoose && !m_config->doLooseEvents()) return true; + + if (!event.m_isLoose && !m_config->doTightEvents()) return true; + + double nominalWeight = event.m_info->auxdata<float>("AnalysisTop_eventWeight"); - // only plot tight selection - // before, we were plotting tight and loose together - if (event.m_isLoose) - return true; + if (m_doNominal) { + double eventWeight = nominalWeight; - double eventWeight = 1.; - if (top::isSimulation(event)) -// eventWeight = event.m_info->mcEventWeight(); - eventWeight = event.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix - else // Only do this for MC - return true; + if (event.m_isLoose) FillHistograms(m_hists_Loose, eventWeight, event); + else FillHistograms(m_hists, eventWeight, event); + } + if (m_doRadHigh) { + // 2 different names are acceptable + double scaleWeight = 1.; + if (m_PMGTruthWeights->hasWeight(" muR = 0.5, muF = 0.5 ")) scaleWeight = m_PMGTruthWeights->getWeight(" muR = 0.5, muF = 0.5 "); + else if (m_PMGTruthWeights->hasWeight(" muR = 0.50, muF = 0.50 ")) scaleWeight = m_PMGTruthWeights->getWeight(" muR = 0.50, muF = 0.50 "); + else top::check(m_PMGTruthWeights->hasWeight(" muR = 0.5, muF = 0.5 "), "JetFlavorPlots::apply(): Weight \" muR = 0.5, muF = 0.5 \" not found. Please report this message!"); + top::check(m_PMGTruthWeights->hasWeight("Var3cUp"), "JetFlavorPlots::apply(): Weight \"Var3cUp\" not found. Please report this message!"); + double eventWeight = scaleWeight * m_PMGTruthWeights->getWeight("Var3cUp") / nominalWeight; + if (event.m_isLoose) FillHistograms(m_hists_RadHigh_Loose, eventWeight, event); + else FillHistograms(m_hists_RadHigh, eventWeight, event); + } + if (m_doRadLow) { + //2 different names are acceptable + double scaleWeight = 1.; + if (m_PMGTruthWeights->hasWeight(" muR = 2.0, muF = 2.0 ")) scaleWeight = m_PMGTruthWeights->getWeight(" muR = 2.0, muF = 2.0 "); + else if (m_PMGTruthWeights->hasWeight(" muR = 2.00, muF = 2.00 ")) scaleWeight = m_PMGTruthWeights->getWeight(" muR = 2.00, muF = 2.00 "); + else top::check(m_PMGTruthWeights->hasWeight(" muR = 2.0, muF = 2.0 "), "JetFlavorPlots::apply(): Weight \" muR = 2.0, muF = 2.0 \" not found. Please report this message!"); + top::check(m_PMGTruthWeights->hasWeight("Var3cUp"), "JetFlavorPlots::apply(): Weight \"Var3cUp\" not found. Please report this message!"); + top::check(m_PMGTruthWeights->hasWeight("Var3cDown"), "JetFlavorPlots::apply(): Weight \"Var3cDown\" not found. Please report this message!"); + double eventWeight = scaleWeight * m_PMGTruthWeights->getWeight("Var3cDown") / nominalWeight; + if (event.m_isLoose) FillHistograms(m_hists_RadLow_Loose, eventWeight, event); + else FillHistograms(m_hists_RadLow, eventWeight, event); + } + return true; + } + + void JetFlavorPlots::FillHistograms(std::shared_ptr<PlotManager> h_ptr, double w_event, const top::Event& event) const { + bool throwWarning = false; for (const auto* const jetPtr : event.m_jets) { int jet_flavor = -99; bool status = jetPtr->getAttribute<int>("PartonTruthLabelID", jet_flavor); if (!status) continue; - if (jet_flavor == 21) { // PDG ID for gluon is 21 - static_cast<TH2D*>(m_hists.hist("gluon_jets"))->Fill(jetPtr->pt()*toGeV, - jetPtr->eta(), - eventWeight); + + if (m_detailed) { + if ((unsigned int) m_nJetsMax >= event.m_jets.size()) { + // vs. nJets and flavour + char name[200]; + // PDG ID for gluon is 21 + if (jet_flavor == 21) sprintf(name, "gluon_jets_njet%lu_%s", event.m_jets.size(), m_jetCollection.c_str()); + // PDG ID for d,u,s is 1,2,3 + else if (jet_flavor >= 1 && jet_flavor <= 3) sprintf(name, "lightquark_jets_njet%lu_%s", event.m_jets.size(), m_jetCollection.c_str()); + // PDG ID for c is 4 + else if (jet_flavor == 4) sprintf(name, "cquark_jets_njet%lu_%s", event.m_jets.size(), m_jetCollection.c_str()); + // PDG ID for b is 5 + else if (jet_flavor == 5) sprintf(name, "bquark_jets_njet%lu_%s", event.m_jets.size(), m_jetCollection.c_str()); + else sprintf(name, "other_jets_njet%lu_%s", event.m_jets.size(), m_jetCollection.c_str()); + + static_cast<TH2D*>(h_ptr->hist(name))->Fill(jetPtr->pt() * toGeV, + jetPtr->eta(), + w_event); + + // if "detailed", also making the quark_jets one + if (jet_flavor >= 1 && jet_flavor <= 4) { + sprintf(name, "quark_jets_%s", m_jetCollection.c_str()); + + static_cast<TH2D*>(h_ptr->hist(name))->Fill(jetPtr->pt() * toGeV, + jetPtr->eta(), + w_event); + } + } else throwWarning = true; + // vs. flavour only + char shortname[200]; + // PDG ID for gluon is 21 + if (jet_flavor == 21) sprintf(shortname, "gluon_jets_%s", m_jetCollection.c_str()); + // PDG ID for d,u,s is 1,2,3 + else if (jet_flavor >= 1 && jet_flavor <= 3) sprintf(shortname, "lightquark_jets_%s", m_jetCollection.c_str()); + // PDG ID for c is 4 + else if (jet_flavor == 4) sprintf(shortname, "cquark_jets_%s", m_jetCollection.c_str()); + // PDG ID for b is 5 + else if (jet_flavor == 5) sprintf(shortname, "bquark_jets_%s", m_jetCollection.c_str()); + else sprintf(shortname, "other_jets_%s", m_jetCollection.c_str()); + + static_cast<TH2D*>(h_ptr->hist(shortname))->Fill(jetPtr->pt() * toGeV, + jetPtr->eta(), + w_event); } else { - static_cast<TH2D*>(m_hists.hist("quark_jets"))->Fill(jetPtr->pt()*toGeV, - jetPtr->eta(), - eventWeight); + // the simplest case, one for gluon, one for quarks + char name[200]; + // PDG ID for gluon is 21 + if (jet_flavor == 21) sprintf(name, "gluon_jets_%s", m_jetCollection.c_str()); + // PDG ID for d,u,s is 1,2,3 + else if (jet_flavor >= 1 && jet_flavor <= 4) sprintf(name, "quark_jets_%s", m_jetCollection.c_str()); + // We are not interested in other PDG IDs + else continue; + + static_cast<TH2D*>(h_ptr->hist(name))->Fill(jetPtr->pt() * toGeV, + jetPtr->eta(), + w_event); } } - return true; -} + if (throwWarning){ + ATH_MSG_WARNING("Warning! Number of jets in the event is " << event.m_jets.size() + << ", but histograms have been booked up to " << m_nJetsMax + << ". Exclusive histograms in number of jets have not been filled.\n"); + } + } -std::string JetFlavorPlots::name() const { - return "JETFLAVORPLOTS"; -} +// function to translate the binnings into vector of bin edges + void JetFlavorPlots::formatBinning(const std::string& str, std::vector<double>& binEdges) { + std::stringstream ss(str); + std::string tok; + char separator = ':'; + while (std::getline(ss, tok, separator)) { + binEdges.push_back(std::atof(tok.c_str())); + } + } + std::string JetFlavorPlots::name() const { + return "JETFLAVORPLOTS"; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFtagEffPlots.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFtagEffPlots.cxx new file mode 100644 index 0000000000000000000000000000000000000000..33360ac3da7d07d11ab60c8ceb933b39238a2baf --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetFtagEffPlots.cxx @@ -0,0 +1,393 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/JetFtagEffPlots.h" + +#include <cmath> +#include <array> +#include <string> + +#include "TopEvent/EventTools.h" +#include "TopConfiguration/TopConfig.h" +#include "TopCorrections/ScaleFactorRetriever.h" + +#include "TH1.h" +#include "TH2D.h" +#include "TFile.h" + +// Systematic include(s): +#include "PATInterfaces/SystematicSet.h" + +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; + +namespace top { + const double JetFtagEffPlots::toGeV = 0.001; + + + JetFtagEffPlots::JetFtagEffPlots(const std::string& name, + TFile* outputFile, const std::string& params, std::shared_ptr<top::TopConfig> config, + EL::Worker* wk) : + m_nominalHashValue(0), + m_CDIfile("xAODBTaggingEfficiency/13TeV/2020-21-13TeV-MC16-CDI-2020-03-11_v3.root"), + m_fill_total_hists(false), + m_histogram_suffix(""), + m_dont_use_event_weight(false), + m_use_track_jets(false), + m_doNominal(false), + m_doMuRup(false), + m_doMuRdown(false), + m_doMuFup(false), + m_doMuFdown(false), + m_doVar3cup(false), + m_doVar3cdown(false), + m_doFSRup(false), + m_doFSRdown(false), + // default pT and eta binning + m_ptBins("15:20:30:45:60:80:110:160:210:260:310:400:500:600:800:1000:1200:1500:1800:2500"), + m_etaBins("0.:0.3:0.8:1.2:2.1:2.8:3.6:4.5"), + m_max_pT(-1), + m_min_pT(-1), + m_N_pT_bins(-1), + m_max_Eta(-1), + m_min_Eta(-1), + m_N_Eta_bins(-1), + m_jetCollection(""), + m_WP("FixedCutBEff_70"), + m_tagger("DL1"), + m_config(config), + m_selection_tool("BTaggingSelectionTool/selTool"), + m_PMGTruthWeights(nullptr), + m_sfRetriever(nullptr) { + CP::SystematicSet nominal; + m_nominalHashValue = nominal.hash(); + + + const std::string truthWeightToolName = "PMGTruthWeightTool"; + if (asg::ToolStore::contains<PMGTools::PMGTruthWeightTool>(truthWeightToolName)) m_PMGTruthWeights = + asg::ToolStore::get<PMGTools::PMGTruthWeightTool>(truthWeightToolName); + else { + m_PMGTruthWeights = new PMGTools::PMGTruthWeightTool(truthWeightToolName); + top::check(m_PMGTruthWeights->initialize(), "Failed to initialize " + truthWeightToolName); + } + //decoding arguments + std::istringstream stream(params); + std::string s; + while (stream >> s) { + if (s.substr(0, 3) == "WP:") m_WP = s.substr(3, s.size() - 3); + else if (s.substr(0, 7) == "tagger:") m_tagger = s.substr(7, s.size() - 7); + else if (s.substr(0, 8) == "CDIfile:") m_CDIfile = s.substr(8, s.size() - 8); + else if (s.substr(0, 3) == "pt:" || s.substr(0, 3) == "pT:") m_ptBins = s.substr(3, s.size() - 3); + else if (s.substr(0, 7) == "abseta:") m_etaBins = s.substr(7, s.size() - 7); + else if (s.substr(0, 7) == "max_pT:") m_max_pT = std::stof(s.substr(7, s.size() - 7)); + else if (s.substr(0, 7) == "min_pT:") m_min_pT = std::stof(s.substr(7, s.size() - 7)); + else if (s.substr(0, 5) == "N_pT:") m_N_pT_bins = std::stoi(s.substr(5, s.size() - 5)); + else if (s.substr(0, 8) == "max_eta:") m_max_Eta = std::stof(s.substr(8, s.size() - 8)); + else if (s.substr(0, 8) == "min_eta:") m_min_Eta = std::stof(s.substr(8, s.size() - 8)); + else if (s.substr(0, 6) == "N_eta:") m_N_Eta_bins = std::stoi(s.substr(6, s.size() - 6)); + else if (s.substr(0, 7) == "suffix:") m_histogram_suffix = s.substr(7, s.size() - 7); + else if (s == "fill_total_hist") m_fill_total_hists = true; + else if (s == "dont_use_event_weight") m_dont_use_event_weight = true; + else if (s == "use_track_jets") m_use_track_jets = true; + else if (s == "NOMINAL") m_doNominal = true; + else if (s == "MURUP") m_doMuRup = true; + else if (s == "MURDOWN") m_doMuRdown = true; + else if (s == "MUFUP") m_doMuFup = true; + else if (s == "MUFDOWN") m_doMuFdown = true; + else if (s == "VAR3CUP") m_doVar3cup = true; + else if (s == "VAR3CDOWN") m_doVar3cdown = true; + else if (s == "FSRUP") m_doFSRup = true; + else if (s == "FSRDOWN") m_doFSRdown = true; + else { + throw std::runtime_error { + "ERROR: Can't understand argument " + s + " for JETFTAGEFFPLOTS." + }; + } + } + + // retrieve jet collection + if (!m_use_track_jets) { + m_jetCollection = m_config->sgKeyJets(); + } else { + m_jetCollection = m_config->sgKeyTrackJets(); + } + + m_sfRetriever = asg::ToolStore::get<ScaleFactorRetriever>("top::ScaleFactorRetriever"); + + // No option were set, run only nominal + if (!m_doNominal && !m_doMuRup && !m_doMuRdown && !m_doMuFup + && !m_doMuFdown && !m_doVar3cup && !m_doVar3cdown && !m_doFSRup && !m_doFSRdown) { + ATH_MSG_INFO("No variation has been set. Assuming nominal."); + m_doNominal = true; + } + + if (m_doNominal) m_hists = std::make_shared<PlotManager>(name + "/JetFtagEffPlots", outputFile, wk); + if (m_doMuRup) m_hists_muRup = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_MuRup", outputFile, wk); + if (m_doMuRdown) m_hists_muRdown = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_MuRdown", outputFile, wk); + + if (m_doMuFup) m_hists_muFup = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_MuFup", outputFile, wk); + if (m_doMuFdown) m_hists_muFdown = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_MuFdown", outputFile, wk); + + if (m_doVar3cup) m_hists_Var3cup = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_Var3cup", outputFile, wk); + + if (m_doVar3cdown) m_hists_Var3cdown = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_Var3cdown", outputFile, wk); + if (m_doFSRup) m_hists_FSRup = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_FSRup", outputFile, wk); + if (m_doFSRup) m_hists_FSRdown = std::make_shared<PlotManager>(name + "/JetFtagEffPlots_FSRdown", outputFile, wk); + + //handle binning and book histograms + std::vector<double> ptBins; + std::vector<double> etaBins; + + if (m_N_pT_bins < 1) { + formatBinning(m_ptBins, ptBins); + formatBinning(m_etaBins, etaBins); + } + + for (std::string flavour:{"B", "C", "L", "T"}) { + if (m_fill_total_hists) { + std::string total_hist_name = flavour + "_total_" + m_jetCollection + m_histogram_suffix; + if (m_N_pT_bins < 1) { + if (m_hists) m_hists->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muRup) m_hists_muRup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muRdown) m_hists_muRdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muFup) m_hists_muFup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muFdown) m_hists_muFdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_Var3cup) m_hists_Var3cup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_Var3cdown) m_hists_Var3cdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_FSRup) m_hists_FSRup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_FSRdown) m_hists_FSRdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + } else { + if (m_hists) m_hists->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muRup) m_hists_muRup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muRdown) m_hists_muRdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muFup) m_hists_muFup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muFdown) m_hists_muFdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_Var3cup) m_hists_Var3cup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_Var3cdown) m_hists_Var3cdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_FSRup) m_hists_FSRup->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_FSRdown) m_hists_FSRdown->addHist(total_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + } + } + + const std::string pass_hist_name = m_tagger + "_" + m_WP + "_" + m_jetCollection + "_" + flavour + "_pass" + m_histogram_suffix; + if (m_N_pT_bins < 1) { + if (m_hists) m_hists->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muRup) m_hists_muRup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muRdown) m_hists_muRdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muFup) m_hists_muFup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_muFdown) m_hists_muFdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_Var3cup) m_hists_Var3cup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_Var3cdown) m_hists_Var3cdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_FSRup) m_hists_FSRup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + if (m_hists_FSRdown) m_hists_FSRdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + ptBins.size() - 1, ptBins.data(), etaBins.size() - 1, etaBins.data()); + } else { + if (m_hists) m_hists->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muRup) m_hists_muRup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muRdown) m_hists_muRdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muFup) m_hists_muFup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_muFdown) m_hists_muFdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_Var3cup) m_hists_Var3cup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_Var3cdown) m_hists_Var3cdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_FSRup) m_hists_FSRup->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + if (m_hists_FSRdown) m_hists_FSRdown->addHist(pass_hist_name, ";pT [GeV];|#eta^{jet}|;Events", + m_N_pT_bins, m_min_pT, m_max_pT, m_N_Eta_bins, m_min_Eta, m_max_Eta); + } + } + + m_selection_tool = asg::AnaToolHandle<IBTaggingSelectionTool>("BTaggingSelectionTool/BTagSelec_" + m_tagger + "_" + m_WP + "_" + m_jetCollection); + top::check(m_selection_tool.setProperty("FlvTagCutDefinitionsFileName", m_CDIfile), "failed to initialize BtagSelectionTool " + m_tagger + "_" + m_WP + "_" + m_jetCollection); + top::check(m_selection_tool.setProperty("TaggerName", m_tagger), "failed to initialize BtagSelectionTool " + m_tagger + "_" + m_WP + "_" + m_jetCollection); + top::check(m_selection_tool.setProperty("OperatingPoint", m_WP), "failed to initialize BtagSelectionTool " + m_tagger + "_" + m_WP + "_" + m_jetCollection); + top::check(m_selection_tool.setProperty("JetAuthor", m_jetCollection), "failed to initialize BtagSelectionTool " + m_tagger + "_" + m_WP + "_" + m_jetCollection); + top::check(m_selection_tool.setProperty("MinPt", m_min_pT*1e3), "failed to initialize BtagSelectionTool, failed in min jet pT"); + top::check(m_selection_tool.setProperty("MaxEta", m_max_Eta), "failed to initialize BtagSelectionTool, failed in max jet eta"); + + top::check(m_selection_tool.initialize(), "failed to initialize BtagSelectionTool " + m_tagger + "_" + m_WP + "_" + m_jetCollection); + } + + bool JetFtagEffPlots::apply(const top::Event& event) const { + //only MC + if (!top::isSimulation(event)) return true; + + // only nominal + if (event.m_hashValue != m_nominalHashValue) return true; + + // do loose or tight events only if requested + if (event.m_isLoose && !m_config->doLooseEvents()) return true; + + if (!event.m_isLoose && !m_config->doTightEvents()) return true; + + float eventWeightNominal = 1.0; + float eventWeightMuRup = 1.0; + float eventWeightMuRdown = 1.0; + float eventWeightMuFup = 1.0; + float eventWeightMuFdown = 1.0; + float eventWeightVar3cUp = 1.0; + float eventWeightVar3cDown = 1.0; + float eventWeightFSRUp = 1.0; + float eventWeightFSRDown = 1.0; + float muRup = GetPMGTruthWeight(WEIGHTTYPE::MURUP); + float muRdown = GetPMGTruthWeight(WEIGHTTYPE::MURDOWN); + float muFup = GetPMGTruthWeight(WEIGHTTYPE::MUFUP); + float muFdown = GetPMGTruthWeight(WEIGHTTYPE::MUFDOWN); + float Var3cUp = GetPMGTruthWeight(WEIGHTTYPE::VAR3CUP); + float Var3cDown = GetPMGTruthWeight(WEIGHTTYPE::VAR3CDOWN); + float FSRUp = GetPMGTruthWeight(WEIGHTTYPE::FSRUP); + float FSRDown = GetPMGTruthWeight(WEIGHTTYPE::FSRDOWN); + + float jvt_sf = event.m_jvtSF; + float pu_weight = 1.0; + if (top::ScaleFactorRetriever::hasPileupSF(event)) { + pu_weight = top::ScaleFactorRetriever::pileupSF(event); + } + float lepton_sf = m_sfRetriever->leptonSF(event, nominal); + + if (m_doNominal) { + eventWeightNominal = event.m_info->auxdataConst<float>("AnalysisTop_eventWeight") * jvt_sf * pu_weight * lepton_sf; + } + if (m_doMuRup) eventWeightMuRup = muRup * jvt_sf * pu_weight * lepton_sf; + if (m_doMuRdown) eventWeightMuRdown = muRdown * jvt_sf * pu_weight * lepton_sf; + if (m_doMuFup) eventWeightMuFup = muFup * jvt_sf * pu_weight * lepton_sf; + if (m_doMuFdown) eventWeightMuFdown = muFdown * jvt_sf * pu_weight * lepton_sf; + if (m_doVar3cup) eventWeightVar3cUp = Var3cUp * jvt_sf * pu_weight * lepton_sf; + if (m_doVar3cdown) eventWeightVar3cDown = Var3cDown * jvt_sf * pu_weight * lepton_sf; + if (m_doFSRup) eventWeightFSRUp = FSRUp * jvt_sf * pu_weight * lepton_sf; + if (m_doFSRdown) eventWeightFSRDown = FSRDown * jvt_sf * pu_weight * lepton_sf; + + if (m_dont_use_event_weight) { + eventWeightNominal = 1.0; + } + + if (m_hists) FillHistograms(m_hists, eventWeightNominal, event); + if (m_hists_muRup) FillHistograms(m_hists_muRup, eventWeightMuRup, event); + if (m_hists_muRdown) FillHistograms(m_hists_muRdown, eventWeightMuRdown, event); + if (m_hists_muFup) FillHistograms(m_hists_muFup, eventWeightMuFup, event); + if (m_hists_muFdown) FillHistograms(m_hists_muFdown, eventWeightMuFdown, event); + if (m_hists_Var3cup) FillHistograms(m_hists_Var3cup, eventWeightVar3cUp, event); + if (m_hists_Var3cdown) FillHistograms(m_hists_Var3cdown, eventWeightVar3cDown, event); + if (m_hists_FSRup) FillHistograms(m_hists_FSRup, eventWeightFSRUp, event); + if (m_hists_FSRdown) FillHistograms(m_hists_FSRdown, eventWeightFSRDown, event); + + return true; + } + + void JetFtagEffPlots::FillHistograms(std::shared_ptr<PlotManager> h_ptr, double w_event, const top::Event& event) const { + const xAOD::JetContainer* jets; + + if (!m_use_track_jets) { + jets = &event.m_jets; + } else { + jets = &event.m_trackJets; + } + + for (unsigned long jet_i = 0; jet_i < jets->size(); jet_i++) { + const xAOD::Jet* jetPtr = jets->at(jet_i); + + int jet_flavor = -99; + bool status = jetPtr->getAttribute<int>("HadronConeExclTruthLabelID", jet_flavor); + + if (!status) continue; + + std::string flav_name; + + if (jet_flavor == 5) flav_name = "B"; + + else if (jet_flavor == 4) flav_name = "C"; + + else if (jet_flavor == 0) flav_name = "L"; + + else if (jet_flavor == 15) flav_name = "T"; + + if (m_fill_total_hists) { + static_cast<TH2D*>(h_ptr->hist(flav_name + "_total_" + m_jetCollection + m_histogram_suffix))->Fill(jetPtr->pt() * toGeV, fabs(jetPtr->eta()), w_event); + } + + bool pass_cut = static_cast<bool>(m_selection_tool->accept(jetPtr)); + + if (pass_cut) { + std::string hist_name = m_tagger + "_" + m_WP + "_" + m_jetCollection + "_" + flav_name + "_pass" + m_histogram_suffix; + static_cast<TH2D*>(h_ptr->hist(hist_name))->Fill(jetPtr->pt() * toGeV, fabs(jetPtr->eta()), w_event); + } + } + } + +// function to translate the binnings into vector of bin edges + void JetFtagEffPlots::formatBinning(const std::string& str, std::vector<double>& binEdges) { + std::stringstream ss(str); + std::string tok; + char separator = ':'; + while (std::getline(ss, tok, separator)) { + binEdges.push_back(std::atof(tok.c_str())); + } + } + + float JetFtagEffPlots::GetPMGTruthWeight(WEIGHTTYPE type) const { + float result = 1; + + if (type == WEIGHTTYPE::MURUP) { + if (m_PMGTruthWeights->hasWeight(" muR = 2.0, muF = 1.0 ")) result = m_PMGTruthWeights->getWeight(" muR = 2.0, muF = 1.0 "); + else if (m_PMGTruthWeights->hasWeight(" muR = 2.00, muF = 1.00 ")) result = m_PMGTruthWeights->getWeight(" muR = 2.00, muF = 1.00 "); + } else if (type == WEIGHTTYPE::MURDOWN) { + if (m_PMGTruthWeights->hasWeight(" muR = 0.5, muF = 1.0 ")) result = m_PMGTruthWeights->getWeight(" muR = 0.5, muF = 1.0 "); + else if (m_PMGTruthWeights->hasWeight(" muR = 0.50, muF = 1.00 ")) result = m_PMGTruthWeights->getWeight(" muR = 0.50, muF = 1.00 "); + } else if (type == WEIGHTTYPE::MUFUP) { + if (m_PMGTruthWeights->hasWeight(" muR = 1.0, muF = 2.0 ")) result = m_PMGTruthWeights->getWeight(" muR = 1.0, muF = 2.0 "); + else if (m_PMGTruthWeights->hasWeight(" muR = 1.00, muF = 2.00 ")) result = m_PMGTruthWeights->getWeight(" muR = 1.00, muF = 2.00 "); + } else if (type == WEIGHTTYPE::MUFDOWN) { + if (m_PMGTruthWeights->hasWeight(" muR = 1.0, muF = 0.5 ")) result = m_PMGTruthWeights->getWeight(" muR = 1.0, muF = 0.5 "); + else if (m_PMGTruthWeights->hasWeight(" muR = 1.00, muF = 0.50 ")) result = m_PMGTruthWeights->getWeight(" muR = 1.00, muF = 0.50 "); + } else if (type == WEIGHTTYPE::VAR3CUP) { + if (m_PMGTruthWeights->hasWeight("Var3cUp")) result = m_PMGTruthWeights->getWeight("Var3cUp"); + } else if (type == WEIGHTTYPE::VAR3CDOWN) { + if (m_PMGTruthWeights->hasWeight("Var3cDown")) result = m_PMGTruthWeights->getWeight("Var3cDown"); + } else if (type == WEIGHTTYPE::FSRUP) { + if (m_PMGTruthWeights->hasWeight("isr:muRfac=1.0_fsr:muRfac=2.0")) result = m_PMGTruthWeights->getWeight("isr:muRfac=1.0_fsr:muRfac=2.0"); + else if (m_PMGTruthWeights->hasWeight("isr:muRfac=1.00_fsr:muRfac=2.00")) result = m_PMGTruthWeights->getWeight("isr:muRfac=1.00_fsr:muRfac=2.00"); + } else if (type == WEIGHTTYPE::FSRDOWN) { + if (m_PMGTruthWeights->hasWeight("isr:muRfac=1.0_fsr:muRfac=0.5")) result = m_PMGTruthWeights->getWeight("isr:muRfac=1.0_fsr:muRfac=0.5"); + else if (m_PMGTruthWeights->hasWeight("isr:muRfac=1.00_fsr:muRfac=0.50")) result = m_PMGTruthWeights->getWeight("isr:muRfac=1.00_fsr:muRfac=0.50"); + } + + return result; + } + + std::string JetFtagEffPlots::name() const { + return "JETFTAGEFFPLOTS"; + } +} // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetNGhostSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetNGhostSelector.cxx index 85124b4b7b93dfa8a8062965d3fb638a8dea3fc8..decfdfbbb4e061a53c5228e5ff5e0bc3655a7793 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetNGhostSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetNGhostSelector.cxx @@ -1,87 +1,136 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: JetNGhostSelector.cxx -// Description: -// Author: Fabian Wilk -// Created: Fri May 8 15:39:38 2015 + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/JetNGhostSelector.h" namespace top { + JetNGhostSelector::JetNGhostSelector(const std::string& params) + : SignValueSelector("", parseType(params)) { + switch (m_type) { + case c: m_name = "JET_N_GHOST c" + SignValueSelector::name(); + break; + + case C: m_name = "JET_N_GHOST C" + SignValueSelector::name(); + break; + + case b: m_name = "JET_N_GHOST b" + SignValueSelector::name(); + break; + + case B: m_name = "JET_N_GHOST B" + SignValueSelector::name(); + break; + + case t: m_name = "JET_N_GHOST t" + SignValueSelector::name(); + break; + + case W: m_name = "JET_N_GHOST W" + SignValueSelector::name(); + break; - JetNGhostSelector::JetNGhostSelector(const std::string& params) - : SignValueSelector( "", parseType( params ) ){ - switch ( m_type ){ - case c: m_name = "JET_N_GHOST c" + SignValueSelector::name(); break; - case C: m_name = "JET_N_GHOST C" + SignValueSelector::name(); break; - case b: m_name = "JET_N_GHOST b" + SignValueSelector::name(); break; - case B: m_name = "JET_N_GHOST B" + SignValueSelector::name(); break; - case t: m_name = "JET_N_GHOST t" + SignValueSelector::name(); break; - case W: m_name = "JET_N_GHOST W" + SignValueSelector::name(); break; - case Z: m_name = "JET_N_GHOST Z" + SignValueSelector::name(); break; - case H: m_name = "JET_N_GHOST H" + SignValueSelector::name(); break; - case tau: m_name = "JET_N_GHOST tau" + SignValueSelector::name(); break; - case Invalid: m_name = "JET_N_GHOST !!! INVALID !!"; break; - } - checkMultiplicityIsInteger(); + case Z: m_name = "JET_N_GHOST Z" + SignValueSelector::name(); + break; + + case H: m_name = "JET_N_GHOST H" + SignValueSelector::name(); + break; + + case tau: m_name = "JET_N_GHOST tau" + SignValueSelector::name(); + break; + + case Invalid: m_name = "JET_N_GHOST !!! INVALID !!"; + break; } + checkMultiplicityIsInteger(); + } + + std::string JetNGhostSelector::parseType(const std::string& params) { + // Initialise the type variable + m_type = Invalid; + // Skip leading whitespace + std::size_t pos { + 0 + }; + while (pos < params.length() - 1 && std::isspace(params[pos])) { + ++pos; + } + + // list of allowed chars + static const std::vector<char> allowedChar = { + 'c', 'C', 'b', 'B', 't', 'W', 'Z', 'H' + }; - std::string JetNGhostSelector::parseType( const std::string & params ){ - // Initialise the type variable - m_type = Invalid; - // Skip leading whitespace - std::size_t pos{ 0 }; - while ( pos < params.length() - 1 && std::isspace( params[pos] ) ) { ++pos; } - - // Check, Use a switch statement hoping that the compiler may use this - // as a hint to optimise this bit using a jump table. - switch ( params[pos] ){ - // The easy cases - case 'c': case 'C': case 'b': case 'B': case 't': case 'W': case 'Z': case 'H': { - if ( pos + 1 < params.length() && std::isspace( params[ pos + 1 ] ) ){ - m_type = static_cast<Type>( params[ pos ] ); - return params.substr( pos + 2 ); - } else if ( params.compare( pos, 4, "tau " ) == 0 ){ - m_type = tau; - return params.substr( pos + 4 ); - } - } - default: { - std::cout << "Could not parse the type from the parameter string\n"; - std::cout << " '" << params << "'\n"; - std::exit(1); - } - } + // check if the char is allowed + if (std::find(allowedChar.begin(), allowedChar.end(), params[pos]) == allowedChar.end()) { + throw std::invalid_argument { + "Cannot parse the type from the parameter string" + }; } - bool JetNGhostSelector::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const { - // If any of the required collections is a nullptr (i.e. has not been - // loaded) return false. - if ( not plEvent.m_jets ){ - return false; - } - - auto func = [&](const xAOD::Jet* truJetPtr) -> bool { - switch ( m_type ){ - case c: { return truJetPtr->auxdata<int>( "GhostCQuarksFinalCount" ); } - case C: { return truJetPtr->auxdata<int>( "GhostCHadronsFinalCount" ); } - case b: { return truJetPtr->auxdata<int>( "GhostBQuarksFinalCount" ); } - case B: { return truJetPtr->auxdata<int>( "GhostBHadronsFinalCount" ); } - case t: { return truJetPtr->auxdata<int>( "GhostTQuarksFinalCount" ); } - case W: { return truJetPtr->auxdata<int>( "GhostWBosonsCount" ); } - case Z: { return truJetPtr->auxdata<int>( "GhostZBosonsCount" ); } - case H: { return truJetPtr->auxdata<int>( "GhostHBosonsCount" ); } - case tau: { return truJetPtr->auxdata<int>( "GhostTausFinalCount" ); } - default: /* No-Op */ return 0; - } - }; - auto count = std::count_if(plEvent.m_jets->begin(), plEvent.m_jets->end(), func); - return checkInt(count, value()); + // process the char + if (pos + 1 < params.length() && std::isspace(params[ pos + 1 ])) { + m_type = static_cast<Type>(params[ pos ]); + return params.substr(pos + 2); + } else if (params.compare(pos, 4, "tau ") == 0) { + m_type = tau; + return params.substr(pos + 4); + } else { + throw std::invalid_argument { + "Cannot parse the type from the parameter string for the common configuration" + }; } + } - std::string JetNGhostSelector::name() const { - return m_name; + bool JetNGhostSelector::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const { + // If any of the required collections is a nullptr (i.e. has not been + // loaded) return false. + if (!plEvent.m_jets) { + return false; } + + auto func = [&](const xAOD::Jet* truJetPtr) -> bool { + switch (m_type) { + case c: { + return truJetPtr->auxdata<int>("GhostCQuarksFinalCount"); + } + + case C: { + return truJetPtr->auxdata<int>("GhostCHadronsFinalCount"); + } + + case b: { + return truJetPtr->auxdata<int>("GhostBQuarksFinalCount"); + } + + case B: { + return truJetPtr->auxdata<int>("GhostBHadronsFinalCount"); + } + + case t: { + return truJetPtr->auxdata<int>("GhostTQuarksFinalCount"); + } + + case W: { + return truJetPtr->auxdata<int>("GhostWBosonsCount"); + } + + case Z: { + return truJetPtr->auxdata<int>("GhostZBosonsCount"); + } + + case H: { + return truJetPtr->auxdata<int>("GhostHBosonsCount"); + } + + case tau: { + return truJetPtr->auxdata<int>("GhostTausFinalCount"); + } + + default: /* No-Op */ return 0; + } + }; + auto count = std::count_if(plEvent.m_jets->begin(), plEvent.m_jets->end(), func); + return checkInt(count, value()); + } + + std::string JetNGhostSelector::name() const { + return m_name; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetResponsePlots.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetResponsePlots.cxx new file mode 100644 index 0000000000000000000000000000000000000000..7a93fd4c263bfbc4bd9004228765e3a6f0871d81 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/JetResponsePlots.cxx @@ -0,0 +1,152 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/JetResponsePlots.h" + +#include "AsgTools/AsgTool.h" +#include "TopEvent/Event.h" +#include "TopEvent/EventTools.h" +#include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/Tokenize.h" +#include "TopCorrections/ScaleFactorRetriever.h" +#include "PATInterfaces/SystematicSet.h" +#include "xAODJet/JetContainer.h" +#include "PMGTools/PMGTruthWeightTool.h" + +#include "TH1.h" +#include "TH2D.h" +#include "TFile.h" + +//using namespace TopEventSelectionTools; +namespace top { + + JetResponsePlots::JetResponsePlots(const std::string& name, + TFile* outputFile, + const std::string& params, + std::shared_ptr<top::TopConfig> config, + EL::Worker* wk) : + m_nominalHashValue(0), + m_deltaR(0.3), + m_bins(30), + m_min(-3), + m_max(3), + m_config(config), + m_PMGTruthWeights(nullptr) { + + CP::SystematicSet nominal; + m_nominalHashValue = nominal.hash(); + + //retrieve PMGTruthWeights + static const std::string truthWeightToolName = "PMGTruthWeightTool"; + if (asg::ToolStore::contains<PMGTools::IPMGTruthWeightTool>(truthWeightToolName)) m_PMGTruthWeights = + asg::ToolStore::get<PMGTools::IPMGTruthWeightTool>(truthWeightToolName); + else { + std::unique_ptr<PMGTools::PMGTruthWeightTool> pmgtruthtool = std::make_unique<PMGTools::PMGTruthWeightTool>(truthWeightToolName); + top::check(pmgtruthtool->initialize(), "Failed to initialize " + truthWeightToolName); + m_PMGTruthWeights = pmgtruthtool.release(); + } + //decoding arguments + std::istringstream stream(params); + std::string s; + while (stream >> s) { + if (s.substr(0,7) == "deltaR:") { + m_deltaR = std::stof(s.substr(7, s.size() - 7)); + m_config->setJetResponseMatchingDeltaR(m_deltaR); + } else if (s.substr(0,5) == "bins:") { + m_bins = std::stoi(s.substr(5, s.size() - 5)); + } else if (s.substr(0,4) == "min:") { + m_min = std::stof(s.substr(4, s.size() - 4)); + } else if (s.substr(0,4) == "max:") { + m_max = std::stof(s.substr(4, s.size() - 4)); + } else if (s.substr(0,10) == "ptBinning:") { + const std::string tmp = s.substr(10, s.size() - 4); + // split by the delimiter + std::vector<std::string> split; + tokenize(tmp, split, ","); + for (const std::string& istring : split) { + m_ptBinning.emplace_back(std::stof(istring)); + } + } else { + throw std::runtime_error{"ERROR: Can't understand argument " + s + "For JETRESPONSEPLOTS"}; + } + } + + if (m_ptBinning.size() < 2) { + throw std::invalid_argument{"pT binning (x axis) size is smaller than 2"}; + } + + m_hists = std::make_shared<PlotManager>(name + "/JetResponsePlots", outputFile, wk); + m_hists->addHist("JetResponse", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_bb", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_b", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_c", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_tau", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_q", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_g", ";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + m_hists->addHist("JetResponse_other",";p_{T}^{truth} [GeV];p_{T}^{reco}/p_{T}^{truth};Events", m_ptBinning.size() - 1, m_ptBinning.data(), m_bins, m_min, m_max); + } + + bool JetResponsePlots::apply(const top::Event& event) const { + //only MC + if (!top::isSimulation(event)) return true; + + // only nominal + if (event.m_hashValue != m_nominalHashValue) return true; + + // do loose or tight events only if requested + if (event.m_isLoose && !m_config->doLooseEvents()) return true; + + if (!event.m_isLoose && !m_config->doTightEvents()) return true; + + const double nominalWeight = event.m_info->auxdata<float>("AnalysisTop_eventWeight"); + + FillHistograms(nominalWeight, event); + + return true; + } + + void JetResponsePlots::FillHistograms(const double w_event, + const top::Event& event) const { + + for (const auto* const jetPtr : event.m_jets) { + int jet_flavor = -99; + bool status = jetPtr->getAttribute<int>("HadronConeExclExtendedTruthLabelID", jet_flavor); + if (!status) continue; + + float matchedPt = -9999; + status = jetPtr->getAttribute<float>("AnalysisTop_MatchedTruthJetPt", matchedPt); + if (!status) continue; + + // protection against division by zero + if (matchedPt < 1e-6) continue; + + const float response = jetPtr->pt() / matchedPt; + + static_cast<TH2D*>(m_hists->hist("JetResponse"))->Fill(matchedPt/1e3, response, w_event); + if (jet_flavor == 55) { + static_cast<TH2D*>(m_hists->hist("JetResponse_bb"))->Fill(matchedPt/1e3, response, w_event); + } else if (jet_flavor == 5 || jet_flavor == 54) { + static_cast<TH2D*>(m_hists->hist("JetResponse_b"))->Fill(matchedPt/1e3, response, w_event); + } else if (jet_flavor == 4 || jet_flavor == 44) { + static_cast<TH2D*>(m_hists->hist("JetResponse_c"))->Fill(matchedPt/1e3, response, w_event); + } else if (jet_flavor == 15) { + static_cast<TH2D*>(m_hists->hist("JetResponse_tau"))->Fill(matchedPt/1e3, response, w_event); + } else { + status = jetPtr->getAttribute<int>("PartonTruthLabelID", jet_flavor); + if (!status) continue; + if (jet_flavor >= 1 && jet_flavor <= 3) { + static_cast<TH2D*>(m_hists->hist("JetResponse_q"))->Fill(matchedPt/1e3, response, w_event); + } else if (jet_flavor == 21) { + static_cast<TH2D*>(m_hists->hist("JetResponse_g"))->Fill(matchedPt/1e3, response, w_event); + } else { + static_cast<TH2D*>(m_hists->hist("JetResponse_other"))->Fill(matchedPt/1e3, response, w_event); + } + } + } + } + + std::string JetResponsePlots::name() const { + return "JETRESPONSEPLOTS"; + } +} // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/KLFitterSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/KLFitterSelector.cxx index 793304c8da591b5e06a8542f688a89631f9a9b5c..57f8eddaaa6f5ab5b5b2af5d45d147f037cdad38 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/KLFitterSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/KLFitterSelector.cxx @@ -1,41 +1,36 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: KLFitterSelector.cxx 666816 2015-05-13 10:59:36Z morrisj $ #include "TopEventSelectionTools/KLFitterSelector.h" #include "TopEvent/Event.h" #include "TopEvent/KLFitterResult.h" -namespace top{ - +namespace top { KLFitterSelector::KLFitterSelector(const std::string& params) : - SignValueSelector("KLFitter", params) - { + SignValueSelector("KLFitter", params) { } - - bool KLFitterSelector::apply(const top::Event& event) const - { + + bool KLFitterSelector::apply(const top::Event& event) const { // check we have a xAOD::KLFitterResultContainer if (event.m_KLFitterResults == nullptr) { return false; } - + for (auto result : *event.m_KLFitterResults) { // check for errors if ( - result->minuitDidNotConverge() == 0 && - result->fitAbortedDueToNaN() == 0 && + result->minuitDidNotConverge() == 0 && + result->fitAbortedDueToNaN() == 0 && result->atLeastOneFitParameterAtItsLimit() == 0 && - result->invalidTransferFunctionAtConvergence() == 0 - ) - { - bool passPermutation = checkFloat( result->logLikelihood() , value() ); + result->invalidTransferFunctionAtConvergence() == 0 + ) { + bool passPermutation = checkFloat(result->logLikelihood(), value()); if (passPermutation) { return true; } } // check for errors - } // Loop over Permutations - if we get this far, all Permutations have failed :( return false; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/LinkDef.h index 64fef85f1b05677101b506deaba2c390d8de9e63..121ac665fe0be0da6c683479338d810bf02f28c9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/LinkDef.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/ToolLoaderBase.h" #include "TopEventSelectionTools/TopEventSelectionToolsLoader.h" diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METMWTSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METMWTSelector.cxx index cc2a2ccc0f2802bbef45c7bf69f132147de388a1..81c442d65c9b209a060852cce198670cd409f2f9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METMWTSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METMWTSelector.cxx @@ -1,53 +1,45 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/METMWTSelector.h" #include "TopEvent/EventTools.h" namespace top { + METMWTSelector::METMWTSelector(const std::string& params) : + SignValueSelector("MET+MWT", params) { + } -METMWTSelector::METMWTSelector(const std::string& params) : - SignValueSelector("MET+MWT", params) { -} - -bool METMWTSelector::apply(const top::Event& event) const { + bool METMWTSelector::apply(const top::Event& event) const { const xAOD::IParticle* lepton = 0; - if (!event.m_electrons.empty()) - lepton = event.m_electrons.front(); - else if (!event.m_muons.empty()) - lepton = event.m_muons.front(); + + if (!event.m_electrons.empty()) lepton = event.m_electrons.front(); + else if (!event.m_muons.empty()) lepton = event.m_muons.front(); else { - std::cout << "MET+MWT Tool: Not got a charged lepton" << std::endl; - exit(1); + throw std::runtime_error("METMWTSelector::apply: No charged lepton in event"); } const double metmwt = event.m_met->met() + top::mwt(*lepton, *event.m_met); return checkFloat(metmwt, value()); -} + } -bool METMWTSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool METMWTSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons - or not event.m_met ){ - return false; + if (not event.m_electrons + or not event.m_muons + or not event.m_met) { + return false; } const xAOD::IParticle* lepton = 0; - if (!event.m_electrons->empty()) - lepton = event.m_electrons->front(); - else if (!event.m_muons->empty()) - lepton = event.m_muons->front(); + if (!event.m_electrons->empty()) lepton = event.m_electrons->front(); + else if (!event.m_muons->empty()) lepton = event.m_muons->front(); else { - std::cout << "MET+MWT Tool: Not got a charged lepton" << std::endl; - exit(1); + throw std::runtime_error("METMWTSelector::applyParticleLevel: No charged lepton in event"); } const double metmwt = event.m_met->met() + top::mwt(*lepton, *event.m_met); return checkFloat(metmwt, value()); -} - - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METSelector.cxx index 6a4c86b13bcd6d390e4c204e96508e490e17a0a2..4d7ff924ba3ddeba022577349aa58bf67f0c7d03 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/METSelector.cxx @@ -1,28 +1,26 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/METSelector.h" #include "TopEvent/EventTools.h" namespace top { + METSelector::METSelector(const std::string& params) : + SignValueSelector("MET", params) { + } -METSelector::METSelector(const std::string& params) : - SignValueSelector("MET", params) { -} - -bool METSelector::apply(const top::Event& event) const { + bool METSelector::apply(const top::Event& event) const { return checkFloat(event.m_met->met(), value()); -} + } -bool METSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool METSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_met ){ - return false; + if (not event.m_met) { + return false; } return checkFloat(event.m_met->met(), value()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLSelector.cxx index e23207d4e08eaaa3156cd4fe4bbb54a7bd8944a4..64dfa0988482db4996faf249458120caabe242c4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLSelector.cxx @@ -1,66 +1,61 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/MLLSelector.h" #include "TopEvent/EventTools.h" namespace top { + MLLSelector::MLLSelector(const std::string& params) : + SignValueSelector("MLL", params) { + } -MLLSelector::MLLSelector(const std::string& params) : - SignValueSelector("MLL", params) { -} - -bool MLLSelector::apply(const top::Event& event) const { + bool MLLSelector::apply(const top::Event& event) const { const xAOD::IParticle* lepton0 = 0; const xAOD::IParticle* lepton1 = 0; if (event.m_electrons.size() == 2) { - lepton0 = event.m_electrons[0]; - lepton1 = event.m_electrons[1]; + lepton0 = event.m_electrons[0]; + lepton1 = event.m_electrons[1]; } else if (event.m_muons.size() == 2) { - lepton0 = event.m_muons[0]; - lepton1 = event.m_muons[1]; + lepton0 = event.m_muons[0]; + lepton1 = event.m_muons[1]; } else if (event.m_electrons.size() == 1 && event.m_muons.size() == 1) { - lepton0 = event.m_electrons[0]; - lepton1 = event.m_muons[0]; + lepton0 = event.m_electrons[0]; + lepton1 = event.m_muons[0]; } else { - std::cout << "MLL: Need two charged leptons" << std::endl; - exit(1); + throw std::runtime_error("MLLSelector::apply: Need two charge leptons"); } const double mll = top::invariantMass(*lepton0, *lepton1); return checkFloat(mll, value()); -} + } - bool MLLSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { - // If any of the required collections is a nullptr (i.e. has not been + bool MLLSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } const xAOD::IParticle* lepton0 = 0; const xAOD::IParticle* lepton1 = 0; if (event.m_electrons->size() == 2) { - lepton0 = (*event.m_electrons)[0]; - lepton1 = (*event.m_electrons)[1]; + lepton0 = (*event.m_electrons)[0]; + lepton1 = (*event.m_electrons)[1]; } else if (event.m_muons->size() == 2) { - lepton0 = (*event.m_muons)[0]; - lepton1 = (*event.m_muons)[1]; + lepton0 = (*event.m_muons)[0]; + lepton1 = (*event.m_muons)[1]; } else if (event.m_electrons->size() == 1 && event.m_muons->size() == 1) { - lepton0 = (*event.m_electrons)[0]; - lepton1 = (*event.m_muons)[0]; + lepton0 = (*event.m_electrons)[0]; + lepton1 = (*event.m_muons)[0]; } else { - std::cout << "MLL: Need two charged leptons" << std::endl; - exit(1); + throw std::runtime_error("MLLSelector::applyParticleLevel: Need two charged leptons"); } const double mll = top::invariantMass(*lepton0, *lepton1); return checkFloat(mll, value()); -} - - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLWindowSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLWindowSelector.cxx index a23a581b098ba3a6b6efdfbbab2322af5e60d0c3..d196a7335d4bfea277ac30dfd2e960feb947eee9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLWindowSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MLLWindowSelector.cxx @@ -1,68 +1,63 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/MLLWindowSelector.h" #include "TopEvent/EventTools.h" namespace top { - -MLLWindow::MLLWindow(std::string params) : - m_cutvalue0(0.), - m_cutvalue1(0.) { + MLLWindow::MLLWindow(std::string params) : + m_cutvalue0(0.), + m_cutvalue1(0.) { std::istringstream(params) >> m_cutvalue0 >> m_cutvalue1; -} + } -bool MLLWindow::apply(const top::Event& event) const { + bool MLLWindow::apply(const top::Event& event) const { const xAOD::IParticle* lepton0 = 0; const xAOD::IParticle* lepton1 = 0; if (event.m_electrons.size() == 2) { - lepton0 = event.m_electrons[0]; - lepton1 = event.m_electrons[1]; + lepton0 = event.m_electrons[0]; + lepton1 = event.m_electrons[1]; } else if (event.m_muons.size() == 2) { - lepton0 = event.m_muons[0]; - lepton1 = event.m_muons[1]; + lepton0 = event.m_muons[0]; + lepton1 = event.m_muons[1]; } else { - std::cout << "need two charged leptons of the same flavour" << std::endl; - exit(1); + throw std::runtime_error("MLLWindowSelector::apply: Need two same-flavour electrons or muons"); } const double mll = top::invariantMass(*lepton0, *lepton1); return mll < m_cutvalue0 || mll > m_cutvalue1; -} - + } -bool MLLWindow::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool MLLWindow::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } const xAOD::IParticle* lepton0 = 0; const xAOD::IParticle* lepton1 = 0; if (event.m_electrons->size() == 2) { - lepton0 = (*event.m_electrons)[0]; - lepton1 = (*event.m_electrons)[1]; + lepton0 = (*event.m_electrons)[0]; + lepton1 = (*event.m_electrons)[1]; } else if (event.m_muons->size() == 2) { - lepton0 = (*event.m_muons)[0]; - lepton1 = (*event.m_muons)[1]; + lepton0 = (*event.m_muons)[0]; + lepton1 = (*event.m_muons)[1]; } else { - std::cout << "need two charged leptons of the same flavour" << std::endl; - exit(1); + throw std::runtime_error("MLLWindowSelector::applyParticleLevel: Need two same-flavour electrons or muons"); } const double mll = top::invariantMass(*lepton0, *lepton1); return mll < m_cutvalue0 || mll > m_cutvalue1; -} + } -std::string MLLWindow::name() const { + std::string MLLWindow::name() const { std::stringstream ss; ss << "MLLWIN " << m_cutvalue0 << " " << m_cutvalue1; return ss.str(); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV1Selector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV1Selector.cxx deleted file mode 100644 index ae0c52beecbfcf5abe55ee62e1c1b08fe65419aa..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV1Selector.cxx +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TopEventSelectionTools/MV1Selector.h" -#include "TopEvent/EventTools.h" - -#include <algorithm> - -namespace top { - -MV1Selector::MV1Selector(const std::string& params) : - SignValueSelector("MV1_N", params, true) { - checkMultiplicityIsInteger(); -} - -bool MV1Selector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* const jetPtr) { return jetPtr->btagging()->MV1_discriminant() > value(); }; - auto count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); - return checkInt(count, multiplicity()); -} - -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c10Selector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c10Selector.cxx index e95e5cd5e203056c4a28728d3f08a33943306b2e..47223c9143f6d5580534a425637692f53c788b4f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c10Selector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c10Selector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/MV2c10Selector.h" #include "TopEvent/EventTools.h" @@ -8,24 +8,23 @@ #include <algorithm> namespace top { - -MV2c10Selector::MV2c10Selector(const std::string& params) : - SignValueSelector("MV2C10_N", params, true) { + MV2c10Selector::MV2c10Selector(const std::string& params) : + SignValueSelector("MV2C10_N", params, true) { checkMultiplicityIsInteger(); -} + } + + bool MV2c10Selector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Jet* const /*jetPtr*/) { + //double mv2c10_discriminant = 0.; + //const bool hasMv2c10 = jetPtr->btagging()->MVx_discriminant("MV2c10", mv2c10_discriminant); -bool MV2c10Selector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* const jetPtr) { - double mv2c10_discriminant = 0.; - const bool hasMv2c10 = jetPtr->btagging()->MVx_discriminant("MV2c10", mv2c10_discriminant); - if (hasMv2c10) - return mv2c10_discriminant > value(); + //if (hasMv2c10) return mv2c10_discriminant > value(); - return false; - }; + return false; + }; auto count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); - return checkInt(count, multiplicity()); -} + return checkInt(count, multiplicity()); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c20Selector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c20Selector.cxx deleted file mode 100644 index da4ae7a65586dbb90f8fb6a31f3e6c307404162d..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MV2c20Selector.cxx +++ /dev/null @@ -1,31 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TopEventSelectionTools/MV2c20Selector.h" -#include "TopEvent/EventTools.h" - -#include <algorithm> - -namespace top { - -MV2c20Selector::MV2c20Selector(const std::string& params) : - SignValueSelector("MV2C20_N", params, true) { - checkMultiplicityIsInteger(); -} - -bool MV2c20Selector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* const jetPtr) { - double mv2c20_discriminant = 0.; - const bool hasMv2c20 = jetPtr->btagging()->MVx_discriminant("MV2c20", mv2c20_discriminant); - if (hasMv2c20) - return mv2c20_discriminant > value(); - - return false; - }; - - auto count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); - return checkInt(count, multiplicity()); -} - -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MWTSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MWTSelector.cxx index ef7bb21c5e332cbc7b9486e38f440e4937d062ca..56c104ffe6cfc7c92798b4dc4450aa5ad58e3a8d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MWTSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MWTSelector.cxx @@ -1,53 +1,45 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/MWTSelector.h" #include "TopEvent/EventTools.h" namespace top { + MWTSelector::MWTSelector(const std::string& params) : + SignValueSelector("MWT", params) { + } -MWTSelector::MWTSelector(const std::string& params) : - SignValueSelector("MWT", params) { -} - -bool MWTSelector::apply(const top::Event& event) const { + bool MWTSelector::apply(const top::Event& event) const { const xAOD::IParticle* lepton = 0; - if (!event.m_electrons.empty()) - lepton = event.m_electrons.front(); - else if (!event.m_muons.empty()) - lepton = event.m_muons.front(); + + if (!event.m_electrons.empty()) lepton = event.m_electrons.front(); + else if (!event.m_muons.empty()) lepton = event.m_muons.front(); else { - std::cout << "MWTSelector: Not got a charged lepton" << std::endl; - exit(1); + throw std::runtime_error("MWTSelector::apply: No charged lepton in event"); } const double mwt = top::mwt(*lepton, *event.m_met); return checkFloat(mwt, value()); -} + } -bool MWTSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool MWTSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons - or not event.m_met ){ - return false; + if (not event.m_electrons + or not event.m_muons + or not event.m_met) { + return false; } const xAOD::IParticle* lepton = 0; - if (!event.m_electrons->empty()) - lepton = event.m_electrons->front(); - else if (!event.m_muons->empty()) - lepton = event.m_muons->front(); + if (!event.m_electrons->empty()) lepton = event.m_electrons->front(); + else if (!event.m_muons->empty()) lepton = event.m_muons->front(); else { - std::cout << "MWTSelector: Not got a charged lepton" << std::endl; - exit(1); + throw std::runtime_error("MWTSelector::applyParticleLevel: No charged lepton in event"); } const double mwt = top::mwt(*lepton, *event.m_met); return checkFloat(mwt, value()); -} - - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MsgCategory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MsgCategory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..543dd0707d10bbec1f8968adea080d2c699c4843 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/MsgCategory.cxx @@ -0,0 +1,6 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#include "TopEventSelectionTools/MsgCategory.h" + +ANA_MSG_SOURCE(TopEventSelectionTools, "TopEventSelectionTools") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonSelector.cxx index 2405da836f709aa3eb724508c954b6e4895e0f0a..01217aebdf670f5dbef48c44555730def8ccbec3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonSelector.cxx @@ -1,41 +1,47 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NElectronNMuonSelector.h" namespace top { - -NElectronNMuonSelector::NElectronNMuonSelector(const std::string& params) : - SignValueSelector("EL_N_OR_MU_N", params, true) { + NElectronNMuonSelector::NElectronNMuonSelector(const std::string& params) : + SignValueSelector("EL_N_OR_MU_N", params, true) { checkMultiplicityIsInteger(); -} + } -bool NElectronNMuonSelector::apply(const top::Event& event) const { - auto elFunc = [&](const xAOD::Electron* elPtr){return elPtr->pt() > value();}; + bool NElectronNMuonSelector::apply(const top::Event& event) const { + auto elFunc = [&](const xAOD::Electron* elPtr) { + return elPtr->pt() > value(); + }; auto elCount = std::count_if(event.m_electrons.begin(), event.m_electrons.end(), elFunc); - auto muFunc = [&](const xAOD::Muon* muPtr){return muPtr->pt() > value();}; + auto muFunc = [&](const xAOD::Muon* muPtr) { + return muPtr->pt() > value(); + }; auto muCount = std::count_if(event.m_muons.begin(), event.m_muons.end(), muFunc); return checkInt(elCount, multiplicity()) || checkInt(muCount, multiplicity()); -} + } -bool NElectronNMuonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NElectronNMuonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } - auto elFunc = [&](const xAOD::TruthParticle* truElPtr){return truElPtr->pt() > value();}; + auto elFunc = [&](const xAOD::TruthParticle* truElPtr) { + return truElPtr->pt() > value(); + }; auto elCount = std::count_if(event.m_electrons->begin(), event.m_electrons->end(), elFunc); - auto muFunc = [&](const xAOD::TruthParticle* truMuPtr){return truMuPtr->pt() > value();}; + auto muFunc = [&](const xAOD::TruthParticle* truMuPtr) { + return truMuPtr->pt() > value(); + }; auto muCount = std::count_if(event.m_muons->begin(), event.m_muons->end(), muFunc); return checkInt(elCount, multiplicity()) || checkInt(muCount, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonTightSelector.cxx index bac0a91f46bc1687ffb0829711488338493031db..dfc8cd0b0a83daaea815502c28870e408cf5ff24 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonTightSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronNMuonTightSelector.cxx @@ -1,41 +1,47 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NElectronNMuonTightSelector.h" namespace top { - -NElectronNMuonTightSelector::NElectronNMuonTightSelector(const std::string& params) : - SignValueSelector("EL_N_OR_MU_N_TIGHT", params, true) { + NElectronNMuonTightSelector::NElectronNMuonTightSelector(const std::string& params) : + SignValueSelector("EL_N_OR_MU_N_TIGHT", params, true) { checkMultiplicityIsInteger(); -} + } -bool NElectronNMuonTightSelector::apply(const top::Event& event) const { - auto elFunc = [&](const xAOD::Electron* elPtr){return elPtr->pt() > value() && elPtr->auxdataConst<char>("passPreORSelection");}; + bool NElectronNMuonTightSelector::apply(const top::Event& event) const { + auto elFunc = [&](const xAOD::Electron* elPtr) { + return elPtr->pt() > value() && elPtr->auxdataConst<char>("passPreORSelection"); + }; auto elCount = std::count_if(event.m_electrons.begin(), event.m_electrons.end(), elFunc); - auto muFunc = [&](const xAOD::Muon* muPtr){return muPtr->pt() > value() && muPtr->auxdataConst<char>("passPreORSelection");}; + auto muFunc = [&](const xAOD::Muon* muPtr) { + return muPtr->pt() > value() && muPtr->auxdataConst<char>("passPreORSelection"); + }; auto muCount = std::count_if(event.m_muons.begin(), event.m_muons.end(), muFunc); return checkInt(elCount, multiplicity()) || checkInt(muCount, multiplicity()); -} + } -bool NElectronNMuonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NElectronNMuonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } - auto elFunc = [&](const xAOD::TruthParticle* truElPtr){return truElPtr->pt() > value();}; + auto elFunc = [&](const xAOD::TruthParticle* truElPtr) { + return truElPtr->pt() > value(); + }; auto elCount = std::count_if(event.m_electrons->begin(), event.m_electrons->end(), elFunc); - auto muFunc = [&](const xAOD::TruthParticle* truMuPtr){return truMuPtr->pt() > value();}; + auto muFunc = [&](const xAOD::TruthParticle* truMuPtr) { + return truMuPtr->pt() > value(); + }; auto muCount = std::count_if(event.m_muons->begin(), event.m_muons->end(), muFunc); return checkInt(elCount, multiplicity()) || checkInt(muCount, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronSelector.cxx index e66390ed04635856df7c1be8559d4293676ab9fa..bc293da7635404926938dca0d18f1c88a293afd5 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronSelector.cxx @@ -1,34 +1,37 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NElectronSelector.h" #include <algorithm> namespace top { - -NElectronSelector::NElectronSelector(const std::string& params) : - SignValueSelector("EL_N", params, true) { + NElectronSelector::NElectronSelector(const std::string& params) : + SignValueSelector("EL_N", params, true) { checkMultiplicityIsInteger(); -} + } -bool NElectronSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Electron* elPtr){return elPtr->pt() > value();}; + bool NElectronSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Electron* elPtr) { + return elPtr->pt() > value(); + }; auto count = std::count_if(event.m_electrons.begin(), event.m_electrons.end(), func); + return checkInt(count, multiplicity()); -} + } -bool NElectronSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NElectronSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons ){ - return false; + if (!event.m_electrons) { + return false; } - auto func = [&](const xAOD::TruthParticle* truElPtr){return truElPtr->pt() > value();}; + auto func = [&](const xAOD::TruthParticle* truElPtr) { + return truElPtr->pt() > value(); + }; auto count = std::count_if(event.m_electrons->begin(), event.m_electrons->end(), func); return checkInt(count, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronTightSelector.cxx index e7fb0357f64e93bae91de1bf44cdddd53319d741..8dcba9f800f357b10f4d3344b9a4a76bc0f99c8f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronTightSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NElectronTightSelector.cxx @@ -1,34 +1,37 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NElectronTightSelector.h" #include <algorithm> namespace top { - -NElectronTightSelector::NElectronTightSelector(const std::string& params) : - SignValueSelector("EL_N_TIGHT", params, true) { + NElectronTightSelector::NElectronTightSelector(const std::string& params) : + SignValueSelector("EL_N_TIGHT", params, true) { checkMultiplicityIsInteger(); -} + } -bool NElectronTightSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Electron* elPtr){return elPtr->pt() > value() && elPtr->auxdataConst<char>("passPreORSelection");}; + bool NElectronTightSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Electron* elPtr) { + return elPtr->pt() > value() && elPtr->auxdataConst<char>("passPreORSelection"); + }; auto count = std::count_if(event.m_electrons.begin(), event.m_electrons.end(), func); + return checkInt(count, multiplicity()); -} + } -bool NElectronTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NElectronTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons ){ - return false; + if (not event.m_electrons) { + return false; } - auto func = [&](const xAOD::TruthParticle* truElPtr){return truElPtr->pt() > value();}; + auto func = [&](const xAOD::TruthParticle* truElPtr) { + return truElPtr->pt() > value(); + }; auto count = std::count_if(event.m_electrons->begin(), event.m_electrons->end(), func); return checkInt(count, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NFwdElectronSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NFwdElectronSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..7849d6abac0a04dbcc7b27f1f42f72af500c0bd8 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NFwdElectronSelector.cxx @@ -0,0 +1,26 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/NFwdElectronSelector.h" +#include <algorithm> + +namespace top { + NFwdElectronSelector::NFwdElectronSelector(const std::string& params) : + SignValueSelector("FWDEL_N", params, true) { + checkMultiplicityIsInteger(); + } + + bool NFwdElectronSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Electron* elPtr) { + return elPtr->pt() > value(); + }; + auto count = std::count_if(event.m_fwdElectrons.begin(), event.m_fwdElectrons.end(), func); + + return checkInt(count, multiplicity()); + } + + bool NFwdElectronSelector::applyParticleLevel(const top::ParticleLevelEvent& /*event*/) const { + return true; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NFwdElectronTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NFwdElectronTightSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..2b6b916db12000d848712c957fefcb5e83ca44f5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NFwdElectronTightSelector.cxx @@ -0,0 +1,32 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/NFwdElectronTightSelector.h" +#include <algorithm> + +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; + +namespace top { + NFwdElectronTightSelector::NFwdElectronTightSelector(const std::string& params) : + SignValueSelector("FWDEL_N_TIGHT", params, true) { + checkMultiplicityIsInteger(); + } + + bool NFwdElectronTightSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Electron* elPtr) { + return elPtr->pt() > value() && elPtr->auxdataConst<char>("passPreORSelection"); + }; + auto count = std::count_if(event.m_fwdElectrons.begin(), event.m_fwdElectrons.end(), func); + + return checkInt(count, multiplicity()); + } + + bool NFwdElectronTightSelector::applyParticleLevel(const top::ParticleLevelEvent& /*event*/) const { + ATH_MSG_INFO("NFwdElectronTightSelector::applyParticleLevel: " + << "no separate fwdElectrons container currently defined at particleLevel" + << "FWDEL_N_TIGHT always returning true at particle level."); + return true; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetBtagSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetBtagSelector.cxx index 0efc659d09a9bedc226cb9e8b1b0831ba708c126..75b90fcd11b2fbf8a966bc73c1ebfa4a02e3686f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetBtagSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetBtagSelector.cxx @@ -1,36 +1,52 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NJetBtagSelector.h" #include "TopConfiguration/TopConfig.h" -namespace top { +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; -NJetBtagSelector::NJetBtagSelector(const std::string& params,std::shared_ptr<top::TopConfig> config) : - SignValueSelector("JET_N_BTAG", params, true, true) { +namespace top { + NJetBtagSelector::NJetBtagSelector(const std::string& params, std::shared_ptr<top::TopConfig> config, + bool doTrackJets) : + SignValueSelector((doTrackJets ? "TJET_N_BTAG" : "JET_N_BTAG"), params, true, true, ":", "_", "DL1r"), + m_doTrackJets(doTrackJets) { checkMultiplicityIsInteger(); - // check if the provided btag WP is really available - if (std::find(config->bTagWP_available().begin(), config->bTagWP_available().end(), valueString()) == config->bTagWP_available().end()) { - std::cout << "NJetBtagSelector is confused\n"; - std::cout << "B-tagging working point " << valueString() << " doesn't seem to be supported.\n"; - std::cout << "Please provide a real one! Did you specified it in the \"BTaggingWP\" field of your cutfile?\n"; - exit(1); + // check if the provided btag WP is really available - need to replace : with _ to match the naming of variables + bool bTagWP_exists = false; + if (m_doTrackJets) bTagWP_exists = + (std::find(config->bTagWP_available_trkJet().begin(), config->bTagWP_available_trkJet().end(), + valueStringDelimReplace()) != config->bTagWP_available_trkJet().end()); + else bTagWP_exists = + (std::find(config->bTagWP_available().begin(), config->bTagWP_available().end(), + valueStringDelimReplace()) != config->bTagWP_available().end()); + + if (!bTagWP_exists) { + ATH_MSG_ERROR("NJetBtagSelector is confused\n" + << "B-tagging working point " << valueString() << " doesn't seem to be supported.\n" + << "Please note that you should provide the argument as ==> bTagAlgorithm:bTagWP now. \n " + << "Please provide a real one! Did you specified it in the \"BTaggingWP\" field of your cutfile?\n"); + throw std::runtime_error("NJetBtagSelector: Invalid btagging selector WP: " + name()); } -} + } -bool NJetBtagSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* jetPtr){ - if(!jetPtr->isAvailable<char>("isbtagged_"+valueString())) { - std::cout << "NJetBtagSelector is confused\n"; - std::cout << "A jet doesn't have the necessady decoration called \"isbtagged_"+valueString()+"\".\n"; - std::cout << "Exiting...\n"; - exit(1); - } - return jetPtr->auxdataConst<char>("isbtagged_"+valueString()); - }; - auto count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); - return checkInt(count, multiplicity()); -} + bool NJetBtagSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Jet* jetPtr) { + if (!jetPtr->isAvailable<char>("isbtagged_" + valueStringDelimReplace())) { + throw std::runtime_error("NJetBtagSelector: Jet doesn't have decoration \"isbtagged_" + + valueStringDelimReplace() + "\""); + } + return jetPtr->auxdataConst<char>("isbtagged_" + valueStringDelimReplace()); + }; + int count = 0; + if (m_doTrackJets) { + count = std::count_if(event.m_trackJets.begin(), event.m_trackJets.end(), func); + } else { + count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); + } + return checkInt(count, multiplicity()); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetSelector.cxx index de9c8de7df8467bee34ad821dd4fab54daba9a2a..d929173ae37eefdb2233fe6d178fa8a34bde231d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NJetSelector.cxx @@ -1,32 +1,35 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NJetSelector.h" namespace top { - -NJetSelector::NJetSelector(const std::string& params) : - SignValueSelector("JET_N", params, true) { + NJetSelector::NJetSelector(const std::string& params) : + SignValueSelector("JET_N", params, true) { checkMultiplicityIsInteger(); -} + } -bool NJetSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* jetPtr){return jetPtr->pt() > value();}; + bool NJetSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; auto count = std::count_if(event.m_jets.begin(), event.m_jets.end(), func); + return checkInt(count, multiplicity()); -} + } -bool NJetSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NJetSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_jets ){ - return false; + if (not event.m_jets) { + return false; } - auto func = [&](const xAOD::Jet* truJetPtr){return truJetPtr->pt() > value();}; + auto func = [&](const xAOD::Jet* truJetPtr) { + return truJetPtr->pt() > value(); + }; auto count = std::count_if(event.m_jets->begin(), event.m_jets->end(), func); return checkInt(count, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NLargeJetSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NLargeJetSelector.cxx index 8670c3b0966e1bddfa445ea5854cb818d2ade196..8340948ad1ed3b0733a65f77a51de239a77dc857 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NLargeJetSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NLargeJetSelector.cxx @@ -1,26 +1,30 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NLargeJetSelector.h" -namespace top{ - +namespace top { NLargeJetSelector::NLargeJetSelector(const std::string& params) : SignValueSelector("LJET_N", params, true) { checkMultiplicityIsInteger(); } bool NLargeJetSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Jet* jetPtr){return jetPtr->pt() > value();}; + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; auto count = std::count_if(event.m_largeJets.begin(), event.m_largeJets.end(), func); + return checkInt(count, multiplicity()); } bool NLargeJetSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { - auto func = [&](const xAOD::Jet* jetPtr){return jetPtr->pt() > value();}; + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; auto count = std::count_if(event.m_largeRJets->begin(), event.m_largeRJets->end(), func); + return checkInt(count, multiplicity()); } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonSelector.cxx index dc1e90ddbef935e6e3dfeb3755337f6fcb9e6c56..97e9fc744847c606dfbfc391d286162afbc21135 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonSelector.cxx @@ -1,34 +1,37 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NMuonSelector.h" #include <algorithm> namespace top { - -NMuonSelector::NMuonSelector(const std::string& params) : - SignValueSelector("MU_N", params, true) { + NMuonSelector::NMuonSelector(const std::string& params) : + SignValueSelector("MU_N", params, true) { checkMultiplicityIsInteger(); -} + } -bool NMuonSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Muon* muPtr){return muPtr->pt() > value();}; + bool NMuonSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Muon* muPtr) { + return muPtr->pt() > value(); + }; auto count = std::count_if(event.m_muons.begin(), event.m_muons.end(), func); + return checkInt(count, multiplicity()); -} + } -bool NMuonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NMuonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_muons ){ - return false; + if (not event.m_muons) { + return false; } - auto func = [&](const xAOD::TruthParticle* truMuPtr){return truMuPtr->pt() > value();}; + auto func = [&](const xAOD::TruthParticle* truMuPtr) { + return truMuPtr->pt() > value(); + }; auto count = std::count_if(event.m_muons->begin(), event.m_muons->end(), func); return checkInt(count, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonTightSelector.cxx index 5f55ef3eb5d0c7320c60063144b9c58a42808dce..8c910717bac4625c319175f6f72994a07889d60b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonTightSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NMuonTightSelector.cxx @@ -1,34 +1,37 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NMuonTightSelector.h" #include <algorithm> namespace top { - -NMuonTightSelector::NMuonTightSelector(const std::string& params) : - SignValueSelector("MU_N_TIGHT", params, true) { + NMuonTightSelector::NMuonTightSelector(const std::string& params) : + SignValueSelector("MU_N_TIGHT", params, true) { checkMultiplicityIsInteger(); -} + } -bool NMuonTightSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Muon* muPtr){return muPtr->pt() > value() && muPtr->auxdataConst<char>("passPreORSelection");}; + bool NMuonTightSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Muon* muPtr) { + return muPtr->pt() > value() && muPtr->auxdataConst<char>("passPreORSelection"); + }; auto count = std::count_if(event.m_muons.begin(), event.m_muons.end(), func); + return checkInt(count, multiplicity()); -} + } -bool NMuonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool NMuonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_muons ){ - return false; + if (not event.m_muons) { + return false; } - auto func = [&](const xAOD::TruthParticle* truMuPtr){return truMuPtr->pt() > value();}; + auto func = [&](const xAOD::TruthParticle* truMuPtr) { + return truMuPtr->pt() > value(); + }; auto count = std::count_if(event.m_muons->begin(), event.m_muons->end(), func); return checkInt(count, multiplicity()); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NPhotonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NPhotonSelector.cxx index b7f017db57d506d0f9dd24cbe1846719bc9d78b4..c48904655cf8c7a40eeb3e893003f30e84cc27ea 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NPhotonSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NPhotonSelector.cxx @@ -1,28 +1,32 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NPhotonSelector.h" #include <algorithm> namespace top { - -NPhotonSelector::NPhotonSelector(const std::string& params) : - SignValueSelector("PH_N", params, true) { + NPhotonSelector::NPhotonSelector(const std::string& params) : + SignValueSelector("PH_N", params, true) { checkMultiplicityIsInteger(); -} + } -bool NPhotonSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::Photon* phPtr){return phPtr->pt() > value();}; + bool NPhotonSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Photon* phPtr) { + return phPtr->pt() > value(); + }; auto count = std::count_if(event.m_photons.begin(), event.m_photons.end(), func); + return checkInt(count, multiplicity()); -} + } -bool NPhotonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { - auto func = [&](const xAOD::TruthParticle* truPhPtr){return truPhPtr->pt() > value();}; - auto count = std::count_if(event.m_photons->begin(), event.m_photons->end(), func); - return checkInt(count, multiplicity()); -} + bool NPhotonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + auto func = [&](const xAOD::TruthParticle* truPhPtr) { + return truPhPtr->pt() > value(); + }; + auto count = std::count_if(event.m_photons->begin(), event.m_photons->end(), func); + return checkInt(count, multiplicity()); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NRCJetSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NRCJetSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..18683b0a3ff2d2682e8e1aa6374b18f95b2d865d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NRCJetSelector.cxx @@ -0,0 +1,30 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/NRCJetSelector.h" + +namespace top { + NRCJetSelector::NRCJetSelector(const std::string& params) : + SignValueSelector("RCJET_N", params, true) { + checkMultiplicityIsInteger(); + } + + bool NRCJetSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; + auto count = std::count_if(event.m_RCJets.begin(), event.m_RCJets.end(), func); + + return checkInt(count, multiplicity()); + } + + bool NRCJetSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; + auto count = std::count_if(event.m_RCJets.begin(), event.m_RCJets.end(), func); + + return checkInt(count, multiplicity()); + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NSoftMuonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NSoftMuonSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..b3e35e59b50160994eb4116ebed37a12ecc0b85d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NSoftMuonSelector.cxx @@ -0,0 +1,28 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/NSoftMuonSelector.h" + +#include <algorithm> + +namespace top { + NSoftMuonSelector::NSoftMuonSelector(const std::string& params) : + SignValueSelector("SOFTMU_N", params, true) { + checkMultiplicityIsInteger(); + } + + bool NSoftMuonSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Muon* muPtr) { + return muPtr->pt() > value(); + }; + auto count = std::count_if(event.m_softmuons.begin(), event.m_softmuons.end(), func); + + return checkInt(count, multiplicity()); + } + + bool NSoftMuonSelector::applyParticleLevel(const top::ParticleLevelEvent& /*event*/) const { + // the soft muon selector at particle level is just dummy for the time being + return true; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauSelector.cxx index 45ccc70007563956836273715ac0522c3f9c8765..29e40db457d6913a0b6f6c4d498cee3deb7122ca 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauSelector.cxx @@ -1,20 +1,35 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NTauSelector.h" namespace top { - -NTauSelector::NTauSelector(const std::string& params) : - SignValueSelector("TAU_N", params, true) { + NTauSelector::NTauSelector(const std::string& params) : + SignValueSelector("TAU_N", params, true) { checkMultiplicityIsInteger(); -} + } -bool NTauSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::TauJet* tauPtr){return tauPtr->pt() > value();}; + bool NTauSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::TauJet* tauPtr) { + return tauPtr->pt() > value(); + }; auto count = std::count_if(event.m_tauJets.begin(), event.m_tauJets.end(), func); + return checkInt(count, multiplicity()); -} + } + + bool NTauSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + // If any of the required collections is a nullptr (i.e. has not been + // loaded) return false. + if (!event.m_taus) { + return false; + } + auto func = [&](const xAOD::TruthParticle* truTauPtr) { + return truTauPtr->pt() > value(); + }; + auto count = std::count_if(event.m_taus->begin(), event.m_taus->end(), func); + return checkInt(count, multiplicity()); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauTightSelector.cxx index 445ecb8a4245ba6e6da94fc9111cb89fe6b51d3a..3a378e488f77f74266e034a5f4e2db055f18a013 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauTightSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NTauTightSelector.cxx @@ -1,20 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NTauTightSelector.h" namespace top { - -NTauTightSelector::NTauTightSelector(const std::string& params) : - SignValueSelector("TAU_N_TIGHT", params, true) { + NTauTightSelector::NTauTightSelector(const std::string& params) : + SignValueSelector("TAU_N_TIGHT", params, true) { checkMultiplicityIsInteger(); -} + } -bool NTauTightSelector::apply(const top::Event& event) const { - auto func = [&](const xAOD::TauJet* tauPtr){return tauPtr->pt() > value() && tauPtr->auxdataConst<char>("passPreORSelection");}; + bool NTauTightSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::TauJet* tauPtr) { + return tauPtr->pt() > value() && tauPtr->auxdataConst<char>("passPreORSelection"); + }; auto count = std::count_if(event.m_tauJets.begin(), event.m_tauJets.end(), func); - return checkInt(count, multiplicity()); -} + return checkInt(count, multiplicity()); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NVarRCJetSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NVarRCJetSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..9d450af68440bc1b0d42fe8b0fc867fd1903d29e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NVarRCJetSelector.cxx @@ -0,0 +1,40 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/NVarRCJetSelector.h" +#include "TopEvent/EventTools.h" +#include <iostream> + +namespace top { + NVarRCJetSelector::NVarRCJetSelector(const std::string& name, const std::string& params) : + SignValueSelector("VRCJET_N " + name, params, true), + m_name(name) { + checkMultiplicityIsInteger(); + } + + bool NVarRCJetSelector::apply(const top::Event& event) const { + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; + + top::check(event.m_VarRCJets.find( + m_name) != event.m_VarRCJets.end(), + "Error in NVarRCJetSelector: Variable-R reclustered jets with parameter " + m_name + " not defined!"); + std::unordered_map< std::string, std::shared_ptr<xAOD::JetContainer> > VarRCJets = event.m_VarRCJets; + auto count = std::count_if(VarRCJets[m_name]->begin(), VarRCJets[m_name]->end(), func); + return checkInt(count, multiplicity()); + } + + bool NVarRCJetSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + auto func = [&](const xAOD::Jet* jetPtr) { + return jetPtr->pt() > value(); + }; + + top::check(event.m_VarRCJets.find( + m_name) != event.m_VarRCJets.end(), + "Error in NVarRCJetSelector: Variable-R reclustered jets with parameter " + m_name + " not defined!"); + auto count = std::count_if(event.m_VarRCJets[m_name]->begin(), event.m_VarRCJets[m_name]->end(), func); + return checkInt(count, multiplicity()); + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NoBadMuonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NoBadMuonSelector.cxx index 9211a78d394a0b85a07682a0f09b88440e608155..742a31aaab335eb2e3143caf2c9bf4666863108f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NoBadMuonSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/NoBadMuonSelector.cxx @@ -1,32 +1,33 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/NoBadMuonSelector.h" #include "TopEvent/EventTools.h" +#include "TopConfiguration/TopConfig.h" namespace top { - - NoBadMuonSelector::NoBadMuonSelector() : - m_muonSelectionTool("CP::MuonSelectionTool") - { - top::check( m_muonSelectionTool.retrieve() , "Failed to retrieve muonSelectionTool" ); + NoBadMuonSelector::NoBadMuonSelector(std::shared_ptr<top::TopConfig> config) : + m_config(config) { + if (!m_config->isTruthDxAOD()) { + m_muonSelectionTool = ToolHandle<CP::IMuonSelectionTool>("CP::MuonSelectionTool"); + top::check(m_muonSelectionTool.retrieve(), "Failed to retrieve muonSelectionTool"); + } } - bool NoBadMuonSelector::apply(const top::Event& event) const - { + bool NoBadMuonSelector::apply(const top::Event& event) const { + if (m_config->isTruthDxAOD()) return true; + for (const auto* const muPtr : event.m_muons) { if (m_muonSelectionTool->isBadMuon(*muPtr)) { - event.m_info->auxdecor<char>("AnalysisTop_HASBADMUON") = 1 ; - return false; + event.m_info->auxdecor<char>("AnalysisTop_HASBADMUON") = 1; + return false; } } return true; } - std::string NoBadMuonSelector::name() const - { + std::string NoBadMuonSelector::name() const { return "NOBADMUON"; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonSelector.cxx index 0ea7add9c1c54a1a8dcf0950aea0d536096cf5f5..60762edc5512163fa5995a48651bd6993328c485 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonSelector.cxx @@ -1,59 +1,49 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/OSLeptonSelector.h" #include "TopEvent/EventTools.h" namespace top { - -bool OSLeptonSelector::apply(const top::Event& event) const { + bool OSLeptonSelector::apply(const top::Event& event) const { unsigned int negative_counter = 0; unsigned int positive_counter = 0; for (const auto* const elPtr : event.m_electrons) - if (elPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + if (elPtr->charge() > 0) ++positive_counter; + else ++negative_counter; for (const auto* const muPtr : event.m_muons) - if (muPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + if (muPtr->charge() > 0) ++positive_counter; + else ++negative_counter; return positive_counter > 0 && negative_counter > 0; -} + } -bool OSLeptonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool OSLeptonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } unsigned int negative_counter = 0; unsigned int positive_counter = 0; - for (const auto elPtr : * event.m_electrons) - if (elPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto elPtr : *event.m_electrons) + if (elPtr->charge() > 0) ++positive_counter; + else ++negative_counter; - for (const auto muPtr : * event.m_muons) - if (muPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto muPtr : *event.m_muons) + if (muPtr->charge() > 0) ++positive_counter; + else ++negative_counter; return positive_counter > 0 && negative_counter > 0; -} + } -std::string OSLeptonSelector::name() const { + std::string OSLeptonSelector::name() const { return "OS"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonTightSelector.cxx index ec7f4756cc3ec8e0577f1f88a5a00fb82020a3b5..6f3fb5bf1b3e9e37f1729dcd23b62314f7491b15 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonTightSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/OSLeptonTightSelector.cxx @@ -1,59 +1,49 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/OSLeptonTightSelector.h" #include "TopEvent/EventTools.h" namespace top { - -bool OSLeptonTightSelector::apply(const top::Event& event) const { + bool OSLeptonTightSelector::apply(const top::Event& event) const { unsigned int negative_counter = 0; unsigned int positive_counter = 0; for (const auto* const elPtr : event.m_electrons) - if (elPtr->charge() > 0 && elPtr->auxdataConst<char>("passPreORSelection")) - ++positive_counter; - else if (elPtr->charge() < 0 && elPtr->auxdataConst<char>("passPreORSelection")) - ++negative_counter; + if (elPtr->charge() > 0 && elPtr->auxdataConst<char>("passPreORSelection")) ++positive_counter; + else if (elPtr->charge() < 0 && elPtr->auxdataConst<char>("passPreORSelection")) ++negative_counter; for (const auto* const muPtr : event.m_muons) - if (muPtr->charge() > 0 && muPtr->auxdataConst<char>("passPreORSelection")) - ++positive_counter; - else if (muPtr->charge() < 0 && muPtr->auxdataConst<char>("passPreORSelection")) - ++negative_counter; + if (muPtr->charge() > 0 && muPtr->auxdataConst<char>("passPreORSelection")) ++positive_counter; + else if (muPtr->charge() < 0 && muPtr->auxdataConst<char>("passPreORSelection")) ++negative_counter; return positive_counter > 0 && negative_counter > 0; -} + } -bool OSLeptonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool OSLeptonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } unsigned int negative_counter = 0; unsigned int positive_counter = 0; - for (const auto elPtr : * event.m_electrons) - if (elPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto elPtr : *event.m_electrons) + if (elPtr->charge() > 0) ++positive_counter; + else ++negative_counter; - for (const auto muPtr : * event.m_muons) - if (muPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto muPtr : *event.m_muons) + if (muPtr->charge() > 0) ++positive_counter; + else ++negative_counter; return positive_counter > 0 && negative_counter > 0; -} + } -std::string OSLeptonTightSelector::name() const { + std::string OSLeptonTightSelector::name() const { return "OS_TIGHT"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ParticleLevelSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ParticleLevelSelector.cxx index d4ca789831e2a79d0bedab9110f27b5044862b4c..60353c83f06fd6578c3d2c7f8c17ec0adcb9a323 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ParticleLevelSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/ParticleLevelSelector.cxx @@ -1,32 +1,19 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: ParticleLevelSelector.cxx -// Description: -// Author: Fabian Wilk -// Created: Tue Oct 27 13:29:16 2015 -// -// (c) by Fabian Wilk -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/ParticleLevelSelector.h" namespace top { - bool ParticleLevelSelector::apply(const top::Event&) const { - return false; - } + bool ParticleLevelSelector::apply(const top::Event&) const { + return false; + } - bool ParticleLevelSelector::applyParticleLevel(const top::ParticleLevelEvent&) const { - return true; - } + bool ParticleLevelSelector::applyParticleLevel(const top::ParticleLevelEvent&) const { + return true; + } - std::string ParticleLevelSelector::name() const { - return "PARTICLE_LEVEL"; - } + std::string ParticleLevelSelector::name() const { + return "PARTICLE_LEVEL"; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PlotManager.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PlotManager.cxx index e4d37838d33a528de9826dd78ed687f689a5ae2e..a31343eb92fcf83eeeec6396f0ef9fe9cd93e82d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PlotManager.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PlotManager.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "EventLoop/Worker.h" @@ -15,108 +15,173 @@ #include <iostream> namespace top { - -PlotManager::PlotManager(const std::string& name, TFile* outputFile, EL::Worker* wk) : + PlotManager::PlotManager(const std::string& name, TFile* outputFile, EL::Worker* wk) : m_wk(wk), m_name(name), m_plotDir(nullptr) { - if (!m_wk) { m_plotDir = outputFile->GetDirectory(m_name.c_str()); - if (!m_plotDir) - m_plotDir = outputFile->mkdir(m_name.c_str()); + if (!m_plotDir) m_plotDir = outputFile->mkdir(m_name.c_str()); + m_plotDir = outputFile->GetDirectory(m_name.c_str());// this is needed if the name contains a sub-directory m_plotDir->cd(); } -} + } -PlotManager::PlotManager(const std::string& sample,const std::string& channel,const std::string& syst,TFile* outputFile) : - m_wk(nullptr), - m_name("SetMe"), - m_plotDir(nullptr) -{ - outputFile->cd(); - gDirectory->cd("/"); - - if( !gDirectory->GetKey(sample.c_str()) ){gDirectory->mkdir(sample.c_str());} - gDirectory->cd(sample.c_str()); - - if( !gDirectory->GetKey(channel.c_str()) ){gDirectory->mkdir(channel.c_str());} - gDirectory->cd(channel.c_str()); - - if( !gDirectory->GetKey(syst.c_str()) ){gDirectory->mkdir(syst.c_str());} - gDirectory->cd(syst.c_str()); - - TString plotDirName = sample + "/" + channel + "/" + syst; - - m_plotDir = outputFile->GetDirectory(plotDirName); - m_plotDir->cd(); -} + PlotManager::PlotManager(const std::string& sample, const std::string& channel, const std::string& syst, + TFile* outputFile) : + m_wk(nullptr), + m_name("SetMe"), + m_plotDir(nullptr) { + outputFile->cd(); + gDirectory->cd("/"); + + if (!gDirectory->GetKey(sample.c_str())) { + gDirectory->mkdir(sample.c_str()); + } + gDirectory->cd(sample.c_str()); -void PlotManager::addHist(const std::string& hname, const std::string& title, int bins, double start, double end) const { + if (!gDirectory->GetKey(channel.c_str())) { + gDirectory->mkdir(channel.c_str()); + } + gDirectory->cd(channel.c_str()); + + if (!gDirectory->GetKey(syst.c_str())) { + gDirectory->mkdir(syst.c_str()); + } + gDirectory->cd(syst.c_str()); + + TString plotDirName = sample + "/" + channel + "/" + syst; + + m_plotDir = outputFile->GetDirectory(plotDirName); + m_plotDir->cd(); + } + + void PlotManager::addHist(const std::string& hname, const std::string& title, int bins, double start, + double end) const { TH1D* h = nullptr; + if (!m_wk) { - m_plotDir->cd(); - h = new TH1D(hname.c_str(), title.c_str(), bins, start, end); - } - else { - std::string pathname = m_name + "/" + hname; - h = new TH1D(pathname.c_str(), title.c_str(), bins, start, end); - m_wk->addOutput(h); + m_plotDir->cd(); + h = new TH1D(hname.c_str(), title.c_str(), bins, start, end); + } else { + std::string pathname = m_name + "/" + hname; + h = new TH1D(pathname.c_str(), title.c_str(), bins, start, end); + m_wk->addOutput(h); } - if (m_histograms.find(hname) != m_histograms.end()) { - std::cout << "ERROR: Running addHist with " << hname << std::endl; - std::cout << "but that histogram already exists" << std::endl; - std::cout << "will not continue" << std::endl; - exit(1); + checkDuplicate(hname); + + h->Sumw2(); + m_histograms.insert(make_pair(hname, h)); + } + + void PlotManager::addHist(const std::string& hname, const std::string& title, int bins, double* binArray) const { + TH1D* h = nullptr; + + if (!m_wk) { + m_plotDir->cd(); + h = new TH1D(hname.c_str(), title.c_str(), bins, binArray); + } else { + std::string pathname = m_name + "/" + hname; + h = new TH1D(pathname.c_str(), title.c_str(), bins, binArray); + m_wk->addOutput(h); } + checkDuplicate(hname); + h->Sumw2(); m_histograms.insert(make_pair(hname, h)); -} + } -void PlotManager::addHist(const std::string& hname, const std::string& title, - int xbins, double xstart, double xend, - int ybins, double ystart, double yend) const { + void PlotManager::addHist(const std::string& hname, const std::string& title, + int xbins, double xstart, double xend, + int ybins, double ystart, double yend) const { TH2D* h = nullptr; + if (!m_wk) { - m_plotDir->cd(); - h = new TH2D(hname.c_str(), title.c_str(), - xbins, xstart, xend, - ybins, ystart, yend); + m_plotDir->cd(); + h = new TH2D(hname.c_str(), title.c_str(), + xbins, xstart, xend, + ybins, ystart, yend); + } else { + std::string pathname = m_name + "/" + hname; + h = new TH2D(pathname.c_str(), title.c_str(), + xbins, xstart, xend, + ybins, ystart, yend); + m_wk->addOutput(h); } - else { - std::string pathname = m_name + "/" + hname; - h = new TH2D(pathname.c_str(), title.c_str(), - xbins, xstart, xend, - ybins, ystart, yend); - m_wk->addOutput(h); + + checkDuplicate(hname); + + h->Sumw2(); + m_histograms.insert(make_pair(hname, h)); + } + + void PlotManager::addHist(const std::string& hname, const std::string& title, + int xbins, double* xbinArray, + int ybins, double* ybinArray) const { + TH2D* h = nullptr; + + if (!m_wk) { + m_plotDir->cd(); + h = new TH2D(hname.c_str(), title.c_str(), + xbins, xbinArray, + ybins, ybinArray); + } else { + std::string pathname = m_name + "/" + hname; + h = new TH2D(pathname.c_str(), title.c_str(), + xbins, xbinArray, + ybins, ybinArray); + m_wk->addOutput(h); } - if (m_histograms.find(hname) != m_histograms.end()) { - std::cout << "ERROR: Running addHist with " << hname << std::endl; - std::cout << "but that histogram already exists" << std::endl; - std::cout << "will not continue" << std::endl; - exit(1); + checkDuplicate(hname); + + h->Sumw2(); + m_histograms.insert(make_pair(hname, h)); + } + + void PlotManager::addHist(const std::string& hname, const std::string& title, + int xbins, double* xbinArray, + int ybins, double ystart, double yend) const { + TH2D* h = nullptr; + + if (!m_wk) { + m_plotDir->cd(); + h = new TH2D(hname.c_str(), title.c_str(), + xbins, xbinArray, + ybins, ystart, yend); + } else { + std::string pathname = m_name + "/" + hname; + h = new TH2D(pathname.c_str(), title.c_str(), + xbins, xbinArray, + ybins, ystart, yend); + m_wk->addOutput(h); } + checkDuplicate(hname); + h->Sumw2(); m_histograms.insert(make_pair(hname, h)); -} + } -TH1* PlotManager::hist(const std::string& name) const { + TH1* PlotManager::hist(const std::string& name) const { if (m_histograms.find(name) == m_histograms.end()) { - std::cout << "Histogram doesn\'t exist: " << name << std::endl; - exit(1); + throw std::runtime_error("PlotManager::hist: Histogram " + name + " does not exist."); } return m_histograms[name]; -} + } -void PlotManager::scaleHistograms(double sf) const { + void PlotManager::scaleHistograms(double sf) const { for (std::unordered_map<std::string, TH1*>::iterator it = begin(m_histograms); it != end(m_histograms); ++it) - it->second->Scale(sf); -} + it->second->Scale(sf); + } + void PlotManager::checkDuplicate(const std::string& hname) const { + if (m_histograms.find(hname) != m_histograms.end()) { + throw std::runtime_error("PlotManager::addHist: Histogram " + hname + " to add already exists."); + } + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrimaryVertexSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrimaryVertexSelector.cxx index e4cadfe007aae09e16aee3a0dcd952c09134be43..f218df9a65cc9a00266b25375cf913bd818a5d1e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrimaryVertexSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrimaryVertexSelector.cxx @@ -1,18 +1,15 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/PrimaryVertexSelector.h" #include "TopEvent/EventTools.h" namespace top { - - PrimaryVertexSelector::PrimaryVertexSelector() - { + PrimaryVertexSelector::PrimaryVertexSelector() { } - bool PrimaryVertexSelector::apply(const top::Event& event) const - { + bool PrimaryVertexSelector::apply(const top::Event& event) const { if (event.m_info->isAvailable<char>("AnalysisTop_PRIVTX")) { if (event.m_info->auxdataConst<char>("AnalysisTop_PRIVTX") == 1) { return true; @@ -21,9 +18,7 @@ namespace top { return false; } - std::string PrimaryVertexSelector::name() const - { + std::string PrimaryVertexSelector::name() const { return "PRIVTX"; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrintEventSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrintEventSelector.cxx index 39ea8edd6434008c556e800d654db6edec29b0ef..c507db4e245a10d1baf456e8be5344a1b532cdfb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrintEventSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/PrintEventSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/PrintEventSelector.h" @@ -8,23 +8,23 @@ #include "TopCorrections/ScaleFactorRetriever.h" -namespace top { +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; -bool PrintEventSelector::apply(const top::Event& event) const { +namespace top { + bool PrintEventSelector::apply(const top::Event& event) const { //print some stuff about the event - std::cout << event << std::endl; - - //print the SF if calculated and if MC -// if (top::isSimulation(event)) { -// top::ScaleFactorRetriever::print(event); -// std::cout << std::endl; -// } + ATH_MSG_INFO(event); + return true; + } + bool PrintEventSelector::applyParticleLevel(const top::ParticleLevelEvent& plEvent) const { + //print some stuff about the event + ATH_MSG_INFO("Particle Level\n" << plEvent); return true; -} + } -std::string PrintEventSelector::name() const { + std::string PrintEventSelector::name() const { return "PRINT"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RecoLevelSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RecoLevelSelector.cxx index 0fe8468d0c682c51215c01ee7676c4657fa99c36..2169e48e6696eaee378f573dd93430ce98b08bff 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RecoLevelSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RecoLevelSelector.cxx @@ -1,32 +1,19 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: RecoLevelSelector.cxx -// Description: -// Author: Fabian Wilk -// Created: Tue Oct 27 13:28:22 2015 -// -// (c) by Fabian Wilk -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/RecoLevelSelector.h" namespace top { - bool RecoLevelSelector::apply(const top::Event&) const { - return true; - } + bool RecoLevelSelector::apply(const top::Event&) const { + return true; + } - bool RecoLevelSelector::applyParticleLevel(const top::ParticleLevelEvent&) const { - return false; - } + bool RecoLevelSelector::applyParticleLevel(const top::ParticleLevelEvent&) const { + return false; + } - std::string RecoLevelSelector::name() const { - return "RECO_LEVEL"; - } + std::string RecoLevelSelector::name() const { + return "RECO_LEVEL"; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RunNumberSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RunNumberSelector.cxx index 334f6ad4753a5a4720beb4b2c26f1083b960a593..78dcb60d05b140f42450bc4a6a177df073db2887 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RunNumberSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/RunNumberSelector.cxx @@ -1,33 +1,29 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/RunNumberSelector.h" #include "TopEvent/EventTools.h" #include "TopConfiguration/TopConfig.h" namespace top { + RunNumberSelector::RunNumberSelector(const std::string& params, std::shared_ptr<top::TopConfig> config) : + SignValueSelector("RUN_NUMBER", params) { + m_config = config; + } -RunNumberSelector::RunNumberSelector(const std::string& params,std::shared_ptr<top::TopConfig> config) : - SignValueSelector("RUN_NUMBER", params) { - m_config = config; -} - -bool RunNumberSelector::apply(const top::Event& event) const { + bool RunNumberSelector::apply(const top::Event& event) const { unsigned int number = 0; - if (!m_config->isMC()) - number = event.m_info -> runNumber(); + + if (!m_config->isMC()) number = event.m_info->runNumber(); else { - if (event.m_info->isAvailable<unsigned int>("RandomRunNumber")) - number = event.m_info->auxdataConst<unsigned int>("RandomRunNumber"); - else { - std::cout << "RunNumberSelector: can't find random Run Number - did you setup the pile-up reweighting tool?" << std::endl; - exit(1); - } + if (event.m_info->isAvailable<unsigned int>("RandomRunNumber")) number = event.m_info->auxdataConst<unsigned int>( + "RandomRunNumber"); + else { + throw std::runtime_error("RunNumberSelector: RandomRunNumber EventInfo decoration not available. Indicates issue with PRW tool."); + } } return checkInt(number, value()); -} - - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonSelector.cxx index 80b7462dc54eb6271ca38617ad6b9ba21154e422..bcebd48d74f4817e7dff54d98bbdb168b06c5250 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/SSLeptonSelector.h" #include "TopEvent/EventTools.h" @@ -12,55 +12,44 @@ // Need to support applying SF to leptons with different quality/isolation at once namespace top { - -bool SSLeptonSelector::apply(const top::Event& event) const { + bool SSLeptonSelector::apply(const top::Event& event) const { unsigned int negative_counter = 0; unsigned int positive_counter = 0; for (const auto* const elPtr : event.m_electrons) - if (elPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + if (elPtr->charge() > 0) ++positive_counter; + else ++negative_counter; for (const auto* const muPtr : event.m_muons) - if (muPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + if (muPtr->charge() > 0) ++positive_counter; + else ++negative_counter; return positive_counter > 1 || negative_counter > 1; -} + } -bool SSLeptonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool SSLeptonSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } unsigned int negative_counter = 0; unsigned int positive_counter = 0; - for (const auto elPtr : * event.m_electrons) - if (elPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto elPtr : *event.m_electrons) + if (elPtr->charge() > 0) ++positive_counter; + else ++negative_counter; - for (const auto muPtr : * event.m_muons) - if (muPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto muPtr : *event.m_muons) + if (muPtr->charge() > 0) ++positive_counter; + else ++negative_counter; return positive_counter > 1 || negative_counter > 1; -} + } - -std::string SSLeptonSelector::name() const { + std::string SSLeptonSelector::name() const { return "SS"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonTightSelector.cxx index d045f741cf1f7f5edb73aa21fb471093de6b4557..96960dceb097c67aefcc1ca9ff0f640693162bb7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonTightSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SSLeptonTightSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/SSLeptonTightSelector.h" #include "TopEvent/EventTools.h" @@ -12,55 +12,44 @@ // Need to support applying SF to leptons with different quality/isolation at once namespace top { - -bool SSLeptonTightSelector::apply(const top::Event& event) const { + bool SSLeptonTightSelector::apply(const top::Event& event) const { unsigned int negative_counter = 0; unsigned int positive_counter = 0; for (const auto* const elPtr : event.m_electrons) - if (elPtr->charge() > 0 && elPtr->auxdataConst<char>("passPreORSelection")) - ++positive_counter; - else if (elPtr->charge() < 0 && elPtr->auxdataConst<char>("passPreORSelection")) - ++negative_counter; + if (elPtr->charge() > 0 && elPtr->auxdataConst<char>("passPreORSelection")) ++positive_counter; + else if (elPtr->charge() < 0 && elPtr->auxdataConst<char>("passPreORSelection")) ++negative_counter; for (const auto* const muPtr : event.m_muons) - if (muPtr->charge() > 0 && muPtr->auxdataConst<char>("passPreORSelection")) - ++positive_counter; - else if (muPtr->charge() < 0 && muPtr->auxdataConst<char>("passPreORSelection")) - ++negative_counter; + if (muPtr->charge() > 0 && muPtr->auxdataConst<char>("passPreORSelection")) ++positive_counter; + else if (muPtr->charge() < 0 && muPtr->auxdataConst<char>("passPreORSelection")) ++negative_counter; return positive_counter > 1 || negative_counter > 1; -} + } -bool SSLeptonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { + bool SSLeptonTightSelector::applyParticleLevel(const top::ParticleLevelEvent& event) const { // If any of the required collections is a nullptr (i.e. has not been // loaded) return false. - if ( not event.m_electrons - or not event.m_muons ){ - return false; + if (not event.m_electrons + or not event.m_muons) { + return false; } unsigned int negative_counter = 0; unsigned int positive_counter = 0; - for (const auto elPtr : * event.m_electrons) - if (elPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto elPtr : *event.m_electrons) + if (elPtr->charge() > 0) ++positive_counter; + else ++negative_counter; - for (const auto muPtr : * event.m_muons) - if (muPtr->charge() > 0) - ++positive_counter; - else - ++negative_counter; + for (const auto muPtr : *event.m_muons) + if (muPtr->charge() > 0) ++positive_counter; + else ++negative_counter; return positive_counter > 1 || negative_counter > 1; -} + } - -std::string SSLeptonTightSelector::name() const { + std::string SSLeptonTightSelector::name() const { return "SS_TIGHT"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SaveEventSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SaveEventSelector.cxx index 66dedd6b06c7727ca26af4635d7f1f75c5d21910..5ae8bc86568cede314de04d52c8753c466953346 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SaveEventSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SaveEventSelector.cxx @@ -1,17 +1,15 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/SaveEventSelector.h" namespace top { - -bool SaveEventSelector::apply(const top::Event&) const { + bool SaveEventSelector::apply(const top::Event&) const { return true; -} + } -std::string SaveEventSelector::name() const { + std::string SaveEventSelector::name() const { return "SAVE"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SignValueSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SignValueSelector.cxx index dc760cfbb5f9c18a1e29bd7f6902490bb00c0530..0bd353b3554d6976e69632272b822b4c9042bfa3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SignValueSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/SignValueSelector.cxx @@ -1,18 +1,23 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/SignValueSelector.h" +#include "TopConfiguration/Tokenize.h" -namespace top { +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; -SignValueSelector::SignValueSelector(const std::string& name, std::string params, bool multiplicityMode, bool cutValueMode) : - m_sign(signNOIDEA), - m_cutvalue(0), - m_cutvalueString(""), - m_multiplicity(-1) { +namespace top { + SignValueSelector::SignValueSelector(const std::string& name, std::string params, bool multiplicityMode, + bool cutValueMode) : + m_sign(signNOIDEA), + m_cutvalue(0), + m_cutvalueString(""), + m_multiplicity(-1) { + m_cutvalueStringDelimReplace = ""; //cutValueMode always set to false if multiplicityMode is false - if (!multiplicityMode) cutValueMode=false; + if (!multiplicityMode) cutValueMode = false; //get the sign and remove it from the params text m_sign = decodesign(params); if (!cutValueMode) std::istringstream(params) >> m_cutvalue >> m_multiplicity; @@ -20,144 +25,187 @@ SignValueSelector::SignValueSelector(const std::string& name, std::string params //form the name string for the tool std::stringstream ss; - if (!multiplicityMode) - ss << name << " " << signstring() << " " << m_cutvalue; + if (!multiplicityMode) ss << name << " " << signstring() << " " << m_cutvalue; else { - if (m_multiplicity < 0) { - std::cout << "Cut value and multiplicity must be set for " << name << std::endl; - exit(1); - } - - if (!cutValueMode) - ss << name << " " << m_cutvalue << " " << signstring() << " " << m_multiplicity; - else - ss << name << " " << m_cutvalueString << " " << signstring() << " " << m_multiplicity; + if (m_multiplicity < 0) { + throw std::runtime_error("Cut value and multiplicity must be set for " + name); + } + + if (!cutValueMode) ss << name << " " << m_cutvalue << " " << signstring() << " " << m_multiplicity; + else ss << name << " " << m_cutvalueString << " " << signstring() << " " << m_multiplicity; } m_name = ss.str(); -} + } + + SignValueSelector::SignValueSelector(const std::string& name, std::string params, bool multiplicityMode, + bool cutValueMode, std::string delim, std::string replace, + std::string default_prefix) : + SignValueSelector(name, params, multiplicityMode, cutValueMode) { + // This function is only if we need a bit of additional string manipulation + // Required for the btagging selector when we start doing "alg:wp" + // If string is empty, do the split, otherwise just return the stored value + + std::vector<std::string> tokens; + tokenize(m_cutvalueString, tokens, delim); + if (tokens.size() > 1) { + for (auto cutString : tokens) { + m_cutvalueStringDelimReplace += cutString; + m_cutvalueStringDelimReplace += replace; + } + // Tidy up the end of the string + m_cutvalueStringDelimReplace = m_cutvalueStringDelimReplace.substr(0, + m_cutvalueStringDelimReplace.length() - + replace.length()); + } + // We are kind, and keep some backwards compatablity, so incase you did not know the syntax changed, hopefully we + // provided the most likely default + else { + ATH_MSG_INFO("SignValueSelector :: We are using a default_prefix as we could not split on a delimiter."); + m_cutvalueStringDelimReplace = default_prefix + replace + m_cutvalueString; + ATH_MSG_INFO("SignValueSelector :: The final result is " << m_cutvalueStringDelimReplace); + } + } -std::string SignValueSelector::name() const { + std::string SignValueSelector::name() const { return m_name; -} + } -void SignValueSelector::checkValueIsInteger() { + void SignValueSelector::checkValueIsInteger() { if (value() != floor(value())) { - std::cout << "The number " << value() << " is not an integer\n"; - std::cout << "As defined in " << name() << "\n"; - std::cout << "Please fix and try again\n"; - exit(1); + ATH_MSG_ERROR("The number " << value() << " is not an integer\n" + << "As defined in " << name() << "\n"); + throw std::runtime_error("Failed parsing value for SignValueSelector"); } -} + } -void SignValueSelector::checkMultiplicityIsInteger() { + void SignValueSelector::checkMultiplicityIsInteger() { if (multiplicity() != floor(multiplicity())) { - std::cout << "The number " << value() << " is not an integer\n"; - std::cout << "As defined in " << name() << "\n"; - std::cout << "Please fix and try again\n"; - exit(1); + ATH_MSG_ERROR("The number " << multiplicity() << " is not an integer\n" + << "As defined in " << name() << "\n"); + throw std::runtime_error("Failed parsing multiplicity cut for SignValueSelector"); } -} + } -SignValueSelector::Sign SignValueSelector::sign() const { + SignValueSelector::Sign SignValueSelector::sign() const { return m_sign; -} + } -double SignValueSelector::value() const { + double SignValueSelector::value() const { return m_cutvalue; -} + } -std::string SignValueSelector::valueString() const { + std::string SignValueSelector::valueString() const { return m_cutvalueString; -} + } + + std::string SignValueSelector::valueStringDelimReplace() const { + return m_cutvalueStringDelimReplace; + } -double SignValueSelector::multiplicity() const { + double SignValueSelector::multiplicity() const { return m_multiplicity; -} + } -SignValueSelector::Sign SignValueSelector::decodesign(std::string& params) { + SignValueSelector::Sign SignValueSelector::decodesign(std::string& params) { Sign tempsign(signNOIDEA); + if (params.find("==") != std::string::npos) { - tempsign = signEQ; - params.erase(params.find("=="), 2); + tempsign = signEQ; + params.erase(params.find("=="), 2); } else if (params.find("<=") != std::string::npos) { - tempsign = signLTEQ; - params.erase(params.find("<="), 2); + tempsign = signLTEQ; + params.erase(params.find("<="), 2); } else if (params.find(">=") != std::string::npos) { - tempsign = signGTEQ; - params.erase(params.find(">="), 2); + tempsign = signGTEQ; + params.erase(params.find(">="), 2); } else if (params.find("<") != std::string::npos) { - tempsign = signLT; - params.erase(params.find("<"), 1); + tempsign = signLT; + params.erase(params.find("<"), 1); } else if (params.find(">") != std::string::npos) { - tempsign = signGT; - params.erase(params.find(">"), 1); + tempsign = signGT; + params.erase(params.find(">"), 1); } return tempsign; -} + } -bool SignValueSelector::checkFloat(double value, double cut) const { + bool SignValueSelector::checkFloat(double value, double cut) const { switch (m_sign) { case signNOIDEA: { - std::cout << "Do not recognise the sign\n"; - exit(1); - } case signEQ: { - std::cout << "Can't compare floats with ==\n"; - exit(1); - } case signLT: - return value < cut; + throw std::runtime_error("SignValueSelector::checkFloat: Can't recognise the sign"); + } + + case signEQ: { + throw std::runtime_error("SignValueSelector::checkFloat: Can't compare floats with =="); + } + + case signLT: + return value < cut; + case signGT: - return value > cut; + return value > cut; + case signLTEQ: - return value <= cut; + return value <= cut; + case signGTEQ: - return value >= cut; + return value >= cut; } return false; -} + } -bool SignValueSelector::checkInt(int value, int cut) const { + bool SignValueSelector::checkInt(int value, int cut) const { switch (m_sign) { case signNOIDEA: { - std::cout << "Do not recognise the sign\n"; - exit(1); - } case signEQ: - return value == cut; + throw std::runtime_error("SignValueSelector::checkInt: Can't recognise the sign"); + } + + case signEQ: + return value == cut; + case signLT: - return value < cut; + return value < cut; + case signGT: - return value > cut; + return value > cut; + case signLTEQ: - return value <= cut; + return value <= cut; + case signGTEQ: - return value >= cut; + return value >= cut; } return false; -} + } -const std::string SignValueSelector::signstring() const { + const std::string SignValueSelector::signstring() const { switch (m_sign) { case signNOIDEA: { - std::cout << "SignValueSelector is confused\n"; - std::cout << "Please check your cuts have all the correct cuts\n"; - std::cout << "e.g. ==, >, >=, <, <=\n"; - exit(1); - } case signEQ: - return "=="; + ATH_MSG_ERROR("SignValueSelector is confused\n" + << "Check that your cuts have one of: " + << "==, >, >=, <, <=\n"); + throw std::runtime_error("SignValueSelector::signstring: Can't recognise the comparison operator"); + } + + case signEQ: + return "=="; + case signLT: - return "<"; + return "<"; + case signGT: - return ">"; + return ">"; + case signLTEQ: - return "<="; + return "<="; + case signGTEQ: - return ">="; + return ">="; } return ""; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TopEventSelectionToolsLoader.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TopEventSelectionToolsLoader.cxx index e66ba923a4284954bc787a3a21e2a7c009c100b4..4af018b1e456829e6fab9afe6b03e7a285ea4e92 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TopEventSelectionToolsLoader.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TopEventSelectionToolsLoader.cxx @@ -1,36 +1,43 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "AsgMessaging/MessageCheck.h" #include "TopEventSelectionTools/TopEventSelectionToolsLoader.h" #include "TopEventSelectionTools/ExamplePlots.h" #include "TopEventSelectionTools/JetFlavorPlots.h" +#include "TopEventSelectionTools/JetResponsePlots.h" +#include "TopEventSelectionTools/JetFtagEffPlots.h" #include "TopEventSelectionTools/FakesMMConfigs.h" +#include "TopEventSelectionTools/GlobalTrigDecisionSelector.h" +#include "TopEventSelectionTools/GlobalTrigMatchSelector.h" #include "TopEventSelectionTools/GRLSelector.h" #include "TopEventSelectionTools/GoodCaloSelector.h" #include "TopEventSelectionTools/HTSelector.h" -#include "TopEventSelectionTools/IP3DSV1Selector.h" #include "TopEventSelectionTools/InitialSelector.h" #include "TopEventSelectionTools/JetCleaningSelector.h" +#include "TopEventSelectionTools/TrackJetCleaningSelector.h" #include "TopEventSelectionTools/JetNGhostSelector.h" #include "TopEventSelectionTools/KLFitterSelector.h" #include "TopEventSelectionTools/METMWTSelector.h" #include "TopEventSelectionTools/METSelector.h" #include "TopEventSelectionTools/MLLSelector.h" #include "TopEventSelectionTools/MLLWindowSelector.h" -#include "TopEventSelectionTools/MV1Selector.h" -#include "TopEventSelectionTools/MV2c20Selector.h" #include "TopEventSelectionTools/MV2c10Selector.h" #include "TopEventSelectionTools/MWTSelector.h" #include "TopEventSelectionTools/NElectronNMuonSelector.h" #include "TopEventSelectionTools/NElectronNMuonTightSelector.h" #include "TopEventSelectionTools/NElectronSelector.h" #include "TopEventSelectionTools/NElectronTightSelector.h" +#include "TopEventSelectionTools/NFwdElectronSelector.h" +#include "TopEventSelectionTools/NFwdElectronTightSelector.h" #include "TopEventSelectionTools/NJetSelector.h" #include "TopEventSelectionTools/NJetBtagSelector.h" #include "TopEventSelectionTools/NMuonSelector.h" +#include "TopEventSelectionTools/NSoftMuonSelector.h" #include "TopEventSelectionTools/NoBadMuonSelector.h" #include "TopEventSelectionTools/NMuonTightSelector.h" #include "TopEventSelectionTools/NPhotonSelector.h" @@ -46,9 +53,13 @@ #include "TopEventSelectionTools/SSLeptonTightSelector.h" #include "TopEventSelectionTools/SaveEventSelector.h" #include "TopEventSelectionTools/TrigDecisionSelector.h" +#include "TopEventSelectionTools/TrigDecisionLooseSelector.h" +#include "TopEventSelectionTools/TrigDecisionTightSelector.h" #include "TopEventSelectionTools/TrigMatchSelector.h" #include "TopEventSelectionTools/RunNumberSelector.h" #include "TopEventSelectionTools/NLargeJetSelector.h" +#include "TopEventSelectionTools/NRCJetSelector.h" +#include "TopEventSelectionTools/NVarRCJetSelector.h" #include "TopConfiguration/TopConfig.h" @@ -57,8 +68,10 @@ #include "TFile.h" namespace top { - - top::EventSelectorBase* TopEventSelectionToolsLoader::initTool(const std::string& name, const std::string& line, TFile* outputFile,std::shared_ptr<top::TopConfig> config, EL::Worker* wk) { + top::EventSelectorBase* TopEventSelectionToolsLoader::initTool(const std::string& name, const std::string& line, + TFile* outputFile, + std::shared_ptr<top::TopConfig> config, + EL::Worker* wk) { //get the first bit of the string and store it in toolname std::istringstream iss(line); std::string toolname; @@ -66,100 +79,76 @@ namespace top { //any parameters? std::string param; - if (line.size() > toolname.size()) - param = line.substr(toolname.size() + 1); + if (line.size() > toolname.size()) param = line.substr(toolname.size() + 1); - if (toolname == "JET_N") - return new top::NJetSelector(param); - else if (toolname == "JET_N_BTAG") - return new top::NJetBtagSelector(param,config); - else if (toolname == "LJET_N") - return new top::NLargeJetSelector(param); - else if (toolname == "MV1_N") - return new top::MV1Selector(param); - else if (toolname == "MV2C20_N") - return new top::MV2c20Selector(param); - else if (toolname == "MV2C10_N") - return new top::MV2c10Selector(param); - else if (toolname == "IP3DSV1_N") - return new top::IP3DSV1Selector(param); - else if (toolname == "EL_N_OR_MU_N") - return new top::NElectronNMuonSelector(param); - else if (toolname == "EL_N_OR_MU_N_TIGHT") - return new top::NElectronNMuonTightSelector(param); - else if (toolname == "EL_N") - return new top::NElectronSelector(param); - else if (toolname == "EL_N_TIGHT") - return new top::NElectronTightSelector(param); - else if (toolname == "MU_N") - return new top::NMuonSelector(param); - else if (toolname == "MU_N_TIGHT") - return new top::NMuonTightSelector(param); - else if (toolname == "PH_N") - return new top::NPhotonSelector(param); - else if (toolname == "TAU_N") - return new top::NTauSelector(param); - else if (toolname == "TAU_N_TIGHT") - return new top::NTauTightSelector(param); - else if (toolname == "MET+MWT") - return new top::METMWTSelector(param); - else if (toolname == "MET") - return new top::METSelector(param); - else if (toolname == "MWT") - return new top::MWTSelector(param); - else if (toolname == "MLLWIN") - return new top::MLLWindow(param); - else if (toolname == "MLL") - return new top::MLLSelector(param); - else if (toolname == "HT") - return new top::HTSelector(param); + if (toolname == "JET_N") return new top::NJetSelector(param); + else if (toolname == "JET_N_BTAG") return new top::NJetBtagSelector(param, config, false); + else if (toolname == "TJET_N_BTAG") return new top::NJetBtagSelector(param, config, true); + else if (toolname == "LJET_N") return new top::NLargeJetSelector(param); + else if (toolname == "RCJET_N") return new top::NRCJetSelector(param); + else if (toolname == "VRCJET_N") { + std::istringstream is(param); + std::string name; + getline(is, name, ' '); + return new top::NVarRCJetSelector(name, param.substr(name.size() + 1)); + } else if (toolname == "MV2C10_N") return new top::MV2c10Selector(param); + else if (toolname == "EL_N_OR_MU_N") return new top::NElectronNMuonSelector(param); + else if (toolname == "EL_N_OR_MU_N_TIGHT") return new top::NElectronNMuonTightSelector(param); + else if (toolname == "EL_N") return new top::NElectronSelector(param); + else if (toolname == "EL_N_TIGHT") return new top::NElectronTightSelector(param); + else if (toolname == "FWDEL_N") return new top::NFwdElectronSelector(param); + else if (toolname == "FWDEL_N_TIGHT") return new top::NFwdElectronTightSelector(param); + else if (toolname == "MU_N") return new top::NMuonSelector(param); + else if (toolname == "SOFTMU_N") return new top::NSoftMuonSelector(param); + else if (toolname == "MU_N_TIGHT") return new top::NMuonTightSelector(param); + else if (toolname == "PH_N") return new top::NPhotonSelector(param); + else if (toolname == "TAU_N") return new top::NTauSelector(param); + else if (toolname == "TAU_N_TIGHT") return new top::NTauTightSelector(param); + else if (toolname == "MET+MWT") return new top::METMWTSelector(param); + else if (toolname == "MET") return new top::METSelector(param); + else if (toolname == "MWT") return new top::MWTSelector(param); + else if (toolname == "MLLWIN") return new top::MLLWindow(param); + else if (toolname == "MLL") return new top::MLLSelector(param); + else if (toolname == "HT") return new top::HTSelector(param); else if (toolname == "NOBADMUON") - return new top::NoBadMuonSelector(); - else if (toolname == "OS") - return new top::OSLeptonSelector(); - else if (toolname == "OS_TIGHT") - return new top::OSLeptonTightSelector(); - else if (toolname == "SS") - return new top::SSLeptonSelector(); - else if (toolname == "SS_TIGHT") - return new top::SSLeptonTightSelector(); - else if (toolname == "INITIAL") - return new top::InitialSelector; - else if (toolname == "SAVE") - return new top::SaveEventSelector; - else if (toolname == "PRINT") - return new top::PrintEventSelector; - else if (toolname == "EXAMPLEPLOTS") - return new top::ExamplePlots(name, outputFile, wk, config); - else if (toolname == "JETFLAVORPLOTS") - return new top::JetFlavorPlots(name, outputFile, wk); - else if (toolname == "GRL") - return new top::GRLSelector(); - else if (toolname == "TRIGDEC") - return new top::TrigDecisionSelector(name,config); - else if (toolname == "TRIGMATCH") - return new top::TrigMatchSelector(name,config); - else if (toolname == "JETCLEAN") - return new top::JetCleaningSelector(param,config); - else if (toolname == "KLFITTER") - return new top::KLFitterSelector(param); - else if (toolname == "JET_N_GHOST") - return new top::JetNGhostSelector(param); - else if (toolname == "GOODCALO") - return new top::GoodCaloSelector(); - else if (toolname == "PRIVTX") - return new top::PrimaryVertexSelector(); - else if (toolname == "RECO_LEVEL") - return new top::RecoLevelSelector(); - else if (toolname == "PARTICLE_LEVEL") - return new top::ParticleLevelSelector(); - else if (toolname == "FAKESMMCONFIGS") - return new top::FakesMMConfigs(param); - else if (toolname == "RUN_NUMBER") - return new top::RunNumberSelector(param,config); + { + if(!config->useMuons()) + { + asg::msgUserCode::ATH_MSG_ERROR("NOBADMUON selection cannot be used if the muon collection is not defined"); + return 0; + } + return new top::NoBadMuonSelector(config); + } + else if (toolname == "OS") return new top::OSLeptonSelector(); + else if (toolname == "OS_TIGHT") return new top::OSLeptonTightSelector(); + else if (toolname == "SS") return new top::SSLeptonSelector(); + else if (toolname == "SS_TIGHT") return new top::SSLeptonTightSelector(); + else if (toolname == "INITIAL") return new top::InitialSelector; + else if (toolname == "SAVE") return new top::SaveEventSelector; + else if (toolname == "PRINT") return new top::PrintEventSelector; + else if (toolname == "EXAMPLEPLOTS") return new top::ExamplePlots(name, outputFile, wk, config); + else if (toolname == "JETFLAVORPLOTS") return new top::JetFlavorPlots(name, outputFile, param, config, wk); + else if (toolname == "JETRESPONSEPLOTS") return new top::JetResponsePlots(name, outputFile, param, config, wk); + else if (toolname == "JETFTAGEFFPLOTS") return new top::JetFtagEffPlots(name, outputFile, param, config, wk); + else if (toolname == "GRL") return new top::GRLSelector(); + else if (toolname == "GTRIGDEC") return new top::GlobalTrigDecisionSelector(); + else if (toolname == "GTRIGMATCH") return new top::GlobalTrigMatchSelector(); + else if (toolname == "TRIGDEC") return new top::TrigDecisionSelector(name, config); + else if (toolname == "TRIGDEC_LOOSE") return new top::TrigDecisionLooseSelector(name, config); + else if (toolname == "TRIGDEC_TIGHT") return new top::TrigDecisionTightSelector(name, config); + else if (toolname == "TRIGMATCH") return new top::TrigMatchSelector(name, config); + else if (toolname == "JETCLEAN") return new top::JetCleaningSelector(param, config); + else if (toolname == "TRACKJETCLEAN") return new top::TrackJetCleaningSelector(config); + else if (toolname == "KLFITTER") return new top::KLFitterSelector(param); + else if (toolname == "JET_N_GHOST") return new top::JetNGhostSelector(param); + else if (toolname == "GOODCALO") return new top::GoodCaloSelector(); + else if (toolname == "PRIVTX") return new top::PrimaryVertexSelector(); + else if (toolname == "RECO_LEVEL") return new top::RecoLevelSelector(); + else if (toolname == "PARTICLE_LEVEL") return new top::ParticleLevelSelector(); + else if (toolname == "FAKESMMCONFIGS") return new top::FakesMMConfigs(param); + else if (toolname == "RUN_NUMBER") return new top::RunNumberSelector(param, config); return nullptr; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrackJetCleaningSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrackJetCleaningSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..4b63e31ac38b2a7b5295fa1e75323cd0eb0d94a5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrackJetCleaningSelector.cxx @@ -0,0 +1,31 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/TrackJetCleaningSelector.h" +#include "TopEvent/EventTools.h" +#include "xAODJet/JetContainer.h" +#include "TopConfiguration/TopConfig.h" + +namespace top { + TrackJetCleaningSelector::TrackJetCleaningSelector(std::shared_ptr<top::TopConfig> config) : + m_config(config) { + } + + bool TrackJetCleaningSelector::apply(const top::Event& event) const { + // Selection is applied only if Variable-R track jets are used + if (m_config->sgKeyTrackJetsType() == "AntiKtVR30Rmax4Rmin02TrackJets") { + static SG::AuxElement::Accessor<char> acc_passDRcut("passDRcut"); + for (const xAOD::Jet* jet : event.m_trackJets) { + top::check(acc_passDRcut.isAvailable( + *jet), "passDRcut info not found in variable-R track jet. Needed for cleaning algorithm."); + if (!acc_passDRcut(*jet)) return false; + } + } + return true; + } + + std::string TrackJetCleaningSelector::name() const { + return "TRACKJETCLEAN"; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TreeManager.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TreeManager.cxx index 5cec34634396e353dc1642ea4eeaee2e996d87d9..b6a953bb90fde5151316fccbdbe171c0f25b2df2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TreeManager.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TreeManager.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/TreeManager.h" @@ -8,135 +8,152 @@ #include <iostream> -namespace top { +#include "TopEventSelectionTools/MsgCategory.h" +using namespace TopEventSelectionTools; -TreeManager::TreeManager() : - m_name("NULL"), - m_tree(nullptr) { -} +namespace top { + TreeManager::TreeManager() : + m_name("NULL"), + m_tree(nullptr) { + } -TreeManager::TreeManager(const std::string& name, TFile* outputFile,const bool setAutoFlushZero) : + TreeManager::TreeManager(const std::string& name, TFile* outputFile, const int nEventAutoFlush, + const int basketSizePrimitive, const int basketSizeVector) : m_name(name), m_tree(nullptr) { outputFile->cd(); m_tree = new TTree(name.c_str(), "tree"); - if (setAutoFlushZero) { - // Fix for ANALYSISTO-44 - m_tree->SetAutoFlush(0); - m_tree->SetAutoSave(0); - } -} + m_tree->SetAutoFlush(nEventAutoFlush); + m_tree->SetAutoSave(0); + m_basketSizePrimitive = basketSizePrimitive; + m_basketSizeVector = basketSizeVector; + } -TreeManager::TreeManager(const TreeManager&& rhs) : + TreeManager::TreeManager(const TreeManager&& rhs) : m_name(std::move(rhs.m_name)), m_tree(std::move(rhs.m_tree)), m_outputVarPointers(std::move(rhs.m_outputVarPointers)) { -} + } -void TreeManager::initialize(const std::string& name, TFile* outputFile,const bool setAutoFlushZero) { + void TreeManager::initialize(const std::string& name, TFile* outputFile, const int nEventAutoFlush, + const int basketSizePrimitive, const int basketSizeVector) { if (m_tree) { - std::cerr << "Tried to call initialize, but tree is already created. Doing nothing." << std::endl; - return; + ATH_MSG_WARNING("Tried to call initialize, but tree is already created. Doing nothing."); + return; } outputFile->cd(); m_tree = new TTree(name.c_str(), "tree"); - if (setAutoFlushZero) { - // Fix for ANALYSISTO-44 - m_tree->SetAutoFlush(0); - m_tree->SetAutoSave(0); - } -} + m_tree->SetAutoFlush(nEventAutoFlush); + m_tree->SetAutoSave(0); + m_basketSizePrimitive = basketSizePrimitive; + m_basketSizeVector = basketSizeVector; + } -void TreeManager::fill() { + void TreeManager::fill() { m_tree->Fill(); -} + } -const std::string& TreeManager::name() const -{ - return m_name; -} - -const char* TreeManager::RootType(const char* typeid_type) { + const std::string& TreeManager::name() const { + return m_name; + } + const char* TreeManager::RootType(const char* typeid_type) { // Check that we received a reasonable input: - if( strlen( typeid_type ) != 1 ) { - // SLogger m_logger( "SCycleBaseNTuple" ); - // REPORT_ERROR( "Received a complex object description: " << typeid_type ); - // throw SError( "SCycleBaseNTuple::RootType received complex object " - // "description", SError::StopExecution ); + if (strlen(typeid_type) != 1) { + // SLogger m_logger( "SCycleBaseNTuple" ); + // REPORT_ERROR( "Received a complex object description: " << typeid_type ); + // throw SError( "SCycleBaseNTuple::RootType received complex object " + // "description", SError::StopExecution ); } // Do the hard-coded translation: - switch( typeid_type[ 0 ] ) { - + switch (typeid_type[ 0 ]) { case 'c': - return "B"; - break; + return "B"; + + break; + case 'h': - return "b"; - break; + return "b"; + + break; + case 's': - return "S"; - break; + return "S"; + + break; + case 't': - return "s"; - break; + return "s"; + + break; + case 'i': - return "I"; - break; + return "I"; + + break; + case 'j': - return "i"; - break; + return "i"; + + break; + case 'f': - return "F"; - break; + return "F"; + + break; + case 'd': - return "D"; - break; + return "D"; + + break; + case 'x': - return "L"; - break; + return "L"; + + break; + case 'y': - return "l"; - break; + return "l"; + + break; + case 'b': - return "O"; - break; + return "O"; + break; } return ""; -} - -const char* TreeManager::TypeidType(const char* root_type) { + } + const char* TreeManager::TypeidType(const char* root_type) { // Do the hard-coded translation: - if( ! strcmp( root_type, "Char_t" ) ) { - return "c"; - } else if( ! strcmp( root_type, "UChar_t" ) ) { - return "h"; - } else if( ! strcmp( root_type, "Short_t" ) ) { - return "s"; - } else if( ! strcmp( root_type, "UShort_t" ) ) { - return "t"; - } else if( ! strcmp( root_type, "Int_t" ) ) { - return "i"; - } else if( ! strcmp( root_type, "UInt_t" ) ) { - return "j"; - } else if( ! strcmp( root_type, "Float_t" ) ) { - return "f"; - } else if( ! strcmp( root_type, "Double_t" ) ) { - return "d"; - } else if( ! strcmp( root_type, "Long64_t" ) ) { - return "x"; - } else if( ! strcmp( root_type, "ULong64_t" ) ) { - return "y"; - } else if( ! strcmp( root_type, "Bool_t" ) ) { - return "b"; + if (!strcmp(root_type, "Char_t")) { + return "c"; + } else if (!strcmp(root_type, "UChar_t")) { + return "h"; + } else if (!strcmp(root_type, "Short_t")) { + return "s"; + } else if (!strcmp(root_type, "UShort_t")) { + return "t"; + } else if (!strcmp(root_type, "Int_t")) { + return "i"; + } else if (!strcmp(root_type, "UInt_t")) { + return "j"; + } else if (!strcmp(root_type, "Float_t")) { + return "f"; + } else if (!strcmp(root_type, "Double_t")) { + return "d"; + } else if (!strcmp(root_type, "Long64_t")) { + return "x"; + } else if (!strcmp(root_type, "ULong64_t")) { + return "y"; + } else if (!strcmp(root_type, "Bool_t")) { + return "b"; } return ""; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionLooseSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionLooseSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e40f0f127305a01266f0f3c198361e567a2152ee --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionLooseSelector.cxx @@ -0,0 +1,46 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/TrigDecisionLooseSelector.h" +#include "TopEvent/Event.h" +#include "TopConfiguration/TopConfig.h" + +#include <sstream> +#include <iostream> + +namespace top { + TrigDecisionLooseSelector::TrigDecisionLooseSelector(const std::string& selectorName, + std::shared_ptr<top::TopConfig> config) { + m_triggers = config->allTriggers_Loose(selectorName); + } + + bool TrigDecisionLooseSelector::apply(const top::Event& event) const { + // this selector does nothing for non-loose events + bool loose = event.m_isLoose; + + if (!loose) return true; + + bool orOfAllTriggers(false); + for (const auto& trigger : m_triggers) { + bool passThisTrigger(false); + if (event.m_info->isAvailable<char>("TRIGDEC_" + trigger)) { + if (event.m_info->auxdataConst<char>("TRIGDEC_" + trigger) == 1) { + passThisTrigger = true; + } + } + + orOfAllTriggers |= passThisTrigger; + } + + return orOfAllTriggers; + } + + std::string TrigDecisionLooseSelector::name() const { + std::string name = "TRIGDEC_LOOSE "; + for (auto trigger : m_triggers) + name += " " + trigger; + + return name; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionSelector.cxx index d4155381ea1854f3e4f22fa21a6684d5e2ba059c..0e3b06d80d060b08b8fb7357e4d826c4a2fa798d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/TrigDecisionSelector.h" #include "TopEvent/Event.h" @@ -10,23 +10,16 @@ #include <iostream> namespace top { - - TrigDecisionSelector::TrigDecisionSelector(const std::string& selectorName,std::shared_ptr<top::TopConfig> config) - { - m_triggers = config->allTriggers(selectorName); - - std::cout<<"Triggers for selector = "<<selectorName<<std::endl; - for (auto s : m_triggers) { - std::cout << "--" << s << "--" << std::endl; - } - + TrigDecisionSelector::TrigDecisionSelector(const std::string& selectorName, std::shared_ptr<top::TopConfig> config) { + m_triggers = config->allTriggers_Tight(selectorName); + for (auto s: config->allTriggers_Loose(selectorName)) + if (std::find(m_triggers.begin(), m_triggers.end(), s) == m_triggers.end()) m_triggers.push_back(s); } - bool TrigDecisionSelector::apply(const top::Event& event) const - { - + bool TrigDecisionSelector::apply(const top::Event& event) const { bool orOfAllTriggers(false); - for (const auto& trigger : m_triggers){ + + for (const auto& trigger : m_triggers) { bool passThisTrigger(false); if (event.m_info->isAvailable<char>("TRIGDEC_" + trigger)) { if (event.m_info->auxdataConst<char>("TRIGDEC_" + trigger) == 1) { @@ -43,9 +36,8 @@ namespace top { std::string TrigDecisionSelector::name() const { std::string name = "TRIGDEC "; for (auto trigger : m_triggers) - name += " " + trigger; + name += " " + trigger; return name; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionTightSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionTightSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..44d4c0df3e485421ea509b2aa2936af7ec5c34d1 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigDecisionTightSelector.cxx @@ -0,0 +1,46 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopEventSelectionTools/TrigDecisionTightSelector.h" +#include "TopEvent/Event.h" +#include "TopConfiguration/TopConfig.h" + +#include <sstream> +#include <iostream> + +namespace top { + TrigDecisionTightSelector::TrigDecisionTightSelector(const std::string& selectorName, + std::shared_ptr<top::TopConfig> config) { + m_triggers = config->allTriggers_Tight(selectorName); + } + + bool TrigDecisionTightSelector::apply(const top::Event& event) const { + // this selector does nothing for loose events + bool loose = event.m_isLoose; + + if (loose) return true; + + bool orOfAllTriggers(false); + for (const auto& trigger : m_triggers) { + bool passThisTrigger(false); + if (event.m_info->isAvailable<char>("TRIGDEC_" + trigger)) { + if (event.m_info->auxdataConst<char>("TRIGDEC_" + trigger) == 1) { + passThisTrigger = true; + } + } + + orOfAllTriggers |= passThisTrigger; + } + + return orOfAllTriggers; + } + + std::string TrigDecisionTightSelector::name() const { + std::string name = "TRIGDEC_TIGHT "; + for (auto trigger : m_triggers) + name += " " + trigger; + + return name; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigMatchSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigMatchSelector.cxx index 2565d134261edfa2a0cb1eca393d7d94b8d348e8..8f1b02428a1c20188bc9af22214d26fa14efb44c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigMatchSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/Root/TrigMatchSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopEventSelectionTools/TrigMatchSelector.h" #include "TopEvent/Event.h" @@ -10,37 +10,33 @@ #include <iostream> namespace top { - - TrigMatchSelector::TrigMatchSelector(const std::string& selectorName,std::shared_ptr<top::TopConfig> config) - { - m_electronTriggers = config->electronTriggers(selectorName); - m_muonTriggers = config->muonTriggers(selectorName); - m_tauTriggers = config->tauTriggers(selectorName); - - std::cout<<"Triggers Matching for selector = "<<selectorName<<std::endl; - for (auto s : m_electronTriggers) { - std::cout << "--Electron Trigger = " << s << "--" << std::endl; - } - for (auto s : m_muonTriggers) { - std::cout << "--Muon Trigger = " << s << "--" << std::endl; - } - for (auto s : m_tauTriggers) { - std::cout << "--Tau Trigger = " << s << "--" << std::endl; - } + TrigMatchSelector::TrigMatchSelector(const std::string& selectorName, std::shared_ptr<top::TopConfig> config) { + m_electronTriggers_Tight = config->electronTriggers_Tight(selectorName); + m_muonTriggers_Tight = config->muonTriggers_Tight(selectorName); + m_tauTriggers_Tight = config->tauTriggers_Tight(selectorName); + m_electronTriggers_Loose = config->electronTriggers_Loose(selectorName); + m_muonTriggers_Loose = config->muonTriggers_Loose(selectorName); + m_tauTriggers_Loose = config->tauTriggers_Loose(selectorName); } - bool TrigMatchSelector::apply(const top::Event& event) const - { + bool TrigMatchSelector::apply(const top::Event& event) const { + // different treatment depending if it's a loose or tight top::Event + bool loose = event.m_isLoose; + // if no trigger menu us associated to this selection, return true // no effect of TRIGMATCH if TRIGDEC wasn't used - if (m_electronTriggers.size()+m_muonTriggers.size()+m_tauTriggers.size() == 0) return true; - + if (!loose) { + if (m_electronTriggers_Tight.size() + m_muonTriggers_Tight.size() + m_tauTriggers_Tight.size() == 0) return true; + } else { + if (m_electronTriggers_Loose.size() + m_muonTriggers_Loose.size() + m_tauTriggers_Loose.size() == 0) return true; + } + bool trigMatch(false); - + // Loop over electrons for (const auto* const elPtr : event.m_electrons) { - // Loop over triggers - for (const auto& trigger : m_electronTriggers) { + // Loop over triggers; loose ones for loose events, tight ones for tight events + for (const auto& trigger : loose ? m_electronTriggers_Loose : m_electronTriggers_Tight) { std::string trig = "TRIGMATCH_" + trigger; if (elPtr->isAvailable<char>(trig)) { if (elPtr->auxdataConst<char>(trig) == 1) { @@ -49,12 +45,12 @@ namespace top { } } // decoration isAvailable } // Loop over triggers - } // Loop over electrons - + } // Loop over electrons + // Loop over muons for (const auto* const muPtr : event.m_muons) { - // Loop over triggers - for (const auto& trigger : m_muonTriggers) { + // Loop over triggers; loose ones for loose events, tight ones for tight events + for (const auto& trigger : loose ? m_muonTriggers_Loose : m_muonTriggers_Tight) { std::string trig = "TRIGMATCH_" + trigger; if (muPtr->isAvailable<char>(trig)) { if (muPtr->auxdataConst<char>(trig) == 1) { @@ -68,8 +64,8 @@ namespace top { // Loop over taus for (const auto* const tauPtr : event.m_tauJets) { - // Loop over triggers - for (const auto& trigger : m_tauTriggers) { + // Loop over triggers; loose ones for loose events, tight ones for tight events + for (const auto& trigger : loose ? m_tauTriggers_Loose : m_tauTriggers_Tight) { std::string trig = "TRIGMATCH_" + trigger; if (tauPtr->isAvailable<char>(trig)) { if (tauPtr->auxdataConst<char>(trig) == 1) { @@ -79,13 +75,12 @@ namespace top { } // decoration isAvailable } // Loop over triggers } // Loop over taus - + return trigMatch; } - + std::string TrigMatchSelector::name() const { std::string name = "TRIGMATCH"; return name; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/EventSelectorBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/EventSelectorBase.h index b673ca4cb9f84c1a6daa74635bb5abb7364e19bc..2edf5a586fd4957fb6f9210c41c62cfdfd8f8b3a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/EventSelectorBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/EventSelectorBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSELECTORBASE_H_ #define EVENTSELECTORBASE_H_ @@ -10,7 +10,6 @@ #include "TopParticleLevel/ParticleLevelEvent.h" namespace top { - /** * @brief This should apply event-level cuts and perform simple plotting on * top::Event objects. @@ -18,8 +17,8 @@ namespace top { * This is the base class, and all classes that do stuff * to events should inherit from it. */ -class EventSelectorBase { -public: + class EventSelectorBase { + public: /** * @brief Default constructor, doesn't do anything. */ @@ -43,7 +42,7 @@ public: /** * @brief Assignment is not allowed. */ - EventSelectorBase& operator=(const EventSelectorBase &) = delete; + EventSelectorBase& operator = (const EventSelectorBase&) = delete; /** * @brief This does stuff based on the information in an event. @@ -71,7 +70,7 @@ public: * @param true if the event should be kept (i.e. it passed the selector * criteria), false otherwise. */ - virtual bool applyParticleLevel( const top::ParticleLevelEvent & ) const { return true; } + virtual bool applyParticleLevel(const top::ParticleLevelEvent&) const {return true;} /** * @brief A human readable name. @@ -80,8 +79,7 @@ public: * implemented for each tool. */ virtual std::string name() const = 0; -}; - + }; } //namespace top #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ExamplePlots.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ExamplePlots.h index d8047e73705741903e35ebb24b99a0c77cca0322..27f7b3eb0acdb7a21e8e53d48cb35abaf794b7ad 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ExamplePlots.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ExamplePlots.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EXAMPLEPLOTS_H_ #define EXAMPLEPLOTS_H_ @@ -11,18 +11,18 @@ class TFile; namespace EL { -class Worker; + class Worker; } namespace top { -class TopConfig; + class TopConfig; /** * @brief An example of how to quickly make some plots at a certain point in * the cutflow. */ -class ExamplePlots : public EventSelectorBase { -public: + class ExamplePlots: public EventSelectorBase { + public: /** * @brief Setup some example plots. * @@ -34,7 +34,8 @@ public: * so that we can attach the files. * @param wk Only used by EventLoop, ok as nullptr as default. */ - ExamplePlots(const std::string& name, TFile* outputFile, EL::Worker* wk = nullptr, std::shared_ptr<top::TopConfig> config = nullptr); + ExamplePlots(const std::string& name, TFile* outputFile, EL::Worker* wk = nullptr, + std::shared_ptr<top::TopConfig> config = nullptr); /** * @brief Fill the histograms. @@ -49,20 +50,18 @@ public: * @return The word EXAMPLEPLOTS. */ std::string name() const override; - -private: + private: ///File units are MeV and normally people like plots in GeV. static const double toGeV; ///Easy access to histograms. PlotManager m_hists; - + // Nominal hash value std::size_t m_nominalHashValue; std::shared_ptr<top::TopConfig> m_config; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/FakesMMConfigs.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/FakesMMConfigs.h index f7788592963bc8d7407be448d99aa6b16e24814a..d4276e47a66addc4257f3a4a9e4bf716497095c7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/FakesMMConfigs.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/FakesMMConfigs.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef FAKESMMCONFIG_H_ #define FAKESMMCONFIG_H_ @@ -10,13 +10,12 @@ class TFile; namespace top { - /** * @brief An example of how to quickly make some plots at a certain point in * the cutflow. */ -class FakesMMConfigs : public EventSelectorBase { -public: + class FakesMMConfigs: public EventSelectorBase { + public: /** * @brief Setup the matrix-method configurations. * @@ -40,12 +39,10 @@ public: * @return The MM weight configurations. */ std::vector<std::string> configurations() const {return m_configurations;}; - -private: + private: // Nominal hash value std::vector<std::string> m_configurations; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GRLSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GRLSelector.h index 8d3a1637ce85b9cfe01c470e987747b50738d81e..dd9d960f49933ac8555a414a37014c87074ec6c0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GRLSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GRLSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef GRLSELECTOR_H_ #define GRLSELECTOR_H_ @@ -8,32 +8,30 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** - * @brief Select events if they are on a GRL specified by the parameter - * GRLFilename in the configuration file. MC simulation events are always - * accepted. - */ - class GRLSelector : public EventSelectorBase { - public: - GRLSelector(); - virtual ~GRLSelector(){}; - - /** - * @brief MC simulation passes, data is checked against the GRL. - * - * @param event The event in question - * @return True for MC simulation, or if the data event is on the GRL. - */ - virtual bool apply(const top::Event& event) const override; - - /** - * @brief The name of the tool. - * - * @return The name of the tool for humans to see. - */ - std::string name() const override; - + * @brief Select events if they are on a GRL specified by the parameter + * GRLFilename in the configuration file. MC simulation events are always + * accepted. + */ + class GRLSelector: public EventSelectorBase { + public: + GRLSelector(); + virtual ~GRLSelector() {}; + + /** + * @brief MC simulation passes, data is checked against the GRL. + * + * @param event The event in question + * @return True for MC simulation, or if the data event is on the GRL. + */ + virtual bool apply(const top::Event& event) const override; + + /** + * @brief The name of the tool. + * + * @return The name of the tool for humans to see. + */ + std::string name() const override; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GlobalTrigDecisionSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GlobalTrigDecisionSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..a29bd4e1caee994094891b49939c71717486b163 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GlobalTrigDecisionSelector.h @@ -0,0 +1,34 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef GLOBALTRIGDECISIONSELECTOR_H_ +#define GLOBALTRIGDECISIONSELECTOR_H_ + +#include "TopEventSelectionTools/EventSelectorBase.h" + +#include <memory> + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +#include "TriggerAnalysisInterfaces/ITrigGlobalEfficiencyCorrectionTool.h" + + +namespace top { + class Event; + class TopConfig; + + class GlobalTrigDecisionSelector: public EventSelectorBase { + public: + GlobalTrigDecisionSelector(); + + bool apply(top::Event const& event) const override; + std::string name() const override; + private: + mutable ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSF; + mutable ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSFLoose; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GlobalTrigMatchSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GlobalTrigMatchSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..35051c8a6a9503906217d9d0c6dbead80d7942b9 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GlobalTrigMatchSelector.h @@ -0,0 +1,34 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef GLOBALTRIGMATCHSELECTOR_H_ +#define GLOBALTRIGMATCHSELECTOR_H_ + +#include "TopEventSelectionTools/EventSelectorBase.h" + +#include <memory> + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +#include "TriggerAnalysisInterfaces/ITrigGlobalEfficiencyCorrectionTool.h" + + +namespace top { + class Event; + + class GlobalTrigMatchSelector: public EventSelectorBase { + public: + GlobalTrigMatchSelector(); + + bool apply(top::Event const& event) const override; + + std::string name() const override; + private: + mutable ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSF; + mutable ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSFLoose; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GoodCaloSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GoodCaloSelector.h index 76ea93cf59efdf11ea63967e116dceba9982b8ac..5cde1f5cd28870f77f206dc4d2bcd9484495618b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GoodCaloSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/GoodCaloSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef GOODCALOSELECTOR_H_ #define GOODCALOSELECTOR_H_ @@ -8,31 +8,29 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** - * @brief Select data events with good Tile and LAr calorimeters. - * MC simulation events are always accepted. - */ - class GoodCaloSelector : public EventSelectorBase { - public: - GoodCaloSelector(); - virtual ~GoodCaloSelector(){}; - - /** - * @brief MC simulation passes, data is checked against the GRL. - * - * @param event The event in question - * @return True for MC simulation, or if the data event is on the GRL. - */ - virtual bool apply(const top::Event& event) const override; - - /** - * @brief The name of the tool. - * - * @return The name of the tool for humans to see. - */ - std::string name() const override; - + * @brief Select data events with good Tile and LAr calorimeters. + * MC simulation events are always accepted. + */ + class GoodCaloSelector: public EventSelectorBase { + public: + GoodCaloSelector(); + virtual ~GoodCaloSelector() {}; + + /** + * @brief MC simulation passes, data is checked against the GRL. + * + * @param event The event in question + * @return True for MC simulation, or if the data event is on the GRL. + */ + virtual bool apply(const top::Event& event) const override; + + /** + * @brief The name of the tool. + * + * @return The name of the tool for humans to see. + */ + std::string name() const override; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/HTSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/HTSelector.h index a6ff79cc18c7a18ff659b3fcadde016b232ea92c..11c69bc7e2a2d33cbf3c1a410d6e96612c112f7d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/HTSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/HTSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef HTSELECTOR_H_ #define HTSELECTOR_H_ @@ -8,21 +8,19 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Apply a cut on the event HT. * * The calculation is done by top::ht(). */ -class HTSelector : public SignValueSelector { -public: + class HTSelector: public SignValueSelector { + public: explicit HTSelector(const std::string& params); virtual bool apply(const top::Event& event) const override; virtual bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/IP3DSV1Selector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/IP3DSV1Selector.h deleted file mode 100644 index b61ac0fc9228dffb1a1ec90e3176d62846ec46c9..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/IP3DSV1Selector.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef IP3DSV1SELECTOR_H_ -#define IP3DSV1SELECTOR_H_ - -#include "TopEventSelectionTools/SignValueSelector.h" - -namespace top { - -/** - * @brief Should count how many jets have an IP3DSV1 weight above some value. - * The user is expected to input something a bit like IP3DSV1 1.8 >= 2, to get - * two jets tagged with 1.8. Maybe in the future we can make this easier to use - * by the person just saying 70% or something for the 0.7 WP? - */ -class IP3DSV1Selector : public SignValueSelector { -public: - explicit IP3DSV1Selector(const std::string& params); - - virtual bool apply(const top::Event& event) const override; -}; - -} - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/InitialSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/InitialSelector.h index 3cc95512248740a7e3491689f6a87e528192b15f..37cbb8f32702fb651fda20b42bd1b79484a2fc0c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/InitialSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/InitialSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef INITIALSELECTOR_H_ #define INITIALSELECTOR_H_ @@ -8,14 +8,13 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief A cut that accepts all events, more useful than you might think. * * Very simple tool that accepts all events so you can see the starting * number of events in the cutflow. */ -class InitialSelector : public EventSelectorBase { + class InitialSelector: public EventSelectorBase { /** * @brief Accept every event * @@ -29,8 +28,7 @@ class InitialSelector : public EventSelectorBase { * @return The word INITIAL. */ virtual std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetCleaningSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetCleaningSelector.h index f86e0e4010891da6ef4adcb70436bfb33bec2168..dac38c57fc4461604ed16995bdbf17b4a4ff9e79 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetCleaningSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetCleaningSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #ifndef JETCLEANINGSELECTOR_H_ #define JETCLEANINGSELECTOR_H_ @@ -10,6 +10,7 @@ #include "AsgTools/AsgTool.h" #include "AsgTools/ToolHandle.h" #include "JetInterface/IJetSelector.h" +#include "JetSelectorTools/IEventCleaningTool.h" namespace top { class TopConfig; @@ -24,8 +25,8 @@ namespace top { * passed the event selection are marked as bad. Probably should check that * this is okay after overlap removal. */ -class JetCleaningSelector : public EventSelectorBase { -public: + class JetCleaningSelector: public EventSelectorBase { + public: /** * @brief Setup the jet group's cleaning tool. * @@ -50,19 +51,30 @@ public: * at. */ std::string name() const override; + private: + /** + * @brief A helper function to check if the event passes BadBatman cleaning + * in a specified range (from config) of RunNUmbers + * + * @return true if event passes + */ + bool checkBadBatman(const top::Event& event) const; -private: ///The jet cleaning tools ToolHandle<IJetSelector> m_jetCleaningToolLooseBad; - ToolHandle<IJetSelector> m_jetCleaningToolTightBad; + ToolHandle<IJetSelector> m_jetCleaningToolTightBad; + + ///The jet event cleaning tools + ToolHandle<ECUtils::IEventCleaningTool> m_jetEventCleaningToolLooseBad; + ToolHandle<ECUtils::IEventCleaningTool> m_jetEventCleaningToolTightBad; ///The level to configure to, so we can print it in the name. std::string m_level; bool m_useLooseBad; + bool m_useEventLevelJetCleaningTool; std::shared_ptr<top::TopConfig> m_config; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFlavorPlots.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFlavorPlots.h index d0f6f11c138c48ac5199b77352f56add76d0f5a6..383a2547715e537329c15046b3b32faf3d275002 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFlavorPlots.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFlavorPlots.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPEVENTSELECTIONTOOLS_JETFLAVORPLOTS_H_ #define TOPEVENTSELECTIONTOOLS_JETFLAVORPLOTS_H_ @@ -9,60 +9,101 @@ #include "TopEventSelectionTools/EventSelectorBase.h" #include "TopEventSelectionTools/PlotManager.h" +#include "PMGTools/PMGTruthWeightTool.h" class TFile; namespace EL { -class Worker; + class Worker; } namespace top { + class TopConfig; /** * @brief An example of how to quickly make some plots at a certain point in * the cutflow. */ -class JetFlavorPlots : public EventSelectorBase { - public: - /** - * @brief Setup some example plots. - * - * Add a bunch of histograms. - * - * @param name The name of the directory to store histograms in, in the - * output file. e.g. you might have ee, mumu and emu. - * @param outputFile The output file. Needs setting up at the very start - * so that we can attach the files. - * @param wk Only used by EventLoop, ok as nullptr as default. - */ - JetFlavorPlots(const std::string& name, TFile* outputFile, - EL::Worker* wk = nullptr); - - /** - * @brief Fill the histograms. - * - * @return True because it doesn't select any events. - */ - bool apply(const top::Event& event) const override; - - /** - * @brief Return the name for the cutflow table. - * - * @return The word JETFLAVORPLOTS. - */ - std::string name() const override; - - private: - // File units are MeV and normally people like plots in GeV. - static const double toGeV; - - // Easy access to histograms. - PlotManager m_hists; - - // Nominal hash value - std::size_t m_nominalHashValue; -}; + class JetFlavorPlots: public EventSelectorBase { + public: + /** + * @brief Setup some example plots. + * + * Add a bunch of histograms. + * + * @param name The name of the directory to store histograms in, in the + * output file. e.g. you might have ee, mumu and emu. + * @param outputFile The output file. Needs setting up at the very start + * so that we can attach the files. + * @param params The arguments, e.g. for the binning of the plots. + * @param config Instance of TopConfig + * @param wk Only used by EventLoop, ok as nullptr as default. + */ + JetFlavorPlots(const std::string& name, TFile* outputFile, const std::string& params, + std::shared_ptr<top::TopConfig> config, + EL::Worker* wk = nullptr); + + /** + * @brief Fill the histograms. + * + * @return True because it doesn't select any events. + */ + bool apply(const top::Event& event) const override; + + /** + * @brief Return the name for the cutflow table. + * + * @return The word JETFLAVORPLOTS. + */ + std::string name() const override; + private: + // File units are MeV and normally people like plots in GeV. + static const double toGeV; + + // Easy access to histograms. + std::shared_ptr<PlotManager> m_hists = nullptr; + std::shared_ptr<PlotManager> m_hists_Loose = nullptr; + std::shared_ptr<PlotManager> m_hists_RadHigh = nullptr; + std::shared_ptr<PlotManager> m_hists_RadHigh_Loose = nullptr; + std::shared_ptr<PlotManager> m_hists_RadLow = nullptr; + std::shared_ptr<PlotManager> m_hists_RadLow_Loose = nullptr; + + // Nominal hash value + std::size_t m_nominalHashValue; + + // for detailed plots (e.g. vs. Njets) + bool m_detailed; + + // to choose between radiation varied and nominal plots + bool m_doNominal; + bool m_doRadHigh; + bool m_doRadLow; + + // pT and eta bin edges, separated by colons + std::string m_ptBins; + std::string m_etaBins; + + // max value for nJets, when doing the plots vs. nJets + int m_nJetsMax; + + // name of the jet collection - this is needed for the names of the histograms + std::string m_jetCollection; + + // shared pointed to instance of TopConfig + std::shared_ptr<top::TopConfig> m_config; + + //PMGTruthWeights + PMGTools::PMGTruthWeightTool* m_PMGTruthWeights; + // function to translate the binnings into vector of bin edges + void formatBinning(const std::string& str, std::vector<double>& binEdges); + //helper function to book histograms + void BookHistograms(std::shared_ptr<PlotManager> h_ptr, std::vector<double> ptBins, std::vector<double> etaBins); + //helper function to fill histograms + void FillHistograms(std::shared_ptr<PlotManager> h_ptr, double w_event, const top::Event& event) const; + //This is to suppress excessive printout + mutable std::atomic<bool> m_throwwarningPMG; + }; } // namespace top #endif // TOPEVENTSELECTIONTOOLS_JETFLAVORPLOTS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFtagEffPlots.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFtagEffPlots.h new file mode 100644 index 0000000000000000000000000000000000000000..b943cceed7d3913c9cf8e80532ed5effd381c5fa --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetFtagEffPlots.h @@ -0,0 +1,123 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TOPEVENTSELECTIONTOOLS_JETFTAGEFFPLOTS_H_ +#define TOPEVENTSELECTIONTOOLS_JETFTAGEFFPLOTS_H_ + +#include <string> + +#include "TopEventSelectionTools/EventSelectorBase.h" +#include "TopEventSelectionTools/PlotManager.h" +#include "PMGTools/PMGTruthWeightTool.h" +#include <AsgTools/AnaToolHandle.h> +#include "FTagAnalysisInterfaces/IBTaggingSelectionTool.h" +#include "TopCorrections/ScaleFactorRetriever.h" +#include "PMGTools/PMGTruthWeightTool.h" + + +class TFile; + +namespace EL { + class Worker; +} + +namespace { + enum class WEIGHTTYPE { + MURUP, MURDOWN, MUFUP, MUFDOWN, VAR3CUP, VAR3CDOWN, FSRUP, FSRDOWN + }; +} + +namespace top { + class TopConfig; + +/** + * @brief An example of how to quickly make some plots at a certain point in + * the cutflow. + */ + class JetFtagEffPlots: public EventSelectorBase { + public: + JetFtagEffPlots(const std::string& name, TFile* outputFile, const std::string& params, + std::shared_ptr<top::TopConfig> config, + EL::Worker* wk = nullptr); + + + bool apply(const top::Event& event) const override; + + + std::string name() const override; + private: + // File units are MeV and normally people like plots in GeV. + static const double toGeV; + + // Easy access to histograms. + std::shared_ptr<PlotManager> m_hists = nullptr; + std::shared_ptr<PlotManager> m_hists_muRup = nullptr; + std::shared_ptr<PlotManager> m_hists_muRdown = nullptr; + std::shared_ptr<PlotManager> m_hists_muFup = nullptr; + std::shared_ptr<PlotManager> m_hists_muFdown = nullptr; + std::shared_ptr<PlotManager> m_hists_Var3cup = nullptr; + std::shared_ptr<PlotManager> m_hists_Var3cdown = nullptr; + std::shared_ptr<PlotManager> m_hists_FSRup = nullptr; + std::shared_ptr<PlotManager> m_hists_FSRdown = nullptr; + + + // Nominal hash value + std::size_t m_nominalHashValue; + + std::string m_CDIfile; + + bool m_fill_total_hists; + + //optional suffix you can add to your histogram + std::string m_histogram_suffix; + bool m_dont_use_event_weight; + bool m_use_track_jets; + bool m_doNominal; + bool m_doMuRup; + bool m_doMuRdown; + bool m_doMuFup; + bool m_doMuFdown; + bool m_doVar3cup; + bool m_doVar3cdown; + bool m_doFSRup; + bool m_doFSRdown; + + // pT and eta bin edges + std::string m_ptBins; + std::string m_etaBins; + + float m_max_pT; + float m_min_pT; + int m_N_pT_bins; + + float m_max_Eta; + float m_min_Eta; + int m_N_Eta_bins; + + // name of the jet collection - this is needed for the names of the histograms + std::string m_jetCollection; + std::string m_WP; + std::string m_tagger; + // shared pointed to instance of TopConfig + std::shared_ptr<top::TopConfig> m_config; + + + asg::AnaToolHandle<IBTaggingSelectionTool> m_selection_tool; + + PMGTools::PMGTruthWeightTool* m_PMGTruthWeights; + + top::ScaleFactorRetriever* m_sfRetriever; + + // function to translate the binnings into vector of bin edges + void formatBinning(const std::string& str, std::vector<double>& binEdges); + + //helper function to fill histograms + void FillHistograms(std::shared_ptr<PlotManager> h_ptr, double w_event, const top::Event& event) const; + + /// A helper function to get the correct truth weight + float GetPMGTruthWeight(WEIGHTTYPE type) const; + }; +} // namespace top + +#endif // TOPEVENTSELECTIONTOOLS_JETFTAGEFFPLOTS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetNGhostSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetNGhostSelector.h index 7a4756df830e22a6b99b64cb7effcab92d3a9d36..abe630f45409d8608fad08a46b16bbe808d632ac 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetNGhostSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetNGhostSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: JetNGhostSelector.h // Description: @@ -13,48 +13,45 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - - class JetNGhostSelector : public SignValueSelector { - public: - explicit JetNGhostSelector(const std::string& params); - - /*! - * @brief Apply on reco level. - * There is no sensible application for a ghost tagging selector at reco - * level, hence return true for any input. - */ - bool apply(const top::Event&) const override { return true; } - - /*! - * @brief Apply on particle level. - * Will calculate the number of ghost tagged jet for the requested type. - * Will return true if that number is equal to order larger than the cut - * value, false otherwise. - */ - bool applyParticleLevel(const top::ParticleLevelEvent& plEvent) const override; - - std::string name() const override; - private: - std::string parseType( const std::string & params ); - - enum Type { - c = static_cast<int>( 'c' ), - C = static_cast<int>( 'C' ), - b = static_cast<int>( 'b' ), - B = static_cast<int>( 'B' ), - t = static_cast<int>( 't' ), - W = static_cast<int>( 'W' ), - Z = static_cast<int>( 'Z' ), - H = static_cast<int>( 'H' ), - tau, - Invalid - }; - Type m_type; - - std::string m_name; + class JetNGhostSelector: public SignValueSelector { + public: + explicit JetNGhostSelector(const std::string& params); + + /*! + * @brief Apply on reco level. + * There is no sensible application for a ghost tagging selector at reco + * level, hence return true for any input. + */ + bool apply(const top::Event&) const override {return true;} + + /*! + * @brief Apply on particle level. + * Will calculate the number of ghost tagged jet for the requested type. + * Will return true if that number is equal to order larger than the cut + * value, false otherwise. + */ + bool applyParticleLevel(const top::ParticleLevelEvent& plEvent) const override; + + std::string name() const override; + private: + std::string parseType(const std::string& params); + + enum Type { + c = static_cast<int>('c'), + C = static_cast<int>('C'), + b = static_cast<int>('b'), + B = static_cast<int>('B'), + t = static_cast<int>('t'), + W = static_cast<int>('W'), + Z = static_cast<int>('Z'), + H = static_cast<int>('H'), + tau, + Invalid }; + Type m_type; - + std::string m_name; + }; } #endif /* _JETNGHOSTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetResponsePlots.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetResponsePlots.h new file mode 100644 index 0000000000000000000000000000000000000000..ba9832783ba6eaf668f4e642dcdb219757b024b1 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/JetResponsePlots.h @@ -0,0 +1,96 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TOPEVENTSELECTIONTOOLS_JETRESPONSEPLOTS_H_ +#define TOPEVENTSELECTIONTOOLS_JETRESPONSEPLOTS_H_ + +#include "TopEventSelectionTools/EventSelectorBase.h" +#include "TopEventSelectionTools/PlotManager.h" +#include "PMGAnalysisInterfaces/IPMGTruthWeightTool.h" +#include "PMGTools/PMGTruthWeightTool.h" +#include "AsgTools/ToolHandle.h" +#include "AsgTools/ToolHandleArray.h" +#include "AsgTools/AnaToolHandle.h" + +#include <string> + +class TFile; + +namespace EL { + class Worker; +} + +namespace top { + class TopConfig; + +/** + * @brief An example of how to quickly make some plots at a certain point in + * the cutflow. + */ + class JetResponsePlots: public EventSelectorBase { + public: + /** + * @brief Setup some example plots. + * + * Add a bunch of histograms. + * + * @param name The name of the directory to store histograms in, in the + * output file. e.g. you might have ee, mumu and emu. + * @param outputFile The output file. Needs setting up at the very start + * so that we can attach the files. + * @param params The arguments, e.g. for the binning of the plots. + * @param config Instance of TopConfig + * @param wk Only used by EventLoop, ok as nullptr as default. + */ + JetResponsePlots(const std::string& name, + TFile* outputFile, + const std::string& params, + std::shared_ptr<top::TopConfig> config, + EL::Worker* wk = nullptr); + + /** + * @brief Fill the histograms. + * + * @return True because it doesn't select any events. + */ + bool apply(const top::Event& event) const override; + + /** + * @brief Helper function to fill the histograms + * + */ + void FillHistograms(const double w_event, + const top::Event& event) const; + + /** + * @brief Return the name for the cutflow table. + * + * @return The word JETRESPONSEPLOTS. + */ + std::string name() const override; + private: + + // Easy access to histograms. + std::shared_ptr<PlotManager> m_hists; + + // Nominal hash value + std::size_t m_nominalHashValue; + + // deltaR used for jet matching + float m_deltaR; + int m_bins; + float m_min; + float m_max; + std::vector<double> m_ptBinning; + + // shared pointed to instance of TopConfig + std::shared_ptr<top::TopConfig> m_config; + + //PMGTruthWeights + ToolHandle<PMGTools::IPMGTruthWeightTool> m_PMGTruthWeights; + + }; +} // namespace top + +#endif // TOPEVENTSELECTIONTOOLS_JETRESPONSEPLOTS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/KLFitterSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/KLFitterSelector.h index 98536f770bbb4ba3c94b394ee04c4a9ae8da29a6..e7fcc3452e506df8ca16b6bf4800b54e6c05f61b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/KLFitterSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/KLFitterSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: KLFitterSelector.h 665436 2015-05-06 19:10:23Z morrisj $ #ifndef ANALYSISTOP_TOPEVENTSELECTIONTOOLS_KLFITTERSELECTOR_H @@ -8,19 +8,18 @@ #include "TopEventSelectionTools/SignValueSelector.h" -namespace top{ - +namespace top { /** * @brief Apply a cut on the KLFitter Results */ - + // Forward declare class Event; - - class KLFitterSelector : public SignValueSelector { - public: - explicit KLFitterSelector(const std::string& params); - bool apply(const top::Event&) const override; + + class KLFitterSelector: public SignValueSelector { + public: + explicit KLFitterSelector(const std::string& params); + bool apply(const top::Event&) const override; }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METMWTSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METMWTSelector.h index 6cea661a59e32a7501891d4e757a2981bd839e16..8881502790109f815b5bf9d6f40706471e662eb7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METMWTSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METMWTSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef METMWTSELECTOR_H_ #define METMWTSELECTOR_H_ @@ -8,19 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Allows a cut on the sum of MET and MWT. */ -class METMWTSelector : public SignValueSelector { -public: + class METMWTSelector: public SignValueSelector { + public: explicit METMWTSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METSelector.h index 4d3dd53103bc3bfd3d826583e1c74836426e49bd..5d3fcdf9bfb902dcb718515b5c6d93da3979ecde 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/METSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef METSELECTOR_H_ #define METSELECTOR_H_ @@ -8,19 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Apply a cut on the event MET. */ -class METSelector : public SignValueSelector { -public: + class METSelector: public SignValueSelector { + public: explicit METSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLSelector.h index 6efd0903f6e8dc7de23bd499ca8be91727b04756..adb1fe3e88d84545d7712f7285883e5d445ed73e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MLLSELECTOR_H_ #define MLLSELECTOR_H_ @@ -8,20 +8,18 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Put a cut on the invariant mass of two same flavour leptons. If you * want to veto a window (say for the Z mass) you instead want MLLWindow. */ -class MLLSelector : public SignValueSelector { -public: + class MLLSelector: public SignValueSelector { + public: explicit MLLSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLWindowSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLWindowSelector.h index 5721b9d9ab926b047056c7a6688fe9478ff03bd3..143e260f6fe6d20feced4b7f16f5902365a3a78d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLWindowSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MLLWindowSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MLLWINDOW_H_ #define MLLWINDOW_H_ @@ -8,12 +8,11 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Reject events in the invariant mass (of two charged leptons) window. */ -class MLLWindow : public EventSelectorBase { -public: + class MLLWindow: public EventSelectorBase { + public: explicit MLLWindow(std::string params); bool apply(const top::Event& event) const override; @@ -21,12 +20,10 @@ public: bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; std::string name() const override; - -private: + private: double m_cutvalue0; double m_cutvalue1; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV1Selector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV1Selector.h deleted file mode 100644 index 764096adfab5f8e94ee6702185b23555b679ec0e..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV1Selector.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef MV1SELECTOR_H_ -#define MV1SELECTOR_H_ - -#include "TopEventSelectionTools/SignValueSelector.h" - -namespace top { - -/** - * @brief Should count how many jets have an mv1 weight above some value. - * mv1 Seem to not be filled yet though. - */ -class MV1Selector : public SignValueSelector { -public: - explicit MV1Selector(const std::string& params); - - bool apply(const top::Event& event) const override; -}; - -} - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c10Selector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c10Selector.h index fe1af683f59ff1a195b554a9b190784a0560c0dd..c1972f98f4bc63a8ff1a579217746d64d45597e9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c10Selector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c10Selector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MV2C10SELECTOR_H_ #define MV2C10SELECTOR_H_ @@ -8,12 +8,11 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Should count how many jets have an mv2c10 weight above some value. */ -class MV2c10Selector : public SignValueSelector { -public: + class MV2c10Selector: public SignValueSelector { + public: explicit MV2c10Selector(const std::string& params); /** @@ -28,8 +27,7 @@ public: * @return True if the event passes the cut, false otherwise. */ bool apply(const top::Event& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c20Selector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c20Selector.h deleted file mode 100644 index 8dcbfcc28fe1af06e8f8f745acddb3770688f274..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MV2c20Selector.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef MV2C20SELECTOR_H_ -#define MV2C20SELECTOR_H_ - -#include "TopEventSelectionTools/SignValueSelector.h" - -namespace top { - -/** - * @brief Should count how many jets have an mv2c20 weight above some value. - * - * Information is taken from these slides presented in PC: - * https://indico.cern.ch/event/394627/contribution/1/5/material/slides/0.pdf - */ -class MV2c20Selector : public SignValueSelector { -public: - explicit MV2c20Selector(const std::string& params); - - /** - * @brief Look at the event and check if the required number of tagged jets - * are there. - * - * If MV2C20 is not in the input file (it is for MC15) then you need to - * return false, since no events pass the cut. If it is there we retrieve - * it and check the value against the user specified cut. - * - * @param event The event to analyse - * @return True if the event passes the cut, false otherwise. - */ - bool apply(const top::Event& event) const override; -}; - -} - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MWTSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MWTSelector.h index 6658fe250f468f54951a5c5bfaaa82e9c18615f3..0f790a6e875d60c35bb7bf82427dfbe9a1203325 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MWTSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MWTSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MWTSELECTOR_H_ #define MWTSELECTOR_H_ @@ -8,20 +8,18 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief Apply a cut on the transverse W mass (taken from the electron or muon * and MET). */ -class MWTSelector : public SignValueSelector { -public: + class MWTSelector: public SignValueSelector { + public: explicit MWTSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MsgCategory.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MsgCategory.h new file mode 100644 index 0000000000000000000000000000000000000000..07ee615c2a723581e651d0fe21ba4cae7bf02768 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/MsgCategory.h @@ -0,0 +1,10 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#ifndef TOPEVENTSELECTIONTOOLS_MSG_CATEGORY_H_ +#define TOPEVENTSELECTIONTOOLS_MSG_CATEGORY_H_ +#include <AsgMessaging/MessageCheck.h> + +ANA_MSG_HEADER(TopEventSelectionTools) + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonSelector.h index 97249a0a86a6c8e90ed839345cde78767af47d1e..55a6fab7e00be6f8d51ce5b48cce77a70eea650f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NELECTRONNMUONSELECTOR_H_ #define NELECTRONNMUONSELECTOR_H_ @@ -8,12 +8,11 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief To accept an event based on a check of electrons and muons. */ -class NElectronNMuonSelector : public SignValueSelector { -public: + class NElectronNMuonSelector: public SignValueSelector { + public: /** * @brief Select events based on multiplicity, which should be an integer. */ @@ -27,13 +26,12 @@ public: bool apply(const top::Event& event) const override; /*! - * @brief The 'OR' of a check against electrons and muons. + * @brief The 'OR' of a check against electrons and muons. * * @return True to keep the event, false otherwise. */ bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonTightSelector.h index d3f72175d8d985a881037563809cd3d8d3f28ec7..62dd308bbb1f469e1f1f7c5eb5f369361d4906b9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonTightSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronNMuonTightSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NELECTRONNMUONTIGHTSELECTOR_H_ #define NELECTRONNMUONTIGHTSELECTOR_H_ @@ -8,13 +8,12 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief To accept an event based on a check of tight electrons and muons. * This is identical to NElectronNMuonSelector in the case of tight selection, so only relevant for loose selection. */ -class NElectronNMuonTightSelector : public SignValueSelector { -public: + class NElectronNMuonTightSelector: public SignValueSelector { + public: /** * @brief Select events based on multiplicity, which should be an integer. */ @@ -28,13 +27,12 @@ public: bool apply(const top::Event& event) const override; /*! - * @brief The 'OR' of a check against electrons and muons. + * @brief The 'OR' of a check against electrons and muons. * * @return True to keep the event, false otherwise. */ bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronSelector.h index 15b89e60b31f92792a63339410fa358fe859d4f0..f21d3600682abf1c38efe503d66660309e6b0ff5 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NELECTRONSELECTOR_H_ #define NELECTRONSELECTOR_H_ @@ -8,19 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good electrons. */ -class NElectronSelector : public SignValueSelector { -public: + class NElectronSelector: public SignValueSelector { + public: explicit NElectronSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronTightSelector.h index 1c71d916e2d096a2f8900a110bda630a37f23518..0c767a2c7a642aee560bdd0d57b97d7ad92f370d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronTightSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NElectronTightSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NELECTRONTIGHTSELECTOR_H_ #define NELECTRONTIGHTSELECTOR_H_ @@ -8,20 +8,18 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good tight electrons. * This is identical to NElectronSelector in the case of tight selection, so only relevant for loose selection. */ -class NElectronTightSelector : public SignValueSelector { -public: + class NElectronTightSelector: public SignValueSelector { + public: explicit NElectronTightSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NFwdElectronSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NFwdElectronSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..fe4f87e38d55ff05e53458de424730c0fd21617e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NFwdElectronSelector.h @@ -0,0 +1,28 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef NFWDELECTRONSELECTOR_H_ +#define NFWDELECTRONSELECTOR_H_ + +#include "TopEventSelectionTools/SignValueSelector.h" + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "AsgTools/AnaToolHandle.h" + +namespace top { +/** + * @brief A tool that selects events with a certain number of good forward electrons. + */ + class NFwdElectronSelector: public SignValueSelector { + public: + explicit NFwdElectronSelector(const std::string& params); + + bool apply(const top::Event& event) const override; + + bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NFwdElectronTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NFwdElectronTightSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..9fa056f75736698d25abcf489c69932e1e2b38c0 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NFwdElectronTightSelector.h @@ -0,0 +1,25 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef NFWDELECTRONTIGHTSELECTOR_H_ +#define NFWDELECTRONTIGHTSELECTOR_H_ + +#include "TopEventSelectionTools/SignValueSelector.h" + +namespace top { +/** + * @brief A tool that selects events with a certain number of good tight electrons. + * This is identical to NElectronSelector in the case of tight selection, so only relevant for loose selection. + */ + class NFwdElectronTightSelector: public SignValueSelector { + public: + explicit NFwdElectronTightSelector(const std::string& params); + + bool apply(const top::Event& event) const override; + + bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetBtagSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetBtagSelector.h index 1c440e79d2397b49138c1a6fa4ad43b74e0af685..045e92c31d54e9430c99ca84078fb6a2d8932b4e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetBtagSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetBtagSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NJETBTAGSELECTOR_H_ #define NJETBTAGSELECTOR_H_ @@ -13,13 +13,16 @@ namespace top { /** * @brief A tool that selects events with a certain number of good jets. */ -class NJetBtagSelector : public SignValueSelector { -public: - explicit NJetBtagSelector(const std::string& params,std::shared_ptr<top::TopConfig> config); + class NJetBtagSelector: public SignValueSelector { + public: + explicit NJetBtagSelector(const std::string& params, std::shared_ptr<top::TopConfig> config, bool doTrackJets); bool apply(const top::Event& event) const override; -}; + const std::string getFullCutName() {return SignValueSelector::valueStringDelimReplace();}; + private: + bool m_doTrackJets; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetSelector.h index 1b66a8f7a08064c07e4b6594e559bad078627718..01fc1306bf724c48943ee2bde9ab08dc3c5f6494 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NJetSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NJETSELECTOR_H_ #define NJETSELECTOR_H_ @@ -8,19 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good jets. */ -class NJetSelector : public SignValueSelector { -public: + class NJetSelector: public SignValueSelector { + public: explicit NJetSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NLargeJetSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NLargeJetSelector.h index 5aff1598bf69cf1a0f3736983ee39d1815b7fbad..8bbc365deb284e9a44c9a1e34b9bb7cf2d514cd7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NLargeJetSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NLargeJetSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NLARGEJETSELECTOR_H_ #define NLARGEJETSELECTOR_H_ @@ -9,17 +9,13 @@ namespace top { - - class NLargeJetSelector : public top::SignValueSelector { - + class NLargeJetSelector: public top::SignValueSelector { public: - explicit NLargeJetSelector(const std::string& params); bool apply(const top::Event& event) const override; - bool applyParticleLevel( const top::ParticleLevelEvent & ) const override; + bool applyParticleLevel(const top::ParticleLevelEvent&) const override; }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonSelector.h index 6dedd2cf3af6b69cd909455a7a6b0f0212279f13..9d8dc6368c476c03d3828b67e1472752d645243d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NMUONSELECTOR_H_ #define NMUONSELECTOR_H_ @@ -8,19 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good muons. */ -class NMuonSelector : public SignValueSelector { -public: + class NMuonSelector: public SignValueSelector { + public: explicit NMuonSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonTightSelector.h index 196485c6aa1d0200441012e5e2887a81d784c55c..af3b37db65e8f4eb4b67db764dc7f3011c160fb5 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonTightSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NMuonTightSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NMUONTIGHTSELECTOR_H_ #define NMUONTIGHTSELECTOR_H_ @@ -8,20 +8,18 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good tight muons. * This is identical to NMuonSelector in the case of tight selection, so only relevant for loose selection. */ -class NMuonTightSelector : public SignValueSelector { -public: + class NMuonTightSelector: public SignValueSelector { + public: explicit NMuonTightSelector(const std::string& params); bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NPhotonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NPhotonSelector.h index 77210fa9371049bee493dd4394f38f790219a8fd..7cfa1595bd139c82ca468358dcef37ab675dd38c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NPhotonSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NPhotonSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NPHOTONSELECTOR_H_ #define NPHOTONSELECTOR_H_ @@ -8,19 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good photons. */ -class NPhotonSelector : public SignValueSelector { -public: + class NPhotonSelector: public SignValueSelector { + public: explicit NPhotonSelector(const std::string& params); bool apply(const top::Event& event) const override; - bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; -}; - + bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NRCJetSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NRCJetSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..22aa918520f6bf1a0feff60424a1907ca8fc5a02 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NRCJetSelector.h @@ -0,0 +1,21 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef NRCJETSELECTOR_H_ +#define NRCJETSELECTOR_H_ + +#include "TopEventSelectionTools/SignValueSelector.h" + + +namespace top { + class NRCJetSelector: public top::SignValueSelector { + public: + explicit NRCJetSelector(const std::string& params); + + bool apply(const top::Event& event) const override; + bool applyParticleLevel(const top::ParticleLevelEvent&) const override; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NSoftMuonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NSoftMuonSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..5f9e8fa5a3c3cf688dd527db70007c5ccb0f1442 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NSoftMuonSelector.h @@ -0,0 +1,24 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef NSOFTMUONSELECTOR_H_ +#define NSOFTMUONSELECTOR_H_ + +#include "TopEventSelectionTools/SignValueSelector.h" + +namespace top { +/** + * @brief A tool that selects events with a certain number of good muons. + */ + class NSoftMuonSelector: public SignValueSelector { + public: + explicit NSoftMuonSelector(const std::string& params); + + bool apply(const top::Event& event) const override; + + bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauSelector.h index 6459759dbfabe64dae5182160bef1ab9835ae565..4c9442fd88379f79379e94e05dd34a527dcbfde3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NTAUSELECTOR_H_ #define NTAUSELECTOR_H_ @@ -8,17 +8,17 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good taus. */ -class NTauSelector : public SignValueSelector { -public: + class NTauSelector: public SignValueSelector { + public: explicit NTauSelector(const std::string& params); bool apply(const top::Event& event) const override; -}; + bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauTightSelector.h index 42432ccb6b81a112f397b4b175faa31b38ba4823..aed9d7bfad4bd2ff45184d16ff8c12e48ec7ed8e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauTightSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NTauTightSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NTAUTIGHTSELECTOR_H_ #define NTAUTIGHTSELECTOR_H_ @@ -8,17 +8,15 @@ #include "TopEventSelectionTools/SignValueSelector.h" namespace top { - /** * @brief A tool that selects events with a certain number of good taus. */ -class NTauTightSelector : public SignValueSelector { -public: + class NTauTightSelector: public SignValueSelector { + public: explicit NTauTightSelector(const std::string& params); bool apply(const top::Event& event) const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NVarRCJetSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NVarRCJetSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..27d0847428518a29306f6aeee01c2267b7dbbe86 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NVarRCJetSelector.h @@ -0,0 +1,22 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef NVARRCJETSELECTOR_H_ +#define NVARRCJETSELECTOR_H_ + +#include "TopEventSelectionTools/SignValueSelector.h" + + +namespace top { + class NVarRCJetSelector: public top::SignValueSelector { + std::string m_name; + public: + explicit NVarRCJetSelector(const std::string& name, const std::string& params); + + bool apply(const top::Event& event) const override; + bool applyParticleLevel(const top::ParticleLevelEvent&) const override; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NoBadMuonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NoBadMuonSelector.h index c0bef23a8488699ff22ca06ca6a87161b7f6d8e9..91df0fc04e3386171bfb90444e82e0b47407554d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NoBadMuonSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/NoBadMuonSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NOBADMUONSELECTOR_H_ #define NOBADMUONSELECTOR_H_ @@ -11,22 +11,22 @@ #include "MuonAnalysisInterfaces/IMuonSelectionTool.h" namespace top { + class TopConfig; /** * @brief A tool that selects events containing no bad muons * https://twiki.cern.ch/twiki/bin/view/Atlas/MuonSelectionTool#is_BadMuon_Flag_Event_Veto * */ - class NoBadMuonSelector : public EventSelectorBase { -public: - + class NoBadMuonSelector: public EventSelectorBase { + public: /** * @brief Event selection if bad muon detected using the official muon selector tool. * * Call the muon selector tool and reject the event if any of the muons that * passed the event selection are marked as bad. */ - explicit NoBadMuonSelector(); + explicit NoBadMuonSelector(std::shared_ptr<top::TopConfig> m_config); /** * @brief Events with a muon flagged bad are rejected @@ -42,12 +42,11 @@ public: * @return The name of the tool for humans to see. */ std::string name() const override; - -private: + private: ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; -}; - + std::shared_ptr<top::TopConfig> m_config; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonSelector.h index 7cf17c830e35fd17ff5cc4939f37e151e52d5366..e157ee334b5ad9f24e9385561a66ccf512d0a47c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef OSSELECTOR_H_ #define OSSELECTOR_H_ @@ -8,22 +8,20 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief Keep only events that have at least one opposite sign lepton pair. * * Try to find at least one lepton (el, mu) with positive charge, * and at least one with negative charge. */ -class OSLeptonSelector : public EventSelectorBase { -public: + class OSLeptonSelector: public EventSelectorBase { + public: bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonTightSelector.h index fc6c0a2986c8313e22cb9dc11b43febf9f001cad..a68975f030f3d70dfe8b249f9c0eccac2261a766 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonTightSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/OSLeptonTightSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef OSTIGHTSELECTOR_H_ #define OSTIGHTSELECTOR_H_ @@ -8,7 +8,6 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief Keep only events that have at least one opposite sign tight lepton pair. * This is identical to OSLeptonSelector in the case of tight selection, so only relevant for loose selection. @@ -16,15 +15,14 @@ namespace top { * Try to find at least one lepton (el, mu) with positive charge, * and at least one with negative charge. */ -class OSLeptonTightSelector : public EventSelectorBase { -public: + class OSLeptonTightSelector: public EventSelectorBase { + public: bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ParticleLevelSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ParticleLevelSelector.h index a78700637a94315b864dc8acb71d65754e1c7801..0cd63139c969bc5d2f510b77be340c613a4e6787 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ParticleLevelSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ParticleLevelSelector.h @@ -1,19 +1,11 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelSelector.h // Description: // Author: Fabian Wilk // Created: Tue Oct 27 13:26:19 2015 -// -// (c) by Fabian Wilk -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. #ifndef _PARTICLELEVELSELECTOR_H_ #define _PARTICLELEVELSELECTOR_H_ @@ -21,35 +13,32 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - + /** + * @brief An event selector that accepts all particle level events and rejects all + * reco level events. + * + * This can be used to define event selections that shall be applied only to + * particle level events. + */ + class ParticleLevelSelector: public EventSelectorBase { /** - * @brief An event selector that accepts all particle level events and rejects all - * reco level events. - * - * This can be used to define event selections that shall be applied only to - * particle level events. + * @brief Reject every event. + * @return Always false. */ - class ParticleLevelSelector : public EventSelectorBase { - /** - * @brief Reject every event. - * @return Always false. - */ - virtual bool apply(const top::Event&) const override; - - /** - * @brief Accept every event. - * @return Always true. - */ - virtual bool applyParticleLevel(const top::ParticleLevelEvent&) const override; + virtual bool apply(const top::Event&) const override; - /** - * @brief The name printed in the cutflow. - * @return The word PARTICLE_LEVEL - */ - virtual std::string name() const override; - }; + /** + * @brief Accept every event. + * @return Always true. + */ + virtual bool applyParticleLevel(const top::ParticleLevelEvent&) const override; + /** + * @brief The name printed in the cutflow. + * @return The word PARTICLE_LEVEL + */ + virtual std::string name() const override; + }; } #endif /* _PARTICLELEVELSELECTOR_H_ */ - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PlotManager.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PlotManager.h index f9eb9219837626145f719943167fab49909e070c..77c88cbb9e1ff9bb55a263336cc9fdb03e0d6295 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PlotManager.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PlotManager.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #ifndef PLOTMANAGER_H_ #define PLOTMANAGER_H_ @@ -17,14 +17,13 @@ namespace EL { } namespace top { - /** * @brief A map that lets you create a bunch of histograms and get hold of them * via a string name. It takes care of writing them to the outputfile too - if * you have one. */ -class PlotManager { -public: + class PlotManager { + public: /** * @brief A name for the selection. Plots will be stored in a folder * with this name in the output file. e.g. ejets, mujets etc. @@ -34,11 +33,11 @@ public: * of a folder because... well... ROOT! */ explicit PlotManager(const std::string& name, TFile* outputFile = nullptr, EL::Worker* wk = nullptr); - - PlotManager(const std::string& sample,const std::string& channel,const std::string& syst,TFile* outputFile); + + PlotManager(const std::string& sample, const std::string& channel, const std::string& syst, TFile* outputFile); /** - * @brief Add a histogram to the output file. + * @brief Add a 1D histogram to the output file. * * @param hname A unique name, notice that we automatically add the name * of the analysis on to this with an underscore. @@ -49,6 +48,17 @@ public: */ void addHist(const std::string& hname, const std::string& title, int bins, double start, double end) const; + /** + * @brief Add a 1D histogram with variable bin size to the output file. + * + * @param hname A unique name, notice that we automatically add the name + * of the analysis on to this with an underscore. + * @param title The histogram title, as root expects. + * @param bins The number of bins, passed directly to root. + * @param binArray The array with bin edges + */ + void addHist(const std::string& hname, const std::string& title, int bins, double* binArray) const; + /** * @brief Add a 2D histogram to the output file. * @@ -58,13 +68,44 @@ public: * @param xbins The number of x-bins, passed directly to root. * @param xstart The starting x-value, passed directly to root. * @param xend The ending x-value, passed directly to root. - * @param xbins The number of y-bins, passed directly to root. - * @param xstart The starting y-value, passed directly to root. - * @param xend The ending y-value, passed directly to root. + * @param ybins The number of y-bins, passed directly to root. + * @param ystart The starting y-value, passed directly to root. + * @param yend The ending y-value, passed directly to root. */ void addHist(const std::string& hname, const std::string& title, - int xbins, double xstart, double xend, - int ybins, double ystart, double yend) const; + int xbins, double xstart, double xend, + int ybins, double ystart, double yend) const; + + /** + * @brief Add a 2D histogram with variable bin size to the output file. + * + * @param hname A unique name, notice that we automatically add the name + * of the analysis on to this with an underscore. + * @param title The histogram title, as root expects. + * @param xbins The number of x-bins, passed directly to root. + * @param xbinArray The array with x-bin edges, passed directly to root. + * @param ybins The number of y-bins, passed directly to root. + * @param ybinArray The array with y-bin edges, passed directly to root. + */ + void addHist(const std::string& hname, const std::string& title, + int xbins, double* xbinArray, + int ybins, double* ybinArray) const; + + /** + * @brief Add a 2D histogram with variable bin size to the output file. + * + * @param hname A unique name, notice that we automatically add the name + * of the analysis on to this with an underscore. + * @param title The histogram title, as root expects. + * @param xbins The number of x-bins, passed directly to root. + * @param xbinArray The array with x-bin edges, passed directly to root. + * @param ybins The number of y-bins, passed directly to root. + * @param ystart The starting y-value, passed directly to root. + * @param yend The ending y-value, passed directly to root. + */ + void addHist(const std::string& hname, const std::string& title, + int xbins, double* xbinArray, + int ybins, double ystart, double yend) const; /** * @brief Recover an existing histogram, to fill it for example. @@ -82,8 +123,17 @@ public: * on each histogram. I'm assuming you have an open file already. */ void scaleHistograms(double sf = 1.) const; + private: + /** + * @brief Helper method to check for duplicates when adding histogram. + * + * If duplicate histogram exists with same name as hname, print + * error message and throw std::runtime_error + * + * @param hname Name of the histogram to check against duplicates. + */ + void checkDuplicate(const std::string& hname) const; -private: EL::Worker* m_wk; ///Name of the folder to store the plots in, in the output file. @@ -93,8 +143,7 @@ private: mutable std::unordered_map<std::string, TH1*> m_histograms; mutable TDirectory* m_plotDir; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrimaryVertexSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrimaryVertexSelector.h index 0d8a6976f837c60611b7f3d450ec7399aaef9170..9ad1c4e91fb9f24b778967a21693ca94acc11b47 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrimaryVertexSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrimaryVertexSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef PRIMARYVERTEXSELECTOR_H_ #define PRIMARYVERTEXSELECTOR_H_ @@ -8,33 +8,31 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** - * @brief Select data events with good Primary vertices - * following: - * https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/InDetTrackingPerformanceGuidelines#Vertexing - * - */ - class PrimaryVertexSelector : public EventSelectorBase { - public: - PrimaryVertexSelector(); - virtual ~PrimaryVertexSelector(){}; - - /** - * @brief MC simulation passes, data is checked against the GRL. - * - * @param event The event in question - * @return True for MC simulation, or if the data event is on the GRL. - */ - virtual bool apply(const top::Event& event) const override; - - /** - * @brief The name of the tool. - * - * @return The name of the tool for humans to see. - */ - std::string name() const override; - + * @brief Select data events with good Primary vertices + * following: + * https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/InDetTrackingPerformanceGuidelines#Vertexing + * + */ + class PrimaryVertexSelector: public EventSelectorBase { + public: + PrimaryVertexSelector(); + virtual ~PrimaryVertexSelector() {}; + + /** + * @brief MC simulation passes, data is checked against the GRL. + * + * @param event The event in question + * @return True for MC simulation, or if the data event is on the GRL. + */ + virtual bool apply(const top::Event& event) const override; + + /** + * @brief The name of the tool. + * + * @return The name of the tool for humans to see. + */ + std::string name() const override; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrintEventSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrintEventSelector.h index 6ece5e33bf21db4dd99f4f05ecf246d640c9ff66..f53b4874579314b843b2e92066a493101ba80442 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrintEventSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/PrintEventSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef PRINTEVENTSELECTOR_H_ #define PRINTEVENTSELECTOR_H_ @@ -8,27 +8,26 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** - * @brief Print some information about the event to the screen using cout. + * @brief Print some information about the event to the screen. * * Prints the run number, event number, mu, and lists of 4-vectors for good * electrons, muons and jets and the event missing ET. */ -class PrintEventSelector : public EventSelectorBase { + class PrintEventSelector: public EventSelectorBase { /** * @brief For each event print some information about it to the terminal. * * @return Also marks the event as passed. */ bool apply(const top::Event& event) const override; + bool applyParticleLevel(const top::ParticleLevelEvent& plEvent) const override; /** * @brief The word PRINT. */ std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RecoLevelSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RecoLevelSelector.h index 30767fd60de01a86f9a58ac27f373cae6c19da2b..ea6aef429700a4b89d92a21039162c48bdef86bf 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RecoLevelSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RecoLevelSelector.h @@ -1,19 +1,11 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: RecoLevelSelector.h // Description: // Author: Fabian Wilk // Created: Tue Oct 27 12:07:02 2015 -// -// (c) by Fabian Wilk -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. #ifndef _RECOLEVELSELECTOR_H_ #define _RECOLEVELSELECTOR_H_ @@ -21,35 +13,32 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - + /** + * @brief An event selector that accepts all reco level events and rejects all + * particle level events. + * + * This can be used to define event selections that shall be applied only to + * reco level events. + */ + class RecoLevelSelector: public EventSelectorBase { /** - * @brief An event selector that accepts all reco level events and rejects all - * particle level events. - * - * This can be used to define event selections that shall be applied only to - * reco level events. + * @brief Accept every event. + * @return Always true. */ - class RecoLevelSelector : public EventSelectorBase { - /** - * @brief Accept every event. - * @return Always true. - */ - virtual bool apply(const top::Event&) const override; - - /** - * @brief Reject every event. - * @return Always false. - */ - virtual bool applyParticleLevel(const top::ParticleLevelEvent&) const override; + virtual bool apply(const top::Event&) const override; - /** - * @brief The name printed in the cutflow. - * @return The word RECO_LEVEL - */ - virtual std::string name() const override; - }; + /** + * @brief Reject every event. + * @return Always false. + */ + virtual bool applyParticleLevel(const top::ParticleLevelEvent&) const override; + /** + * @brief The name printed in the cutflow. + * @return The word RECO_LEVEL + */ + virtual std::string name() const override; + }; } #endif /* _RECOLEVELSELECTOR_H_ */ - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RunNumberSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RunNumberSelector.h index 034c084136af7dc96b27d248535e5733f0973c2b..c536617dd76d8ddd30a2723c8aab9a77aba33f7d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RunNumberSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/RunNumberSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef RUNNUMBERSELECTOR_H_ #define RUNNUMBERSELECTOR_H_ @@ -9,21 +9,19 @@ namespace top { -class TopConfig; + class TopConfig; /** * @brief Apply a cut on the (random) run number. */ -class RunNumberSelector : public SignValueSelector { -public: - explicit RunNumberSelector(const std::string& params,std::shared_ptr<top::TopConfig> config); + class RunNumberSelector: public SignValueSelector { + public: + explicit RunNumberSelector(const std::string& params, std::shared_ptr<top::TopConfig> config); bool apply(const top::Event& event) const override; - -private: + private: std::shared_ptr<top::TopConfig> m_config; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonSelector.h index ccc6ca9017311f1985d8fabd41378a067bbbae3a..43c26866718cf4350c1766f38cd5c8a9f67de809 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SSSELECTOR_H_ #define SSSELECTOR_H_ @@ -8,20 +8,18 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief Keep only events that have at least one same sign lepton pair. * */ -class SSLeptonSelector : public EventSelectorBase{ -public: + class SSLeptonSelector: public EventSelectorBase { + public: bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonTightSelector.h index eba687dc27d12bddc649f53156fc1c0267c54f7a..4abbac6852466e006df382ba9e2283cc5c2e4a56 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonTightSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SSLeptonTightSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SSTIGHTSELECTOR_H_ #define SSTIGHTSELECTOR_H_ @@ -8,21 +8,19 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief Keep only events that have at least one same sign tight lepton pair. * This is identical to SSLeptonSelector in the case of tight selection, so only relevant for loose selection. * */ -class SSLeptonTightSelector : public EventSelectorBase{ -public: + class SSLeptonTightSelector: public EventSelectorBase { + public: bool apply(const top::Event& event) const override; bool applyParticleLevel(const top::ParticleLevelEvent& event) const override; std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SaveEventSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SaveEventSelector.h index 5100a9a24998125e9c20490b86b6fdee69f90954..7b98e5174510f0f62c82a6f4fc73ee1d0a55298b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SaveEventSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SaveEventSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SAVEEVENTSELECTOR_H_ #define SAVEEVENTSELECTOR_H_ @@ -8,7 +8,6 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief Save this event in the output file. * @@ -16,7 +15,7 @@ namespace top { * selection, but it will also write out the selected objects to the output * file in the CollectionTree. */ -class SaveEventSelector : public EventSelectorBase { + class SaveEventSelector: public EventSelectorBase { /** * @brief Accept every event * @@ -31,8 +30,7 @@ class SaveEventSelector : public EventSelectorBase { * @return The word SAVE. */ std::string name() const override; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SignValueSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SignValueSelector.h index f84a7fa55a6d9f332601cc840446217cb712f15b..7509b9e8c128ef5fbd6295b95ef86e5a6cc8794d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SignValueSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/SignValueSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SIGNVALUESELECTOR_H_ #define SIGNVALUESELECTOR_H_ @@ -8,26 +8,25 @@ #include "TopEventSelectionTools/EventSelectorBase.h" namespace top { - /** * @brief Many of the tools need a sign (>=) and a value (2). For example, if * we want at least two leptons. This is an intermediate 'base' class that * implements all the functionality these tools need in one place. */ -class SignValueSelector : public EventSelectorBase { -public: + class SignValueSelector: public EventSelectorBase { + public: /** * @brief Many of the tools will be supplied with an equality (or inequality) by * the user. They're decoded from the text input and saved in this 'sign' * format. */ enum Sign { - signNOIDEA, //the user clearly did something wrong, expect to exit / crash - signEQ, // == - signLT, // < - signGT, // > - signLTEQ, // <= - signGTEQ // >= + signNOIDEA, //the user clearly did something wrong, expect to exit / crash + signEQ, // == + signLT, // < + signGT, // > + signLTEQ, // <= + signGTEQ // >= }; /** @@ -46,14 +45,24 @@ public: * The default behaviour is false (the cut value is not a string). Note that * cutValueMode = true only makes sense if multiplicityMode = true */ - SignValueSelector(const std::string& name, std::string params, bool multiplicityMode = false, bool cutValueMode = false); + SignValueSelector(const std::string& name, std::string params, bool multiplicityMode = false, + bool cutValueMode = false); + /** + * @brief Overloaded constructor with additional options to do string splitting on delimiter and concatantion with a + *new string + * @param delim - delimiter to split with + * @param replace - string to replace the delimiter when concatanating + * @param default_prefix - if it was not possible to split, the code was probably expecting something to be + *prepended to the string so cover this + */ + SignValueSelector(const std::string& name, std::string params, bool multiplicityMode, bool cutValueMode, + std::string delim, std::string replace, std::string default_prefix); /** * @brief The name is generated in the constructor for this kind of tool. */ virtual std::string name() const override; - -protected: + protected: /** * @brief Integers are annoying in C++. * @@ -92,6 +101,12 @@ protected: */ std::string valueString() const; + + /** + * @brief valueString which is manipulated to replace delimiter with new string + */ + std::string valueStringDelimReplace() const; + /** * @brief Get the cut multiplicity assigned in the constructor. * @@ -148,8 +163,7 @@ protected: * @return A short string version of the name */ const std::string signstring() const; - -private: + private: ///Hold the name of the tool, filled by the constructor. std::string m_name; @@ -164,8 +178,10 @@ private: ///The multiplicity for cuts that take both a value and a multiplicity e.g. EL_N 25000 >= 2 double m_multiplicity; -}; + ///The value of the cut when it is a string, with replacement of delimiter with a replacement substring + std::string m_cutvalueStringDelimReplace; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ToolLoaderBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ToolLoaderBase.h index da968a368a03a7619e7647fd541e21961ae0ecf0..1be42ac25c44ee4750617ee72c364f7814c09f0a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ToolLoaderBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/ToolLoaderBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOOLLOADERBASE_H_ #define TOOLLOADERBASE_H_ @@ -13,7 +13,7 @@ class TFile; namespace EL { -class Worker; + class Worker; } namespace top { @@ -30,8 +30,8 @@ namespace top { * should act as a good reference. Basically you want an if (blah == "mytool") * then new MyTool(). */ -class ToolLoaderBase { -public: + class ToolLoaderBase { + public: ///Constructor doesn't do anything. ToolLoaderBase() {} @@ -56,11 +56,11 @@ public: * the name was not found (since this might not be the only tool loader in * the program). */ - virtual top::EventSelectorBase* initTool(const std::string& name, const std::string& line, TFile* outputFile, std::shared_ptr<top::TopConfig> config,EL::Worker* wk = nullptr) = 0; + virtual top::EventSelectorBase* initTool(const std::string& name, const std::string& line, TFile* outputFile, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk = nullptr) = 0; ClassDef(top::ToolLoaderBase, 0); -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TopEventSelectionToolsLoader.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TopEventSelectionToolsLoader.h index 16799d188300ad461d4803765957d9b1e5a8bfe5..4d2ac4b39bcb7e69e135b224f104565b21166e5c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TopEventSelectionToolsLoader.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TopEventSelectionToolsLoader.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef EVENTSELECTIONTOOLLOADER_H_ #define EVENTSELECTIONTOOLLOADER_H_ @@ -8,7 +8,6 @@ #include "TopEventSelectionTools/ToolLoaderBase.h" namespace top { - /** * @brief This is used to load tools in this package in a factory like way. It * has one important function. After that has been called, you can dispose of @@ -19,8 +18,8 @@ namespace top { * you'll be glad to hear that it's fine but we're not there yet. * 2) Don't put any xAOD headers in here. Same reason. */ -class TopEventSelectionToolsLoader : public ToolLoaderBase { -public: + class TopEventSelectionToolsLoader: public ToolLoaderBase { + public: /** * @brief Convert the string name into a tool-object. * @@ -44,11 +43,11 @@ public: * the name was not found (since this might not be the only tool loader in * the program). */ - top::EventSelectorBase* initTool(const std::string& name, const std::string& line, TFile* outputFile, std::shared_ptr<top::TopConfig> config,EL::Worker* wk = nullptr); + top::EventSelectorBase* initTool(const std::string& name, const std::string& line, TFile* outputFile, + std::shared_ptr<top::TopConfig> config, EL::Worker* wk = nullptr); ClassDef(top::TopEventSelectionToolsLoader, 0) -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrackJetCleaningSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrackJetCleaningSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..658771ea1baf264b5344e3cb581c948d236fc607 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrackJetCleaningSelector.h @@ -0,0 +1,30 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TRACKJETCLEANINGSELECTOR_H_ +#define TRACKJETCLEANINGSELECTOR_H_ + +#include "TopEventSelectionTools/EventSelectorBase.h" + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "JetInterface/IJetSelector.h" +#include "JetSelectorTools/IEventCleaningTool.h" + +namespace top { + class TopConfig; + + class TrackJetCleaningSelector: public EventSelectorBase { + public: + explicit TrackJetCleaningSelector(std::shared_ptr<top::TopConfig> config); + + bool apply(const top::Event& event) const override; + + std::string name() const override; + private: + std::shared_ptr<top::TopConfig> m_config; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TreeManager.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TreeManager.h index 62c76f601c30c5573e1c15196aaf6d75e3bb19e9..0a0c7595f5a9ed75f213255b74e2aa6939563715 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TreeManager.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TreeManager.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TREEMANAGER_H_ #define TREEMANAGER_H_ @@ -16,7 +16,6 @@ class TFile; namespace top { - /** * @brief A class that hopefully makes making a flat ntuple tree a bit easier * since you don't need to worry about what type to make the branches and stuff. @@ -24,8 +23,8 @@ namespace top { * Almost all this code is stolen from SFrame: * http://sourceforge.net/p/sframe */ -class TreeManager { -public: + class TreeManager { + public: /** * @brief Default constructor - note need to initialize the class if you use this. */ @@ -38,40 +37,40 @@ public: * @param file The file to write the tree to. * @param name The name of the tree (e.g. nominal, systematic1 etc). */ - TreeManager(const std::string& name, TFile* outputFile,const bool setAutoFlushZero = false); + TreeManager(const std::string& name, TFile* outputFile, const int, const int, const int); ///We do allow you to move it TreeManager(const TreeManager&& rhs); ///But not to copy it. - TreeManager(const TreeManager&)= delete; + TreeManager(const TreeManager&) = delete; ///Or assign it. - TreeManager& operator=(TreeManager const&) = delete; + TreeManager& operator = (TreeManager const&) = delete; /** * @brief Initialize the class with a new output file */ - void initialize(const std::string& name, TFile* outputFile,const bool setAutoFlushZero = false); + void initialize(const std::string& name, TFile* outputFile, const int, const int, const int); /** * @brief Calls TTree::Fill. Needed to fill the tree. */ void fill(); - + /** * @brief name of the TTree */ const std::string& name() const; /** @brief function object type used for branch filters */ - typedef std::function<int(TreeManager const *, std::string const &)> BranchFilter; + typedef std::function<int (TreeManager const*, std::string const&)> BranchFilter; /** @copydoc TreeManager::m_branchFilters */ - std::vector<BranchFilter> & branchFilters() { return m_branchFilters; } + std::vector<BranchFilter>& branchFilters() {return m_branchFilters;} /** @copydoc TreeManager::m_branchFilters */ - std::vector<BranchFilter> const & branchFilters() const { return m_branchFilters; } + std::vector<BranchFilter> const& branchFilters() const {return m_branchFilters;} /** * @brief The idea is to simplify the creation of branches so that you don't @@ -87,32 +86,30 @@ public: */ template<class T> void makeOutputVariable(T& obj, const std::string name) { - for (auto branchFilter : branchFilters()) { - int status = branchFilter(this, name); - if (status > 0) - break; - if (status == 0) - return; - } - const char* type_name = typeid(obj).name(); - if (strlen( type_name ) == 1) { - std::ostringstream leaflist; - leaflist << name << "/" << RootType( type_name ); - m_tree->Branch(name.c_str(), &obj, leaflist.str().c_str()); - } else { - m_outputVarPointers.push_back( &obj ); - T** pointer = reinterpret_cast< T** >( &m_outputVarPointers.back() ); - m_tree->Branch( name.c_str(), pointer ); - } + for (auto branchFilter : branchFilters()) { + int status = branchFilter(this, name); + if (status > 0) break; + if (status == 0) return; + } + const char* type_name = typeid(obj).name(); + if (strlen(type_name) == 1) { + std::ostringstream leaflist; + leaflist << name << "/" << RootType(type_name); + m_tree->Branch(name.c_str(), &obj, leaflist.str().c_str(), m_basketSizePrimitive); + } else { + m_outputVarPointers.push_back(&obj); + T** pointer = reinterpret_cast< T** >(&m_outputVarPointers.back()); + m_tree->Branch(name.c_str(), pointer, m_basketSizeVector); + } } -private: - /** + private: + /** * name of the tree */ std::string m_name; - - + + /** * @brief Stolen from SFrame code. * @@ -171,8 +168,10 @@ private: */ std::vector<BranchFilter> m_branchFilters; -}; - + // Two member variables to manage the size of the tree branch baskets + int m_basketSizePrimitive; + int m_basketSizeVector; + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionLooseSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionLooseSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..858fbf230f5d46c3ed3a8c18be9e3a616867a042 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionLooseSelector.h @@ -0,0 +1,63 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TRIGDECISIONLOOSESELECTOR_H_ +#define TRIGDECISIONLOOSESELECTOR_H_ + +#include "TopEventSelectionTools/EventSelectorBase.h" +#include <memory> + + +namespace top { + // Forward declare + class Event; + class TopConfig; + /** + * @brief Sometimes you may want to select events that pass a certain trigger, + * or triggers. + * + * This code only accepts the event if it passes at least one of the triggers + * that it was configured with. It does an 'OR' of all the trigger decisions. + * + * This will only be applied on the loose trees (i.e. those with "_Loose" in their names) + * + * For example: + * + * @code + * TRIGDEC HLT_e24_tight_L1EM20V HLT_e60_medium1 + * @endcode + * + * Would select the event if either of those passes. + */ + class TrigDecisionLooseSelector: public EventSelectorBase { + public: + /** + * @brief A tool to select events that pass a certain trigger (or any + * trigger in a list). + * + * @param name The name of the current event selection - e.g. ee + * @param config - this will give use a std::vector<std::string> of triggers to check + */ + TrigDecisionLooseSelector(const std::string& selectorName, std::shared_ptr<top::TopConfig> config); + + /** + * @brief Select events based on the 'OR' of a few user defined triggers. + * The thinking is you might want to pass e25i or e30 so "TRIGDEC e25i e30". + * + * @param event The event in question. Not used by the trigger decision + * tool. I guess it finds out the information some other, internal, way. + * + * @return True if at least one of the triggers in the string list passed. + */ + virtual bool apply(const top::Event& event) const override; + + ///TRIGDEC because we might have a tool for trigger matching too at some point + std::string name() const override; + private: + ///List of triggers to 'or' together for each event. If any one passes, the event passes + std::vector<std::string> m_triggers; + }; +} + +#endif /* TRIGDECISIONLOOSESELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionSelector.h index f28926146e7c1cbfccd443dd293893bce9f366cb..f89d01a7b28b3a1191d5b58d4c456a4a77aaeb6c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TRIGDECISIONSELECTOR_H_ #define TRIGDECISIONSELECTOR_H_ @@ -11,51 +11,50 @@ namespace top { // Forward declare - class Event; + class Event; class TopConfig; /** - * @brief Sometimes you may want to select events that pass a certain trigger, - * or triggers. - * - * This code only accepts the event if it passes at least one of the triggers - * that it was configured with. It does an 'OR' of all the trigger decisions. - * - * For example: - * - * @code - * TRIGDEC HLT_e24_tight_L1EM20V HLT_e60_medium1 - * @endcode - * - * Would select the event if either of those passes. - */ - class TrigDecisionSelector : public EventSelectorBase { - public: - /** - * @brief A tool to select events that pass a certain trigger (or any - * trigger in a list). - * - * @param name The name of the current event selection - e.g. ee - * @param config - this will give use a std::vector<std::string> of triggers to check - */ - TrigDecisionSelector(const std::string& selectorName,std::shared_ptr<top::TopConfig> config); - - /** - * @brief Select events based on the 'OR' of a few user defined triggers. - * The thinking is you might want to pass e25i or e30 so "TRIGDEC e25i e30". - * - * @param event The event in question. Not used by the trigger decision - * tool. I guess it finds out the information some other, internal, way. - * - * @return True if at least one of the triggers in the string list passed. - */ - virtual bool apply(const top::Event& event) const override; - - ///TRIGDEC because we might have a tool for trigger matching too at some point - std::string name() const override; - - private: - ///List of triggers to 'or' together for each event. If any one passes, the event passes - std::vector<std::string> m_triggers; + * @brief Sometimes you may want to select events that pass a certain trigger, + * or triggers. + * + * This code only accepts the event if it passes at least one of the triggers + * that it was configured with. It does an 'OR' of all the trigger decisions. + * + * For example: + * + * @code + * TRIGDEC HLT_e24_tight_L1EM20V HLT_e60_medium1 + * @endcode + * + * Would select the event if either of those passes. + */ + class TrigDecisionSelector: public EventSelectorBase { + public: + /** + * @brief A tool to select events that pass a certain trigger (or any + * trigger in a list). + * + * @param name The name of the current event selection - e.g. ee + * @param config - this will give use a std::vector<std::string> of triggers to check + */ + TrigDecisionSelector(const std::string& selectorName, std::shared_ptr<top::TopConfig> config); + + /** + * @brief Select events based on the 'OR' of a few user defined triggers. + * The thinking is you might want to pass e25i or e30 so "TRIGDEC e25i e30". + * + * @param event The event in question. Not used by the trigger decision + * tool. I guess it finds out the information some other, internal, way. + * + * @return True if at least one of the triggers in the string list passed. + */ + virtual bool apply(const top::Event& event) const override; + + ///TRIGDEC because we might have a tool for trigger matching too at some point + std::string name() const override; + private: + ///List of triggers to 'or' together for each event. If any one passes, the event passes + std::vector<std::string> m_triggers; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionTightSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionTightSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..ccafb865bae10e67db27dc01639807da15a01ea5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigDecisionTightSelector.h @@ -0,0 +1,63 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TRIGDECISIONTIGHTSELECTOR_H_ +#define TRIGDECISIONTIGHTSELECTOR_H_ + +#include "TopEventSelectionTools/EventSelectorBase.h" +#include <memory> + + +namespace top { + // Forward declare + class Event; + class TopConfig; + /** + * @brief Sometimes you may want to select events that pass a certain trigger, + * or triggers. + * + * This code only accepts the event if it passes at least one of the triggers + * that it was configured with. It does an 'OR' of all the trigger decisions. + * + * This will only be applied on the tight trees, not the loose ones (i.e. not those with "_Loose" in their names) + * + * For example: + * + * @code + * TRIGDEC_TIGHT HLT_e24_tight_L1EM20V HLT_e60_medium1 + * @endcode + * + * Would select the event if either of those passes. + */ + class TrigDecisionTightSelector: public EventSelectorBase { + public: + /** + * @brief A tool to select events that pass a certain trigger (or any + * trigger in a list). + * + * @param name The name of the current event selection - e.g. ee + * @param config - this will give use a std::vector<std::string> of triggers to check + */ + TrigDecisionTightSelector(const std::string& selectorName, std::shared_ptr<top::TopConfig> config); + + /** + * @brief Select events based on the 'OR' of a few user defined triggers. + * The thinking is you might want to pass e25i or e30 so "TRIGDEC e25i e30". + * + * @param event The event in question. Not used by the trigger decision + * tool. I guess it finds out the information some other, internal, way. + * + * @return True if at least one of the triggers in the string list passed. + */ + virtual bool apply(const top::Event& event) const override; + + ///TRIGDEC because we might have a tool for trigger matching too at some point + std::string name() const override; + private: + ///List of triggers to 'or' together for each event. If any one passes, the event passes + std::vector<std::string> m_triggers; + }; +} + +#endif /* TRIGDECISIONTIGHTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigMatchSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigMatchSelector.h index 7c59a84f7be310bb9653197be8642c6d7a72d4d9..a8289514396fbb94a69aeb2cbc4bc97d54a73c2c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigMatchSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools/TopEventSelectionTools/TrigMatchSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TRIGMATCHSELECTOR_H_ #define TRIGMATCHSELECTOR_H_ @@ -8,29 +8,30 @@ #include "TopEventSelectionTools/EventSelectorBase.h" #include <memory> -namespace top { +namespace top { // Forward declare - class Event; + class Event; class TopConfig; /** - * @brief Match offline object to trigger. - * - */ - class TrigMatchSelector : public EventSelectorBase { - public: - - TrigMatchSelector(const std::string& selectorName,std::shared_ptr<top::TopConfig> config); - - virtual bool apply(const top::Event& event) const override; - - std::string name() const override; - - private: - ///List of triggers to 'or' together for each event. If any one passes, the event passes - std::vector<std::string> m_electronTriggers; - std::vector<std::string> m_muonTriggers; - std::vector<std::string> m_tauTriggers; + * @brief Match offline object to trigger. + * + */ + class TrigMatchSelector: public EventSelectorBase { + public: + TrigMatchSelector(const std::string& selectorName, std::shared_ptr<top::TopConfig> config); + + virtual bool apply(const top::Event& event) const override; + + std::string name() const override; + private: + ///List of triggers to 'or' together for each event. If any one passes, the event passes + std::vector<std::string> m_electronTriggers_Tight; + std::vector<std::string> m_muonTriggers_Tight; + std::vector<std::string> m_tauTriggers_Tight; + std::vector<std::string> m_electronTriggers_Loose; + std::vector<std::string> m_muonTriggers_Loose; + std::vector<std::string> m_tauTriggers_Loose; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/CMakeLists.txt index fb7a8522b0a0785a64e5e63b677a7ee99719af3f..f4694ce281f46ea49f0b1877d4956b7a35ef5632 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/CMakeLists.txt @@ -1,7 +1,5 @@ -# Auto-generated on: 2017-03-08 14:47:36.923782 - # Declare the name of this package: -atlas_subdir( TopExamples None ) +atlas_subdir( TopExamples ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC @@ -20,10 +18,6 @@ atlas_depends_on_subdirs( PUBLIC # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO Math MathMore MathCore Graf Physics ) - -# Custom definitions needed for this package: -add_definitions( -g ) - # Build a library that other components can link against: atlas_add_library( TopExamples Root/*.cxx Root/*.h Root/*.icc TopExamples/*.h TopExamples/*.icc TopExamples/*/*.h @@ -95,5 +89,9 @@ atlas_add_executable( mini-to-plots PathResolver ${ROOT_LIBRARIES} TopExamples ) +atlas_add_executable( combineATOutputs + util/combineATOutputs.cxx + LINK_LIBRARIES ${ROOT_LIBRARIES} + TopExamples ) atlas_install_scripts( scripts/* ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/README.md b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..40ca8b1e65d5c75cd4d6d31efacdcf06113030c7 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/README.md @@ -0,0 +1,40 @@ +This package can be used to submit grid jobs with AnalysisTop and TOPQ datasets. +If you're looking for a tutorial on how to submit a grid job, you might like to try + * https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TopxAODStartGuideR21 + +The classes are flexible enough to allow the user to define new sample/derivation lists in a few lines. + +Usage (for submitting grid jobs) + +> `getExamples` +# This will copy the scripts using PathResolver to ${PWD}/grid + +> `lsetup rucio pyami panda` +# These tools need to be available for the TopExample scripts to function + +> `./01SubmitToGrid.py` +# This will run through the preconfigured list of samples and submit grid jobs +# You will want to edit this file to specify your own grid name, your own job suffixes and point to your cut file +# You may also want to define new samples (see MC16.py to see how they are added to the classes) + +> `./02DownloadFromGrid.py` +> `./03LocalAnalysis.py --run` +> `./04Plot.py` + +Usage (for making histograms) + +``` +- top::NoSelectionAnalysis: If the grid part didn't do any selection, use me! +- top::DileptonAnalysis: If the grid part did ee, mumu and emu, use me! +- top::LJetsAnalysis: For e+jets and mu+jets use me! +- top::LJetsTtresAnalysis: Includes largeR jets! +``` + +All the codes above use (mostly) the same histograms which are added and filled by using DefaultPlots.h. +The event loop is run by mini-to-plots.cxx, something like this: + +``` +./mini-to-plots Dilepton /path/to/file/grid_datasetname/input.txt +``` + +The word Dilepton tells it to load the top::DileptonAnalysis. You can see how this works in AnalysisTools.h addPlots(). The grid tag is extracted from the path, so that's important to keep in. diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/AnalysisTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/AnalysisTools.cxx index da3fe026d52cae881519d1130ea1bcdaf33348aa..6f33a13f8361acdc2b9f63670e71b7917ee739d7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/AnalysisTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/AnalysisTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/AnalysisTools.h" #include "TopExamples/NoSelectionAnalysis.h" @@ -27,38 +27,35 @@ #include <memory> namespace top { - -std::unique_ptr<top::AnalysisBase> loadAnalysis(const std::string& name, TFile* outputFile, EL::Worker* wk) { - if (name == "Dilepton") - return std::unique_ptr<top::AnalysisBase>(new top::DileptonAnalysis(outputFile, wk)); - else if (name == "LJets") - return std::unique_ptr<top::AnalysisBase>(new top::LJetsAnalysis(outputFile, wk)); - else if (name == "NoSelection") - return std::unique_ptr<top::AnalysisBase>(new top::NoSelectionAnalysis(outputFile, wk)); - else if (name == "LJetsTtres") - return std::unique_ptr<top::AnalysisBase>(new top::LJetsTtresAnalysis(outputFile)); + std::unique_ptr<top::AnalysisBase> loadAnalysis(const std::string& name, TFile* outputFile, EL::Worker* wk) { + if (name == "Dilepton") return std::unique_ptr<top::AnalysisBase>(new top::DileptonAnalysis(outputFile, wk)); + else if (name == "LJets") return std::unique_ptr<top::AnalysisBase>(new top::LJetsAnalysis(outputFile, wk)); + else if (name == + "NoSelection") return std::unique_ptr<top::AnalysisBase>(new top::NoSelectionAnalysis(outputFile, wk)); + else if (name == "LJetsTtres") return std::unique_ptr<top::AnalysisBase>(new top::LJetsTtresAnalysis(outputFile)); else { - std::cout << "I only know about:\n"; - std::cout << "NoSelection\n"; - std::cout << "LJets\n"; - std::cout << "Dilepton\n"; - std::cout << "LJetsTtres\n"; - exit(1); + std::cout << "I only know about:\n"; + std::cout << "NoSelection\n"; + std::cout << "LJets\n"; + std::cout << "Dilepton\n"; + std::cout << "LJetsTtres\n"; + exit(1); } //make sure this never happens with the if statement above return nullptr; -} + } -const std::string getSampleNumberAsString(const std::string& filename, const std::string& infoContainerName) { + const std::string getSampleNumberAsString(const std::string& filename, const std::string& infoContainerName) { xAOD::TEvent xaodEvent(xAOD::TEvent::kBranchAccess); std::unique_ptr<TFile> fileForSampleNumber(TFile::Open(filename.c_str())); top::check(xaodEvent.readFrom(fileForSampleNumber.get()), "xAOD::TEvent readFrom failed"); xaodEvent.getEntry(0); const xAOD::EventInfo* info(0); - if (!xaodEvent.retrieve(info, infoContainerName)) - throw std::string("xAOD::TEvent couldn't get hold of ") + infoContainerName; + if (!xaodEvent.retrieve(info, + infoContainerName)) throw std::string("xAOD::TEvent couldn't get hold of ") + + infoContainerName; //data is padded with zero until it's 8 char long in ATLAS std::stringstream ss; @@ -66,24 +63,25 @@ const std::string getSampleNumberAsString(const std::string& filename, const std //but MC simulation is not padded in dataset names :) if (info->eventType(xAOD::EventInfo::IS_SIMULATION)) { - ss.str(""); - ss << info->mcChannelNumber(); + ss.str(""); + ss << info->mcChannelNumber(); } return ss.str(); -} + } -double sfToOneInversefb(unsigned int mcChannelNumber, double mcWeightsInSample) { + double sfToOneInversefb(unsigned int mcChannelNumber, double mcWeightsInSample) { //load the x-section from a file SampleXsection tdp; + // const char* const rc = getenv("ROOTCOREBIN"); // std::string filename = std::string(rc) + "/data/TopDataPreparation/XSection-MC15-13TeV-fromSusyGrp.data"; std::string filename = PathResolverFindCalibFile("TopDataPreparation/XSection-MC15-13TeV-fromSusyGrp.data"); if (!tdp.readFromFile(filename.c_str())) { - std::cout << "TopDataPreparation - could not read file\n"; - std::cout << filename << "\n"; - std::cout << "Maybe check it exists, first?" << std::endl; - exit(1); + std::cout << "TopDataPreparation - could not read file\n"; + std::cout << filename << "\n"; + std::cout << "Maybe check it exists, first?" << std::endl; + exit(1); } //calculate @@ -106,37 +104,36 @@ double sfToOneInversefb(unsigned int mcChannelNumber, double mcWeightsInSample) std::cout << "Scale factor to 1 fb-1 : " << sf << "\n"; return sf; -} + } -void updateCutflow(const std::string& name, TH1D*& histogram, TFile* inputFile) { + void updateCutflow(const std::string& name, TH1D*& histogram, TFile* inputFile) { const auto* const temp = dynamic_cast<TH1D*> (inputFile->Get(name.c_str())); + if (histogram == nullptr) { - histogram = dynamic_cast<TH1D*> (temp->Clone()); - histogram->SetDirectory(0); - } else - histogram->Add(temp); -} + histogram = dynamic_cast<TH1D*> (temp->Clone()); + histogram->SetDirectory(0); + } else histogram->Add(temp); + } -std::string gridTagFromDirectoryName(const std::string inputFile) { + std::string gridTagFromDirectoryName(const std::string inputFile) { std::string gridTag = inputFile; try { - gridTag.erase(gridTag.rfind("/")); - gridTag = gridTag.substr(gridTag.rfind("/") + 1); + gridTag.erase(gridTag.rfind("/")); + gridTag = gridTag.substr(gridTag.rfind("/") + 1); - for (int i = 0; i < 3; ++i) - gridTag = gridTag.erase(0, gridTag.find(".") + 1); + for (int i = 0; i < 3; ++i) + gridTag = gridTag.erase(0, gridTag.find(".") + 1); - gridTag = gridTag.erase(gridTag.rfind(".")); + gridTag = gridTag.erase(gridTag.rfind(".")); } catch (...) { - gridTag = "unkown"; + gridTag = "unkown"; } return gridTag; -} + } -bool passesPreSelection(const top::Event& topEvent, const std::string& name) { + bool passesPreSelection(const top::Event& topEvent, const std::string& name) { return topEvent.m_info->auxdata<int>(name); -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/ContainerNames.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/ContainerNames.cxx index ca8b4a924da73ccdfbdc57d9b5afd40d08336796..2c8e04577a9e1afef35b713d193eb960738d590d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/ContainerNames.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/ContainerNames.cxx @@ -1,20 +1,20 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/ContainerNames.h" #include <ostream> -std::ostream& operator<<(std::ostream& os, const top::ContainerNames& names) { - os << "EventInfo " << names.eventInfoName << "\n"; - os << "ElectronCollection: " << names.electronCollectionName << "\n"; - os << "MuonCollection: " << names.muonCollectionName << "\n"; - os << "JetCollection: " << names.jetCollectionName << "\n"; - os << "LargeJetCollection: " << names.largeJetCollectionName << "\n"; - os << "MET: " << names.metName << "\n"; - os << "TauCollection: " << names.tauCollectionName << "\n"; - os << "TruthCollection: " << names.truthCollectionName << "\n"; +std::ostream & operator << (std::ostream& os, const top::ContainerNames& names) { + os << "EventInfo " << names.eventInfoName << "\n"; + os << "ElectronCollection: " << names.electronCollectionName << "\n"; + os << "MuonCollection: " << names.muonCollectionName << "\n"; + os << "JetCollection: " << names.jetCollectionName << "\n"; + os << "LargeJetCollection: " << names.largeJetCollectionName << "\n"; + os << "MET: " << names.metName << "\n"; + os << "TauCollection: " << names.tauCollectionName << "\n"; + os << "TruthCollection: " << names.truthCollectionName << "\n"; - return os; + return os; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DefaultPlots.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DefaultPlots.cxx index 6fb972a4bb32fa3051c7559467c7b4a9bb3a973d..6d70bd0385cf2a55625e59b831f1cd2337b80390 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DefaultPlots.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DefaultPlots.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/DefaultPlots.h" @@ -16,8 +16,7 @@ #include "TH1.h" namespace top { - -void addPlots(top::PlotManager& manager) { + void addPlots(top::PlotManager& manager) { manager.addHist("control_sig_njet", ";Number of selected jets;Events", 12, -0.5, 11.5); manager.addHist("control_sig_met", ";E_{T}^{miss} [GeV];Events / 10 GeV", 22, 0, 220); manager.addHist("control_met", ";E_{T}^{miss} [GeV];Events / 5 GeV", 45, 0, 225); @@ -25,9 +24,9 @@ void addPlots(top::PlotManager& manager) { manager.addHist("control_invmass", ";Invariant mass [GeV];Events / 5 GeV", 34, 15, 185); manager.addHist("control_sig_invmass", ";Invariant mass [GeV];Events / 10 GeV", 40, 11, 411); manager.addHist("control_sig_invmass_cut", ";Invariant mass [GeV];Events / 10 GeV", 40, 11, 411); - manager.addHist("dy_dphi",";#Delta#phi;Events", 10, 0., M_PI); - manager.addHist("dy_dphi_zpt",";Z p_{T} [GeV];Events", 30., 0., 300.); - manager.addHist("dy_counter",";DD norm;Events", 5., 0., 5.); + manager.addHist("dy_dphi", ";#Delta#phi;Events", 10, 0., M_PI); + manager.addHist("dy_dphi_zpt", ";Z p_{T} [GeV];Events", 30., 0., 300.); + manager.addHist("dy_counter", ";DD norm;Events", 5., 0., 5.); manager.addHist("mu", ";<#mu>;Events", 50, 0., 50.); manager.addHist("mc_weight", ";MC Event Weight", 100, -1.5, 5e6); @@ -55,47 +54,47 @@ void addPlots(top::PlotManager& manager) { manager.addHist("jet_eta", ";Jet #eta;Jets", 25, -2.5, 2.5); manager.addHist("jet_phi", ";Jet #phi;Jets", 25, -M_PI, M_PI); manager.addHist("jet_e", ";Jet E / GeV;Jets", 50, 0, 250); - manager.addHist("jet_mv2c20", ";Jet mv2c20;Jets", 50, 0, 1); + manager.addHist("jet_mv2c10", ";Jet mv2c10;Jets", 50, 0, 1); manager.addHist("jet0_pt", ";Jet0 p_{T} / GeV; Events / 10 GeV", 25, 5, 255); manager.addHist("jet0_eta", ";Jet0 #eta; Jets", 25, -2.5, 2.5); manager.addHist("jet0_phi", ";Jet0 #phi; Jets", 25, -M_PI, M_PI); manager.addHist("jet0_e", ";Jet0 E / GeV; Jets", 50, 0, 250); - manager.addHist("jet0_mv2c20", ";Jet0 mv2c20; Jets", 50, 0, 1); + manager.addHist("jet0_mv2c10", ";Jet0 mv2c10; Jets", 50, 0, 1); manager.addHist("jet1_pt", ";Jet1 p_{T} / GeV; Events / 10 GeV", 25, 5, 255); manager.addHist("jet1_eta", ";Jet1 #eta; Jets", 25, -2.5, 2.5); manager.addHist("jet1_phi", ";Jet1 #phi; Jets", 25, -M_PI, M_PI); manager.addHist("jet1_e", ";Jet1 E / GeV; Jets", 50, 0, 250); - manager.addHist("jet1_mv2c20", ";Jet1 mv2c20; Jets", 50, 0, 1); + manager.addHist("jet1_mv2c10", ";Jet1 mv2c10; Jets", 50, 0, 1); manager.addHist("jet2_pt", ";Jet2 p_{T} / GeV; Events / 10 GeV", 25, 5, 255); manager.addHist("jet2_eta", ";Jet2 #eta; Jets", 25, -2.5, 2.5); manager.addHist("jet2_phi", ";Jet2 #phi; Jets", 25, -M_PI, M_PI); manager.addHist("jet2_e", ";Jet2 E / GeV; Jets", 50, 0, 250); - manager.addHist("jet2_mv2c20", ";Jet2 mv2c20; Jets", 50, 0, 1); + manager.addHist("jet2_mv2c10", ";Jet2 mv2c10; Jets", 50, 0, 1); manager.addHist("jet3_pt", ";Jet3 p_{T} / GeV; Events / 10 GeV", 25, 5, 255); manager.addHist("jet3_eta", ";Jet3 #eta; Jets", 25, -2.5, 2.5); manager.addHist("jet3_phi", ";Jet3 #phi; Jets", 25, -M_PI, M_PI); manager.addHist("jet3_e", ";Jet3 E / GeV; Jets", 50, 0, 250); - manager.addHist("jet3_mv2c20", ";Jet3 mv2c20; Jets", 50, 0, 1); + manager.addHist("jet3_mv2c10", ";Jet3 mv2c10; Jets", 50, 0, 1); manager.addHist("met_et", ";MET / GeV;Events / 5 GeV", 40, 0, 200); manager.addHist("met_phi", ";MET #phi;Events", 40, -M_PI, M_PI); -} + } -void fillPlots(const top::Event& topEvent, top::PlotManager& manager, double eventWeight) { + void fillPlots(const top::Event& topEvent, top::PlotManager& manager, double eventWeight) { const double toGeV = 0.001; manager.hist("mu")->Fill(topEvent.m_info->averageInteractionsPerCrossing(), eventWeight); if (top::isSimulation(topEvent)) { -// manager.hist("mc_weight")->Fill(topEvent.m_info->mcEventWeight(), eventWeight); - manager.hist("mc_weight")->Fill(topEvent.m_truthEvent->at(0)->weights()[0], eventWeight);// FIXME temporary bugfix + manager.hist("mc_weight")->Fill(topEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight")); - if (top::ScaleFactorRetriever::hasPileupSF(topEvent)) - manager.hist("pileup_weight")->Fill(top::ScaleFactorRetriever::pileupSF(topEvent), eventWeight); + if (top::ScaleFactorRetriever::hasPileupSF(topEvent)) manager.hist("pileup_weight")->Fill(top::ScaleFactorRetriever::pileupSF( + topEvent), + eventWeight); } manager.hist("el_n")->Fill(topEvent.m_electrons.size(), eventWeight); @@ -104,53 +103,52 @@ void fillPlots(const top::Event& topEvent, top::PlotManager& manager, double eve //loop over all the electrons - new for loop style is cool for (const auto* const elPtr : topEvent.m_electrons) { - manager.hist("el_pt")->Fill(elPtr->pt() * toGeV, eventWeight); - manager.hist("el_eta")->Fill(elPtr->eta(), eventWeight); - manager.hist("el_phi")->Fill(elPtr->phi(), eventWeight); - manager.hist("el_e")->Fill(elPtr->e() * toGeV, eventWeight); - manager.hist("el_m")->Fill(elPtr->m() * toGeV, eventWeight); - manager.hist("el_charge")->Fill(elPtr->charge(), eventWeight); + manager.hist("el_pt")->Fill(elPtr->pt() * toGeV, eventWeight); + manager.hist("el_eta")->Fill(elPtr->eta(), eventWeight); + manager.hist("el_phi")->Fill(elPtr->phi(), eventWeight); + manager.hist("el_e")->Fill(elPtr->e() * toGeV, eventWeight); + manager.hist("el_m")->Fill(elPtr->m() * toGeV, eventWeight); + manager.hist("el_charge")->Fill(elPtr->charge(), eventWeight); } for (const auto* const muPtr : topEvent.m_muons) { - manager.hist("mu_pt")->Fill(muPtr->pt() * toGeV, eventWeight); - manager.hist("mu_eta")->Fill(muPtr->eta(), eventWeight); - manager.hist("mu_phi")->Fill(muPtr->phi(), eventWeight); - manager.hist("mu_e")->Fill(muPtr->e() * toGeV, eventWeight); - manager.hist("mu_m")->Fill(muPtr->m() * toGeV, eventWeight); - manager.hist("mu_charge")->Fill(muPtr->charge(), eventWeight); + manager.hist("mu_pt")->Fill(muPtr->pt() * toGeV, eventWeight); + manager.hist("mu_eta")->Fill(muPtr->eta(), eventWeight); + manager.hist("mu_phi")->Fill(muPtr->phi(), eventWeight); + manager.hist("mu_e")->Fill(muPtr->e() * toGeV, eventWeight); + manager.hist("mu_m")->Fill(muPtr->m() * toGeV, eventWeight); + manager.hist("mu_charge")->Fill(muPtr->charge(), eventWeight); } //plot for all jets, and also the four leading jets separately unsigned int i = 0; - std::array<std::string, 4> numbers{ {"jet0", "jet1", "jet2", "jet3"} }; + std::array<std::string, 4> numbers {{ + "jet0", "jet1", "jet2", "jet3" + }}; for (const auto* const jetPtr : topEvent.m_jets) { - manager.hist("jet_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); - manager.hist("jet_eta")->Fill(jetPtr->eta(), eventWeight); - manager.hist("jet_phi")->Fill(jetPtr->phi(), eventWeight); - manager.hist("jet_e")->Fill(jetPtr->e() * toGeV, eventWeight); + manager.hist("jet_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); + manager.hist("jet_eta")->Fill(jetPtr->eta(), eventWeight); + manager.hist("jet_phi")->Fill(jetPtr->phi(), eventWeight); + manager.hist("jet_e")->Fill(jetPtr->e() * toGeV, eventWeight); - double mv2c20_discriminant = 0.; - jetPtr->btagging()->MVx_discriminant("MV2c20", mv2c20_discriminant); + double mv2c10_discriminant = 0.; + //jetPtr->btagging()->MVx_discriminant("MV2c10", mv2c10_discriminant); - manager.hist("jet_mv2c20")->Fill(mv2c20_discriminant, eventWeight); + manager.hist("jet_mv2c10")->Fill(mv2c10_discriminant, eventWeight); - if (i < numbers.size()) { - manager.hist(numbers[i] + "_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); - manager.hist(numbers[i] + "_eta")->Fill(jetPtr->eta(), eventWeight); - manager.hist(numbers[i] + "_phi")->Fill(jetPtr->phi(), eventWeight); - manager.hist(numbers[i] + "_e")->Fill(jetPtr->e() * toGeV, eventWeight); - manager.hist(numbers[i] + "_mv2c20")->Fill(mv2c20_discriminant, eventWeight); - } + if (i < numbers.size()) { + manager.hist(numbers[i] + "_pt")->Fill(jetPtr->pt() * toGeV, eventWeight); + manager.hist(numbers[i] + "_eta")->Fill(jetPtr->eta(), eventWeight); + manager.hist(numbers[i] + "_phi")->Fill(jetPtr->phi(), eventWeight); + manager.hist(numbers[i] + "_e")->Fill(jetPtr->e() * toGeV, eventWeight); + manager.hist(numbers[i] + "_mv2c10")->Fill(mv2c10_discriminant, eventWeight); + } - ++i; + ++i; } manager.hist("met_et")->Fill(topEvent.m_met->met() * toGeV, eventWeight); manager.hist("met_phi")->Fill(topEvent.m_met->phi(), eventWeight); - - -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DileptonAnalysis.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DileptonAnalysis.cxx index 2d242c8ce9fa363b8730412547f692dacbca1033..fea19b10ea6ff292ac8b7993dfd3fd73e6611522 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DileptonAnalysis.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/DileptonAnalysis.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/DileptonAnalysis.h" #include "TopExamples/DefaultPlots.h" @@ -17,7 +17,6 @@ #include <fstream> namespace top { - /** * @brief Setup the analysis, add some histograms. * @@ -26,32 +25,32 @@ namespace top { * and with / without weights to nullptr. They are loaded from the input files. * Also three counters are set to 0 for the number of processed events. */ -DileptonAnalysis::DileptonAnalysis(TFile* outputFile, EL::Worker* wk) : - m_mcChannelNumber(0), - m_runNumber(0), - m_histsElEl("ee", outputFile, wk), - m_histsMuMu("mumu", outputFile, wk), - m_histsElMu("emu", outputFile, wk), - m_cutflowEventsElEl(nullptr), - m_cutflowMCWeightsElEl(nullptr), - m_cutflowEventsMuMu(nullptr), - m_cutflowMCWeightsMuMu(nullptr), - m_cutflowEventsElMu(nullptr), - m_cutflowMCWeightsElMu(nullptr), - m_counterElEl(0), - m_counterMuMu(0), - m_counterElMu(0) { - //add some default histograms for each channel - top::addPlots(m_histsElEl); - top::addPlots(m_histsMuMu); - top::addPlots(m_histsElMu); - - //a special histogram for emu - m_histsElMu.addHist("ht", ";HT / GeV;Events / 20 GeV", 40, 0, 800); -} - -DileptonAnalysis::~DileptonAnalysis() { -} + DileptonAnalysis::DileptonAnalysis(TFile* outputFile, EL::Worker* wk) : + m_mcChannelNumber(0), + m_runNumber(0), + m_histsElEl("ee", outputFile, wk), + m_histsMuMu("mumu", outputFile, wk), + m_histsElMu("emu", outputFile, wk), + m_cutflowEventsElEl(nullptr), + m_cutflowMCWeightsElEl(nullptr), + m_cutflowEventsMuMu(nullptr), + m_cutflowMCWeightsMuMu(nullptr), + m_cutflowEventsElMu(nullptr), + m_cutflowMCWeightsElMu(nullptr), + m_counterElEl(0), + m_counterMuMu(0), + m_counterElMu(0) { + //add some default histograms for each channel + top::addPlots(m_histsElEl); + top::addPlots(m_histsMuMu); + top::addPlots(m_histsElMu); + + //a special histogram for emu + m_histsElMu.addHist("ht", ";HT / GeV;Events / 20 GeV", 40, 0, 800); + } + + DileptonAnalysis::~DileptonAnalysis() { + } /** * @brief When a new input file is opened we want to grab the cutflow histograms @@ -59,14 +58,14 @@ DileptonAnalysis::~DileptonAnalysis() { * * @param inputFile The file that was just opened. */ -void DileptonAnalysis::newFile(TFile* inputFile) { + void DileptonAnalysis::newFile(TFile* inputFile) { updateCutflow("ee/cutflow", m_cutflowEventsElEl, inputFile); updateCutflow("ee/cutflow_mc", m_cutflowMCWeightsElEl, inputFile); updateCutflow("mumu/cutflow", m_cutflowEventsMuMu, inputFile); updateCutflow("mumu/cutflow_mc", m_cutflowMCWeightsMuMu, inputFile); updateCutflow("emu/cutflow", m_cutflowEventsElMu, inputFile); updateCutflow("emu/cutflow_mc", m_cutflowMCWeightsElMu, inputFile); -} + } /** * @brief Work out if it's ee, mumu or emu and send the event to the correct @@ -80,27 +79,23 @@ void DileptonAnalysis::newFile(TFile* inputFile) { * * @param topEvent The event in question */ -void DileptonAnalysis::event(const top::Event& topEvent) { + void DileptonAnalysis::event(const top::Event& topEvent) { m_runNumber = topEvent.m_info->runNumber(); double eventWeight = 1.; if (top::isSimulation(topEvent)) { - m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); -// eventWeight = topEvent.m_info->mcEventWeight(); - eventWeight = topEvent.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); + eventWeight = topEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); } //std::cout << topEvent << std::endl; - if (top::passesPreSelection(topEvent, "ee")) - eeAnalysis(topEvent, eventWeight); + if (top::passesPreSelection(topEvent, "ee")) eeAnalysis(topEvent, eventWeight); - if (top::passesPreSelection(topEvent, "mumu")) - mumuAnalysis(topEvent, eventWeight); + if (top::passesPreSelection(topEvent, "mumu")) mumuAnalysis(topEvent, eventWeight); - if (top::passesPreSelection(topEvent, "emu")) - emuAnalysis(topEvent, eventWeight); -} + if (top::passesPreSelection(topEvent, "emu")) emuAnalysis(topEvent, eventWeight); + } /** * @brief Plot some control regions, then the final plots for the analysis. @@ -116,7 +111,7 @@ void DileptonAnalysis::event(const top::Event& topEvent) { * exactly two electrons for the rest of this function. * @param eventWeight The event weight to be used when filling plots. */ -void DileptonAnalysis::eeAnalysis(const top::Event& topEvent, double eventWeight) { + void DileptonAnalysis::eeAnalysis(const top::Event& topEvent, double eventWeight) { ++m_counterElEl; const auto* e0 = topEvent.m_electrons[0]; @@ -130,45 +125,38 @@ void DileptonAnalysis::eeAnalysis(const top::Event& topEvent, double eventWeight const bool inZWindow = fabs(Z.M() - 91000.) < 10000.; //plot the met for all events in the Z-window - if (inZWindow && gteq2jets) - m_histsElEl.hist("control_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); + if (inZWindow && gteq2jets) m_histsElEl.hist("control_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); //plot the invariant mass for low MET events - if (!metgt60 && gteq2jets) - m_histsElEl.hist("control_invmass")->Fill(Z.M() / 1000., eventWeight); + if (!metgt60 && gteq2jets) m_histsElEl.hist("control_invmass")->Fill(Z.M() / 1000., eventWeight); //plot njet in zwindow for low MET events - if (inZWindow && !metgt60) - m_histsElEl.hist("control_njet")->Fill(topEvent.m_jets.size(), eventWeight); + if (inZWindow && !metgt60) m_histsElEl.hist("control_njet")->Fill(topEvent.m_jets.size(), eventWeight); //DY control region: inside Z window, but lower pt cut to signal region if (inZWindow && metgt30 && gteq2jets) { - m_histsElEl.hist("dy_dphi")->Fill(fabs(top::deltaPhi(*e0, *e1)), eventWeight); - m_histsElEl.hist("dy_dphi_zpt")->Fill(Z.Pt() * toGeV, eventWeight); - m_histsElEl.hist("dy_counter")->Fill(1., eventWeight); + m_histsElEl.hist("dy_dphi")->Fill(fabs(top::deltaPhi(*e0, *e1)), eventWeight); + m_histsElEl.hist("dy_dphi_zpt")->Fill(Z.Pt() * toGeV, eventWeight); + m_histsElEl.hist("dy_counter")->Fill(1., eventWeight); } //signal region - all cuts except Z mass - if (gteq2jets && metgt60) - m_histsElEl.hist("control_sig_invmass")->Fill(Z.M() * toGeV, eventWeight); + if (gteq2jets && metgt60) m_histsElEl.hist("control_sig_invmass")->Fill(Z.M() * toGeV, eventWeight); - if (!inZWindow && gteq2jets && metgt60) - m_histsElEl.hist("control_sig_invmass_cut")->Fill(Z.M() * toGeV, eventWeight); + if (!inZWindow && gteq2jets && + metgt60) m_histsElEl.hist("control_sig_invmass_cut")->Fill(Z.M() * toGeV, eventWeight); //signal region - all cuts except njet - if (!inZWindow && metgt60) - m_histsElEl.hist("control_sig_njet")->Fill(topEvent.m_jets.size(), eventWeight); + if (!inZWindow && metgt60) m_histsElEl.hist("control_sig_njet")->Fill(topEvent.m_jets.size(), eventWeight); //signal region - all cuts except met - if (!inZWindow && gteq2jets) - m_histsElEl.hist("control_sig_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); + if (!inZWindow && gteq2jets) m_histsElEl.hist("control_sig_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); //pretag selection - if (gteq2jets && !inZWindow && metgt60) - top::fillPlots(topEvent, m_histsElEl, eventWeight); -} + if (gteq2jets && !inZWindow && metgt60) top::fillPlots(topEvent, m_histsElEl, eventWeight); + } -void DileptonAnalysis::mumuAnalysis(const top::Event& topEvent, double eventWeight) { + void DileptonAnalysis::mumuAnalysis(const top::Event& topEvent, double eventWeight) { ++m_counterMuMu; const auto* mu0 = topEvent.m_muons[0]; @@ -182,43 +170,36 @@ void DileptonAnalysis::mumuAnalysis(const top::Event& topEvent, double eventWeig const bool inZWindow = fabs(Z.M() - 91000.) < 10000.; //plot the met for all events in the Z-window - if (inZWindow && gteq2jets) - m_histsMuMu.hist("control_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); + if (inZWindow && gteq2jets) m_histsMuMu.hist("control_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); //plot the invariant mass for low MET events - if (!metgt60 && gteq2jets) - m_histsMuMu.hist("control_invmass")->Fill(Z.M() / 1000., eventWeight); + if (!metgt60 && gteq2jets) m_histsMuMu.hist("control_invmass")->Fill(Z.M() / 1000., eventWeight); //plot njet in zwindow for low MET events - if (inZWindow && !metgt60) - m_histsMuMu.hist("control_njet")->Fill(topEvent.m_jets.size(), eventWeight); + if (inZWindow && !metgt60) m_histsMuMu.hist("control_njet")->Fill(topEvent.m_jets.size(), eventWeight); //DY control region: inside Z window, but lower pt cut to signal region if (inZWindow && metgt30 && gteq2jets) { - m_histsMuMu.hist("dy_dphi")->Fill(fabs(top::deltaPhi(*mu0, *mu1)), eventWeight); - m_histsMuMu.hist("dy_dphi_zpt")->Fill(Z.Pt() * toGeV, eventWeight); - m_histsMuMu.hist("dy_counter")->Fill(1., eventWeight); + m_histsMuMu.hist("dy_dphi")->Fill(fabs(top::deltaPhi(*mu0, *mu1)), eventWeight); + m_histsMuMu.hist("dy_dphi_zpt")->Fill(Z.Pt() * toGeV, eventWeight); + m_histsMuMu.hist("dy_counter")->Fill(1., eventWeight); } //signal region - all cuts except Z mass - if (gteq2jets && metgt60) - m_histsMuMu.hist("control_sig_invmass")->Fill(Z.M() * toGeV, eventWeight); + if (gteq2jets && metgt60) m_histsMuMu.hist("control_sig_invmass")->Fill(Z.M() * toGeV, eventWeight); - if (!inZWindow && gteq2jets && metgt60) - m_histsMuMu.hist("control_sig_invmass_cut")->Fill(Z.M() * toGeV,eventWeight); + if (!inZWindow && gteq2jets && + metgt60) m_histsMuMu.hist("control_sig_invmass_cut")->Fill(Z.M() * toGeV, eventWeight); //signal region - all cuts except njet - if (!inZWindow && metgt60) - m_histsMuMu.hist("control_sig_njet")->Fill(topEvent.m_jets.size(), eventWeight); + if (!inZWindow && metgt60) m_histsMuMu.hist("control_sig_njet")->Fill(topEvent.m_jets.size(), eventWeight); //signal region - all cuts except met - if (!inZWindow && gteq2jets) - m_histsMuMu.hist("control_sig_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); + if (!inZWindow && gteq2jets) m_histsMuMu.hist("control_sig_met")->Fill(topEvent.m_met->met() * toGeV, eventWeight); //pretag selection - if (gteq2jets && !inZWindow && metgt60) - top::fillPlots(topEvent, m_histsMuMu, eventWeight); -} + if (gteq2jets && !inZWindow && metgt60) top::fillPlots(topEvent, m_histsMuMu, eventWeight); + } /** * @brief emu channel @@ -230,7 +211,7 @@ void DileptonAnalysis::mumuAnalysis(const top::Event& topEvent, double eventWeig * @param topEvent The event in question * @param eventWeight The weights that are used when filling the histograms. */ -void DileptonAnalysis::emuAnalysis(const top::Event& topEvent, double eventWeight) { + void DileptonAnalysis::emuAnalysis(const top::Event& topEvent, double eventWeight) { ++m_counterElMu; //does it pass some cuts? @@ -238,10 +219,10 @@ void DileptonAnalysis::emuAnalysis(const top::Event& topEvent, double eventWeigh const double ht = top::ht(topEvent); if (gteq2jets && ht > 120. * toGeV) { - m_histsElMu.hist("ht")->Fill(ht * toGeV, eventWeight); - top::fillPlots(topEvent, m_histsElMu, eventWeight); + m_histsElMu.hist("ht")->Fill(ht * toGeV, eventWeight); + top::fillPlots(topEvent, m_histsElMu, eventWeight); } -} + } /** * @brief Print cutflows for each of the three channels. Save any histograms @@ -250,7 +231,7 @@ void DileptonAnalysis::emuAnalysis(const top::Event& topEvent, double eventWeigh * * @param outputFile Root file to save the histograms to. */ -void DileptonAnalysis::finalise(TFile* outputFile) { + void DileptonAnalysis::finalise(TFile* outputFile) { //to screen std::cout << "Cutflows directly from the input files:\n"; printCutflow(std::cout, m_cutflowEventsElEl, m_cutflowMCWeightsElEl, "ee", m_counterElEl); @@ -259,10 +240,8 @@ void DileptonAnalysis::finalise(TFile* outputFile) { //tofile - mc use channel number, data use run number std::stringstream ss; - if (m_mcChannelNumber > 0) - ss << m_mcChannelNumber; - else - ss << m_runNumber; + if (m_mcChannelNumber > 0) ss << m_mcChannelNumber; + else ss << m_runNumber; std::ofstream cutflowfile_ee(ss.str() + "_ee_cutflow.txt"); std::ofstream cutflowfile_mumu(ss.str() + "_mumu_cutflow.txt"); @@ -279,8 +258,8 @@ void DileptonAnalysis::finalise(TFile* outputFile) { //if MC then calculate a SF to 1 fb-1 double sf = 1.; if (m_mcChannelNumber != 0) { - const double mcWeightsInSample = m_cutflowMCWeightsElEl->GetBinContent(1); - sf = sfToOneInversefb(m_mcChannelNumber, mcWeightsInSample); + const double mcWeightsInSample = m_cutflowMCWeightsElEl->GetBinContent(1); + sf = sfToOneInversefb(m_mcChannelNumber, mcWeightsInSample); } //save the plots for the three channels @@ -288,8 +267,7 @@ void DileptonAnalysis::finalise(TFile* outputFile) { m_histsMuMu.scaleHistograms(sf); m_histsElMu.scaleHistograms(sf); outputFile->Write(); - -} + } /** * @brief Prints the cutflow table to the screen or a file. This is not scaled @@ -308,28 +286,27 @@ void DileptonAnalysis::finalise(TFile* outputFile) { * @param localYield Yield that the local code ran over. It should match the * number from the grid (since you ran on the same events). */ -void DileptonAnalysis::printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, const std::string& name, const unsigned int localYield) { + void DileptonAnalysis::printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, + const std::string& name, const unsigned int localYield) { out << name << " cutflow:\n"; out << " " << - std::setw(4) << "Num" << - std::setw(30) << "Name" << - std::setw(20) << "Grid (Events)" << - std::setw(20) << "Grid (MC Weights)" << - std::setw(20) << "Local (Events)" << "\n"; + std::setw(4) << "Num" << + std::setw(30) << "Name" << + std::setw(20) << "Grid (Events)" << + std::setw(20) << "Grid (MC Weights)" << + std::setw(20) << "Local (Events)" << "\n"; for (int i = 1; i <= eventHist->GetNbinsX(); ++i) { - out << " " << std::setw(4) << i - << std::setw(30) << eventHist->GetXaxis()->GetBinLabel(i) - << std::setw(20) << eventHist->GetBinContent(i) - << std::setw(20) << mcWeightHist->GetBinContent(i); + out << " " << std::setw(4) << i + << std::setw(30) << eventHist->GetXaxis()->GetBinLabel(i) + << std::setw(20) << eventHist->GetBinContent(i) + << std::setw(20) << mcWeightHist->GetBinContent(i); - if (i == eventHist->GetNbinsX()) - out << std::setw(20) << localYield; + if (i == eventHist->GetNbinsX()) out << std::setw(20) << localYield; - out << "\n"; + out << "\n"; } out << "\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/EventLoaderDirect.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/EventLoaderDirect.cxx index bbcf69ec9151df6afedb48e6c6e0b59fcbefa088..96b7c4fc4089743ccd26f09245d86e1584429b57 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/EventLoaderDirect.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/EventLoaderDirect.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/EventLoaderDirect.h" @@ -16,68 +16,79 @@ #include "xAODTruth/TruthParticleContainer.h" namespace top { + EventLoaderDirect::EventLoaderDirect(const ContainerNames& names) : + m_containerNames(names) { + } -EventLoaderDirect::EventLoaderDirect(const ContainerNames& names) : - m_containerNames(names) { -} - -EventLoaderDirect::~EventLoaderDirect() { -} + EventLoaderDirect::~EventLoaderDirect() { + } -top::Event EventLoaderDirect::loadEvent(xAOD::TEvent& xaodEvent) { + top::Event EventLoaderDirect::loadEvent(xAOD::TEvent& xaodEvent) { top::Event te; //EventInfo - top::check(xaodEvent.retrieve(te.m_info, m_containerNames.eventInfoName), "xAOD::TEvent retrieve failed to get " + m_containerNames.eventInfoName); + top::check(xaodEvent.retrieve(te.m_info, + m_containerNames.eventInfoName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.eventInfoName); //Electrons if (m_containerNames.electronCollectionName != "None") { - const xAOD::ElectronContainer* electrons(0); - top::check(xaodEvent.retrieve(electrons, m_containerNames.electronCollectionName), "xAOD::TEvent retrieve failed to get " + m_containerNames.electronCollectionName); - te.m_electrons = *electrons; + const xAOD::ElectronContainer* electrons(0); + top::check(xaodEvent.retrieve(electrons, + m_containerNames.electronCollectionName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.electronCollectionName); + te.m_electrons = *electrons; } //Muons if (m_containerNames.muonCollectionName != "None") { - const xAOD::MuonContainer* muons(0); - top::check(xaodEvent.retrieve(muons, m_containerNames.muonCollectionName), "xAOD::TEvent retrieve failed to get " + m_containerNames.muonCollectionName); - te.m_muons = *muons; + const xAOD::MuonContainer* muons(0); + top::check(xaodEvent.retrieve(muons, + m_containerNames.muonCollectionName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.muonCollectionName); + te.m_muons = *muons; } //Jets if (m_containerNames.jetCollectionName != "None") { - const xAOD::JetContainer* jets(0); - top::check(xaodEvent.retrieve(jets, m_containerNames.jetCollectionName), "xAOD::TEvent retrieve failed to get " + m_containerNames.jetCollectionName); - te.m_jets = *jets; + const xAOD::JetContainer* jets(0); + top::check(xaodEvent.retrieve(jets, + m_containerNames.jetCollectionName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.jetCollectionName); + te.m_jets = *jets; } //LargeJets if (m_containerNames.largeJetCollectionName != "None") { - const xAOD::JetContainer* largeJets(0); - top::check(xaodEvent.retrieve(largeJets, m_containerNames.largeJetCollectionName), "xAOD::TEvent retrieve failed to get " + m_containerNames.largeJetCollectionName); - te.m_largeJets = *largeJets; + const xAOD::JetContainer* largeJets(0); + top::check(xaodEvent.retrieve(largeJets, + m_containerNames.largeJetCollectionName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.largeJetCollectionName); + te.m_largeJets = *largeJets; } //Taus if (m_containerNames.tauCollectionName != "None") { - const xAOD::TauJetContainer* taus(0); - top::check(xaodEvent.retrieve(taus, m_containerNames.tauCollectionName), "xAOD::TEvent retrieve failed to get " + m_containerNames.tauCollectionName); - te.m_tauJets = *taus; + const xAOD::TauJetContainer* taus(0); + top::check(xaodEvent.retrieve(taus, + m_containerNames.tauCollectionName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.tauCollectionName); + te.m_tauJets = *taus; } //MET if (m_containerNames.metName != "None") { - - const xAOD::MissingETContainer* mets(0); - check(xaodEvent.retrieve(mets, m_containerNames.metName), "xAOD::TEvent retrieve failed to get " + m_containerNames.metName); - te.m_met = (*mets)[MissingETBase::Source::total()]; - + const xAOD::MissingETContainer* mets(0); + check(xaodEvent.retrieve(mets, + m_containerNames.metName), + "xAOD::TEvent retrieve failed to get " + m_containerNames.metName); + te.m_met = (*mets)[MissingETBase::Source::total()]; } return te; -} + } -void EventLoaderDirect::print(std::ostream& os) const { + void EventLoaderDirect::print(std::ostream& os) const { os << "EventLoaderDirect Configuration\n"; os << "No object corrections and no object selection\n"; @@ -88,7 +99,5 @@ void EventLoaderDirect::print(std::ostream& os) const { os << "Jet ContainerName: " << m_containerNames.jetCollectionName << "\n"; os << "LargeJet ContainerName: " << m_containerNames.largeJetCollectionName << "\n"; os << "MET ContainerName: " << m_containerNames.metName << "\n"; + } } - -} - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsAnalysis.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsAnalysis.cxx index dff88a5bc5e6862501ae5bec99e73e2d880437ce..f825145316f923c3de487244115a9292b850e0d5 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsAnalysis.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsAnalysis.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/LJetsAnalysis.h" #include "TopExamples/DefaultPlots.h" @@ -17,18 +17,17 @@ #include <fstream> namespace top { - -LJetsAnalysis::LJetsAnalysis(TFile* outputFile, EL::Worker* wk) : - m_mcChannelNumber(0), - m_runNumber(0), - m_histsEl("ejets", outputFile, wk), - m_histsMu("mujets", outputFile, wk), - m_cutflowEventsEl(nullptr), - m_cutflowMCWeightsEl(nullptr), - m_cutflowEventsMu(nullptr), - m_cutflowMCWeightsMu(nullptr), - m_counterEl(0), - m_counterMu(0) { + LJetsAnalysis::LJetsAnalysis(TFile* outputFile, EL::Worker* wk) : + m_mcChannelNumber(0), + m_runNumber(0), + m_histsEl("ejets", outputFile, wk), + m_histsMu("mujets", outputFile, wk), + m_cutflowEventsEl(nullptr), + m_cutflowMCWeightsEl(nullptr), + m_cutflowEventsMu(nullptr), + m_cutflowMCWeightsMu(nullptr), + m_counterEl(0), + m_counterMu(0) { //add some default histograms for each channel top::addPlots(m_histsEl); top::addPlots(m_histsMu); @@ -36,46 +35,45 @@ LJetsAnalysis::LJetsAnalysis(TFile* outputFile, EL::Worker* wk) : //some extra histograms m_histsEl.addHist("mwt", ";MWT [GeV];Events", 20, 0, 200); m_histsMu.addHist("mwt", ";MWT [GeV];Events", 20, 0, 200); -} + } -LJetsAnalysis::~LJetsAnalysis() { -} + LJetsAnalysis::~LJetsAnalysis() { + } -void LJetsAnalysis::newFile(TFile* inputFile) { + void LJetsAnalysis::newFile(TFile* inputFile) { updateCutflow("ejets/cutflow", m_cutflowEventsEl, inputFile); updateCutflow("ejets/cutflow_mc", m_cutflowMCWeightsEl, inputFile); updateCutflow("mujets/cutflow", m_cutflowEventsMu, inputFile); updateCutflow("mujets/cutflow_mc", m_cutflowMCWeightsMu, inputFile); -} + } -void LJetsAnalysis::event(const top::Event& topEvent) { + void LJetsAnalysis::event(const top::Event& topEvent) { m_runNumber = topEvent.m_info->runNumber(); double eventWeight = 1.; if (top::isSimulation(topEvent)) { - m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); -// eventWeight = topEvent.m_info->mcEventWeight(); - eventWeight = topEvent.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); + eventWeight = topEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); } //std::cout << topEvent << std::endl; if (top::passesPreSelection(topEvent, "ejets")) { - top::fillPlots(topEvent, m_histsEl, eventWeight); - const double mwt = top::mwt(*topEvent.m_electrons[0], *topEvent.m_met); - m_histsEl.hist("mwt")->Fill(mwt * top::toGeV, eventWeight); - ++m_counterEl; + top::fillPlots(topEvent, m_histsEl, eventWeight); + const double mwt = top::mwt(*topEvent.m_electrons[0], *topEvent.m_met); + m_histsEl.hist("mwt")->Fill(mwt * top::toGeV, eventWeight); + ++m_counterEl; } if (top::passesPreSelection(topEvent, "mujets")) { - top::fillPlots(topEvent, m_histsMu, eventWeight); - const double mwt = top::mwt(*topEvent.m_muons[0], *topEvent.m_met); - m_histsMu.hist("mwt")->Fill(mwt * top::toGeV, eventWeight); - ++m_counterMu; + top::fillPlots(topEvent, m_histsMu, eventWeight); + const double mwt = top::mwt(*topEvent.m_muons[0], *topEvent.m_met); + m_histsMu.hist("mwt")->Fill(mwt * top::toGeV, eventWeight); + ++m_counterMu; } -} + } -void LJetsAnalysis::finalise(TFile* outputFile) { + void LJetsAnalysis::finalise(TFile* outputFile) { //to screen std::cout << "Cutflows directly from the input files:\n"; printCutflow(std::cout, m_cutflowEventsEl, m_cutflowMCWeightsEl, "ejets", m_counterEl); @@ -83,10 +81,8 @@ void LJetsAnalysis::finalise(TFile* outputFile) { //tofile - mc use channel number, data use run number std::stringstream ss; - if (m_mcChannelNumber > 0) - ss << m_mcChannelNumber; - else - ss << m_runNumber; + if (m_mcChannelNumber > 0) ss << m_mcChannelNumber; + else ss << m_runNumber; std::ofstream cutflowfile_ejets(ss.str() + "_ejets_cutflow.txt"); std::ofstream cutflowfile_mujets(ss.str() + "_mujets_cutflow.txt"); @@ -100,14 +96,14 @@ void LJetsAnalysis::finalise(TFile* outputFile) { //normalise to 1 fb-1 for MC simulation double sf = 1.; if (m_mcChannelNumber != 0) { - const double mcWeightsInSample = m_cutflowMCWeightsEl->GetBinContent(1); - sf = sfToOneInversefb(m_mcChannelNumber, mcWeightsInSample); + const double mcWeightsInSample = m_cutflowMCWeightsEl->GetBinContent(1); + sf = sfToOneInversefb(m_mcChannelNumber, mcWeightsInSample); } m_histsEl.scaleHistograms(sf); m_histsMu.scaleHistograms(sf); outputFile->Write(); -} + } /** * @brief Prints the cutflow table to the screen or a file. This is not scaled @@ -126,28 +122,27 @@ void LJetsAnalysis::finalise(TFile* outputFile) { * @param localYield Yield that the local code ran over. It should match the * number from the grid (since you ran on the same events). */ -void LJetsAnalysis::printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, const std::string& name, const unsigned int localYield) { + void LJetsAnalysis::printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, + const std::string& name, const unsigned int localYield) { out << name << " cutflow:\n"; out << " " << - std::setw(4) << "Num" << - std::setw(20) << "Name" << - std::setw(20) << "Grid (Events)" << - std::setw(20) << "Grid (MC Weights)" << - std::setw(20) << "Local (Events)" << "\n"; + std::setw(4) << "Num" << + std::setw(20) << "Name" << + std::setw(20) << "Grid (Events)" << + std::setw(20) << "Grid (MC Weights)" << + std::setw(20) << "Local (Events)" << "\n"; for (int i = 1; i <= eventHist->GetNbinsX(); ++i) { - out << " " << std::setw(4) << i - << std::setw(20) << eventHist->GetXaxis()->GetBinLabel(i) - << std::setw(20) << eventHist->GetBinContent(i) - << std::setw(20) << mcWeightHist->GetBinContent(i); + out << " " << std::setw(4) << i + << std::setw(20) << eventHist->GetXaxis()->GetBinLabel(i) + << std::setw(20) << eventHist->GetBinContent(i) + << std::setw(20) << mcWeightHist->GetBinContent(i); - if (i == eventHist->GetNbinsX()) - out << std::setw(20) << localYield; + if (i == eventHist->GetNbinsX()) out << std::setw(20) << localYield; - out << "\n"; + out << "\n"; } out << "\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsTtresAnalysis.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsTtresAnalysis.cxx index 10b610aaff076f52e04e0576be442d73d88684a1..a599fd3419c3b1d19c9b1db03f5dcb260667d3e9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsTtresAnalysis.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/LJetsTtresAnalysis.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/LJetsTtresAnalysis.h" #include "TopExamples/DefaultPlots.h" @@ -20,34 +20,31 @@ namespace top { - -LJetsTtresAnalysis::LJetsTtresAnalysis(TFile* outputFile) : - m_mcChannelNumber(0), - m_histsREl("rejets", outputFile), - m_histsRMu("rmujets", outputFile), - m_histsBEl("bejets", outputFile), - m_histsBMu("bmujets", outputFile), - m_cutflowEventsREl(nullptr), - m_cutflowMCWeightsREl(nullptr), - m_cutflowEventsRMu(nullptr), - m_cutflowMCWeightsRMu(nullptr), - m_cutflowEventsBEl(nullptr), - m_cutflowMCWeightsBEl(nullptr), - m_cutflowEventsBMu(nullptr), - m_cutflowMCWeightsBMu(nullptr), - m_counterREl(0), - m_counterRMu(0), - m_counterBEl(0), - m_counterBMu(0), - m_neutrinoBuilder("MeV"), - m_chi2("MeV") - { - + LJetsTtresAnalysis::LJetsTtresAnalysis(TFile* outputFile) : + m_mcChannelNumber(0), + m_histsREl("rejets", outputFile), + m_histsRMu("rmujets", outputFile), + m_histsBEl("bejets", outputFile), + m_histsBMu("bmujets", outputFile), + m_cutflowEventsREl(nullptr), + m_cutflowMCWeightsREl(nullptr), + m_cutflowEventsRMu(nullptr), + m_cutflowMCWeightsRMu(nullptr), + m_cutflowEventsBEl(nullptr), + m_cutflowMCWeightsBEl(nullptr), + m_cutflowEventsBMu(nullptr), + m_cutflowMCWeightsBMu(nullptr), + m_counterREl(0), + m_counterRMu(0), + m_counterBEl(0), + m_counterBMu(0), + m_neutrinoBuilder("MeV"), + m_chi2("MeV") { //tell it to load AKT10 SetContainerNames()->largeJetCollectionName = "CorrectedSelectedAntiKt10LCTopoTrimmedPtFrac30SmallR5Jets"; // AntiKt10LCTopoTrimmedPtFrac30SmallR5Jets //SetContainerNames()->largeJetCollectionName = "CorrectedSelectedAntiKt10LCTopoJets"; m_chi2.Init(TtresChi2::DATA2012SUMMER2013); - + //add some default histograms for each channel top::addPlots(m_histsREl); top::addPlots(m_histsRMu); @@ -115,12 +112,12 @@ LJetsTtresAnalysis::LJetsTtresAnalysis(TFile* outputFile) : m_histsBEl.addHist("mtt", ";boosted m_{tt} [GeV];Events", 30, 0, 3000); m_histsBMu.addHist("mtt", ";boosted m_{tt} [GeV];Events", 30, 0, 3000); -} + } -LJetsTtresAnalysis::~LJetsTtresAnalysis() { -} + LJetsTtresAnalysis::~LJetsTtresAnalysis() { + } -void LJetsTtresAnalysis::newFile(TFile* inputFile) { + void LJetsTtresAnalysis::newFile(TFile* inputFile) { updateCutflow("rejets/cutflow", m_cutflowEventsREl, inputFile); updateCutflow("rejets/cutflow_mc", m_cutflowMCWeightsREl, inputFile); updateCutflow("rmujets/cutflow", m_cutflowEventsRMu, inputFile); @@ -129,38 +126,38 @@ void LJetsTtresAnalysis::newFile(TFile* inputFile) { updateCutflow("bejets/cutflow_mc", m_cutflowMCWeightsBEl, inputFile); updateCutflow("bmujets/cutflow", m_cutflowEventsBMu, inputFile); updateCutflow("bmujets/cutflow_mc", m_cutflowMCWeightsBMu, inputFile); -} + } -void LJetsTtresAnalysis::fillIt(top::PlotManager &hists, const top::Event& topEvent, bool isBoosted) { + void LJetsTtresAnalysis::fillIt(top::PlotManager& hists, const top::Event& topEvent, bool isBoosted) { double eventWeight = 1.; + if (top::isSimulation(topEvent)) { - m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); -// eventWeight = topEvent.m_info->mcEventWeight(); - eventWeight = topEvent.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); + eventWeight = topEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); } top::fillPlots(topEvent, hists, eventWeight); double mwt = -1; - if (topEvent.m_electrons.size() == 1) - mwt = top::mwt(*topEvent.m_electrons[0], *topEvent.m_met); - if (topEvent.m_muons.size() == 1) - mwt = top::mwt(*topEvent.m_muons[0], *topEvent.m_met); + if (topEvent.m_electrons.size() == 1) mwt = top::mwt(*topEvent.m_electrons[0], *topEvent.m_met); + if (topEvent.m_muons.size() == 1) mwt = top::mwt(*topEvent.m_muons[0], *topEvent.m_met); hists.hist("mwt")->Fill(mwt * top::toGeV, eventWeight); hists.hist("met")->Fill(topEvent.m_met->met() * top::toGeV, eventWeight); TLorentzVector lepton; - if (topEvent.m_electrons.size() == 1) - lepton.SetPtEtaPhiE(topEvent.m_electrons[0]->pt(), topEvent.m_electrons[0]->eta(), topEvent.m_electrons[0]->phi(), topEvent.m_electrons[0]->e()); - if (topEvent.m_muons.size() == 1) - lepton.SetPtEtaPhiE(topEvent.m_muons[0]->pt(), topEvent.m_muons[0]->eta(), topEvent.m_muons[0]->phi(), topEvent.m_muons[0]->e()); + if (topEvent.m_electrons.size() == 1) lepton.SetPtEtaPhiE( + topEvent.m_electrons[0]->pt(), topEvent.m_electrons[0]->eta(), + topEvent.m_electrons[0]->phi(), topEvent.m_electrons[0]->e()); + if (topEvent.m_muons.size() == 1) lepton.SetPtEtaPhiE(topEvent.m_muons[0]->pt(), + topEvent.m_muons[0]->eta(), + topEvent.m_muons[0]->phi(), topEvent.m_muons[0]->e()); hists.hist("lep_pt")->Fill(lepton.Pt() * top::toGeV, eventWeight); hists.hist("lep_eta")->Fill(lepton.Eta(), eventWeight); hists.hist("lep_phi")->Fill(lepton.Phi(), eventWeight); if (isBoosted) { - const xAOD::Jet *selJet = nullptr; + const xAOD::Jet* selJet = nullptr; for (const auto* const jetPtr : topEvent.m_jets) { if (jetPtr->auxdata<int>("closeToLepton") == 1) { selJet = jetPtr; @@ -168,7 +165,7 @@ void LJetsTtresAnalysis::fillIt(top::PlotManager &hists, const top::Event& topEv } } - const xAOD::Jet *largeJet = nullptr; + const xAOD::Jet* largeJet = nullptr; for (const auto* const jetPtr : topEvent.m_largeJets) { if (jetPtr->auxdata<int>("good") == 1) { largeJet = jetPtr; @@ -184,12 +181,15 @@ void LJetsTtresAnalysis::fillIt(top::PlotManager &hists, const top::Event& topEv hists.hist("ljetSel_eta")->Fill(largeJet->eta(), eventWeight); hists.hist("ljetSel_phi")->Fill(largeJet->phi(), eventWeight); - TLorentzVector tt(0,0,0,0); + TLorentzVector tt(0, 0, 0, 0); tt += largeJet->p4(); tt += lepton; tt += selJet->p4(); - std::vector<TLorentzVector*> vec_nu = m_neutrinoBuilder.candidatesFromWMass_Rotation(&lepton, topEvent.m_met->met(), topEvent.m_met->phi(), true); - TLorentzVector nu(0,0,0,0); + std::vector<TLorentzVector*> vec_nu = m_neutrinoBuilder.candidatesFromWMass_Rotation(&lepton, + topEvent.m_met->met(), + topEvent.m_met->phi(), + true); + TLorentzVector nu(0, 0, 0, 0); if (vec_nu.size() > 0) { nu = *(vec_nu[0]); for (size_t z = 0; z < vec_nu.size(); ++z) delete vec_nu[z]; @@ -210,30 +210,33 @@ void LJetsTtresAnalysis::fillIt(top::PlotManager &hists, const top::Event& topEv hists.hist("ljet_phi")->Fill(topEvent.m_largeJets[0]->phi(), eventWeight); } } else { // is resolved - // inputs + // inputs // LEPTON --> TLorentzVector for your lepton // vjets --> std::vector<TLorentzVector*> for the jets // vjets_btagged --> std::vector<bool> to say if the jets are btagged or not // met --> TLorentzVector for your MET // outputs, they will be filled by the TTBarLeptonJetsBuilder_chi2 - int igj3, igj4; // index for the Whad + int igj3, igj4; // index for the Whad int igb3, igb4; // index for the b's - int ign1; // index for the neutrino (because chi2 can test both pz solution) + int ign1; // index for the neutrino (because chi2 can test both pz solution) double chi2ming1, chi2ming1H, chi2ming1L; - std::vector<TLorentzVector *> vjets; + std::vector<TLorentzVector*> vjets; std::vector<bool> vjets_btagged; for (size_t z = 0; z < topEvent.m_jets.size(); ++z) { - vjets.push_back(new TLorentzVector(0,0,0,0)); - vjets[z]->SetPtEtaPhiE(topEvent.m_jets[z]->pt(), topEvent.m_jets[z]->eta(), topEvent.m_jets[z]->phi(), topEvent.m_jets[z]->e()); - const xAOD::BTagging *myBTag = topEvent.m_jets[z]->btagging(); + vjets.push_back(new TLorentzVector(0, 0, 0, 0)); + vjets[z]->SetPtEtaPhiE(topEvent.m_jets[z]->pt(), topEvent.m_jets[z]->eta(), + topEvent.m_jets[z]->phi(), topEvent.m_jets[z]->e()); + //const xAOD::BTagging* myBTag = topEvent.m_jets[z]->btagging(); // https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/BTagingxAODEDM // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/BTaggingBenchmarks - vjets_btagged.push_back(myBTag->SV1plusIP3D_discriminant() > 1.85); // best discriminant available for 8 TeV (cut at 70%) + //vjets_btagged.push_back(myBTag->SV1plusIP3D_discriminant() > 1.85); // best discriminant available for 8 TeV + // (cut at 70%) } - TLorentzVector met(0,0,0,0); + TLorentzVector met(0, 0, 0, 0); met.SetPtEtaPhiM(topEvent.m_met->met(), 0, topEvent.m_met->phi(), 0); - bool status = m_chi2.findMinChiSquare(&lepton, &vjets, &vjets_btagged, &met, igj3, igj4, igb3, igb4, ign1, chi2ming1, chi2ming1H, chi2ming1L); // status has to be true + bool status = m_chi2.findMinChiSquare(&lepton, &vjets, &vjets_btagged, &met, igj3, igj4, igb3, igb4, ign1, + chi2ming1, chi2ming1H, chi2ming1L); // status has to be true double mtt = -1; if (status) mtt = m_chi2.getResult_Mtt(); @@ -244,20 +247,21 @@ void LJetsTtresAnalysis::fillIt(top::PlotManager &hists, const top::Event& topEv vjets.clear(); vjets_btagged.clear(); } -} + } -void LJetsTtresAnalysis::event(const top::Event& topEvent) { + void LJetsTtresAnalysis::event(const top::Event& topEvent) { double eventWeight = 1.; + if (top::isSimulation(topEvent)) { - m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); + m_mcChannelNumber = topEvent.m_info->mcChannelNumber(); // eventWeight = topEvent.m_info->mcEventWeight(); - eventWeight = topEvent.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + eventWeight = topEvent.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix } int pass_rejets = top::passesPreSelection(topEvent, "rejets"); int pass_rmujets = top::passesPreSelection(topEvent, "rmujets"); - int pass_bejets = top::passesPreSelection(topEvent, "bejets"); + int pass_bejets = top::passesPreSelection(topEvent, "bejets"); int pass_bmujets = top::passesPreSelection(topEvent, "bmujets"); if (pass_rejets) fillIt(m_histsREl, topEvent, false); @@ -268,54 +272,37 @@ void LJetsTtresAnalysis::event(const top::Event& topEvent) { // fill overlap histogram with 1 if there is an overlap // fill it with 0 for resolved only or 2 if it is boosted only - if (pass_rejets && pass_bejets) - m_histsREl.hist("overlap")->Fill(1.0, eventWeight); + if (pass_rejets && pass_bejets) m_histsREl.hist("overlap")->Fill(1.0, eventWeight); - if (pass_rejets && !pass_bejets) - m_histsREl.hist("overlap")->Fill(0.0, eventWeight); + if (pass_rejets && !pass_bejets) m_histsREl.hist("overlap")->Fill(0.0, eventWeight); - if (!pass_rejets && pass_bejets) - m_histsREl.hist("overlap")->Fill(2.0, eventWeight); + if (!pass_rejets && pass_bejets) m_histsREl.hist("overlap")->Fill(2.0, eventWeight); - if (pass_rmujets && pass_bmujets) - m_histsRMu.hist("overlap")->Fill(1.0, eventWeight); + if (pass_rmujets && pass_bmujets) m_histsRMu.hist("overlap")->Fill(1.0, eventWeight); - if (pass_rmujets && !pass_bmujets) - m_histsRMu.hist("overlap")->Fill(0.0, eventWeight); + if (pass_rmujets && !pass_bmujets) m_histsRMu.hist("overlap")->Fill(0.0, eventWeight); - if (!pass_rmujets && pass_bmujets) - m_histsRMu.hist("overlap")->Fill(2.0, eventWeight); + if (!pass_rmujets && pass_bmujets) m_histsRMu.hist("overlap")->Fill(2.0, eventWeight); - if (pass_rejets && pass_bejets) - m_histsBEl.hist("overlap")->Fill(1.0, eventWeight); + if (pass_rejets && pass_bejets) m_histsBEl.hist("overlap")->Fill(1.0, eventWeight); - if (pass_rejets && !pass_bejets) - m_histsBEl.hist("overlap")->Fill(0.0, eventWeight); + if (pass_rejets && !pass_bejets) m_histsBEl.hist("overlap")->Fill(0.0, eventWeight); - if (!pass_rejets && pass_bejets) - m_histsBEl.hist("overlap")->Fill(2.0, eventWeight); + if (!pass_rejets && pass_bejets) m_histsBEl.hist("overlap")->Fill(2.0, eventWeight); - if (pass_rmujets && pass_bmujets) - m_histsBMu.hist("overlap")->Fill(1.0, eventWeight); + if (pass_rmujets && pass_bmujets) m_histsBMu.hist("overlap")->Fill(1.0, eventWeight); - if (pass_rmujets && !pass_bmujets) - m_histsBMu.hist("overlap")->Fill(0.0, eventWeight); + if (pass_rmujets && !pass_bmujets) m_histsBMu.hist("overlap")->Fill(0.0, eventWeight); - if (!pass_rmujets && pass_bmujets) - m_histsBMu.hist("overlap")->Fill(2.0, eventWeight); + if (!pass_rmujets && pass_bmujets) m_histsBMu.hist("overlap")->Fill(2.0, eventWeight); - if (pass_rejets) - m_counterREl++; - if (pass_rmujets) - m_counterRMu++; - if (pass_bejets) - m_counterBEl++; - if (pass_bmujets) - m_counterBMu++; - -} + if (pass_rejets) m_counterREl++; + if (pass_rmujets) m_counterRMu++; + if (pass_bejets) m_counterBEl++; + if (pass_bmujets) m_counterBMu++; + } -void LJetsTtresAnalysis::finalise(TFile* outputFile) { + void LJetsTtresAnalysis::finalise(TFile* outputFile) { std::cout << "Cutflows directly from the input files:\n"; printCutflow(m_cutflowEventsREl, m_cutflowMCWeightsREl, "rejets", m_counterREl); printCutflow(m_cutflowEventsRMu, m_cutflowMCWeightsRMu, "rmujets", m_counterRMu); @@ -326,8 +313,8 @@ void LJetsTtresAnalysis::finalise(TFile* outputFile) { //normalise to 1 fb-1 for MC simulation double sf = 1.; if (m_mcChannelNumber != 0) { - const double mcWeightsInSample = m_cutflowMCWeightsREl->GetBinContent(1); - sf = sfToOneInversefb(m_mcChannelNumber, mcWeightsInSample); + const double mcWeightsInSample = m_cutflowMCWeightsREl->GetBinContent(1); + sf = sfToOneInversefb(m_mcChannelNumber, mcWeightsInSample); } m_histsREl.scaleHistograms(sf); @@ -336,31 +323,29 @@ void LJetsTtresAnalysis::finalise(TFile* outputFile) { m_histsBEl.scaleHistograms(sf); m_histsBMu.scaleHistograms(sf); outputFile->Write(); -} - + } -void LJetsTtresAnalysis::printCutflow(TH1D* eventHist, TH1D* mcWeightHist, const std::string& name, unsigned int localYield) { + void LJetsTtresAnalysis::printCutflow(TH1D* eventHist, TH1D* mcWeightHist, const std::string& name, + unsigned int localYield) { std::cout << name << " cutflow:\n"; - std::cout << " " << - std::setw(4) << "Num" << - std::setw(20) << "Name" << - std::setw(20) << "Grid (Events)" << - std::setw(20) << "Grid (MC Weights)" << - std::setw(20) << "Local (Events)" << "\n"; + std::cout << " " << + std::setw(4) << "Num" << + std::setw(20) << "Name" << + std::setw(20) << "Grid (Events)" << + std::setw(20) << "Grid (MC Weights)" << + std::setw(20) << "Local (Events)" << "\n"; for (int i = 1; i <= eventHist->GetNbinsX(); ++i) { - std::cout << " " << std::setw(4) << i + std::cout << " " << std::setw(4) << i << std::setw(20) << eventHist->GetXaxis()->GetBinLabel(i) << std::setw(20) << eventHist->GetBinContent(i) << std::setw(20) << mcWeightHist->GetBinContent(i); - if (i == eventHist->GetNbinsX()) - std::cout << std::setw(20) << localYield; + if (i == eventHist->GetNbinsX()) std::cout << std::setw(20) << localYield; - std::cout << "\n"; + std::cout << "\n"; } std::cout << "\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MakeTopConfig.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MakeTopConfig.cxx index ed837826902d6dd554f215666dbe4b8602e30955..fdf30956a4740446b54a3ee1980923f55a45a544 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MakeTopConfig.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MakeTopConfig.cxx @@ -1,27 +1,27 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/MakeTopConfig.h" #include "TopConfiguration/TopConfig.h" #include "TopConfiguration/TopPersistentSettings.h" #include "TopEvent/EventTools.h" -namespace top{ - MakeTopConfig::MakeTopConfig( const std::string& name ) : - asg::AsgMetadataTool( name ) - { +namespace top { + MakeTopConfig::MakeTopConfig(const std::string& name) : + asg::AsgMetadataTool(name) { } - - std::shared_ptr<top::TopConfig> MakeTopConfig::makeTopConfig() - { + + std::shared_ptr<top::TopConfig> MakeTopConfig::makeTopConfig() { ///-- Get the settings from the input file const top::TopPersistentSettings* settings(nullptr); - top::check( inputMetaStore()->retrieve(settings,"TopPersistentSettings") , "Failed to retrieve TopPersistentSettings"); - + + top::check(inputMetaStore()->retrieve(settings, "TopPersistentSettings"), + "Failed to retrieve TopPersistentSettings"); + ///-- Create the top::TopConfig from the TopPersistentSettings --/// - std::shared_ptr<top::TopConfig> config( new top::TopConfig( settings ) ); - + std::shared_ptr<top::TopConfig> config(new top::TopConfig(settings)); + return config; } } \ No newline at end of file diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MiniToFlatAnalysis.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MiniToFlatAnalysis.cxx index 6e5577de23e0f03dd430573d1e8defd3ecc663ab..8993881a7a03f3693a384d49a93da66584146a43 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MiniToFlatAnalysis.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MiniToFlatAnalysis.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/MiniToFlatAnalysis.h" @@ -29,20 +29,21 @@ namespace top { m_outputFileName("SetMe"), m_outputFile(nullptr) { - declareProperty("config" , m_config); - declareProperty("outputFileName" , m_outputFileName = "miniout.root"); + declareProperty("config", m_config); + declareProperty("outputFileName", m_outputFileName = "miniout.root"); } StatusCode MiniToFlatAnalysis::initialize() { m_topTools = std::unique_ptr<top::TopToolStore> (new top::TopToolStore("top::TopToolStore")); - top::check(m_topTools->setProperty("config", m_config) , + top::check(m_topTools->setProperty("config", m_config), "Failed to set config for topTools"); - top::check(m_topTools->initialize() , "Failed to initialize"); + top::check(m_topTools->initialize(), "Failed to initialize"); - m_sfCalc = std::unique_ptr<top::ScaleFactorCalculator> (new top::ScaleFactorCalculator("top::ScaleFactorCalculator")); - top::check(m_sfCalc->setProperty("config", m_config) , + m_sfCalc = + std::unique_ptr<top::ScaleFactorCalculator> (new top::ScaleFactorCalculator("top::ScaleFactorCalculator")); + top::check(m_sfCalc->setProperty("config", m_config), "Failed to set config for sfCalc"); - top::check(m_sfCalc->initialize() , "Failed to initialize"); + top::check(m_sfCalc->initialize(), "Failed to initialize"); m_evtMaker = std::unique_ptr<top::TopEventMaker>(new top::TopEventMaker("top::TopEventMaker")); top::check(m_evtMaker->setProperty("config", m_config), @@ -59,14 +60,15 @@ namespace top { StatusCode MiniToFlatAnalysis::execute() { // Re-do Scale Factors - You cannot do this with a flat ntuple - top::check(m_sfCalc->execute() , "Failed to calculate scale factors"); + top::check(m_sfCalc->execute(), "Failed to calculate scale factors"); - const xAOD::SystematicEventContainer* allSystematics = m_evtMaker->systematicEvents(m_config->sgKeyTopSystematicEvents()); + const xAOD::SystematicEventContainer* allSystematics = m_evtMaker->systematicEvents( + m_config->sgKeyTopSystematicEvents()); // ATH_MSG_INFO(" Total number of SystematicEvents (inc Nominal) = "<<allSystematics->size()); for (auto currentSystematic : *allSystematics) { // Make a top::Event - top::Event topEvent = m_evtMaker->makeTopEvent(*currentSystematic); + top::Event topEvent = m_evtMaker->makeTopEvent(currentSystematic); topEvent.m_saveEvent = false; // Reset the ttree indicies (probably should be done somewhere else) @@ -89,12 +91,10 @@ namespace top { return StatusCode::SUCCESS; } - StatusCode MiniToFlatAnalysis::finalize() { m_outputFile->cd(); m_event_saver->finalize(); return StatusCode::SUCCESS; } - } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MinixAODAnalysis.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MinixAODAnalysis.cxx index 7500728ba29c4f874aabef5d8a078c123fc9850d..68b74c4025b3e6f253c230c16eeae780570a4335 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MinixAODAnalysis.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/MinixAODAnalysis.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples//MinixAODAnalysis.h" @@ -18,120 +18,112 @@ #include "TFile.h" #include "TDirectoryFile.h" -namespace top{ - MinixAODAnalysis::MinixAODAnalysis( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + MinixAODAnalysis::MinixAODAnalysis(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - + m_topTools(nullptr), m_sfCalc(nullptr), m_evtMaker(nullptr), - + m_outputFileName("SetMe"), m_outputFile(nullptr), - + m_firstEvent(true), m_sampleName("SetMe"), - m_plots() - { - declareProperty( "config" , m_config ); - declareProperty( "outputFileName" , m_outputFileName = "miniout.root" ); - declareProperty( "sampleName" , m_sampleName = "Example" ); + m_plots() { + declareProperty("config", m_config); + declareProperty("outputFileName", m_outputFileName = "miniout.root"); + declareProperty("sampleName", m_sampleName = "Example"); } - - StatusCode MinixAODAnalysis::initialize() - { - - m_topTools = std::unique_ptr<top::TopToolStore> ( new top::TopToolStore( "top::TopToolStore" ) ); - top::check( m_topTools->setProperty("config",m_config) , "Failed to set property" ); - top::check( m_topTools->initialize() , "Failed to initialize" ); - - m_sfCalc = std::unique_ptr<top::ScaleFactorCalculator> ( new top::ScaleFactorCalculator( "top::ScaleFactorCalculator" ) ); - top::check( m_sfCalc->setProperty("config",m_config) , "Failed to set property" ); - top::check( m_sfCalc->initialize() , "Failed to initialize" ); - - m_evtMaker = std::unique_ptr<top::TopEventMaker> ( new top::TopEventMaker( "top::TopEventMaker" ) ); - top::check( m_evtMaker->setProperty("config",m_config) , "Failed to set property" ); - top::check( m_evtMaker->initialize() , "Failed to initialize" ); - - m_outputFile = new TFile(m_outputFileName.c_str(),"RECREATE"); - - + + StatusCode MinixAODAnalysis::initialize() { + m_topTools = std::unique_ptr<top::TopToolStore> (new top::TopToolStore("top::TopToolStore")); + top::check(m_topTools->setProperty("config", m_config), "Failed to set property"); + top::check(m_topTools->initialize(), "Failed to initialize"); + + m_sfCalc = + std::unique_ptr<top::ScaleFactorCalculator> (new top::ScaleFactorCalculator("top::ScaleFactorCalculator")); + top::check(m_sfCalc->setProperty("config", m_config), "Failed to set property"); + top::check(m_sfCalc->initialize(), "Failed to initialize"); + + m_evtMaker = std::unique_ptr<top::TopEventMaker> (new top::TopEventMaker("top::TopEventMaker")); + top::check(m_evtMaker->setProperty("config", m_config), "Failed to set property"); + top::check(m_evtMaker->initialize(), "Failed to initialize"); + + m_outputFile = new TFile(m_outputFileName.c_str(), "RECREATE"); + + return StatusCode::SUCCESS; } - - StatusCode MinixAODAnalysis::execute() - { - + + StatusCode MinixAODAnalysis::execute() { ///-- Re-do Scale Factors - You cannot do this with a flat ntuple --/// - top::check( m_sfCalc->execute() , "Failed to calculate scale factors" ); + top::check(m_sfCalc->execute(), "Failed to calculate scale factors"); - const xAOD::SystematicEventContainer* allSystematics = m_evtMaker->systematicEvents( m_config->sgKeyTopSystematicEvents() ); + const xAOD::SystematicEventContainer* allSystematics = m_evtMaker->systematicEvents( + m_config->sgKeyTopSystematicEvents()); // ATH_MSG_INFO(" Total number of SystematicEvents (inc Nominal) = "<<allSystematics->size()); - + ///-- OK, this is a bit ugly, it will be cleaned up massively in future versions --/// ///-- This is a demonstration program only --/// - - + + if (m_firstEvent) { m_firstEvent = false; - + // Setup a top::PlotManager for each channel and each syst for (auto channel : *m_config->allSelectionNames()) { - std::unordered_map<std::string,top::PlotManager*> channelPlotMap; + std::unordered_map<std::string, top::PlotManager*> channelPlotMap; for (auto currentSystematic : *allSystematics) { - channelPlotMap.insert( std::make_pair( - m_config->systematicName( currentSystematic->hashValue() ) , - new top::PlotManager(m_sampleName,channel,m_config->systematicName( currentSystematic->hashValue() ) ,m_outputFile) - ) ); + channelPlotMap.insert(std::make_pair( + m_config->systematicName(currentSystematic->hashValue()), + new top::PlotManager(m_sampleName, channel, + m_config->systematicName(currentSystematic->hashValue()), + m_outputFile) + )); } - m_plots.insert( std::make_pair( channel , channelPlotMap ) ); + m_plots.insert(std::make_pair(channel, channelPlotMap)); } - - for (Itr i=m_plots.begin();i!=m_plots.end();++i) { - for (Itr2 j=(*i).second.begin();j!=(*i).second.end();++j) { - top::addPlots( *((*j).second) ); + + for (Itr i = m_plots.begin(); i != m_plots.end(); ++i) { + for (Itr2 j = (*i).second.begin(); j != (*i).second.end(); ++j) { + top::addPlots(*((*j).second)); } } - } - + for (auto currentSystematic : *allSystematics) { ///-- Make a top::Event --/// - top::Event topEvent = m_evtMaker->makeTopEvent( *currentSystematic ); + top::Event topEvent = m_evtMaker->makeTopEvent(currentSystematic); ///-- Loop over all selections --/// for (auto sel : *m_config->allSelectionNames()) { - Itr channelPlotMap = m_plots.find( sel ); + Itr channelPlotMap = m_plots.find(sel); if (channelPlotMap != m_plots.end()) { - ///-- If selection passes, plot the top::Event --/// - if (currentSystematic->isAvailable<int>(sel)){ + if (currentSystematic->isAvailable<int>(sel)) { bool passSelection = currentSystematic->auxdataConst<int>(sel) == 1 ? true : false; - if (passSelection){ - - Itr2 systPlotMap = (*channelPlotMap).second.find( m_config->systematicName( currentSystematic->hashValue() ) ); + if (passSelection) { + Itr2 systPlotMap = + (*channelPlotMap).second.find(m_config->systematicName(currentSystematic->hashValue())); if (systPlotMap != (*channelPlotMap).second.end()) { - top::fillPlots(topEvent ,*((*systPlotMap).second) , 1. ); + top::fillPlots(topEvent, *((*systPlotMap).second), 1.); } - } - } } } } - - return StatusCode::SUCCESS; + + return StatusCode::SUCCESS; } - - - StatusCode MinixAODAnalysis::finalize() - { + + StatusCode MinixAODAnalysis::finalize() { m_outputFile->cd(); m_outputFile->Write(); - - return StatusCode::SUCCESS; + + return StatusCode::SUCCESS; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/NoSelectionAnalysis.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/NoSelectionAnalysis.cxx index 06738694bfa3fd33fb6836477e448077be79fb67..f2a52c5c4133d1c3c1e8070654b04242e52b6e3d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/NoSelectionAnalysis.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/Root/NoSelectionAnalysis.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopExamples/NoSelectionAnalysis.h" #include "TopExamples/DefaultPlots.h" @@ -15,65 +15,61 @@ #include <iostream> namespace top { - -NoSelectionAnalysis::NoSelectionAnalysis(TFile* outputFile, EL::Worker* wk) : - m_hists("all", outputFile, wk), - m_cutflowEvents(nullptr), - m_cutflowMCWeights(nullptr), - m_counter(0) { + NoSelectionAnalysis::NoSelectionAnalysis(TFile* outputFile, EL::Worker* wk) : + m_hists("all", outputFile, wk), + m_cutflowEvents(nullptr), + m_cutflowMCWeights(nullptr), + m_counter(0) { top::addPlots(m_hists); -} + } -NoSelectionAnalysis::~NoSelectionAnalysis() { -} + NoSelectionAnalysis::~NoSelectionAnalysis() { + } -void NoSelectionAnalysis::newFile(TFile* inputFile) { + void NoSelectionAnalysis::newFile(TFile* inputFile) { top::updateCutflow("all/cutflow", m_cutflowEvents, inputFile); top::updateCutflow("all/cutflow_mc", m_cutflowMCWeights, inputFile); -} + } -void NoSelectionAnalysis::event(const top::Event& topEvent) { + void NoSelectionAnalysis::event(const top::Event& topEvent) { ++m_counter; double eventWeight = 1.; - if (top::isSimulation(topEvent)) -// eventWeight = topEvent.m_info->mcEventWeight(); - eventWeight = topEvent.m_truthEvent->at(0)->weights()[0];// FIXME temporary bugfix + if (top::isSimulation(topEvent)) eventWeight = topEvent.m_info->auxdataConst<float>("AnalysisTop_eventWeight"); //std::cout << topEvent << std::endl; top::fillPlots(topEvent, m_hists, eventWeight); -} + } -void NoSelectionAnalysis::finalise(TFile* outputFile) { + void NoSelectionAnalysis::finalise(TFile* outputFile) { std::cout << "Cutflow directly from the input files:\n"; printCutflow(m_cutflowEvents, m_cutflowMCWeights, "all", m_counter); //write out plots outputFile->Write(); -} + } -void NoSelectionAnalysis::printCutflow(TH1D* eventHist, TH1D* mcWeightHist, const std::string& name, unsigned int localYield) { + void NoSelectionAnalysis::printCutflow(TH1D* eventHist, TH1D* mcWeightHist, const std::string& name, + unsigned int localYield) { std::cout << name << " cutflow:\n"; - std::cout << " " << - std::setw(4) << "Num" << - std::setw(20) << "Name" << - std::setw(20) << "Grid (Events)" << - std::setw(20) << "Grid (MC Weights)" << - std::setw(20) << "Local (Events)" << "\n"; + std::cout << " " << + std::setw(4) << "Num" << + std::setw(20) << "Name" << + std::setw(20) << "Grid (Events)" << + std::setw(20) << "Grid (MC Weights)" << + std::setw(20) << "Local (Events)" << "\n"; for (int i = 1; i <= eventHist->GetNbinsX(); ++i) { - std::cout << " " << std::setw(4) << i + std::cout << " " << std::setw(4) << i << std::setw(20) << eventHist->GetXaxis()->GetBinLabel(i) << std::setw(20) << eventHist->GetBinContent(i) << std::setw(20) << mcWeightHist->GetBinContent(i); - if (i == eventHist->GetNbinsX()) - std::cout << std::setw(20) << localYield; + if (i == eventHist->GetNbinsX()) std::cout << std::setw(20) << localYield; - std::cout << "\n"; + std::cout << "\n"; } std::cout << "\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisBase.h index 0b7568412561ba32151fb808de70213841c0ff7b..99735ec988836fc27bff4cf7e59d2182b5785cd3 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISBASE_H_ #define ANALYSISBASE_H_ @@ -10,21 +10,21 @@ class TFile; namespace top { -class Event; + class Event; /** * @brief An interface so that the analysis codes look the same and can be * run by the mini-to-plots executable. */ -class AnalysisBase { -public: + class AnalysisBase { + public: /** * @brief This is run once only at the very start. You might want to book * some histograms or something. */ AnalysisBase() { - //container names - m_containerNames.eventInfoName ="EventInfo"; + //container names + m_containerNames.eventInfoName = "EventInfo"; m_containerNames.electronCollectionName = "CorrectedSelectedElectrons"; m_containerNames.muonCollectionName = "CorrectedSelectedMuons"; m_containerNames.jetCollectionName = "CorrectedSelectedAntiKt4EMTopoJets"; @@ -63,14 +63,12 @@ public: */ virtual void finalise(TFile*) = 0; - const ContainerNames containerNames() const { return m_containerNames; } - - ContainerNames* SetContainerNames() { return &m_containerNames; } + const ContainerNames containerNames() const {return m_containerNames;} -private: + ContainerNames* SetContainerNames() {return &m_containerNames;} + private: top::ContainerNames m_containerNames; -}; - + }; } #endif /* ANALYSISBASE_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisTools.h index da27cc947fe1bc530369b906cbd936d8f198a6b3..649cd8490d02927ae2ef2448140395076bd45cd1 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/AnalysisTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOOLS_H #define ANALYSISTOOLS_H @@ -19,15 +19,14 @@ namespace EL { } /** - * @file TopExamples/AnalysisTools.h + * @file AnalysisTools.h * * @brief A few functions for analysis code in the final stages. */ namespace top { - ///Sometimes you want things in GeV, no. Do by multiplication. -const double toGeV = 0.001; + const double toGeV = 0.001; /** * @brief Load one of the three analyses in a factory like way. @@ -42,7 +41,7 @@ const double toGeV = 0.001; * @return a unique ptr (these things are magic, they delete themselves when they * are no longer needed) to the analysis code. */ -std::unique_ptr<top::AnalysisBase> loadAnalysis(const std::string& name, TFile* outputFile, EL::Worker* wk=nullptr); + std::unique_ptr<top::AnalysisBase> loadAnalysis(const std::string& name, TFile* outputFile, EL::Worker* wk = nullptr); /** * @brief Open an xAOD and return the sample number as a string. @@ -58,7 +57,7 @@ std::unique_ptr<top::AnalysisBase> loadAnalysis(const std::string& name, TFile* * * @return run number for data, MC channel number for MC simulation. */ -const std::string getSampleNumberAsString(const std::string& filename, const std::string& infoContainerName); + const std::string getSampleNumberAsString(const std::string& filename, const std::string& infoContainerName); /** * @brief Calculate a scale factor to one inverse fb given the sum of weights @@ -71,7 +70,7 @@ const std::string getSampleNumberAsString(const std::string& filename, const std * section using TopDataPreparation * @param mcWeightsInSample The sum of the MC weights in the MC sample */ -double sfToOneInversefb(unsigned int mcChannelNumber, double mcWeightsInSample); + double sfToOneInversefb(unsigned int mcChannelNumber, double mcWeightsInSample); /** * @brief We want to add a histogram with name "name" from file "inputFile" to @@ -85,7 +84,7 @@ double sfToOneInversefb(unsigned int mcChannelNumber, double mcWeightsInSample); * modified by this function! * @param inputFile The inputFile to read the histogram from. */ -void updateCutflow(const std::string& name, TH1D*& histogram, TFile* inputFile); + void updateCutflow(const std::string& name, TH1D*& histogram, TFile* inputFile); /** * @brief Messy. @@ -98,7 +97,7 @@ void updateCutflow(const std::string& name, TH1D*& histogram, TFile* inputFile); * @param inputFile A path with a specific naming convention for the last directory. * @return The e<blah>_s<blah>_r<blah> or equivalent. */ -std::string gridTagFromDirectoryName(const std::string inputFile); + std::string gridTagFromDirectoryName(const std::string inputFile); /** * @brief The top-xaod code is decorating events with a integer (not bool!) @@ -111,8 +110,7 @@ std::string gridTagFromDirectoryName(const std::string inputFile); * @param name The channel we're interested in. e.g. ee * @return True if the event passed the grid selection, false otherwise. */ -bool passesPreSelection(const top::Event& topEvent, const std::string& name); - + bool passesPreSelection(const top::Event& topEvent, const std::string& name); } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/ContainerNames.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/ContainerNames.h index da373bec6f88063d69513c7d1a9ea1127aa13f54..d2496e6c045113f55528b340f7cfdb628658105f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/ContainerNames.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/ContainerNames.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef CONTAINERNAMES_H_ #define CONTAINERNAMES_H_ @@ -8,8 +8,7 @@ #include <string> namespace top { - -struct ContainerNames { + struct ContainerNames { std::string eventInfoName; std::string electronCollectionName; std::string muonCollectionName; @@ -18,10 +17,9 @@ struct ContainerNames { std::string metName; std::string tauCollectionName; std::string truthCollectionName; -}; - + }; } -std::ostream& operator<<(std::ostream& os, const top::ContainerNames& names); +std::ostream& operator << (std::ostream& os, const top::ContainerNames& names); #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DefaultPlots.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DefaultPlots.h index 6b1e6238de553005bb730401c31bdc00de410772..d60e0be9908aefb249b72f83b3c131f06a142d59 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DefaultPlots.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DefaultPlots.h @@ -1,13 +1,13 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef DEFAULTPLOTS_H_ #define DEFAULTPLOTS_H_ namespace top { -class PlotManager; -class Event; + class PlotManager; + class Event; /** * @brief Since a few of the analyses might want some 'default' plots we've put @@ -18,7 +18,7 @@ class Event; * @param manager This is a little package that lets you store a bunch of * histograms and then refer to them by name. */ -void addPlots(top::PlotManager& manager); + void addPlots(top::PlotManager& manager); /** * @brief Fill the plots made by the addPlots function. This should be run every @@ -30,8 +30,7 @@ void addPlots(top::PlotManager& manager); * @param eventWeight Maybe you're running on MC simulation and the events are * weighted and you want to plot them with weights? */ -void fillPlots(const top::Event& topEvent, top::PlotManager& manager, double eventWeight); - + void fillPlots(const top::Event& topEvent, top::PlotManager& manager, double eventWeight); } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DileptonAnalysis.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DileptonAnalysis.h index 33bc7a81cff360068ed169170b05d8310c0c475a..430a9a5d2d9f671dfc45b3e0715f32cba74d677a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DileptonAnalysis.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/DileptonAnalysis.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef DILEPTONANALYSIS_H_ #define DILEPTONANALYSIS_H_ @@ -16,22 +16,21 @@ namespace EL { } namespace top { - -class DileptonAnalysis : public AnalysisBase { -public: - DileptonAnalysis(TFile* outputFile, EL::Worker* wk=nullptr); + class DileptonAnalysis: public AnalysisBase { + public: + DileptonAnalysis(TFile* outputFile, EL::Worker* wk = nullptr); ~DileptonAnalysis(); void newFile(TFile* inputFile) override; void event(const top::Event& topEvent) override; void finalise(TFile* outputFile) override; - -private: + private: void eeAnalysis(const top::Event& topEvent, double eventWeight); void mumuAnalysis(const top::Event& topEvent, double eventWeight); void emuAnalysis(const top::Event& topEvent, double eventWeight); - void printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, const std::string& name, const unsigned int localYield); + void printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, + const std::string& name, const unsigned int localYield); ///MC Channel number is needed to calculate the SF (to 1 fb-1) at the end of the job unsigned int m_mcChannelNumber; @@ -56,8 +55,7 @@ private: unsigned int m_counterElEl; unsigned int m_counterMuMu; unsigned int m_counterElMu; -}; - + }; } #endif /* DILEPTONANALYSIS_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/EventLoaderDirect.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/EventLoaderDirect.h index bfcb184a5c784669ab56f2062dfaa0aa6c9d9022..6102101f7086f5d421895a13f525fee073e5034c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/EventLoaderDirect.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/EventLoaderDirect.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef LOADALL_H_ #define LOADALL_H_ @@ -10,9 +10,8 @@ #include "TopEvent/Event.h" namespace top { - -class EventLoaderDirect { -public: + class EventLoaderDirect { + public: EventLoaderDirect(const ContainerNames& names); ~EventLoaderDirect(); @@ -22,13 +21,11 @@ public: void print(std::ostream& os) const; ///Get hold of the container names (in derived classes too). - const ContainerNames containerNames() const { return m_containerNames; } - -private: + const ContainerNames containerNames() const {return m_containerNames;} + private: ///Store the container names ContainerNames m_containerNames; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsAnalysis.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsAnalysis.h index b03b50b7119cb8973d5bfe427d531b39b4bea7bc..b569b6ba73d007b0ab91283fa12695a093d22b54 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsAnalysis.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsAnalysis.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef LJETSANALYSIS_H_ #define LJETSANALYSIS_H_ @@ -18,18 +18,17 @@ namespace EL { } namespace top { - -class LJetsAnalysis : public AnalysisBase { -public: - LJetsAnalysis(TFile* outputFile, EL::Worker* wk=nullptr); + class LJetsAnalysis: public AnalysisBase { + public: + LJetsAnalysis(TFile* outputFile, EL::Worker* wk = nullptr); ~LJetsAnalysis(); void newFile(TFile* inputFile) override; void event(const top::Event& topEvent) override; void finalise(TFile* outputFile) override; - -private: - void printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, const std::string& name, const unsigned int localYield); + private: + void printCutflow(std::ostream& out, const TH1D* const eventHist, const TH1D* const mcWeightHist, + const std::string& name, const unsigned int localYield); ///used for output filename (for MC) unsigned int m_mcChannelNumber; @@ -47,8 +46,7 @@ private: unsigned int m_counterEl; unsigned int m_counterMu; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsTtresAnalysis.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsTtresAnalysis.h index f7101f61b7dbd45f9029f0611ede9289278ef2f5..6ab4306a8af7fa7376050d4199db37f3f3c7b506 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsTtresAnalysis.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/LJetsTtresAnalysis.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef LJETSTTRESANALYSIS_H_ #define LJETSTTRESANALYSIS_H_ @@ -17,20 +17,18 @@ class TH1D; class TFile; namespace top { - -class LJetsTtresAnalysis : public AnalysisBase { -public: + class LJetsTtresAnalysis: public AnalysisBase { + public: LJetsTtresAnalysis(TFile* outputFile); ~LJetsTtresAnalysis(); void newFile(TFile* inputFile) override; void event(const top::Event& topEvent) override; void finalise(TFile* outputFile) override; - -private: + private: void printCutflow(TH1D* eventHist, TH1D* mcWeightHist, const std::string& name, unsigned int localYield); - void fillIt(top::PlotManager &hist, const top::Event& topEvent, bool isBoosted); + void fillIt(top::PlotManager& hist, const top::Event& topEvent, bool isBoosted); unsigned int m_mcChannelNumber; @@ -57,8 +55,7 @@ private: TtresNeutrinoBuilder m_neutrinoBuilder; TtresChi2 m_chi2; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MakeTopConfig.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MakeTopConfig.h index ccd2505a1f348f0a205c14e95f5d05ebdad1d93f..b78dbc121e8af44927ca6a3863d98b0bb441953f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MakeTopConfig.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MakeTopConfig.h @@ -1,19 +1,15 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ -// $Id: MakeTopConfig.h 681944 2015-07-09 21:59:27Z morrisj $ #ifndef ANALYSISTOP_NEXTGEN_MAKETOPCONFIG_H -#define ANALYSISTOP_NEXTGEN_MAKTOPCONFIG_H +#define ANALYSISTOP_NEXTGEN_MAKETOPCONFIG_H /** * @author John Morris <john.morris@cern.ch> * * @brief MakeTopConfig - it makes a top::TopConfig from the metadata * - * $Revision: 681944 $ - * $Date: 2015-07-09 23:59:27 +0200 (Thu, 09 Jul 2015) $ - * * **/ @@ -22,14 +18,13 @@ // Framework include(s): #include "AsgTools/AsgMetadataTool.h" -namespace top{ +namespace top { class TopConfig; - class MakeTopConfig : public asg::AsgMetadataTool { - public: - explicit MakeTopConfig( const std::string& name ); - - std::shared_ptr<top::TopConfig> makeTopConfig(); - + class MakeTopConfig: public asg::AsgMetadataTool { + public: + explicit MakeTopConfig(const std::string& name); + + std::shared_ptr<top::TopConfig> makeTopConfig(); }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MiniToFlatAnalysis.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MiniToFlatAnalysis.h index 92c2f8888ce8f674cade28139e437546b5a9c607..1adde5c9abaed1cc2cfc08d841f4ece9bd2f6461 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MiniToFlatAnalysis.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MiniToFlatAnalysis.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: MiniToFlatAnalysis.h 733950 2016-04-05 11:21:48Z tneep $ #ifndef TOPEXAMPLES_MINITOFLATANALYSIS_H_ @@ -26,8 +26,8 @@ // Forward declaration(s): namespace top { -class TopConfig; -class PlotManager; + class TopConfig; + class PlotManager; } class TFile; @@ -38,30 +38,29 @@ class TFile; #include "TopAnalysis/EventSaverFlatNtuple.h" namespace top { -class MiniToFlatAnalysis : public asg::AsgTool { - public: - explicit MiniToFlatAnalysis(const std::string& name); - virtual ~MiniToFlatAnalysis() {} + class MiniToFlatAnalysis: public asg::AsgTool { + public: + explicit MiniToFlatAnalysis(const std::string& name); + virtual ~MiniToFlatAnalysis() {} - // Delete Standard constructors - MiniToFlatAnalysis(const MiniToFlatAnalysis& rhs) = delete; - MiniToFlatAnalysis(MiniToFlatAnalysis&& rhs) = delete; - MiniToFlatAnalysis& operator=(const MiniToFlatAnalysis& rhs) = delete; + // Delete Standard constructors + MiniToFlatAnalysis(const MiniToFlatAnalysis& rhs) = delete; + MiniToFlatAnalysis(MiniToFlatAnalysis&& rhs) = delete; + MiniToFlatAnalysis& operator = (const MiniToFlatAnalysis& rhs) = delete; - virtual StatusCode initialize(); - virtual StatusCode execute(); - virtual StatusCode finalize(); + virtual StatusCode initialize(); + virtual StatusCode execute(); + virtual StatusCode finalize(); + private: + std::shared_ptr<top::TopConfig> m_config; - private: - std::shared_ptr<top::TopConfig> m_config; + std::unique_ptr<top::TopToolStore> m_topTools; + std::unique_ptr<top::ScaleFactorCalculator> m_sfCalc; + std::unique_ptr<top::TopEventMaker> m_evtMaker; + std::unique_ptr<top::EventSaverFlatNtuple> m_event_saver; - std::unique_ptr<top::TopToolStore> m_topTools; - std::unique_ptr<top::ScaleFactorCalculator> m_sfCalc; - std::unique_ptr<top::TopEventMaker> m_evtMaker; - std::unique_ptr<top::EventSaverFlatNtuple> m_event_saver; - - std::string m_outputFileName; - ::TFile* m_outputFile; -}; + std::string m_outputFileName; + ::TFile* m_outputFile; + }; } // namespace top #endif // TOPEXAMPLES_MINITOFLATANALYSIS_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MinixAODAnalysis.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MinixAODAnalysis.h index 26f2398ca648746d4e350976b50c46e65deee0cd..2a6ad4a4c263dcd1c91232810e3a8f340ff7e458 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MinixAODAnalysis.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/MinixAODAnalysis.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: MinixAODAnalysis.h 683667 2015-07-17 02:24:59Z morrisj $ #ifndef ANALYSISTOP_TOPEXAMPLES_MINIXAODANALYSIS_H @@ -12,7 +12,7 @@ * @brief MinixAODAnalysis * * $Revision: 683667 $ - * $Date: 2015-07-17 04:24:59 +0200 (Fri, 17 Jul 2015) $ + * $Date: 2015-07-17 03:24:59 +0100 (Fri, 17 Jul 2015) $ * * **/ @@ -24,7 +24,7 @@ #include "AsgTools/AsgTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; class PlotManager; } @@ -34,38 +34,36 @@ class TFile; #include "TopCorrections/ScaleFactorCalculator.h" #include "TopEvent/TopEventMaker.h" -namespace top{ - class MinixAODAnalysis : public asg::AsgTool { - public: - explicit MinixAODAnalysis( const std::string& name ); - virtual ~MinixAODAnalysis(){} - - // Delete Standard constructors - MinixAODAnalysis(const MinixAODAnalysis& rhs) = delete; - MinixAODAnalysis(MinixAODAnalysis&& rhs) = delete; - MinixAODAnalysis& operator=(const MinixAODAnalysis& rhs) = delete; - - virtual StatusCode initialize(); - virtual StatusCode execute(); - virtual StatusCode finalize(); - - private: - std::shared_ptr<top::TopConfig> m_config; - - std::unique_ptr<top::TopToolStore> m_topTools; - std::unique_ptr<top::ScaleFactorCalculator> m_sfCalc; - std::unique_ptr<top::TopEventMaker> m_evtMaker; - - std::string m_outputFileName; - ::TFile* m_outputFile; - - // Analysis - bool m_firstEvent; - std::string m_sampleName; - std::unordered_map<std::string,std::unordered_map<std::string,top::PlotManager*>> m_plots; - typedef std::unordered_map<std::string,std::unordered_map<std::string,top::PlotManager*>>::const_iterator Itr; - typedef std::unordered_map<std::string,top::PlotManager*>::const_iterator Itr2; +namespace top { + class MinixAODAnalysis: public asg::AsgTool { + public: + explicit MinixAODAnalysis(const std::string& name); + virtual ~MinixAODAnalysis() {} + // Delete Standard constructors + MinixAODAnalysis(const MinixAODAnalysis& rhs) = delete; + MinixAODAnalysis(MinixAODAnalysis&& rhs) = delete; + MinixAODAnalysis& operator = (const MinixAODAnalysis& rhs) = delete; + + virtual StatusCode initialize(); + virtual StatusCode execute(); + virtual StatusCode finalize(); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::unique_ptr<top::TopToolStore> m_topTools; + std::unique_ptr<top::ScaleFactorCalculator> m_sfCalc; + std::unique_ptr<top::TopEventMaker> m_evtMaker; + + std::string m_outputFileName; + ::TFile* m_outputFile; + + // Analysis + bool m_firstEvent; + std::string m_sampleName; + std::unordered_map<std::string, std::unordered_map<std::string, top::PlotManager*> > m_plots; + typedef std::unordered_map<std::string, std::unordered_map<std::string, top::PlotManager*> >::const_iterator Itr; + typedef std::unordered_map<std::string, top::PlotManager*>::const_iterator Itr2; }; } #endif \ No newline at end of file diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/NoSelectionAnalysis.h b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/NoSelectionAnalysis.h index 0f6ca4c7490d20173c16cfed600d7d85ae20a070..ec3a05c61f4170e7dd06cdb80aedf54ebe1b81aa 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/NoSelectionAnalysis.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/TopExamples/NoSelectionAnalysis.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef NOSELECTIONANALYSIS_H_ #define NOSELECTIONANALYSIS_H_ @@ -18,17 +18,15 @@ namespace EL { } namespace top { - -class NoSelectionAnalysis : public AnalysisBase { -public: - NoSelectionAnalysis(TFile* outputFile, EL::Worker* wk=nullptr); + class NoSelectionAnalysis: public AnalysisBase { + public: + NoSelectionAnalysis(TFile* outputFile, EL::Worker* wk = nullptr); ~NoSelectionAnalysis(); void newFile(TFile* inputFile) override; void event(const top::Event& topEvent) override; void finalise(TFile* outputFile) override; - -private: + private: void printCutflow(TH1D* eventHist, TH1D* mcWeightHist, const std::string& name, unsigned int localYield); top::PlotManager m_hists; @@ -37,8 +35,7 @@ private: TH1D* m_cutflowMCWeights; unsigned int m_counter; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/AtlasStyle.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/AtlasStyle.py index 987ae94ffcb02ee8441f0d03f66ae7efe3efa414..a4f55fc299b46bb0a342868b4af8a4d00e0ab58c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/AtlasStyle.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/AtlasStyle.py @@ -3,7 +3,7 @@ import ROOT def SetAtlasStyle(): - print 'Applying ATLAS style settings...' + print('Applying ATLAS style settings...') atlasStyle = AtlasStyle() ROOT.gROOT.SetStyle("ATLAS") ROOT.gROOT.ForceStyle() @@ -77,4 +77,4 @@ def AtlasStyle(): atlasStyle.SetPadTickX(1) atlasStyle.SetPadTickY(1) -SetAtlasStyle() \ No newline at end of file +SetAtlasStyle() diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/__init__.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/__init__.py index 324aa2caa1080affaee3960302ba05612aa5d8cb..74583d364ec2ca794156596c7254d9b234a940c6 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/__init__.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/__init__.py @@ -1,3 +1,2 @@ # Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -# PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/__init__.py diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/ami.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/ami.py index 0277362e58df1dd3906d8d9bc0412487a5fd23c2..11f85a41b73cfd64fe9f20449c1828d5b7ac59e8 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/ami.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/ami.py @@ -1,20 +1,48 @@ #!/usr/bin/env python -# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +import re import os import sys from xml.dom.minidom import parse, parseString import logger + try: import pyAMI.client import pyAMI.atlas.api #import pyAMI except: - print "Maybe you didn't do localSetupPyAMI?" + print("Maybe you didn't do localSetupPyAMI?") sys.exit() + +# Call this function when the AMI client throws any exceptions. +# Quite likely, this is due to a missing VOMS proxy, so point +# that out to the user and exit with error code. +def exit_with_pyami_exception(): + print('') + print(logger.FAIL + 'is your voms proxy okay?' + logger.ENDC) + print('Try voms-proxy-init -voms atlas') + sys.exit(1) + + +# Exception to be thrown when information cannot be extracted +# from an LDN, e.g. the p-tag cannot be identified. +class ldn_decypher_error(Exception): + """Raised when information cannot be extracted from an LDN""" + pass + + +# Exception to be thrown when the wrong LDN type is fed into a +# function (e.g. data-type LDN into an MC-only function). This +# assumes there are only data and MC as types. +class ldn_wrong_type(Exception): + """Raised when an LDN of a wrong type is used""" + pass + + def getContainerContents(containerName): amiclient = pyAMI.client.Client('atlas') @@ -22,11 +50,9 @@ def getContainerContents(containerName): data = "'%"+query+"%'" argument = 'SearchQuery -glite="select dataset.logicalDatasetName, dataset.identifier where dataset.logicalDatasetName like %s" -processingStep=real_data -project=dataSuper_001' % data - #print 'argument', argument maxTries = 3 - #print argument failures = 0 for i in range(maxTries): try: @@ -34,58 +60,35 @@ def getContainerContents(containerName): except: failures += 1 - if failures == maxTries: - print '' - print logger.FAIL + 'is your voms proxy okay?' + logger.ENDC - print 'Try voms-proxy-init -voms atlas' - sys.exit(1) - - #print 'made it' + if failures == maxTries: exit_with_pyami_exception() - #txt = results.output('xml') - #print txt dom = parseString(results) rows = dom.getElementsByTagName('row') - #final = {} datasets = [] - #print 'found', len(rows) for row in rows: - #print 'here', row fields = row.getElementsByTagName('field') for field in fields: - #print field.attributes['name'].value if field.attributes['name'].value == 'logicalDatasetName': retName=field.firstChild.nodeValue - #print retName -# if field.attributes['name'].value == 'identifier': identifier = field.firstChild.nodeValue - #print identifier #Now search for all datasets that match that - #print 'PART 2' - #argument.append("entity=contained_dataset") argument = 'SearchQuery -glite="SELECT contained_dataset.contained_datasetName WHERE dataset.identifier=%s" -processingStep=real_data -project=dataSuper_001' % identifier results = amiclient.execute(argument, format='xml') - #print results - #txt = results.output('xml') - #print txt dom = parseString(results) container = dom.getElementsByTagName('row') - #print len(container) for dataset in container: fields = dataset.getElementsByTagName('field') for field in fields: if field.attributes['name'].value == 'contained_datasetName': - #print 'hello' - #print field.firstChild.nodeValue datasets.append(field.firstChild.nodeValue.encode('ascii','ignore') + '/') - return sorted(datasets) + def askAmi(query, property = 'totalEvents'): amiclient = pyAMI.client.Client('atlas') @@ -93,9 +96,7 @@ def askAmi(query, property = 'totalEvents'): query = query.replace('*', '%%') data = "'"+query+"'" - #argument.append("entity=dataset") argument = 'SearchQuery -glite="SELECT dataset.logicalDatasetName, dataset.%s WHERE dataset.logicalDatasetName LIKE %s"' % (property, data) - #print argument if data.find('data') > -1: argument += ' -processingStep=real_data' @@ -123,11 +124,11 @@ def askAmi(query, property = 'totalEvents'): argument += ' -project=mc14_001' elif data.find('mc15') > -1: argument += ' -project=mc15_001' + elif data.find('mc16') > -1: + argument += ' -project=mc16_001' maxTries = 3 - #print argument - failures = 0 for i in range(maxTries): final = {} @@ -138,29 +139,20 @@ def askAmi(query, property = 'totalEvents'): except: failures += 1 - if failures == maxTries: - print '' - print logger.FAIL + 'is your voms proxy okay?' + logger.ENDC - print 'Try voms-proxy-init -voms atlas' - sys.exit(1) + if failures == maxTries: exit_with_pyami_exception() - #print results.getElementsByTagName('error') - #txt = results.output('xml') - #print txt dom = parseString(results) #they changed it so that a voms-proxy-init error now returns a search #result with error in it. That's annoying. mayBeAnError = dom.getElementsByTagName('error') for row in mayBeAnError: - print row.firstChild.nodeValue + print(row.firstChild.nodeValue) sys.exit(1) rows = dom.getElementsByTagName('row') for row in rows: - #print 'here', row.toprettyxml() - fields = row.getElementsByTagName('field') retName = '' retNev = 0 @@ -169,50 +161,206 @@ def askAmi(query, property = 'totalEvents'): if field.attributes['name'].value == 'logicalDatasetName': retName = field.firstChild.nodeValue - if field.attributes['name'].value == property: - if field.firstChild != None: - retNev = field.firstChild.nodeValue - - #print retName, retNev + if field.attributes['name'].value == property: + if field.firstChild != None: + retNev = field.firstChild.nodeValue final[retName] = retNev else: try: - results = pyAMI.atlas.api.list_datasets(amiclient, query, fields="ldn,events,modified") + results = pyAMI.atlas.api.list_datasets(amiclient, query, fields="ldn,events,modified") except: failures += 1 - if failures == maxTries: - print '' - print logger.FAIL + 'is your voms proxy okay?' + logger.ENDC - print 'Try voms-proxy-init -voms atlas' - sys.exit(1) - - for row in results: + if failures == maxTries: exit_with_pyami_exception() + + for row in results: retName = row["ldn"] retNev = row["events"] - - #print retName, retNev + final[retName] = retNev - - #unicode -> normalcode results = {} for k in final.keys(): results[str(k)] = int(final[k]) - - return results + +# Take a single LDN, extract its dataset number and return it. +def get_dataset_number(ldn): + if is_data(ldn): raise ldn_wrong_type + regex = re.compile("\.[0-9]{6}\.") + match = regex.search(ldn) + if not match: raise ldn_decypher_error + else: return match.group(0)[1:-1] + + +# Take a single LDN, extract its p-tag and return it. +def get_ptag(ldn): + regex = re.compile("_p[0-9]+") + match = regex.search(ldn) + if not match: raise ldn_decypher_error + else: return match.group(0)[1:] + + +# Return the type of LDN we're looking at (e.g. simul.HITS, +# recon.AOD, DAOD_TOPQ1 or other derivation). +def get_type(ldn): + match = re.search("\.recon\.AOD\.", ldn) + if match: return match.group(0)[1:-1] + match = re.search("\.simul.HITS\.", ldn) + if match: return match.group(0)[1:-1] + match = re.search("\.DAOD_[A-Z]+[0-9]+\.", ldn) + if match: return match.group(0)[1:-1] + # If none of the above, raise exception. + raise ldn_decypher_error + + +# Get the data scope of a data-type LDN (e.g. +# data15_13TeV.periodA or data16_13TeV.AllYear) and return it. +# This function should only be called on data LDNs. +def get_data_scope(ldn): + if not is_data(ldn): raise ldn_wrong_type + regex = re.compile("data[0-9]+.*?\..*?\.") + match = regex.search(ldn) + if not match: raise ldn_decypher_error + else: return match.group(0)[:-1] + + +# Get a list of all derivations registered on AMI for a list of +# LDNs. This removes the p-tags from the LDNs and replaces them +# with wildcards to search on AMI. The function returns a +# dictionary with dataset numbers as keys, and a list of LDNs as +# values. The LDNs are assumed to be TOPQ derivations. +def get_derivations(ldns): + amiclient = pyAMI.client.Client('atlas') + regex = re.compile("_p[0-9]+") + wildcards = [regex.sub('_p%', d) for d in ldns] + try: results = pyAMI.atlas.api.list_datasets(amiclient, patterns = wildcards) + except pyAMI.exception.Error: exit_with_pyami_exception() + + dictionary = dict() + + # Make sure the dictionary has empty lists prepared for all + # LDNs that were searched for. If MC, use the dataset number + # as dictionary key, if data, use the data scope. + for ldn in ldns: + try: dictionary[get_dataset_number(ldn)] = [] + except ldn_wrong_type: dictionary[get_data_scope(ldn)] = [] + + # Go through the results and add them to appropriate + # dictionary entries (appending to lists). + for d in results: + try: dictionary[get_dataset_number(d['ldn'])].append(d['ldn']) + except ldn_wrong_type: dictionary[get_data_scope(d['ldn'])].append(d['ldn']) + return dictionary + + +# Check whether an LDN is actually available and valid on AMI. +def is_available(ldn): + amiclient = pyAMI.client.Client('atlas') + try: results = pyAMI.atlas.api.list_datasets(amiclient, patterns = [ldn], fields = ['ldn']) + except pyAMI.exception.Error: exit_with_pyami_exception() + for d in results: + if d['ldn'] == ldn: return True + return False + + +# Check whether an LDN refers to data (and not MC). +def is_data(ldn): + if (ldn[0:4] == "data"): return True + return False + + +# From a given list of LDNs, pick the latest one (i.e. extract +# the p-tag and pick the LDN with the highest one). If the p-tag +# cannot be identified, just return None. +def pick_newest_derivation(ldn_list): + if len(ldn_list) == 0: return "" + try: + get_ptag_as_int = lambda a: int(get_ptag(a)[1:]) + return sorted(ldn_list, key = get_ptag_as_int)[-1] + except ldn_decypher_error: + return None + + +# Print the status of a list of samples on AMI. This takes a list +# of objects of type TopExamples.grid.Sample, wich then contain +# lists of datasets. Set the second argument to "True" will make +# the function stop on any errors. +def check_sample_status(samples, stop_on_error = False): + for s in samples: + print('\n' + logger.WARNING + s.name + logger.ENDC + " (%s %s)" % (len(s.datasets), "dataset" if len(s.datasets) == 1 else "datasets")) + derivations = get_derivations(s.datasets) + status_ok = True + + for ldn in s.datasets: + # First try to understand what type of LDN we're looking + # at (e.g. recon.AOD or DAOD_xx derivations). If this + # fails, exit here. + try: + dataset_type = get_type(ldn) + except: + print("Could not identify dataset type (e.g. recon.AOD or DAOD_TOPQ1) of LDN: %s" % ldn) + sys.exit(1) + + # Try to guess the name of the dictionary key. If the + # LDN is of type MC, then the dataset number should be + # the key, for data it's the data scope. + try: dict_key = get_dataset_number(ldn) + except ldn_wrong_type: dict_key = get_data_scope(ldn) + latest_ldn = pick_newest_derivation(derivations[dict_key]) + + status_msg = "" + + # First output whether the requested LDN exists and + # has a valid entry in the AMI database. + if is_available(ldn): + status_msg = logger.OKGREEN + "found" + logger.ENDC + else: + status_msg = logger.FAIL + "not found" + logger.ENDC + status_ok = False + + # If the dataset is _not_ a derivation, output its type + # and mark it in red. + if dataset_type[0:5] != "DAOD_": + status_msg += ", " + logger.WARNING + "Type: " + dataset_type + logger.ENDC + status_ok = False + + # Then output the derivation status: (1) no derivation + # available at all, (2) derivations available, but the + # requested p-tag is not the latest, (3) requested p-tag + # is the latest. + if not latest_ldn: + status_ok = False + elif not ldn == latest_ldn: + try: + status_msg += ", " + logger.WARNING + "latest p-tag: " + get_ptag(latest_ldn) + logger.ENDC + status_ok = False + except ldn_decypher_error: + print("Could not identify p-tag of LDN: %s" % latest_ldn) + sys.exit(1) + else: + status_msg += ", " + logger.OKGREEN + "latest" + logger.ENDC + + print(" - %s (%s)" % (ldn, status_msg)) + + # Make the function stop if requested and any of the + # datasets of the previous sample list had problems. + if (stop_on_error and not status_ok): + print("\nRequested to stop on error. Please check the above samples ... ") + sys.exit(1) + + if __name__ == '__main__': #data - print 'Testing data15' + print('Testing data15') results = askAmi('data15_comm.%.physics_Main.%.DAOD_TOPQ1.%p2356') for ds in sorted(results): - print ds + print(ds) #MC simulation - print 'Testing MC15' + print('Testing MC15') results = askAmi('mc15_13TeV.%.DAOD_TOPQ1.%p2352') for ds in sorted(results): - print ds + print(ds) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/analysis.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/analysis.py index 704290bf991a145d355fa4ab53d33303afd0d66b..1cc750b9331d86f28c5fa2bfaf9b42a49578cf69 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/analysis.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/analysis.py @@ -85,18 +85,18 @@ class TopDataPreparation: def queryAmi(amiSamples, tag): sys.stdout.write('-> %s: ' % tag) sys.stdout.flush() - print tag + print(tag) ds = ami.askAmi(tag) - print len(ds), 'datasets' + print(len(ds), 'datasets') amiSamples.update(ds) def cacheAmi(ptaglist): try: amiSamples = pickle.load(open("amiyields.pickle", "rb" )) - print logger.OKBLUE + 'Using cached yields - to force me to query AMI delete amiyields.pickle' + logger.ENDC - except IOError, ioex: + print(logger.OKBLUE + 'Using cached yields - to force me to query AMI delete amiyields.pickle' + logger.ENDC) + except IOError as ioex: if ioex.errno == 2: - print logger.OKBLUE + 'Asking AMI' + logger.ENDC + print(logger.OKBLUE + 'Asking AMI' + logger.ENDC) amiSamples = {} @@ -109,7 +109,7 @@ def cacheAmi(ptaglist): queryAmi(amiSamples, 'mc15_13TeV.%.DAOD_TOPQ%.%' + ptag) if len(amiSamples) == 0: - print logger.FAIL + 'Something went wrong when trying to get the data from ami' + logger.ENDC + print(logger.FAIL + 'Something went wrong when trying to get the data from ami' + logger.ENDC) sys.exit(1) else: pickle.dump(amiSamples, open("amiyields.pickle", "wb")) @@ -134,7 +134,7 @@ def getDatasetYield(directoryName): f = ROOT.TFile.Open(fileName) if not f: - print logger.FAIL + 'ERROR: Failed to open %s' % fileName + logger.ENDC + print(logger.FAIL + 'ERROR: Failed to open %s' % fileName + logger.ENDC) continue #Look for TDirectory file (not TTree) and read the cutflow from @@ -154,7 +154,7 @@ def getDatasetYield(directoryName): def makeDirectory(outputDirectory): try: os.makedirs(outputDirectory) - print 'Made directory', outputDirectory + print('Made directory', outputDirectory) except: #directory already exists pass @@ -207,7 +207,7 @@ def check(analysis, directory, runDirectory, samples): if not IsInList: ptaglist.append(tag) - print ptaglist + print(ptaglist) amiSamples = cacheAmi(ptaglist) @@ -228,11 +228,11 @@ def check(analysis, directory, runDirectory, samples): analyses = [] bad = [] - print '%s%50s %90s %12s %12s%s' % (logger.OKBLUE, 'dsid.gridtag', 'local location', 'local yield', 'ami yield', logger.ENDC) + print('%s%50s %90s %12s %12s%s' % (logger.OKBLUE, 'dsid.gridtag', 'local location', 'local yield', 'ami yield', logger.ENDC)) for sample in samples: existingSampleFilenames = [] - print logger.OKBLUE + sample.name + logger.ENDC + print(logger.OKBLUE + sample.name + logger.ENDC) for ds in sample.datasets: splitName = ds.replace('/','').split('.') shortname = splitName[1] + '.' + splitName[-2] + '.' + splitName[-1] @@ -268,7 +268,7 @@ def check(analysis, directory, runDirectory, samples): evenshortername = makeNameFitOnTerminal(shortname, 50) eventshorterfilename = makeFileNameFitOnTerminal(directory.split('/')[-1], 60) - print '%s%50s %90s %12d %12d%s' % (colourstart, evenshortername, eventshorterfilename, directoryYield, amiYield, colourend) + print('%s%50s %90s %12d %12d%s' % (colourstart, evenshortername, eventshorterfilename, directoryYield, amiYield, colourend)) if amiYield > 0 and directoryYield != amiYield: bad.append(ds) @@ -294,31 +294,31 @@ def check(analysis, directory, runDirectory, samples): analyses.append('cd %s;hadd -f %s.root %s' % (runDirectory, sample.name, mergelist)) if '--debug' in sys.argv: - print '' - print '' - print 'These commands are going to be run:' + print('') + print('') + print('These commands are going to be run:') for l in analyses: - print l + print(l) if '--bad' in sys.argv: - print '' - print '' - print 'These are datasets where the ami yield does not match' - print 'TopExamples.grid.Add("Resubmit").datasets = [' + print('') + print('') + print('These are datasets where the ami yield does not match') + print('TopExamples.grid.Add("Resubmit").datasets = [') for l in bad: - print '"%s",' % l + print('"%s",' % l) - print ']' - print "resubmit = TopExamples.grid.Samples(['Resubmit'])" - print 'TopExamples.grid.submit(config, resubmit)' + print(']') + print("resubmit = TopExamples.grid.Samples(['Resubmit'])") + print('TopExamples.grid.submit(config, resubmit)') if '--run' in sys.argv: makeDirectory(runDirectory) - print '' - print '' - print analyses + print('') + print('') + print(analyses) for i, l in enumerate(analyses): - print logger.OKBLUE + l + logger.ENDC - os.system(l) + print(logger.OKBLUE + l + logger.ENDC) + o.ssysteml() diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/grid.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/grid.py index 2930dd177421917656563efd71640368653034e4..4ee66715d8c67c3e9837c05b7db9f79502f8df9c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/grid.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/grid.py @@ -6,22 +6,8 @@ import sys import distutils.spawn import logger import analysis - -try: - import rucio.client -except: - print logger.FAIL + 'DANGER DANGER DANGER' + logger.ENDC - print 'Could not find rucio.client.Client. If you use setupATLAS (you should) then' - print '"localSetupRucioClients" and run this again' - sys.exit(1) - -try: - rucio = rucio.client.Client() -except: - print logger.FAIL + 'DANGER DANGER DANGER' + logger.ENDC - print 'Could not setup rucio.client.Client.' - print 'Did you do voms-proxy-init -voms atlas ?' - sys.exit(1) +import ROOT +from PathResolver import PathResolver availableDatasets = {} @@ -44,13 +30,13 @@ class Sample: if n != 1: suffix = 's' - print logger.OKGREEN + ' %s ' % self.name + logger.ENDC + '(%d dataset%s)' % (n, suffix) + print(logger.OKGREEN + ' %s ' % self.name + logger.ENDC + '(%d dataset%s)' % (n, suffix)) for i, l in enumerate(self.datasets): note = 'Not found' if l in actuallyExists: note = 'Found' - print ' -%2d %s %s' % (i, l, note) + print(' -%2d %s %s' % (i, l, note)) def Add(name): availableDatasets[name] = Sample(name) @@ -62,58 +48,113 @@ def AvailableDatasets(): def Samples(names): samples = [] for n in names: + #removing whitespaces from concatenated lines - ANALYSISTO-553 + for ds in range(0,len(availableDatasets[n].datasets)): + availableDatasets[n].datasets[ds]=availableDatasets[n].datasets[ds].replace(' ','') samples.append(availableDatasets[n]) return samples +def basicInDSNameShortener(*args): + # don't ask what args[0] is; just use args[1] (sorry for my lack of understanding of python) + # if you want to use a different function defined outside this module, you don't need to bother + inDSName = args[1] + splitted = inDSName.split('.') + + runNumber = splitted[1] + physicsName = splitted[2] + if splitted[0] == "user" or splitted[0] == "group": #this is in case we run on private derivations, either produced with user or group role + runNumber = splitted[2] + physicsName = splitted[3] + derivation = splitted[-2] + tags = splitted[-1].replace('/','') + + #grid complains dataset names are too long + #stupid grid + if len(physicsName) > 20: + physicsName = physicsName.split('_')[0] + + outDSName = runNumber + '.' + physicsName + '.' + derivation + '.' + tags + return outDSName + class Config: code = 'top-xaod' - cutsFile = 'nocuts.txt' - - gridUsername = '' - suffix = '' - excludedSites = '' - forceSite = '' - noSubmit = False - CMake = False # False by default - need to set to True for CMake-based releases (release 21) - mergeType = 'Default' #None, Default, xAOD - destSE = '' - memory = '2000' #in MB + settingsFile = 'nocuts.txt' + combine_outputFile = None + combine_prefixes = None + + gridUsername = '' + groupProduction = None + suffix = '' + excludedSites = '' + forceSite = '' + noSubmit = False + CMake = (os.getenv('ROOTCORE_RELEASE_SERIES')=='25') # ROOTCORE_RELEASE_SERIES variable used to identify release (CMake required for R21) + mergeType = 'Default' #None, Default, xAOD + destSE = '' + memory = '2000' #in MB maxNFilesPerJob = '' - otherOptions = '' + otherOptions = '' + skipShowerCheck = False + nameShortener = basicInDSNameShortener # default shortener function + customTDPFile = None + reuseTarBall = False + checkPRW = False def details(self): - cutsFileIsARealFile = checkForFile(self.settingsFile) - txt = '(' + logger.FAIL + 'not found' + logger.ENDC + ')' - if cutsFileIsARealFile: - txt = '(exists)' - - print logger.OKBLUE + 'Analysis Settings:' + logger.ENDC - print ' -Code: ', self.code - print ' -CutsFile: ', self.settingsFile, txt - - print logger.OKBLUE + 'Grid Settings:' + logger.ENDC - print ' -GridUsername: ', self.gridUsername - print ' -Suffix: ', self.suffix - print ' -ExcludedSites: ', self.excludedSites - print ' -ForceSite: ', self.forceSite - print ' -NoSubmit: ', self.noSubmit - print ' -MergeType: ', self.mergeType, 'out of (None, Default, xAOD)' - print ' -memory: ', self.memory, 'in MB' - print ' -maxNFilesPerJob', self.maxNFilesPerJob - print ' -OtherOptions: ', self.otherOptions + txt = '(' + iconfigFile=0 + for configFile in self.settingsFile.split(','): + cutsFileIsARealFile = checkForFile(ROOT.PathResolver.find_file(configFile, "DATAPATH", ROOT.PathResolver.LocalSearch)) + if cutsFileIsARealFile: + txt += 'exists' + else: + txt += logger.FAIL + 'not found' + logger.ENDC + ')' + if iconfigFile!=len(self.settingsFile.split(','))-1: + txt += ',' + iconfigFile += 1 + txt += ')' + + print(logger.OKBLUE + 'Analysis Settings:' + logger.ENDC) + print(' -Code: ', self.code) + print(' -CutsFile: ', self.settingsFile, txt) + print(' -Combine_outputFile: ', self.combine_outputFile) + print(' -Combine_prefixes: ', self.combine_prefixes) + + if (self.groupProduction != None): + logger.WARNING + "Option groupProduction is obsolete. Production mode is deduced from gridUsername (e.g. if it's 'phys-top')." + logger.ENDC + if self.gridUsername.find('phys-') == 0: + self.groupProduction = True + txt = ' (group production)' + else: + self.groupProduction = False + txt = '' + print(logger.OKBLUE + 'Grid Settings:' + logger.ENDC) + print(' -GridUsername: ', self.gridUsername, txt) + print(' -Suffix: ', self.suffix) + print(' -ExcludedSites: ', self.excludedSites) + print(' -ForceSite: ', self.forceSite) + print(' -NoSubmit: ', self.noSubmit) + print(' -MergeType: ', self.mergeType, 'out of (None, Default, xAOD)') + print(' -memory: ', self.memory, 'in MB') + print(' -maxNFilesPerJob', self.maxNFilesPerJob) + print(' -skipShowerCheck', self.skipShowerCheck) + print(' -OtherOptions: ', self.otherOptions) + print(' -nameShortener: ', self.nameShortener) + print(' -reuseTarBall: ', self.reuseTarBall) + print(' -checkPRW: ', self.checkPRW) txt = self.destSE if len(txt) == 0: txt = '<not set>' - print ' -DestSE ', txt + print(' -DestSE ', txt) - print '' + print('') def checkMergeType(configuration): type = configuration.mergeType if type != "None" and type != "Default" and type != "xAOD": - print "MergeType must be set to either None, Default or xAOD" - print 'Not', type, "Since that doesn't make sense" + print("MergeType must be set to either None, Default or xAOD") + print('Not', type, "Since that doesn't make sense") sys.exit() #If settings.txt doesn't exist your grid job will fail @@ -122,9 +163,9 @@ def checkForFile(filename): def checkForPrun(): if distutils.spawn.find_executable('prun') == None: - print logger.FAIL + 'DANGER DANGER DANGER' + logger.ENDC - print 'Could not find prun. If you use setupATLAS (you should) then' - print '"localSetupPandaClient --noAthenaCheck" and run this again' + print(logger.FAIL + 'DANGER DANGER DANGER' + logger.ENDC) + print('Could not find prun. If you use setupATLAS (you should) then') + print('"localSetupPandaClient --noAthenaCheck" and run this again') sys.exit() #I see a crash if I setup with rcSetup Top,1.4.0 @@ -136,15 +177,15 @@ def findPackages(): debug = False if debug: - print 'finding packages' - print cmd + print('finding packages') + print(cmd) for l in os.popen(cmd).readlines(): if debug: - print l.strip() + print(l.strip()) if debug: - print 'done' + print('done') #Given a list of datasets, the command to run and a mode (egamma, muons) this #submits one prun job per run @@ -153,63 +194,113 @@ def submit(config, allSamples): checkForPrun() checkMergeType(config) config.details() - checkForShowerAlgorithm(allSamples) + if not config.skipShowerCheck: + for configFile in config.settingsFile.split(','): + checkForShowerAlgorithm(allSamples, configFile) + if config.checkPRW: + for configFile in config.settingsFile.split(','): + checkPRWFile(allSamples, configFile) tarfile = 'top-xaod.tar.gz' - #We don't want to use an old, out-of-date file - #Delete the file if it exists - try: - os.remove(tarfile) - except OSError, e: - #Number 2 is 'file doesn't exist' which is okay for us - if e.errno == 2: - pass - else: - raise + # Delete the old tarball if requested + if not config.reuseTarBall: + try: + os.remove(tarfile) + except OSError as e: + #Number 2 is 'file doesn't exist' which is okay for us + if e.errno == 2: + pass + else: + raise #Check for cuts file - if not checkForFile(config.settingsFile): - print logger.FAIL + "DANGER DANGER. HIGH VOLTAGE" + logger.ENDC - print '%s does not exist in this directory' % config.settingsFile - print 'please make it before submitting' - - if config.settingsFile == 'dil-cuts.txt' or config.settingsFile == 'ljets-cuts.txt': - print 'or... copy it with' - print 'cp $ROOTCOREBIN/data/TopAnalysis/%s .' % config.settingsFile - - sys.exit(1) - - #Look in the cuts file for the output filename - outputFilename = 'EMPTY' - for l in open(config.settingsFile): - #ignore text after comments - if l.find('#') > -1: - l = l.split('#')[0] - - if l.find('OutputFilename') > -1: - outputFilename = l.replace('OutputFilename', '').strip() - - if outputFilename == 'EMPTY': - print 'OutputFilename not found in %s' % config.settingsFile - sys.exit(1) + for configFile in config.settingsFile.split(','): + if not checkForFile(configFile): + print(logger.WARNING + " WARNING - Did not find config file %s in this dir "%(configFile) + logger.ENDC) + print(logger.WARNING + " - Attempt to find this file in a sensible location using PathResolver... " + logger.ENDC) + settingsFilePath = ROOT.PathResolver.find_file(configFile, "DATAPATH", ROOT.PathResolver.LocalSearch) + if settingsFilePath == "": + print(logger.FAIL + "DANGER DANGER. HIGH VOLTAGE" + logger.ENDC) + print('%s does not exist in this directory and cannot be found using PathResolver, exiting!' % configFile) + sys.exit(1) + else: + print(logger.WARNING + " - Found an appropriate file %s "%(settingsFilePath) + logger.ENDC) + + outputFiles = [] + for configFile in config.settingsFile.split(','): + settingsFilePath = ROOT.PathResolver.find_file(configFile, "DATAPATH", ROOT.PathResolver.LocalSearch) + + #Look in the cuts file for the output filename + outputFilename = 'EMPTY' + for l in open(settingsFilePath, "r"): + #ignore text after comments + if l.find('#') > -1: + l = l.split('#')[0] + if l.find('OutputFilename') > -1: + outputFilename = l.replace('OutputFilename', '').strip() + if outputFilename == 'EMPTY': + print(logger.FAIL + 'OutputFilename not found in ' + settingsFilePath + logger.ENDC) + sys.exit(1) + else: + outputFiles.append(outputFilename) + + outputFilenames='' # string defining the output file(s) + combineArgument='' # argument of command for combining the multiple output files, if need be + if len(outputFiles) == 0: # at this stage this shouldn't happen + print(logger.FAIL + 'No OutputFileName found' + logger.ENDC) + sys.exit(1) + elif len(outputFiles) ==1: # the simplest case + outF = outputFiles[0] + outputFilenames = outF.replace(".root","_root") + ":" + outF + else: # len(outputFiles) >=2: multiple output files, or a single combined one + # check if the output files are unique + if len(outputFiles) != len(set(outputFiles)): + print(logger.FAIL + 'Two of the output file names are identical. Check the config files (separated by commas).' + logger.ENDC) + sys.exit(1) + if config.combine_outputFile == None: # no combination asked + iconfigFile = 0 + for configFile in outputFiles: + cFile = configFile.replace(".root","_root") + ":" + configFile + outputFilenames += cFile + if iconfigFile != len(outputFiles)-1: + outputFilenames += ',' + iconfigFile += 1 + else: # combination of the multiple output files + # retrieving the prefixes + prefixes = config.combine_prefixes.split(',') + # check if the prefixes are unique + if len(prefixes) != len(set(prefixes)): + print(logger.FAIL + 'Two of the prefixes (separated by commas) are identical. Check the combine_prefixes option.' + logger.ENDC) + sys.exit(1) + # check if the prefixes and the output files have same length + if len(prefixes) != len(outputFiles): + print(logger.FAIL + 'When combining the outputs, there should be as many prefixes as there are output files (separated by commas). Check the combine_prefixes and settingsFile options.' + logger.ENDC) + sys.exit(1) + # using combined file name + outputFilenames = config.combine_outputFile.replace(".root","_root") + ":" + config.combine_outputFile + # building the input file argument of the combination + iconfigFile = 0 + for outFile in outputFiles: + combineArgument += outFile + combineArgument += ":" + combineArgument += prefixes[iconfigFile] + if iconfigFile != len(outputFiles)-1: + combineArgument += ',' + iconfigFile += 1 + - #print outputFilename + #print outputFilenames these = [] - print logger.OKBLUE + 'For these samples' + logger.ENDC + print(logger.OKBLUE + 'For these samples' + logger.ENDC) - #Only submit jobs if the dataset actually exists (check with rucio) for sample in allSamples: currentDatasets = sample.datasets actuallyExists = [] for ds in currentDatasets: - if checkDatasetExists(ds): - actuallyExists.append(ds) - - sample.details(actuallyExists) - these += actuallyExists + these.append(ds) #check if it's a release - which automatically would set rootVer and cmtConfig if not config.CMake: @@ -219,44 +310,48 @@ def submit(config, allSamples): if len(these) > 1: plural = 's' - print '' - print logger.OKBLUE + 'Starting submission of %d sample%s' % (len(these), plural) + logger.ENDC - print '' + print('') + print(logger.OKBLUE + 'Starting submission of %d sample%s' % (len(these), plural) + logger.ENDC) + print('') isfirst = True - for i, d in enumerate(these): - print logger.OKBLUE + 'Submitting %d of %d' % (i+1, len(these)) + logger.ENDC - - splitted = d.split('.') - - runNumber = splitted[1] - txt = splitted[2] - if splitted[0] == "user": - runNumber = splitted[2] - txt = splitted[3] - derivation = splitted[-2] - tags = splitted[-1].replace('/','') - - #grid complains dataset names are too long - #stupid grid - if len(txt) > 20: - txt = txt.split('_')[0] - - n = runNumber + '.' + txt + '.' + derivation + '.' + tags + for i, d_concatenated in enumerate(these): + d = getShortenedConcatenatedSample(d_concatenated) # in case of coma-separated list of samples with same DSID and same first tag of each type + print(logger.OKBLUE + 'Submitting %d of %d' % (i+1, len(these)) + logger.ENDC) #Make the output dataset name - output = 'user.' + config.gridUsername + '.' + n + '.' + config.suffix + #for group production it has to start with "group." and we asume that gridUsername is the name of the group (e.g. phys-top) + if config.groupProduction: + output = 'group.' + config.gridUsername + '.' + config.nameShortener(d) + '.' + config.suffix + else: + output = 'user.' + config.gridUsername + '.' + config.nameShortener(d) + '.' + config.suffix cmd = 'prun \\\n' - cmd += '--inDS=' + d + ' \\\n' + #special care for group production - we assume that gridUsername is the name of the group (e.g. phys-top) + if config.groupProduction: + cmd += '--official --voms atlas:/atlas/' + config.gridUsername + '/Role=production \\\n' + cmd += '--inDS=' + d_concatenated + ' \\\n' # the inDS may be a comma-separated list of samples with same DSID and same first tag of each type cmd += '--outDS=' + output + ' \\\n' if config.CMake: - cmd += '--useAthenaPackages --cmtConfig=x86_64-slc6-gcc49-opt \\\n' + CMTCONFIG = os.getenv("CMTCONFIG") + cmd += '--useAthenaPackages --cmtConfig=%s \\\n'%(CMTCONFIG) else: - cmd += '--useRootCore \\\n' + cmd += '--useRootCore \\\n' cmd += '--writeInputToTxt=IN:in.txt \\\n' - cmd += '--outputs=%s \\\n' % outputFilename - cmd += '--exec="%s %s in.txt" \\\n' % (config.code, config.settingsFile) + cmd += '--outputs=%s \\\n' % outputFilenames + # write the --exec commands - will possibly AnalysisTop several times + cmd += '--exec="' + iconfigFile=0 + for configFile in config.settingsFile.split(','): + cmd += '%s %s in.txt' % (config.code, configFile) + if iconfigFile!=len(config.settingsFile.split(','))-1: + cmd += '; ' + iconfigFile += 1 + elif combineArgument != '': + cmd += '; combineATOutputs ' + config.combine_outputFile + " " + combineArgument + cmd += '" \\\n' + else: + cmd += '" \\\n' #you might really hate a certain site if len(config.excludedSites) > 0: @@ -268,11 +363,19 @@ def submit(config, allSamples): #tar-up the first time only, to save time when submitting if isfirst: - cmd += '--outTarBall=%s \\\n' % tarfile + if checkForFile(tarfile) and config.reuseTarBall:# reuse existing tarball if it already exists + print(logger.OKBLUE + 'Reusing existing tarball %s' % (tarfile) + logger.ENDC) + cmd += '--inTarBall=%s \\\n' % tarfile + elif config.reuseTarBall:# reuse existing tarball if it already exists + print(logger.WARNING + 'Tarball %s not found - will re-create it' % (tarfile) + logger.ENDC) + cmd += '--outTarBall=%s \\\n' % tarfile + else: + cmd += '--outTarBall=%s \\\n' % tarfile isfirst = False else: cmd += '--inTarBall=%s \\\n' % tarfile + #maybe you don't want to submit the job? if config.noSubmit: cmd += '--noSubmit \\\n' @@ -307,17 +410,17 @@ def submit(config, allSamples): cmd += '\n' #show people what you're about to do - print cmd + print(cmd) #then do it for l in os.popen(cmd).readlines(): - print '>> ', l.strip() + print('>> ', l.strip()) #Make a directory if it doesn't exist def makeDirectory(outputDirectory): try: os.makedirs(outputDirectory) - print 'Made directory', outputDirectory + print('Made directory', outputDirectory) except: #directory already exists pass @@ -331,73 +434,190 @@ def convertAODtoTOPQ(derivationToUse, ptag, samples): for i, ds in enumerate(sample.datasets): sample.datasets[i] = ds.replace('AOD', derivationToUse).replace('/', '') + '_' + ptag -#Get a list of dataset names matching some pattern with stars in, using dq2-ls -def listDatasets(theScope, datasetPattern): - response = rucio.list_dids(scope = theScope, filters = {'name' : datasetPattern}) - - names = [] - for l in response: - names.append(l) - - return names - -#Download all datasets that match the pattern, to the outputDirectory -def download(theScope, datasetPattern, outputDirectory): - #Make sure the directory where these need to go exists - makeDirectory(outputDirectory) - - #Get datasets matching the pattern - intdatasets = listDatasets(theScope, datasetPattern) - txt = '' - if len(intdatasets) != 1: - txt = 's' - - print 'Found %d dataset%s:' % (len(intdatasets), txt) - - for ds in intdatasets: - print ' %s' % ds - - for j, d in enumerate(intdatasets): - cmd = 'rucio download %s:%s --dir %s' % (theScope, d, outputDirectory) - print logger.OKBLUE + 'Dataset %d of %d: %s' % (j+1, len(intdatasets), cmd) + logger.ENDC - - #Run the dq2 command - os.system(cmd) - -#Prun submits to datasets that don't exist, so do a quick check first... -def checkDatasetExists(name): - theScope = name.split('.')[0] - #name = 'data15_13TeV.00266904.physics_Main.merge.DAOD_TOPQ1.f594_m1435_p2361' - if theScope == "user" or theScope == "group": - theScope = name.split('.')[0] + "." + name.split('.')[1] - reply = listDatasets(theScope, name) - #print reply - return len(reply) == 1 - if __name__ == '__main__': - print "You don't run this directly!" - print 'For an example, see 01SubmitToGrid.py' + print("You don't run this directly!") + print('For an example, see 01SubmitToGrid.py') -def checkForShowerAlgorithm(Samples): +def checkForShowerAlgorithm(Samples, cutfile): + settingsFilePath = ROOT.PathResolver.find_file(cutfile, "DATAPATH", ROOT.PathResolver.LocalSearch) noShowerDatasets = [] - tdp = analysis.TopDataPreparation(os.getenv('ROOTCOREBIN') + '/data/TopDataPreparation/XSection-MC15-13TeV.data') + customTDPFile = None + tmp = open(settingsFilePath, "r") + for line in tmp.readlines(): + if "TDPPath" not in line: + continue + else: + customTDPFile = line.strip().split("TDPPath")[1] + break + print(customTDPFile) + if customTDPFile: + tdpFile = ROOT.PathResolver.find_calib_file(customTDPFile) + else: + tdpFile = ROOT.PathResolver.find_file("dev/AnalysisTop/TopDataPreparation/XSection-MC16-13TeV.data", "CALIBPATH", ROOT.PathResolver.RecursiveSearch) + # Load the file + print(tdpFile) + tdp = analysis.TopDataPreparation(tdpFile) for TopSample in availableDatasets.values(): for List in Samples: SublistSamples = List.datasets - for sample in SublistSamples: + for sample_concatenated in SublistSamples: + sample=getShortenedConcatenatedSample(sample_concatenated) # in the case of comma-separated samples with same DSIDs and same first tags (it's the same sample) scope = sample.split('.')[0] if 'mc' not in scope: continue dsid = sample.split('.')[1] dsid = int(dsid) - hasShower = tdp.getShower(dsid) in ['sherpa','sherpa21','pythia','pythia8','herwigpp'] + hasShower = tdp.getShower(dsid) in ['sherpa','sherpa21','pythia','pythia8','herwigpp','amcatnlopythia8', 'herwigpp713', 'sherpa228'] #print hasShower," ",sample if not tdp.hasID(dsid) or not hasShower: noShowerDatasets += [dsid] if len(noShowerDatasets) > 0: - print 'The following datasets do not have a showering algorithm defined in TopDataPreparation and will fail on the grid. Please ask for this to be fixed in TopDataPreparation!' + print('TopDataPreparation .data file specified in '+settingsFilePath+' was checked.') + print('The following datasets do not have a showering algorithm defined in TopDataPreparation and will fail on the grid. Please ask for this to be fixed in TopDataPreparation!') for ds in set(noShowerDatasets): - print ds + print(ds) raise RuntimeError("Datasets without shower.") + +def isAF2(dataset): + tags = dataset.split('.')[-1] + tagList = tags.split('_') + for tag in tagList: + if tag.find('a')>-1: + return True + return False + +def isData(dataset): + scope = dataset.split('.')[0] + if scope.find('data')>-1: + return True + else: + return False + +def checkPRWFile(Samples, cutfile): + # Some imports + import subprocess, shlex + + # We need to find the PRW files being used and make use of the checkPRW + # checkPRW.py --inDsTxt=my.datasets.txt path/to/prwConfigs/*.root + # First, find the PRW names from cutfile + settingsFilePath = ROOT.PathResolver.find_file(cutfile, "DATAPATH", ROOT.PathResolver.LocalSearch) + print(logger.OKBLUE + " - Processing checks for PRWConfig in " + settingsFilePath + logger.ENDC) + tmp = open(settingsFilePath, "r") + PRWConfig = None + PRWConfig_FS = None + PRWConfig_AF = None + for line in tmp.readlines(): + line = line.split('#', 1)[0].strip() + if line.startswith("PRWConfigFiles_AF"): + PRWConfig_AF = [ ROOT.PathResolver.find_file( x, "CALIBPATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] + PRWConfig_AF.extend( [ ROOT.PathResolver.find_file( x, "DATAPATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] ) + PRWConfig_AF.extend( [ ROOT.PathResolver.find_file( x, "PATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] ) + elif line.startswith("PRWConfigFiles_FS"): + PRWConfig_FS = [ ROOT.PathResolver.find_file( x, "CALIBPATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] + PRWConfig_FS.extend( [ ROOT.PathResolver.find_file( x, "DATAPATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] ) + PRWConfig_FS.extend( [ ROOT.PathResolver.find_file( x, "PATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] ) + elif line.startswith("PRWConfigFiles"): + PRWConfig = [ ROOT.PathResolver.find_file( x, "CALIBPATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] + PRWConfig.extend( [ ROOT.PathResolver.find_file( x, "DATAPATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] ) + PRWConfig.extend( [ ROOT.PathResolver.find_file( x, "PATH", ROOT.PathResolver.RecursiveSearch ) for x in line.split()[1:] ] ) + + if PRWConfig and PRWConfig_AF: + print(logger.FAIL + " - Problem in cutfile " + settingsFilePath + ": PRWConfigFiles is inconsistent with usage of PRWConfigFiles_AF" + logger.ENDC) + return + elif PRWConfig and PRWConfig_FS: + print(logger.FAIL + " - Problem in cutfile " + settingsFilePath + ": PRWConfigFiles is inconsistent with usage of PRWConfigFiles_FS" + logger.ENDC) + return + elif PRWConfig and not PRWConfig_FS and not PRWConfig_AF: + PRWConfig_FS = PRWConfig + PRWConfig_AF = PRWConfig + elif not PRWConfig and not PRWConfig_FS and not PRWConfig_AF: + print(logger.FAIL + " - Error reading PRWConfigFiles from cutfile" + logger.ENDC) + return + # else: we assume that PRWConfigFiles_FS and PRWConfigFiles_AF are set + + # Print the PRW files + print(logger.OKGREEN + "PRW files used for FS:" + logger.ENDC) + print(logger.OKGREEN + "\n".join(PRWConfig_FS) + logger.ENDC) + print(logger.OKGREEN + "PRW files used for AF2:" + logger.ENDC) + print(logger.OKGREEN + "\n".join(PRWConfig_AF) + logger.ENDC) + + # Create a temporary sample list + tmpFileNameFS = "samplesforprwcheck_FS.txt" + tmpOutFS = open(tmpFileNameFS,"w") + tmpFileNameAF = "samplesforprwcheck_AF.txt" + tmpOutAF = open(tmpFileNameAF,"w") + for List in Samples: + SublistSamples = List.datasets + for sample_concatenated in SublistSamples: # the listed samples may be comma-separated list of samples + for sample in sample_concatenated.split(','): # we need to check all of them, not just the first one + if (isData(sample)): + continue + else: + if not isAF2(sample): + tmpOutFS.write(sample+"\n") + else: + tmpOutAF.write(sample+"\n") + tmpOutFS.close() + tmpOutAF.close() + + # then do the check + if (os.path.getsize(tmpFileNameFS)): # what follows only makes sense if the file isn't empty + # Make the FS command + cmdFS = "checkPRW.py --inDsTxt %s %s"%(tmpFileNameFS, " ".join(PRWConfig_FS)) + print(logger.OKBLUE + " - Running command : " + cmdFS + logger.ENDC) + # Run + procFS = subprocess.Popen(shlex.split(cmdFS)) + procFS.wait() + else: + print(logger.OKBLUE + " - No PRWConfig check is needed for FS." + logger.ENDC) + if (os.path.getsize(tmpFileNameAF)): # what follows only makes sense if the file isn't empty + # Make the AF command + cmdAF = "checkPRW.py --inDsTxt %s %s"%(tmpFileNameAF, " ".join(PRWConfig_AF)) + print(logger.OKBLUE + " - Running command : " + cmdAF + logger.ENDC) + # Run + procAF = subprocess.Popen(shlex.split(cmdAF)) + procAF.wait() + else: + print(logger.OKBLUE + " - No PRWConfig check is needed for AF2." + logger.ENDC) + # At the moment, just print the output, but we need to learn what to catch also + +## gets the first AMI tag of a kind +def getFirstTag(tags,letter): + tagList = tags.split('_') + first = '' + for tag in tagList: + if tag.find(letter,0,1) != -1 and tag[1:].isdigit() and first == '': + first = tag + return first + + +# In MC16, a given DSID can have been "split" into several datasets, were some have more ami-tags +# This function takes as input a coma-separated list of datasets, and returns the name of the first sample if we are in such case +# It throws an error if the DSID of these datasets is different, or if the first ami-tag of each time is different for the different datasets +def getShortenedConcatenatedSample(sampleName): + samples = sampleName.split(',') + if len(samples) == 1: # the simplest case + return samples[0] + + # check if the DSIDs are all the same + DSID = samples[0].split('.')[1] + firstTagOfFirstSample = { 'e':'', 's':'', 'a':'', 'r':'', 'f':'', 'm':'', 'p':'', } + isFirstSample = True + for s in samples: + if s.split('.')[1] != DSID: + print(logger.FAIL + " Issue with this concatenated sample: " + sampleName + logger.ENDC) + print(logger.FAIL + " This syntax can only work if all dataset containers have the same DSID " + logger.ENDC) + raise RuntimeError("Issue with contatenated samples.") + AmiTags = s.split('.')[-1] + for tagType in firstTagOfFirstSample: + if firstTagOfFirstSample[tagType] == '' and isFirstSample: + firstTagOfFirstSample[tagType] = getFirstTag(AmiTags,tagType) + elif firstTagOfFirstSample[tagType] != getFirstTag(AmiTags,tagType): + print(logger.FAIL + " Issue with this concatenated sample: " + sampleName + logger.ENDC) + print(logger.FAIL + " This syntax can only work if all dataset containers have the same first tag of each type " + logger.ENDC) + print(logger.FAIL + " And it seems there are two samples in this list, one with " + firstTagOfFirstSample[tagType] + " and one with " + getFirstTag(AmiTags,tagType) + " as first " + tagType + "-tag" + logger.ENDC) + raise RuntimeError("Issue with contatenated samples.") + isFirstSample = False + return samples[0] # if we survived all the tests, return the first of the list diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/logger.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/logger.py index e34f34601a339cf44f8d0781cbd7aa665bb57e9a..5461d70ea7f7a1de2a5d00efa5004a7524efe48a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/logger.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/logger.py @@ -3,6 +3,6 @@ HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' -WARNING = '\033[93m' +WARNING = '\033[33m' FAIL = '\033[91m' -ENDC = '\033[m' \ No newline at end of file +ENDC = '\033[m' diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/plot.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/plot.py index dca8f4cb7181e4a7b8216ff3025f41e92eed93e3..dde501e1a954ffc752d42884440bbf567f0e0b8d 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/plot.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/plot.py @@ -14,9 +14,9 @@ ROOT.gROOT.SetBatch(True) def makeDirectory(outputDirectory): try: os.makedirs(outputDirectory) - print 'Made directory', outputDirectory + print('Made directory', outputDirectory) except: - print 'directory already exists:', outputDirectory + print('directory already exists:', outputDirectory) pass class Proc: @@ -42,9 +42,9 @@ class Plotter: makeDirectory(self.imgDirectory) - print logger.OKBLUE +'Stack configuration'+ logger.ENDC + print(logger.OKBLUE +'Stack configuration'+ logger.ENDC) for currentProcess in stack: - print ' Name %s Colour %d Caption %s' % (currentProcess.name, currentProcess.colour, currentProcess.caption) + print(' Name %s Colour %d Caption %s' % (currentProcess.name, currentProcess.colour, currentProcess.caption)) def doneAndDusted(self): self.out.write('</html>\n') @@ -54,7 +54,7 @@ class Plotter: if not self.files.has_key(fileName): f = ROOT.TFile.Open(fileName) if not f: - print logger.FAIL + 'Failed to open %s' % fileName + logger.ENDC + print(logger.FAIL + 'Failed to open %s' % fileName + logger.ENDC) raise Exception('Failed to open %s' % fileName) self.files[fileName] = f @@ -81,7 +81,7 @@ class Plotter: return legend def plot(self, histName): - print 'plotting ', histName + print('plotting ', histName) self.c1.Clear() entries = [] diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/web.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/web.py index 4628028985ab7811dbf9817b22ed465217e7598b..d64280be04b4af4476a91af4b6e20b191b1cb0b4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/web.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/python/web.py @@ -27,10 +27,10 @@ def makeDict(scope, query): def makeTable(name, ids): - print '---++ %s (%d)' % (name, len(ids)) + print('---++ %s (%d)' % (name, len(ids))) - print '''%TABLE{tablewidth="100%" columnwidths="6%,70%,12%,12%"}%''' - print '| %8s | %60s | %22s | %22s | %22s | %22s |' % ( '*DSID*', '*Description*', '*Primary xAOD yield*', '*TOPQ1 yield*', '*Primary size [GB]*', '*xAOD size [GB]*' ) + print('''%TABLE{tablewidth="100%" columnwidths="6%,70%,12%,12%"}%''') + print('| %8s | %60s | %22s | %22s | %22s | %22s |' % ( '*DSID*', '*Description*', '*Primary xAOD yield*', '*TOPQ1 yield*', '*Primary size [GB]*', '*xAOD size [GB]*' )) for id in ids: dsids_sofar.append(id) @@ -96,35 +96,17 @@ def makeTable(name, ids): topq1_size_txt = "%15d (%0.0f%%)" % (topq1_size * toGB, frac) - print '| %d|%s| %d| %s| %4.2f| %s|' % (id, twisty, aod_yield, topq1_yield_txt, aod_size * toGB, topq1_size_txt) + print('| %d|%s| %d| %s| %4.2f| %s|' % (id, twisty, aod_yield, topq1_yield_txt, aod_size * toGB, topq1_size_txt)) - print '' + print('') if __name__ == '__main__': query = '*.AOD.*_r5591_r5625' query13 = '*.merge.AOD.*_r5787_r5853' - print '%TOC%' + print('%TOC%') - print ''' -On this page we have listed the main DC14 samples. You can find more details on -the DC14StartPage and DC14DataMCSampleInfo. - -For 8 !TeV we list - * *Primary xAOD:* =%s= - * *TOPQ1:* =%s= - -For 13 !TeV we list - * *Primary xAOD:* =%s= - * *TOPQ1:* =%s= - -For more details on which containers are removed see TopDerivations. -No event selection is currently applied to MC in TOPQ1. -Since the only difference between TOPQ1 and TOPQ2 is the event selection we -don't make TOPQ2 for MC. -''' % (query, query.replace('AOD','DAOD_TOPQ1') + '_p1854', query13, query13.replace('AOD','DAOD_TOPQ1') + '_p1852') - - print '---+ Introduction' + print('---+ Introduction') aods_idtag, aods_idonly = makeDict('mc14_8TeV', query) topq1_idtag, topq1_idonly = makeDict('mc14_8TeV', query.replace('AOD','DAOD_TOPQ1') + '_p1854') @@ -138,7 +120,7 @@ don't make TOPQ2 for MC. #sys.exit() dsids_sofar = [] - print '---+ 8 !TeV' + print('---+ 8 !TeV') makeTable('ttbar', [117050]) makeTable('single top', [110101, 110119, 110140]) @@ -163,7 +145,7 @@ don't make TOPQ2 for MC. dsids_sofar = [] - print '---+ 13 !TeV' + print('---+ 13 !TeV') makeTable('ttbar', [110401]) makeTable('single top', [110070, 110071, 110305]) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/01SubmitToGrid.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/01SubmitToGrid.py index 33a6e28001b324b8370ae9b36eaa03c7dc897e93..e37a7f43a8b7725513ec394d9497bdf9eb310f80 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/01SubmitToGrid.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/01SubmitToGrid.py @@ -1,23 +1,40 @@ #!/usr/bin/env python -# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration import TopExamples.grid import DerivationTags -import Data -import MC15c_TOPQ1 +import Data_rel21 +import MC16_TOPQ1 + +## fancy function to shorten the physics part of the name of a sample +#def MyFancyShortener(superLongInDSName): + #splitted = superLongInDSName.split('.') + #runNumber = splitted[1] + #physicsName = splitted[2] + #if splitted[0] == "user" or splitted[0] == "group": #this is in case we run on private derivations, either produced with user or group role + #runNumber = splitted[2] + #physicsName = splitted[3] + #tags = splitted[-1].replace('/','') + #physicsName = physicsName.split('_')[0] + #outDSName = runNumber + '.' + physicsName + '.someFunnyTags' + #return outDSName config = TopExamples.grid.Config() config.code = 'top-xaod' -config.settingsFile = 'dil-cuts.txt' +config.settingsFile = 'validation-cuts.txt' +#config.settingsFile = 'validation-cuts_Topo.txt,validation-cuts_PFlow.txt' +#config.combine_outputFile = 'out.root' +#config.combine_prefixes = 'Topo,PFlow' -config.gridUsername = 'aknue' -config.suffix = '02-04-24' +config.gridUsername = 'iconnell' # use e.g. phys-top or phys-higgs for group production +config.suffix = '17-10-03' config.excludedSites = '' config.noSubmit = False config.mergeType = 'Default' #'None', 'Default' or 'xAOD' config.destSE = '' #This is the default (anywhere), or try e.g. 'UKI-SOUTHGRID-BHAM-HEP_LOCALGROUPDISK' # by default the requested memory is set to 2GB, if you need to increase this, please disable the line below!!! # config.memory = '4000' +#config.nameShortener = MyFancyShortener # to use your own physics part shortening function - uncomment here and in the function definition above ############################################################################### @@ -32,26 +49,31 @@ config.destSE = '' #This is the default (anywhere), or try e.g. 'UKI-SOUT ############################################################################### -# Data - look in Data.py -# Change if you want TOPQ2/3/4 -names = ['Data15_TOPQ1', 'Data16_TOPQ1'] +# Data - look in Data_rel21.py +# Change if you want TOPQ2/3/4/5 +names = ['Data15_TOPQ1', + 'Data16_TOPQ1', + 'Data17_TOPQ1'] samples = TopExamples.grid.Samples(names) +TopExamples.ami.check_sample_status(samples) # Call with (samples, True) to halt on error TopExamples.grid.submit(config, samples) ############################################################################### -###MC Simulation - look in MC15c_TOPQ1.py +###MC Simulation - look in MC16_TOPQ1.py ###Using list of TOPQ1 25ns MC samples, consistent mixture of p-tags ###Edit these lines if you don't want to run everything! -names = [ - 'TOPQ1_ttbar_PowPy6', - 'TOPQ1_singleTop_PowPy6', - 'TOPQ1_ttV', - 'TOPQ1_Wjets_Sherpa221', - 'TOPQ1_Zjets_Sherpa221', - 'TOPQ1_Diboson_Sherpa', -] - +names = ['TOPQ1_ttbar_PowPy8', + 'TOPQ1_ttbar_dil_PowPy8', + 'TOPQ1_tchan_lep_PowPy6', + 'TOPQ1_Wt_inc_PowPy6', + 'TOPQ1_schan_noAllHad_PowPy6', + 'TOPQ1_diboson_Sherpa', + 'TOPQ1_Zjets_Sherpa221', + 'TOPQ1_Wjets_Sherpa221', + 'TOPQ1_ttV', + ] samples = TopExamples.grid.Samples(names) +TopExamples.ami.check_sample_status(samples) # Call with (samples, True) to halt on error TopExamples.grid.submit(config, samples) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/Data_rel21.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/Data_rel21.py index f9593fb3a49b205d1d3520cbd1b80f20113934f1..b8495f2ecce188402d91fd879746fcfcb48475b1 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/Data_rel21.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/Data_rel21.py @@ -3,17 +3,336 @@ import TopExamples.grid import TopExamples.ami -# Just a few runs processed with 21.0.19.2 -DATA16 = [ - 'data16_13TeV.00297730.physics_Main.deriv.DAOD_{}.r9264_p3083_p3142', - 'data16_13TeV.00304008.physics_Main.deriv.DAOD_{}.r9264_p3083_p3142', - 'data16_13TeV.00307126.physics_Main.deriv.DAOD_{}.r9264_p3083_p3142', - 'data16_13TeV.00311071.physics_Main.deriv.DAOD_{}.r9264_p3083_p3142', - 'data16_13TeV.00311287.physics_Main.deriv.DAOD_{}.r9264_p3083_p3142', - 'data16_13TeV.00311321.physics_Main.deriv.DAOD_{}.r9264_p3083_p3142', - ] +# Period containers +DATA15 = ['data15_13TeV.periodA.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodC.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodD.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodE.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodF.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodG.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodH.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180', + 'data15_13TeV.periodJ.physics_Main.PhysCont.DAOD_{}.grp15_v01_p3180',] + +DATA16 = ['data16_13TeV.periodA.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodB.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodC.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodD.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodE.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodF.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodG.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodI.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodK.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180', + 'data16_13TeV.periodL.physics_Main.PhysCont.DAOD_{}.grp16_v01_p3180',] + +DATA17 = ['data17_13TeV.periodB.physics_Main.PhysCont.DAOD_{}.grp17_v01_p3213', + 'data17_13TeV.periodC.physics_Main.PhysCont.DAOD_{}.grp17_v01_p3213', + 'data17_13TeV.periodD.physics_Main.PhysCont.DAOD_{}.grp17_v01_p3267', + 'data17_13TeV.periodE.physics_Main.PhysCont.DAOD_{}.grp17_v01_p3267', + # Period F is waiting for feedback on the runs to use... + ] + +DATA15RUN = [ 'data15_13TeV.00276689.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284006.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271048.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270806.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281381.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284427.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00283780.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279867.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00282784.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279928.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276336.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276731.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271516.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276329.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276416.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279284.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270953.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276511.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276245.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00283608.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276952.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00282992.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00267152.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281143.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279345.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279259.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280423.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270816.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00283074.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280319.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276073.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280977.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280368.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271388.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00267073.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280673.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281070.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279685.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281411.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284285.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276161.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281385.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276212.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281317.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00267167.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276790.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279813.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276183.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280500.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00278912.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279932.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00283155.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00278968.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00282631.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284473.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00266919.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276954.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00266904.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281130.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00283270.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281075.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00278748.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280464.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276189.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00281074.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271421.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284484.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279169.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271744.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280520.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280950.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270588.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279279.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279764.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00267162.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270949.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280273.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276330.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280614.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280853.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00282625.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276262.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279515.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270448.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00278727.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00267639.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00278970.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00270441.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00278880.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280231.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276176.physics_Main.deriv.DAOD_{}.r9412_p3083_p3180', + 'data15_13TeV.00282712.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271595.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280862.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276778.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279598.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276181.physics_Main.deriv.DAOD_{}.r9412_p3083_p3180', + 'data15_13TeV.00283429.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284420.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284154.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00279984.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00267638.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00284213.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00271298.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00280753.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data15_13TeV.00276147.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + ] + +# all data16 runs available with 21.0.19.4 + +DATA16RUN = [ 'data16_13TeV.00297730.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298595.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298609.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298633.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298687.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298690.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298771.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298773.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298862.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00298967.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299055.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299144.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299147.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299184.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299241.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299243.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299288.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299343.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00299584.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300279.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300345.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300415.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300418.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300487.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300540.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300571.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300600.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300655.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300687.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300784.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300800.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300863.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00300908.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00301912.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00301915.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00301918.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00301932.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00301973.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302053.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302137.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302265.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302269.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302300.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302347.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302380.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302391.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302393.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302737.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302829.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302831.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302872.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302919.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302925.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00302956.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303007.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303059.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303079.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303201.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303208.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303264.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303266.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303291.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303304.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303338.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303421.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303499.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303560.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303638.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303832.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303846.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303892.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00303943.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304006.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304008.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304128.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304178.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304198.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304211.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304243.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304308.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304337.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304409.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304431.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00304494.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305380.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305543.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305571.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305618.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305671.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305674.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305723.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305727.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305735.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305777.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305811.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00305920.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306269.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306278.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306310.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306384.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306419.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306442.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306448.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00306451.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307126.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307195.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307259.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307306.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307354.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307358.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307394.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307454.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307514.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307539.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307569.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307601.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307619.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307656.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307710.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307716.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307732.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307861.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00307935.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00308047.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00308084.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309375.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309390.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309440.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309516.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309640.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309674.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00309759.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310015.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310247.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310249.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310341.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310370.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310405.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310468.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310473.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310634.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310691.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310738.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310809.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310863.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310872.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00310969.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311071.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311170.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311244.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311287.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311321.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311365.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311402.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311473.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + 'data16_13TeV.00311481.physics_Main.deriv.DAOD_{}.r9264_p3083_p3180', + ] + +# Use the period containers which have removed duplicate runs with different tags +DATA17RUN = [ ] + +# Individual runs +TopExamples.grid.Add('Data15Runs_TOPQ1').datasets = [i.format('TOPQ1') for i in DATA15RUN] +TopExamples.grid.Add('Data15Runs_TOPQ2').datasets = [i.format('TOPQ2') for i in DATA15RUN] +TopExamples.grid.Add('Data15Runs_TOPQ3').datasets = [i.format('TOPQ3') for i in DATA15RUN] +TopExamples.grid.Add('Data15Runs_TOPQ4').datasets = [i.format('TOPQ4') for i in DATA15RUN] +TopExamples.grid.Add('Data15Runs_TOPQ5').datasets = [i.format('TOPQ5') for i in DATA15RUN] + +TopExamples.grid.Add('Data16Runs_TOPQ1').datasets = [i.format('TOPQ1') for i in DATA16RUN] +TopExamples.grid.Add('Data16Runs_TOPQ2').datasets = [i.format('TOPQ2') for i in DATA16RUN] +TopExamples.grid.Add('Data16Runs_TOPQ3').datasets = [i.format('TOPQ3') for i in DATA16RUN] +TopExamples.grid.Add('Data16Runs_TOPQ4').datasets = [i.format('TOPQ4') for i in DATA16RUN] +TopExamples.grid.Add('Data16Runs_TOPQ5').datasets = [i.format('TOPQ5') for i in DATA16RUN] + +TopExamples.grid.Add('Data17Runs_TOPQ1').datasets = [i.format('TOPQ1') for i in DATA17RUN] +TopExamples.grid.Add('Data17Runs_TOPQ2').datasets = [i.format('TOPQ2') for i in DATA17RUN] +TopExamples.grid.Add('Data17Runs_TOPQ3').datasets = [i.format('TOPQ3') for i in DATA17RUN] +TopExamples.grid.Add('Data17Runs_TOPQ4').datasets = [i.format('TOPQ4') for i in DATA17RUN] +TopExamples.grid.Add('Data17Runs_TOPQ5').datasets = [i.format('TOPQ5') for i in DATA17RUN] + +# Period containers - preferred choice +TopExamples.grid.Add('Data15_TOPQ1').datasets = [i.format('TOPQ1') for i in DATA15] +TopExamples.grid.Add('Data15_TOPQ2').datasets = [i.format('TOPQ2') for i in DATA15] +TopExamples.grid.Add('Data15_TOPQ3').datasets = [i.format('TOPQ3') for i in DATA15] +TopExamples.grid.Add('Data15_TOPQ4').datasets = [i.format('TOPQ4') for i in DATA15] TopExamples.grid.Add('Data16_TOPQ1').datasets = [i.format('TOPQ1') for i in DATA16] TopExamples.grid.Add('Data16_TOPQ2').datasets = [i.format('TOPQ2') for i in DATA16] TopExamples.grid.Add('Data16_TOPQ3').datasets = [i.format('TOPQ3') for i in DATA16] TopExamples.grid.Add('Data16_TOPQ4').datasets = [i.format('TOPQ4') for i in DATA16] + +TopExamples.grid.Add('Data17_TOPQ1').datasets = [i.format('TOPQ1') for i in DATA17] +TopExamples.grid.Add('Data17_TOPQ2').datasets = [i.format('TOPQ2') for i in DATA17] +TopExamples.grid.Add('Data17_TOPQ3').datasets = [i.format('TOPQ3') for i in DATA17] +TopExamples.grid.Add('Data17_TOPQ4').datasets = [i.format('TOPQ4') for i in DATA17] diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/MC16_TOPQ1.py b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/MC16_TOPQ1.py index ff488b4cc8afbc19d61a60f5ed9d9d54230d5675..62d3afbd821d3f99a349e1135f5800a8e4a793dd 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/MC16_TOPQ1.py +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/MC16_TOPQ1.py @@ -2,7 +2,207 @@ import TopExamples.grid -# just a test sample processed with 21.0.19.2+DerivationFrameworkTop-00-04-06 TopExamples.grid.Add("TOPQ1_ttbar_PowPy8").datasets = [ - "group.phys-top.mc15_13TeV.410501.PowPy8EG_A14_ttbar_hdamp258p75_lep.DAOD_TOPQ1.AOD.e5458_s3126_r9364_r9315_p3144.v1_EXT0", - ] \ No newline at end of file + 'mc16_13TeV.410501.PowhegPythia8EvtGen_A14_ttbar_hdamp258p75_nonallhad.deriv.DAOD_TOPQ1.e5458_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_ttbar_dil_PowPy8").datasets = [ + 'mc16_13TeV.410503.PowhegPythia8EvtGen_A14_ttbar_hdamp258p75_dil.deriv.DAOD_TOPQ1.e5475_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_tchan_lep_PowPy6").datasets = [ + 'mc16_13TeV.410011.PowhegPythiaEvtGen_P2012_singletop_tchan_lept_top.deriv.DAOD_TOPQ1.e3824_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410012.PowhegPythiaEvtGen_P2012_singletop_tchan_lept_antitop.deriv.DAOD_TOPQ1.e3824_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_Wt_inc_PowPy6").datasets = [ + 'mc16_13TeV.410013.PowhegPythiaEvtGen_P2012_Wt_inclusive_top.deriv.DAOD_TOPQ1.e3753_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410014.PowhegPythiaEvtGen_P2012_Wt_inclusive_antitop.deriv.DAOD_TOPQ1.e3753_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_schan_noAllHad_PowPy6").datasets = [ + 'mc16_13TeV.410025.PowhegPythiaEvtGen_P2012_SingleTopSchan_noAllHad_top.deriv.DAOD_TOPQ1.e3998_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410026.PowhegPythiaEvtGen_P2012_SingleTopSchan_noAllHad_antitop.deriv.DAOD_TOPQ1.e3998_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_tZ_noAllHad_PowPy6").datasets = [ + 'mc16_13TeV.410560.MadGraphPythia8EvtGen_A14_tZ_4fl_tchan_noAllHad.deriv.DAOD_TOPQ1.e5803_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_tZ_trilepton_PowPy6").datasets = [ + 'mc16_13TeV.410550.MadGraphPythia8EvtGen_A14_tZ_4fl_tchan_trilepton.deriv.DAOD_TOPQ1.e5803_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_tWZ").datasets = [ + 'mc16_13TeV.410217.aMcAtNloHerwigppEvtGen_UEEE5_CTEQ6L1_CT10ME_260000_tWZDR.deriv.DAOD_TOPQ1.e4851_s3126_r9364_r9315_p3215', + ] + + +TopExamples.grid.Add("TOPQ1_ttbargamma").datasets = [ + 'mc16_13TeV.410082.MadGraphPythia8EvtGen_A14NNPDF23LO_ttgamma_noallhad.deriv.DAOD_TOPQ1.e4404_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_photons").datasets = [ + 'mc16_13TeV.301535.Sherpa_CT10_eegammaPt10_35.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301536.Sherpa_CT10_mumugammaPt10_35.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301899.Sherpa_CT10_eegammaPt35_70.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301900.Sherpa_CT10_eegammaPt70_140.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301901.Sherpa_CT10_eegammaPt140.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301902.Sherpa_CT10_mumugammaPt35_70.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301903.Sherpa_CT10_mumugammaPt70_140.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.301904.Sherpa_CT10_mumugammaPt140.deriv.DAOD_TOPQ1.e3952_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364510.Sherpa_222_NNPDF30NNLO_tautaugamma_pty_7_15.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364511.Sherpa_222_NNPDF30NNLO_tautaugamma_pty_15_35.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364512.Sherpa_222_NNPDF30NNLO_tautaugamma_pty_35_70.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364513.Sherpa_222_NNPDF30NNLO_tautaugamma_pty_70_140.deriv.DAOD_TOPQ1.e5982_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364514.Sherpa_222_NNPDF30NNLO_tautaugamma_pty_140_E_CMS.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364517.Sherpa_222_NNPDF30NNLO_nunugamma_pty_35_70.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364518.Sherpa_222_NNPDF30NNLO_nunugamma_pty_70_140.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364519.Sherpa_222_NNPDF30NNLO_nunugamma_pty_140_E_CMS.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364521.Sherpa_222_NNPDF30NNLO_enugamma_pty_7_15.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364523.Sherpa_222_NNPDF30NNLO_enugamma_pty_35_70.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364524.Sherpa_222_NNPDF30NNLO_enugamma_pty_70_140.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364525.Sherpa_222_NNPDF30NNLO_enugamma_pty_140_E_CMS.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364526.Sherpa_222_NNPDF30NNLO_munugamma_pty_7_15.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364528.Sherpa_222_NNPDF30NNLO_munugamma_pty_35_70.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364529.Sherpa_222_NNPDF30NNLO_munugamma_pty_70_140.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364530.Sherpa_222_NNPDF30NNLO_munugamma_pty_140_E_CMS.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364531.Sherpa_222_NNPDF30NNLO_taunugamma_pty_7_15.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364533.Sherpa_222_NNPDF30NNLO_taunugamma_pty_35_70.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364534.Sherpa_222_NNPDF30NNLO_taunugamma_pty_70_140.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364535.Sherpa_222_NNPDF30NNLO_taunugamma_pty_140_E_CMS.deriv.DAOD_TOPQ1.e5928_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_diboson_Sherpa").datasets = [ + 'mc16_13TeV.363355.Sherpa_221_NNPDF30NNLO_ZqqZvv.deriv.DAOD_TOPQ1.e5525_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363356.Sherpa_221_NNPDF30NNLO_ZqqZll.deriv.DAOD_TOPQ1.e5525_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363357.Sherpa_221_NNPDF30NNLO_WqqZvv.deriv.DAOD_TOPQ1.e5525_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363358.Sherpa_221_NNPDF30NNLO_WqqZll.deriv.DAOD_TOPQ1.e5525_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363359.Sherpa_221_NNPDF30NNLO_WpqqWmlv.deriv.DAOD_TOPQ1.e5583_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363360.Sherpa_221_NNPDF30NNLO_WplvWmqq.deriv.DAOD_TOPQ1.e5583_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363360.Sherpa_221_NNPDF30NNLO_WplvWmqq.deriv.DAOD_TOPQ1.e5983_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363489.Sherpa_221_NNPDF30NNLO_WlvZqq.deriv.DAOD_TOPQ1.e5525_s3126_r9364_r9315_p3215', + 'mc16_13TeV.363494.Sherpa_221_NNPDF30NNLO_vvvv.deriv.DAOD_TOPQ1.e5332_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364250.Sherpa_222_NNPDF30NNLO_llll.deriv.DAOD_TOPQ1.e5894_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364253.Sherpa_222_NNPDF30NNLO_lllv.deriv.DAOD_TOPQ1.e5916_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364254.Sherpa_222_NNPDF30NNLO_llvv.deriv.DAOD_TOPQ1.e5916_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364255.Sherpa_222_NNPDF30NNLO_lvvv.deriv.DAOD_TOPQ1.e5916_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_Zjets_Sherpa221").datasets = [ + 'mc16_13TeV.364100.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV0_70_CVetoBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364101.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV0_70_CFilterBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364102.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364103.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV70_140_CVetoBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364104.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV70_140_CFilterBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364105.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV70_140_BFilter.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364106.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV140_280_CVetoBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364107.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV140_280_CFilterBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364108.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV140_280_BFilter.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364109.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV280_500_CVetoBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364110.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV280_500_CFilterBVeto.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364111.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV280_500_BFilter.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364112.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV500_1000.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364113.Sherpa_221_NNPDF30NNLO_Zmumu_MAXHTPTV1000_E_CMS.deriv.DAOD_TOPQ1.e5271_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364114.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV0_70_CVetoBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364115.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV0_70_CFilterBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364116.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364117.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV70_140_CVetoBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364118.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV70_140_CFilterBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364119.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV70_140_BFilter.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364120.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV140_280_CVetoBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364121.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV140_280_CFilterBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364122.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV140_280_BFilter.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364123.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV280_500_CVetoBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364124.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV280_500_CFilterBVeto.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364125.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV280_500_BFilter.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364126.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV500_1000.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364127.Sherpa_221_NNPDF30NNLO_Zee_MAXHTPTV1000_E_CMS.deriv.DAOD_TOPQ1.e5299_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364128.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV0_70_CVetoBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364129.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV0_70_CFilterBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364130.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364131.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV70_140_CVetoBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364132.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV70_140_CFilterBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364133.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV70_140_BFilter.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364134.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV140_280_CVetoBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364135.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV140_280_CFilterBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364136.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV140_280_BFilter.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364137.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV280_500_CVetoBVeto.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364138.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV280_500_CFilterBVeto.deriv.DAOD_TOPQ1.e5313_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364139.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV280_500_BFilter.deriv.DAOD_TOPQ1.e5313_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364140.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV500_1000.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364141.Sherpa_221_NNPDF30NNLO_Ztautau_MAXHTPTV1000_E_CMS.deriv.DAOD_TOPQ1.e5307_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364198.Sherpa_221_NN30NNLO_Zmm_Mll10_40_MAXHTPTV0_70_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364199.Sherpa_221_NN30NNLO_Zmm_Mll10_40_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364200.Sherpa_221_NN30NNLO_Zmm_Mll10_40_MAXHTPTV70_280_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364201.Sherpa_221_NN30NNLO_Zmm_Mll10_40_MAXHTPTV70_280_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364202.Sherpa_221_NN30NNLO_Zmm_Mll10_40_MAXHTPTV280_E_CMS_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364203.Sherpa_221_NN30NNLO_Zmm_Mll10_40_MAXHTPTV280_E_CMS_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364204.Sherpa_221_NN30NNLO_Zee_Mll10_40_MAXHTPTV0_70_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364205.Sherpa_221_NN30NNLO_Zee_Mll10_40_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364206.Sherpa_221_NN30NNLO_Zee_Mll10_40_MAXHTPTV70_280_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364207.Sherpa_221_NN30NNLO_Zee_Mll10_40_MAXHTPTV70_280_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364208.Sherpa_221_NN30NNLO_Zee_Mll10_40_MAXHTPTV280_E_CMS_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364209.Sherpa_221_NN30NNLO_Zee_Mll10_40_MAXHTPTV280_E_CMS_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364210.Sherpa_221_NN30NNLO_Ztt_Mll10_40_MAXHTPTV0_70_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364211.Sherpa_221_NN30NNLO_Ztt_Mll10_40_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364212.Sherpa_221_NN30NNLO_Ztt_Mll10_40_MAXHTPTV70_280_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364213.Sherpa_221_NN30NNLO_Ztt_Mll10_40_MAXHTPTV70_280_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364214.Sherpa_221_NN30NNLO_Ztt_Mll10_40_MAXHTPTV280_E_CMS_BVeto.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364215.Sherpa_221_NN30NNLO_Ztt_Mll10_40_MAXHTPTV280_E_CMS_BFilter.deriv.DAOD_TOPQ1.e5421_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_Wjets_Sherpa221").datasets = [ + 'mc16_13TeV.364156.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV0_70_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364157.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV0_70_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364158.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364159.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV70_140_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364160.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV70_140_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364161.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV70_140_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364162.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV140_280_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364163.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV140_280_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364164.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV140_280_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364165.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV280_500_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364166.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV280_500_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364167.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV280_500_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364168.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV500_1000.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364169.Sherpa_221_NNPDF30NNLO_Wmunu_MAXHTPTV1000_E_CMS.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364170.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV0_70_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364171.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV0_70_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364172.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364173.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV70_140_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364174.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV70_140_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364175.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV70_140_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364176.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV140_280_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364177.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV140_280_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364178.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV140_280_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364179.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV280_500_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364180.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV280_500_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364181.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV280_500_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364182.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV500_1000.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364183.Sherpa_221_NNPDF30NNLO_Wenu_MAXHTPTV1000_E_CMS.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364184.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV0_70_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364185.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV0_70_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364186.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV0_70_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364187.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV70_140_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364188.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV70_140_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364189.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV70_140_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364190.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV140_280_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364191.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV140_280_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364192.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV140_280_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364193.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV280_500_CVetoBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364194.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV280_500_CFilterBVeto.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364195.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV280_500_BFilter.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364196.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV500_1000.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + 'mc16_13TeV.364197.Sherpa_221_NNPDF30NNLO_Wtaunu_MAXHTPTV1000_E_CMS.deriv.DAOD_TOPQ1.e5340_s3126_r9364_r9315_p3215', + ] + +TopExamples.grid.Add("TOPQ1_ttV").datasets = [ + 'mc16_13TeV.410081.MadGraphPythia8EvtGen_A14NNPDF23_ttbarWW.deriv.DAOD_TOPQ1.e4111_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410155.aMcAtNloPythia8EvtGen_MEN30NLO_A14N23LO_ttW.deriv.DAOD_TOPQ1.e5070_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410156.aMcAtNloPythia8EvtGen_MEN30NLO_A14N23LO_ttZnunu.deriv.DAOD_TOPQ1.e5070_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410157.aMcAtNloPythia8EvtGen_MEN30NLO_A14N23LO_ttZqq.deriv.DAOD_TOPQ1.e5070_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410218.aMcAtNloPythia8EvtGen_MEN30NLO_A14N23LO_ttee.deriv.DAOD_TOPQ1.e5070_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410219.aMcAtNloPythia8EvtGen_MEN30NLO_A14N23LO_ttmumu.deriv.DAOD_TOPQ1.e5070_s3126_r9364_r9315_p3215', + 'mc16_13TeV.410220.aMcAtNloPythia8EvtGen_MEN30NLO_A14N23LO_tttautau.deriv.DAOD_TOPQ1.e5070_s3126_r9364_r9315_p3215', + ] diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/getExamples b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/getExamples index 71008675d5497606523cc5a69306eebd5fc73bac..875d6375cc7ed96cd9c34ec123f039238e76be2e 100755 --- a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/getExamples +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/scripts/getExamples @@ -1,6 +1,8 @@ #!/usr/bin/env python import sys import os +import ROOT +from PathResolver import PathResolver output = os.getcwd() + '/grid' if len(sys.argv) == 2: @@ -13,13 +15,25 @@ elif len(sys.argv) > 2: print sys.argv[0], '<directory>' sys.exit() -print 'copying scripts to', output -start = os.getenv('ROOTCOREBIN') + '/user_scripts/TopExamples/*.py' -#print start +# We cannot use a wildcard anymore as everything is stored in /bin/ +list_of_scripts = ["01SubmitToGrid.py", + "02DownloadFromGrid.py", + "03LocalAnalysis.py", + "04Plot.py", + "10AmiYield.py", + "11CrossSection.py", + "DerivationTags.py", + "Data_rel21.py", + "MC16_TOPQ1.py" + ] +print 'Using PathResolver to copy scripts to', output if not os.path.exists(output): os.makedirs(output) -cmd = 'cp ' + start + ' ' + output -#print cmd -os.system(cmd) +for script in list_of_scripts: + full_path = ROOT.PathResolver.find_file(script, "PATH") + print "Copying",full_path + cmd = "cp %s %s"%(full_path, output) + os.system(cmd) + diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopExamples/util/combineATOutputs.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/util/combineATOutputs.cxx new file mode 100644 index 0000000000000000000000000000000000000000..ce3a13a2f8717a9aab1ce208b96e134c41c4b1bc --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopExamples/util/combineATOutputs.cxx @@ -0,0 +1,168 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#include <TROOT.h> +#include <TFile.h> +#include <TList.h> +#include <TKey.h> +#include <TString.h> +#include <TObject.h> +#include <TTree.h> + +#include <string> +#include <iostream> +#include <algorithm> +#include <memory> +#include <cstdio> + +// for debugging +// #define XXX std::cout << "I am here: " << __FILE__ << ":" << __LINE__ << std::endl; + +// this function is adapted from René Brun's $ROOTSYS/tutorials/io/copyFiles.C macro +void CopyDirToNewDir(std::shared_ptr<TDirectory> source, std::shared_ptr<TDirectory> outFile, TString prefix="") { + //copy all objects and subdirs of directory source as a subdir of the current directory +// source->ls(); + outFile->cd(); + //loop on all entries of this directory + TKey *key; + TIter nextkey(source->GetListOfKeys()); + while ((key = (TKey*)nextkey())) { + const char *classname = key->GetClassName(); + TClass* cl = gROOT->GetClass(classname); + if (!cl) continue; + if (cl->InheritsFrom(TDirectory::Class())) { + source->cd(key->GetName()); + std::shared_ptr<TDirectory> subdir(gDirectory); + TString name = prefix; + if (prefix != "") name.Append("_"); + name+=subdir->GetName(); + std::shared_ptr<TDirectory> adir{outFile->mkdir(name)}; + outFile->cd(); + CopyDirToNewDir(subdir,adir); // no prefix for sub-directories + adir->Write(); + outFile->cd(); + } else if (cl->InheritsFrom(TTree::Class())) { + std::unique_ptr<TTree> T{(TTree*)source->Get(key->GetName())}; + outFile->cd(); + std::unique_ptr<TTree> newT{T->CloneTree(-1,"fast")}; + TString name = prefix; + if (prefix != "") name.Append("_"); + name+=newT->GetName(); + newT->SetName(name); + newT->Write(); + } else { + source->cd(); + std::unique_ptr<TObject>obj{key->ReadObj()}; + outFile->cd(); + TString name = prefix; + if (prefix != "") name.Append("_"); + name+=obj->GetName(); + obj->Write(name); + } + } +} + +int main(int argc, char** argv) { + + if (argc != 3) { + std::cout<<"Usage:"<<std::endl; + std::cout<<" combineATOuputs outputFile inputFile1[:prefix1][,inputFile2[:prefix2][,inputFile3[:prefix3]]]"<<std::endl; + std::cout<<"Examples:"<<std::endl; + std::cout<<" combineATOuputs out_combined.root out_EMTopo.root:EMTopo,out_EMPflow.root:EMPflow"<<std::endl; + std::cout<<" combineATOuputs out_combined.root out_EMTopo.root,out_EMPflow.root:EMPflow"<<std::endl; + exit(1); + } + + // processing the input files string + std::string outString(argv[2]); + std::vector<std::string> tempStringVector; + + // looping on the input files string and split it + std::string::size_type start = 0, end = 0; + while ((end = outString.find(",", start)) != std::string::npos) { + std::string token = outString.substr(start, end - start); + if(token.size()) tempStringVector.push_back(token); + start = end + 1; + } + tempStringVector.push_back(outString.substr(start, end - start));// the last element + + // separate in intput files and prefixes + std::vector<std::string> inFileNames; + std::vector<std::string> prefixes; + for (auto s: tempStringVector) { + std::vector<std::string> tmp; + std::string::size_type st = 0, ed = 0; + while ((ed = s.find(":", st)) != std::string::npos) { + std::string tk = s.substr(st, ed - st); + if(tk.size()) tmp.push_back(tk); + st = ed + 1; + } + tmp.push_back(s.substr(st, ed - st));// the last element + if (tmp.size()>2) { + std::cout<<"Error: can't interpret "<<s<<std::endl; + exit(1); + } + std::string tmp_fileName = tmp[0]; + std::string tmp_prefix = tmp.size()==2?tmp[1]:""; // if no prefix is provided, empty prefix is assumed + + // checking if the file or prefix is not already used + if (std::find(inFileNames.begin(), inFileNames.end(), tmp_fileName) != inFileNames.end()) { + std::cout<<"Error: can't use twice the same input file "<<tmp_fileName<<std::endl; + exit(1); + } + if (std::find(prefixes.begin(), prefixes.end(), tmp_prefix) != prefixes.end()) { + std::cout<<"Error: can't use twice the same prefix "<<tmp_prefix<<std::endl; + exit(1); + } + // checking if the file is not also the name of the output file + if (std::find(inFileNames.begin(), inFileNames.end(), argv[1]) != inFileNames.end()) { + std::cout<<"Error: can't use the input file "<<argv[1]<<" as name for the output file"<<std::endl; + exit(1); + } + + // now adding the input files and prefixed in the vectors + inFileNames.push_back(tmp_fileName); + prefixes.push_back(tmp_prefix); + } + + // the output file + std::string tempOutFileName(argv[1]); + tempOutFileName+=".tmp"; + std::shared_ptr<TFile> fout{TFile::Open(tempOutFileName.c_str(),"recreate")}; + + // now looping on the input files + for (unsigned int i = 0; i<inFileNames.size(); i++) { + std::shared_ptr<TFile> f{TFile::Open(inFileNames[i].c_str(),"read")}; + if (f == nullptr) { + std::cout<<"Error: impossible to open input file"<<inFileNames[i]<<std::endl; + fout->Close(); + exit(1); + } + else if (f->TestBit(TFile::kWriteError)) { + fout->Close(); + exit(1); + } + else { + std::cout<<"Copy content of file "<<inFileNames[i]<<" in file "<<argv[1]<<" with prefix "<<prefixes[i]<<std::endl; + CopyDirToNewDir(f, fout, TString(prefixes[i])); + f->Close(); + } + } + + // check if output file is buggy + if (fout->TestBit(TFile::kWriteError)) { + std::cout<<"Error: output file looks buggy"<<std::endl; + fout->Close(); + exit(1); + } + fout->Close(); + + // rename output file with its final name - crash if we can't do that + if (std::rename(fout->GetName(), argv[1]) != 0) { + std::cout<<"Error: impossible to rename output file"<<std::endl; + exit(1); + } + + return 0; +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/CMakeLists.txt deleted file mode 100644 index 18c2a2477a833ea557f1df47af41e1834ce1bb00..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ - -# Declare the name of this package: -atlas_subdir( TopFakes ) - -# This package depends on other packages: -atlas_depends_on_subdirs( PUBLIC - TopEvent - TopConfiguration ) - -# This package uses ROOT: -find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO Math MathCore MathMore Graf Matrix ) - -# Generate a CINT dictionary source file: -set( _extraHeader ) -if( XAOD_STANDALONE ) - set( _extraHeader TopFakes/TopFakesMMWeightCalculator.h ) -endif() -atlas_add_root_dictionary( TopFakes _cintDictSource - ROOT_HEADERS ${_extraHeader} TopFakes/FakesWeights.h TopFakes/MMEffSet.h - TopFakes/MMEfficiency.h TopFakes/MatrixUtils.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) - -# Build a library that other components can link against: -atlas_add_library( TopFakes Root/*.cxx Root/*.h Root/*.icc - TopFakes/*.h TopFakes/*.icc TopFakes/*/*.h - TopFakes/*/*.icc ${_cintDictSource} - PUBLIC_HEADERS TopFakes - LINK_LIBRARIES TopEvent - TopConfiguration - ${ROOT_LIBRARIES} - INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) - -# Install data files from the package: -atlas_install_data( data/* ) - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/FakesWeights.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/FakesWeights.cxx deleted file mode 100644 index 5d5a3222c876c11091919341e5edcc0a6b76a01d..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/FakesWeights.cxx +++ /dev/null @@ -1,596 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -////////////////////////////////////////////////////////////////////// -// -// Author : -// Anna Henrichs <anna.henrichs@cern.ch> -// Michele Pinamonti <michele.pinamonti@cern.ch> -// Creation : -// Purpose : main method to retrieve event-by-event weights -// from the Matrix Method -// Updated : -// 2016-07-14 : TTP: replace _isRun1 by _period -// 2016-01-29 : FD: set _isRun1 = false -// set default weighter -// remove pt/dR variable, never used -// 2016-02-02 : FD update SetupWeighterDefault -// 2016-02-12 : SetupWeighterDefault : default do not use dPhi -////////////////////////////////////////////////////////////////////// - -#include "TopFakes/FakesWeights.h" -#include "TopFakes/MMEffSet.h" -#include "TopFakes/MMEfficiency.h" -#include "TopFakes/MatrixUtils.h" - -#include "TH1F.h" -#include "TH2F.h" -#include "TFile.h" -#include "TString.h" -#include "TObjString.h" -#include <cmath> -#include <iostream> - - -using namespace std; - -// CONSTRUCTOR -FakesWeights::FakesWeights() : _mmUtil(0) { - _channel = EJETS; - _dataPath = "data"; - _dataPathIsSet = false; - _isInitialized = false; - _debug = false; - - _period = MMEffSet::Period::Year2015; - _trig1_el = ""; - _trig2_el = ""; - _trig3_el = ""; - _trig1_mu = ""; - _trig2_mu = ""; - _trig3_mu = ""; - _ps1_el = 1; - _ps2_el = 1; - _ps3_el = 1; - _ps1_mu = 1; - _ps2_mu = 1; - _ps3_mu = 1; - _ptTres_el = 0; - _ptTres_mu = 0; - - for (int i = 0; i < 4; ++i) - _EffSet[i] = 0; -} - -// DESTRUCTOR -FakesWeights::~FakesWeights(){ - delete _mmUtil; - - for (int i = 0; i < 4; ++i) - delete _EffSet[i]; -} - -// =============================================== -void FakesWeights::SetDataPath(std::string path) { - // method to set the path were efficiencies are - _dataPath = path; - if(_isInitialized) for(int i=0;i<4;i++) _EffSet[i]->SetDataPath(path); - _dataPathIsSet = true; -} - -// =============================================== -void FakesWeights::SetDebug(bool debug){ - _debug = debug; -} - -// =============================================== -void FakesWeights::SetPeriod(int period){ - _period = period; -} - -// =============================================== -void FakesWeights::SetTriggerNamesEl(std::string trig1,std::string trig2,std::string trig3){ - _trig1_el = trig1; - _trig2_el = trig2; - _trig3_el = trig3; -} - -// =============================================== -void FakesWeights::SetTriggerNamesMu(std::string trig1,std::string trig2,std::string trig3){ - _trig1_mu = trig1; - _trig2_mu = trig2; - _trig3_mu = trig3; -} - -// =============================================== -void FakesWeights::SetTriggerPrescalesEl(float ps1,float ps2,float ps3){ - _ps1_el = ps1; - _ps2_el = ps2; - _ps3_el = ps3; -} - -// =============================================== -void FakesWeights::SetTriggerPrescalesMu(float ps1,float ps2,float ps3){ - _ps1_mu = ps1; - _ps2_mu = ps2; - _ps3_mu = ps3; -} - -// =============================================== -void FakesWeights::SetTriggerThresholdEl(float thres){ - _ptTres_el = thres; -} - -// =============================================== -void FakesWeights::SetTriggerThresholdMu(float thres){ - _ptTres_mu = thres; -} - -// =============================================== -void FakesWeights::SetupWeighter(int channel, std::string aReal, std::string aFake, std::string aReal2, std::string aFake2) { - // method to set up tools which calculate the weights - - std::cout << "--------------------------------------------------------" << std::endl; - std::cout << " FakesWeights::INFO: Setting-up Matrix Method Weighter." << std::endl; - if(channel==EJETS) std::cout << " channel: e+jets" << std::endl; - if(channel==MUJETS) std::cout << " channel: µ+jets" << std::endl; - if(channel==EE) std::cout << " channel: ee" << std::endl; - if(channel==MUMU) std::cout << " channel: µµ" << std::endl; - if(channel==EMU) std::cout << " channel: eµ" << std::endl; - if(channel==EMU){ - std::cout << " real eff(e): " << aReal << std::endl; - std::cout << " fake eff(e): " << aFake << std::endl; - std::cout << " real eff(µ): " << aReal2 << std::endl; - std::cout << " fake eff(µ): " << aFake2 << std::endl; - } - else{ - std::cout << " real eff: " << aReal << std::endl; - std::cout << " fake eff: " << aFake << std::endl; - } - std::cout << "--------------------------------------------------------" << std::endl; - _channel = channel; - _mmUtil = new MatrixUtils(); - _EffSet[0] = new MMEffSet(channel==EJETS || channel==EE || channel==EMU, true, _debug); // isEle, isReal - _EffSet[1] = new MMEffSet(channel==EJETS || channel==EE || channel==EMU, false, _debug); - _EffSet[2] = new MMEffSet(channel==EE, true, _debug); - _EffSet[3] = new MMEffSet(channel==EE, false, _debug); - for(int i=0;i<4;i++){ - _EffSet[i]->SetPeriod(_period); - } - if(_period!=MMEffSet::Period::Year2012){ - if(channel==EJETS || channel==EE || channel==EMU){ - _EffSet[0]->SetTriggerNames(_trig1_el,_trig2_el,_trig3_el); - _EffSet[1]->SetTriggerNames(_trig1_el,_trig2_el,_trig3_el); - _EffSet[0]->SetTriggerPrescales(_ps1_el,_ps2_el,_ps3_el); - _EffSet[1]->SetTriggerPrescales(_ps1_el,_ps2_el,_ps3_el); - _EffSet[0]->SetTriggerThreshold(_ptTres_el); - _EffSet[1]->SetTriggerThreshold(_ptTres_el); - } - else if(channel==MUJETS || channel==MUMU){ - _EffSet[0]->SetTriggerNames(_trig1_mu,_trig2_mu,_trig3_mu); - _EffSet[1]->SetTriggerNames(_trig1_mu,_trig2_mu,_trig3_mu); - _EffSet[0]->SetTriggerPrescales(_ps1_mu,_ps2_mu,_ps3_mu); - _EffSet[1]->SetTriggerPrescales(_ps1_mu,_ps2_mu,_ps3_mu); - _EffSet[0]->SetTriggerThreshold(_ptTres_mu); - _EffSet[1]->SetTriggerThreshold(_ptTres_mu); - } - if(channel==EE){ - _EffSet[2]->SetTriggerNames(_trig1_el,_trig2_el,_trig3_el); - _EffSet[3]->SetTriggerNames(_trig1_el,_trig2_el,_trig3_el); - _EffSet[2]->SetTriggerPrescales(_ps1_el,_ps2_el,_ps3_el); - _EffSet[3]->SetTriggerPrescales(_ps1_el,_ps2_el,_ps3_el); - _EffSet[2]->SetTriggerThreshold(_ptTres_el); - _EffSet[3]->SetTriggerThreshold(_ptTres_el); - } - else if(channel==MUMU || channel==EMU){ - _EffSet[2]->SetTriggerNames(_trig1_mu,_trig2_mu,_trig3_mu); - _EffSet[3]->SetTriggerNames(_trig1_mu,_trig2_mu,_trig3_mu); - _EffSet[2]->SetTriggerPrescales(_ps1_mu,_ps2_mu,_ps3_mu); - _EffSet[3]->SetTriggerPrescales(_ps1_mu,_ps2_mu,_ps3_mu); - _EffSet[2]->SetTriggerThreshold(_ptTres_mu); - _EffSet[3]->SetTriggerThreshold(_ptTres_mu); - } - } - _isInitialized = true; - // setup data path if already specified - if(_dataPathIsSet){ - if(_debug) std::cout << " --> Setting-up data-path = " << _dataPath << std::endl; - SetDataPath(_dataPath); - } - // setup firt lepton, for all the channels - _EffSet[0]->SetupEff(aReal); - _EffSet[1]->SetupEff(aFake); - // setup the second lepton in the same way as the first one for ee and µµ, but following aReal2/aFake2 for eµ - if(channel==EE || channel==EMU || channel==MUMU){ - if(aReal2!="") _EffSet[2]->SetupEff(aReal2); - else _EffSet[2]->SetupEff(aReal); - if(aFake2!="") _EffSet[3]->SetupEff(aFake2); - else _EffSet[3]->SetupEff(aFake); - } -} - -// ======================================================= -float FakesWeights::GetFakesWeightLJets(bool tight){ - // retrieve MM weight for semileptonic events - - float f = GetFakeEff(); // fake efficiency of lepton - float r = GetRealEff(); // real efficiency of lepton - if(f<0 || r<0) return 0.; // added for events which are neglected by trigger splitting - - double nf, nr; - // - float weight = _mmUtil->lepton_weight(!tight, r, f, (double&)nf, (double&)nr); - // protection against too large weights : this should not happen - // and is due in general to histo bins with large statistical fluctuations - if( weight > 5 || weight < -5 ){ - r = _EffSet[0]->GetEff(true); - f = _EffSet[1]->GetEff(true); - weight = _mmUtil->lepton_weight(!tight, r, f, (double&)nf, (double&)nr); - } - - // scale by prescales! FIXME - if(_EffSet[0]->GetPrescale()!=1) weight *= _EffSet[0]->GetPrescale(); - - return weight; -} - -// ======================================================= -float FakesWeights::GetFakesWeightDilep(bool tight1,bool tight2){ - // retrieve MM weight for dilepton events - - float f1 = GetFakeEff(); // fake efficiency of 1st lepton - float r1 = GetRealEff(); // real efficiency of 1st lepton - float f2 = GetFakeEff2(); // fake efficiency of 2nd lepton - float r2 = GetRealEff2(); // real efficiency of 2nd lepton - if(f1<0 || f2<0 || r1<0 || r2<0) return 0.; // added for events which are neglected by trigger splitting - - double nrf, nfr, nff; - // fill the 4*4 matrix with efficiencies - _mmUtil->fill_matrix(r1,f1,r2,f2); - // retrieve the weights - return _mmUtil->dilepton_weight(!tight1, r1, f1, !tight2, r2, f2, (double&)nrf, (double&)nfr, (double&)nff); -} - -// ======================================================= -float FakesWeights::GetFakesWeightDilepLL(bool tight1,bool tight2){ - // retrieve MM weight for dilepton events (loose-loose) - return _mmUtil->dilepton_LL_weight(!tight1,!tight2); -} - -// ======================================================= -float FakesWeights::GetFakesWeightDilepLT(bool tight1,bool tight2){ - // retrieve MM weight for dilepton events (loose-tight) - return _mmUtil->dilepton_LT_weight(!tight1,!tight2); -} - -// ======================================================= -float FakesWeights::GetFakesWeightDilepTL(bool tight1,bool tight2){ - // retrieve MM weight for dilepton events (tight-loose) - return _mmUtil->dilepton_TL_weight(!tight1,!tight2); -} - -// ======================================================= -float FakesWeights::GetFakesWeightDilepTT(bool tight1,bool tight2){ - // retrieve MM weight for dilepton events (tight-tight) - return _mmUtil->dilepton_TT_weight(!tight1,!tight2); -} - -// ======================================================= -float FakesWeights::GetRealEff(){ - // method to get the real efficiency - float R = _EffSet[0]->GetEff(); - return R; -} - -// ======================================================= -float FakesWeights::GetFakeEff(){ - // method to get the fake efficiency - float F = _EffSet[1]->GetEff(); - return F; -} - -// ======================================================= -float FakesWeights::GetRealEff2(){ - // method to get the real efficiency (of 2nd lepton) - float R = _EffSet[2]->GetEff(); - return R; -} - -// ======================================================= -float FakesWeights::GetFakeEff2(){ - // method to get the real efficiency (of 2nd lepton) - float F = _EffSet[3]->GetEff(); - return F; -} - -// ======================================================= -void FakesWeights::SetLepton(MMEvent event,MMLepton lepton){ - // set the MMEvent and MMLepton objects for l+jet case - _EffSet[0]->SetLepton(event,lepton); - _EffSet[1]->SetLepton(event,lepton); -} - -// ======================================================= -void FakesWeights::SetLeptons(MMEvent event,MMLepton lepton1,MMLepton lepton2){ - // set the MMEvent and MMLepton objects for dilepton case - - // hack by Finn & Xiaowen to treat the trigger bias in the correct way - // a. if any lepton in the event matches the high pt trigger - if( (lepton1.trigger&2)>0 || (lepton2.trigger&2)>0 ){ - // -- > apply pt dependent nonbiased efficiencies ( e.g. e24vh if pt<61 and e60 if pt>61 ) - // ~~ > hack: switch the biased trigger off ;) - if( (lepton1.trigger&1)>0 ) { - lepton1.trigger -= 1; - if( (lepton1.trigger&4)==0 ) lepton1.trigger += (1 << 2); - } - if( (lepton2.trigger&1)>0 ){ - lepton2.trigger -= 1; - if( (lepton2.trigger&4)==0 ) lepton2.trigger += (1 << 2); - } - } - // b. if no lepton in the event matches this trigger - else{ - // -- > apply the low pt biased trigger efficiency ( e24vhi ) to one lepton that matches this trigger and pt dependent unbiased efficiencies to the others ( e.g. e24vh if pt<61 and e60 if pt>61 ) - // -- > if more than one lepton matches e24vhi than apply that efficiency to the highest pt one and the unbiased e24vh to the other(s). - // ~~ > hack: if both leptons are matched to the biased trigger, switch off the trigger for the lowest pt one - if( (lepton1.trigger&1)>0 && (lepton2.trigger&1)>0 ){ - if( lepton1.pt > lepton2.pt ) lepton2.trigger -= 1; - if( lepton2.pt > lepton1.pt ) lepton1.trigger -= 1; - } - } - - _EffSet[0]->SetLepton(event,lepton1); - _EffSet[1]->SetLepton(event,lepton1); - _EffSet[2]->SetLepton(event,lepton2); - _EffSet[3]->SetLepton(event,lepton2); -} - -// ======================================================= -MatrixUtils* FakesWeights::GetMatrixUtils(){ - // retrieve the matrix - return _mmUtil; -} - -// ======================================================= -void FakesWeights::SetupWeighterDefault(int channel, std::string syst){ - // - // default set up - // - - // default efficiencies - if (syst=="") _syst = NONE; - // fake eff with removal of real lepton contamination from W/Z MC +30% - correlates electron and muon - else if(syst=="MCup") _syst = MCup; - // fake eff with removal of real lepton contamination from W/Z MC -30% - correlates electron and muon - else if(syst=="MCdown") _syst = MCdown; - // fake eff with removal of real lepton contamination from W/Z MC +30% - only for electron - else if(syst=="MCupel") _syst = MCupel; - // fake eff with removal of real lepton contamination from W/Z MC -30% - only for electron - else if(syst=="MCdownel") _syst = MCdownel; - // fake eff with removal of real lepton contamination from W/Z MC +30% - only for muon - else if(syst=="MCupmu") _syst = MCupmu; - // fake eff with removal of real lepton contamination from W/Z MC -30% - only for muon - else if(syst=="MCdownmu") _syst = MCdownmu; - // fake eff from alternative region - returns nominal for emu channel, otherwise equivalent to CRfakeel (CRfakemu) for e+jets and ee (mu+jets and mumu) channels - else if(syst=="CRfake") _syst = CRfake; - // fake eff from alternative region (only for electrons, useful for dilepton) - else if(syst=="CRfakeel") _syst = CRfakeel; - // fake eff from alternative region (only for muons, useful for dilepton) - else if(syst=="CRfakemu") _syst = CRfakemu; - // real eff from alternative region - correlates electron and muon - else if(syst=="CRreal") _syst = CRreal; - // real eff from alternative region - only for electron - else if(syst=="CRrealel") _syst = CRrealel; - // real eff from alternative region - only for muon - else if(syst=="CRrealmu") _syst = CRrealmu; - // efficiencies with alternative parametrisation (only for l+jet) - else if(syst=="EffPar") _syst = EffPar; - else { - std::cout << " FakesWeights::ERROR: Specified systematic NOT supported: " << syst << std::endl; - return; - } - - // E + JETS - if(channel == FakesWeights::EJETS){ - if(_syst==NONE) SetupWeighter( FakesWeights::EJETS, "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR"); - else if(_syst==MCup || _syst==MCupel) SetupWeighter( FakesWeights::EJETS, "Default:NS:eta:pt:jetpt:dR", "Default_MCup:NB/NS:eta:pt:jetpt:dR"); - else if(_syst==MCdown || _syst==MCdownel) SetupWeighter( FakesWeights::EJETS, "Default:NS:eta:pt:jetpt:dR", "Default_MCdown:NB/NS:eta:pt:jetpt:dR"); - else if(_syst==CRreal || _syst==CRrealel) SetupWeighter( FakesWeights::EJETS, "Default_CRreal:NB:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR"); - else if(_syst==CRfake || _syst==CRfakeel) SetupWeighter( FakesWeights::EJETS, "Default:NS:eta:pt:jetpt:dR", "Default_CRfake:NB/NS:eta:pt:jetpt:dR"); - else if(_syst==EffPar) SetupWeighter( FakesWeights::EJETS, "Default:NS:eta:pt:jetpt:dR:dPhi", "Default:NB/NS:eta:pt:jetpt:dR:dPhi"); - else if(_syst==MCupmu || _syst==MCdownmu || _syst==CRrealmu || _syst==CRfakemu ) { - std::cout << " FakesWeights::WARNING: Requested muon-specific systematic "<<syst<<" in e+jets channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::EJETS); - } - } - - // MU + JETS - else if(channel == FakesWeights::MUJETS){ - if(_syst==NONE) SetupWeighter( FakesWeights::MUJETS, "Default:NS/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - else if(_syst==MCup || _syst==MCupmu) SetupWeighter( FakesWeights::MUJETS, "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCup:NB/NS/TR:eta:pt:jetpt:dR"); - else if(_syst==MCdown || _syst==MCdownmu) SetupWeighter( FakesWeights::MUJETS, "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCdown:NB/NS/TR:eta:pt:jetpt:dR"); - else if(_syst==CRreal || _syst==CRrealmu) SetupWeighter( FakesWeights::MUJETS, "Default_CRreal:NB/TR:eta:pt:jetpt:dR","Default:NB/NS/TR:eta:pt:jetpt:dR"); - else if(_syst==CRfake || _syst==CRfakemu) SetupWeighter( FakesWeights::MUJETS, "Default:NS/TR:eta:pt:jetpt:dR", "Default_CRfake:NB/NS/TR:eta:pt:jetpt:dR"); - else if(_syst==EffPar) SetupWeighter( FakesWeights::MUJETS, "Default:NS/TR:eta:pt:jetpt:dR:dPhi", "Default:NB/NS/TR:eta:pt:jetpt:dR:dPhi"); - else if(_syst==MCupel || _syst==MCdownel || _syst==CRrealel || _syst==CRfakeel ) { - std::cout << " FakesWeights::WARNING: Requested electron-specific systematic "<<syst<<" in mu+jets channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::MUJETS); - } - } - - // E E - else if(channel == FakesWeights::EE){ - if(_syst==NONE) SetupWeighter( FakesWeights::EE, "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR"); - else if (_syst==MCup || _syst==MCupel) SetupWeighter( FakesWeights::EE, "Default:NS:eta:pt:jetpt:dR", "Default_MCup:NB/NS:eta:pt:jetpt:dR"); - else if (_syst==MCdown || _syst==MCdownel) SetupWeighter( FakesWeights::EE, "Default:NS:eta:pt:jetpt:dR", "Default_MCdown:NB/NS:eta:pt:jetpt:dR"); - else if (_syst==CRreal || _syst==CRrealel) SetupWeighter( FakesWeights::EE, "Default_CRreal:NB/TR:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR"); - else if (_syst==CRfake || _syst==CRfakeel) SetupWeighter( FakesWeights::EE, "Default:NS:eta:pt:jetpt:dR", "Default_CRfake:NB/NS:eta:pt:jetpt:dR"); - else if(_syst==EffPar) { - std::cout << " FakesWeights::WARNING: Requested systematic "<<syst<<" is not relevant for dilepton channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::EE); - } - else if(_syst==MCupmu || _syst==MCdownmu || _syst==CRrealmu || _syst==CRfakemu ) { - std::cout << " FakesWeights::WARNING: Requested muon-specific systematic "<<syst<<" in ee channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::EE); - } - } - - // MU MU - else if(channel == FakesWeights::MUMU){ - if(_syst==NONE) SetupWeighter( FakesWeights::MUMU, "Default:NS/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - else if (_syst==MCup || _syst==MCupmu) SetupWeighter( FakesWeights::MUMU, "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCup:NB/NS/TR:eta:pt:jetpt:dR"); - else if (_syst==MCdown || _syst==MCdownmu) SetupWeighter( FakesWeights::MUMU, "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCdown:NB/NS/TR:eta:pt:jetpt:dR"); - else if (_syst==CRreal || _syst==CRrealmu) SetupWeighter( FakesWeights::MUMU, "Default_CRreal:NB/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - else if (_syst==CRfake || _syst==CRfakemu) SetupWeighter( FakesWeights::MUMU, "Default:NS/TR:eta:pt:jetpt:dR", "Default_CRfake:NB/NS/TR:eta:pt:jetpt:dR"); - else if(_syst==EffPar) { - std::cout << " FakesWeights::WARNING: Requested systematic "<<syst<<" is not relevant for dilepton channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::MUMU); - } - else if(_syst==MCupel || _syst==MCdownel || _syst==CRrealel || _syst==CRfakeel ) { - std::cout << " FakesWeights::WARNING: Requested electron-specific systematic "<<syst<<" in mumu channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::MUMU); - } - } - - // E MU - else if(channel == FakesWeights::EMU){ - if(_syst==NONE) { - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==MCup) { - std::cout << " FakesWeights::WARNING: Requested systematic MCup in emu channel will consider this variation totally correlated between the electron and the muon" << std::endl; - std::cout << " FakesWeights::WARNING: Please use MCupel and MCupmu to get the systematic variation only for electron and muon, respectively" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default_MCup:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCup:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==MCdown) { - std::cout << " FakesWeights::WARNING: Requested systematic MCdown in emu channel will consider this variation totally correlated between the electron and the muon" << std::endl; - std::cout << " FakesWeights::WARNING: Please use MCdownel and MCdownmu to get the systematic variation only for electron and muon, respectively" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default_MCdown:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCdown:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==MCupel) { - std::cout << " FakesWeights::WARNING: Requested systematic MCupel in emu channel will consider this variation only for the electron" << std::endl; - std::cout << " FakesWeights::WARNING: Please use MCup instead to get this systematic variation for both electron and muon totally correlated" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default_MCup:NB/NS:eta:pt:jetpt:dR", - "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR"); - } - else if (_syst==MCdownel) { - std::cout << " FakesWeights::WARNING: Requested systematic MCdownel in emu channel will consider this variation only for the electron" << std::endl; - std::cout << " FakesWeights::WARNING: Please use MCdown instead to get this systematic variation for both electron and muon totally correlated" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default_MCdown:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==MCupmu) { - std::cout << " FakesWeights::WARNING: Requested systematic MCupmu in emu channel will consider this variation only for the muon" << std::endl; - std::cout << " FakesWeights::WARNING: Please use MCup instead to get this systematic variation for both electron and muon totally correlated" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCup:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==MCdownmu) { - std::cout << " FakesWeights::WARNING: Requested systematic MCdownmu in emu channel will consider this variation only for the muon" << std::endl; - std::cout << " FakesWeights::WARNING: Please use MCdown instead to get this systematic variation for both electron and muon totally correlated" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default_MCdown:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==CRfake) { - std::cout << " FakesWeights::WARNING: Requested systematic CRfake in emu channel is not possible - using nominal instead" << std::endl; - std::cout << " FakesWeights::WARNING: Please use CRfakeel and CRfakemu to get the systematic variation only for electron and muon, respectively" << std::endl; - SetupWeighterDefault(FakesWeights::EMU); - } - else if (_syst==CRfakeel) { - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default_CRfake:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==CRfakemu) { - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default_CRfake:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==CRreal) { - std::cout << " FakesWeights::WARNING: Requested systematic CRreal in emu channel will consider this variation totally correlated between the electron and the muon" << std::endl; - std::cout << " FakesWeights::WARNING: Please use CRrealel and CRrealmu to get the systematic variation only for electron and muon, respectively" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default_CRreal:NB/TR:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default_CRreal:NB/TR:eta:pt:jetpt:dR","Default:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==CRrealel) { - std::cout << " FakesWeights::WARNING: Requested systematic CRrealel in emu channel will consider this variation only for the electron" << std::endl; - std::cout << " FakesWeights::WARNING: Please use CRreal instead to get this systematic variation for both electron and muon totally correlated" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default_CRreal:NB/TR:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default:NS/TR:eta:pt:jetpt:dR", "Default:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if (_syst==CRrealmu) { - std::cout << " FakesWeights::WARNING: Requested systematic CRrealmu in emu channel will consider this variation only for the muon" << std::endl; - std::cout << " FakesWeights::WARNING: Please use CRreal instead to get this systematic variation for both electron and muon totally correlated" << std::endl; - SetupWeighter( FakesWeights::EMU, - "Default:NS:eta:pt:jetpt:dR", "Default:NB/NS:eta:pt:jetpt:dR", - "Default_CRreal:NB/TR:eta:pt:jetpt:dR","Default:NB/NS/TR:eta:pt:jetpt:dR"); - } - else if(_syst==EffPar) { - std::cout << " FakesWeights::WARNING: Requested systematic "<<syst<<" is not relevant for dilepton channel - using nominal instead" << std::endl; - SetupWeighterDefault(FakesWeights::EMU); - } - } - else std::cout << "ERROR: Unsupported channel number: " << channel << std::endl; -} - -// ======================================================= -// for backward compatibility -void FakesWeights::SetupWeighterDefault(int channel,std::string name,std::string syst){ - std::cout << " FakesWeights::INFO: Specifying " << name << " not needed anymore." << std::endl; - SetupWeighterDefault(channel,syst); -} - -// ======================================================= -void FakesWeights::SetLeptonDefault(float lep_pt, float lep_eta, - float el_cl_eta, float dR_lj_min, - float dPhi_lnu, float jet_pt0, - int jet_n, int nJet_tagged, int trigger) -{ - // - // default method to setup MMLepton and MMEvent objects - // - - // turn eta's into abs value, just to be sure - lep_eta = TMath::Abs(lep_eta); - el_cl_eta = TMath::Abs(el_cl_eta); - // - MMLepton lepton; - lepton.pt = lep_pt; - lepton.eta = lep_eta; - lepton.cleta = el_cl_eta; - lepton.dR = dR_lj_min; - lepton.dPhi = dPhi_lnu; // NEW!! - lepton.trigger = trigger; - MMEvent event; - event.njets = jet_n; - event.ntag = nJet_tagged; - event.jetpt = jet_pt0; - SetLepton(event,lepton); -} - -// ======================================================= -float FakesWeights::GetFakesWeightLJetsDefault(bool tight, float lep_pt, - float lep_eta, float el_cl_eta, - float dR_lj_min, - float dPhi_lnu, // NEW!! - float jet_pt0, int jet_n, - int nJet_tagged, int trigger) -{ - - SetLeptonDefault(lep_pt,lep_eta,el_cl_eta,dR_lj_min,dPhi_lnu, - jet_pt0,jet_n,nJet_tagged,trigger); - return GetFakesWeightLJets(tight); -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/LinkDef.h deleted file mode 100644 index fd03d0685a9a00c5d7fa6cae7499bb3f79b65431..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/LinkDef.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef STANDALONE//for standalone compilation only -#include "TopFakes/TopFakesMMWeightCalculator.h" -#endif -#include "TopFakes/FakesWeights.h" -#include "TopFakes/MMEffSet.h" -#include "TopFakes/MMEfficiency.h" -#include "TopFakes/MatrixUtils.h" - -#ifdef __CINT__ - -#ifndef STANDALONE//for standalone compilation only -#pragma extra_include "TopFakes/TopFakesMMWeightCalculator.h"; -#endif -#pragma extra_include "TopFakes/FakesWeights.h"; -#pragma extra_include "TopFakes/MMEffSet.h"; -#pragma extra_include "TopFakes/MMEfficiency.h"; -#pragma extra_include "TopFakes/MatrixUtils.h"; - -#pragma link off all globals; -#pragma link off all classes; -#pragma link off all functions; -#pragma link C++ nestedclass; - -//for loading the object selection at run time -#ifndef STANDALONE//for standalone compilation only -#pragma link C++ class top::TopFakesMMWeightCalculator+; -#endif -#pragma link C++ class FakesWeights+; -#pragma link C++ class MMEffSet+; -#pragma link C++ class MMEfficiency+; -#pragma link C++ class MatrixUtils+; - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MMEffSet.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MMEffSet.cxx deleted file mode 100644 index 7f2f01efd5d8a1c5c469a8f8b9939652d2616560..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MMEffSet.cxx +++ /dev/null @@ -1,508 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -////////////////////////////////////////////////////////////////////// -// -// Author : Michele Pinamonti <michele.pinamonti@cern.ch> -// Creation : -// Purpose : base class to set efficiencies for the matrix method -// Updated : -// 2016-01-29 : FD: set _isRun1 = false and set muon triggers for Run2 -////////////////////////////////////////////////////////////////////// - -#include "TopFakes/MMEffSet.h" -#include "TopFakes/MMEfficiency.h" -#include "TopFakes/MatrixUtils.h" - -#include "TH1F.h" -#include "TH2F.h" -#include "TFile.h" -#include "TString.h" -#include "TObjString.h" -#include <cmath> -#include <iostream> - -using namespace std; - -MMEffSet::MMEffSet(bool isEle, bool isReal, bool debug) { - _Estimate = ""; - _dataPath = "data"; - _isEle = isEle; - _isReal = isReal; - _effIsRead = false; - _useCorr = false; - _numCond = 0; - _splitBitMask = 0; - _debug = debug; - _period = Period::Year2015; - _ptTres = 0; - _trig1 = ""; - _trig2 = ""; - _trig3 = ""; - _trigger = -100; - - for (int i = 0; i < 10; ++i) { - _Eff[i] = 0; - _EffCorr[i] = 0; - } -} - -MMEffSet::~MMEffSet(){ - for (int i = 0; i < 10; ++i) { - delete _Eff[i]; - delete _EffCorr[i]; - } -} - -void MMEffSet::SetupEff(std::string aEff){ - _Estimate = aEff; - ParseOptions(_Estimate,&_optMap); - if(_optMap["Conditions"]=="x"){ // if x is there as condition, wait before initializing - if(_debug) std::cout << "Custom conditions. Not setting up efficiencies yet." << std::endl; - return; - } - else if(_optMap["Conditions"].find("NB/NS/TR")!=std::string::npos) AddNumBtagAndNumJetsShortAndTriggerSplit(); - else if(_optMap["Conditions"].find("NB/NJ/TR")!=std::string::npos) AddNumBtagAndNumJetsAndTriggerSplit(); - else if(_optMap["Conditions"].find("NB/NS")!=std::string::npos) AddNumBtagAndNumJetsShortSplit(); - else if(_optMap["Conditions"].find("NB/NJ")!=std::string::npos) AddNumBtagAndNumJetsSplit(); - else if(_optMap["Conditions"].find("NB/TR")!=std::string::npos) AddNumBtagAndTriggerSplit(); - else if(_optMap["Conditions"].find("NS/TR")!=std::string::npos) AddNumJetsShortAndTriggerSplit(); - else if(_optMap["Conditions"].find("NJ/TR")!=std::string::npos) AddNumJetsAndTriggerSplit(); - else if(_optMap["Conditions"].find("NB")!=std::string::npos) AddNumBtagSplit(); - else if(_optMap["Conditions"].find("NS")!=std::string::npos) AddNumJetsShortSplit(); - else if(_optMap["Conditions"].find("NJ")!=std::string::npos) AddNumJetsSplit(); - else if(_optMap["Conditions"].find("TR")!=std::string::npos) AddTriggerSplit(); - else{ - _numCond = 1; - _condVec.push_back(_optMap["Conditions"]); - } - if(_optMap["Conditions"].find("corr")!=std::string::npos) AddCorrection(); - ReadEfficiencies(); -} - -void MMEffSet::SetDataPath(std::string path){ - _dataPath = path; -} - -void MMEffSet::ParseOptions(std::string s,std::map<std::string,std::string> *m){ - TString ss(s); - TObjArray *optArray = ss.Tokenize(":"); - (*m)["Name"] = ((TObjString*)optArray->At(0))->GetString(); - (*m)["Conditions"] = ((TObjString*)optArray->At(1))->GetString(); - for(int i=0;i<(int)optArray->GetEntries()-2;i++){ - (*m)[Form("Histo%d",i)] = ((TObjString*)optArray->At(i+2))->GetString(); - } - delete optArray; -} - -void MMEffSet::AddCustomSplit(std::string config){ - std::vector<std::string> condVec = Tokenize(config,":"); - if(_numCond>0) _condVec = Combine(_condVec,condVec); - else _condVec = condVec; - _numCond = _condVec.size(); -} - -void MMEffSet::ReadEfficiencies(){ - if(_effIsRead) return; - // real - for(int i=0;i<(int)_condVec.size();i++){ - _Eff[i] = new MMEfficiency(); - ReadEfficiency(_Eff[i],_Estimate,_condVec[i]); - if(_useCorr){ - _EffCorr[i] = new MMEfficiency(); - ReadEfficiency(_EffCorr[i],_Estimate,_condVec[i],true); - } - } - _effIsRead = true; -} - -void MMEffSet::AddNumBtagSplit(){ - AddCustomSplit("0b:ge1b"); - _splitBitMask |= (NBTAG_MASK); -} -void MMEffSet::AddNumJetsSplit(){ - AddCustomSplit("1j:2or3j:ge4j"); - _splitBitMask |= (NJETS_MASK); -} -void MMEffSet::AddNumJetsShortSplit(){ - AddCustomSplit("1j:ge2j"); - _splitBitMask |= (NJETSSHORT_MASK); -} -void MMEffSet::AddTriggerSplit(){ - // for Run1 - if(_period == Period::Year2012){ - if(_isEle){ - AddCustomSplit("e24vhi:e60:e24vh"); - _ptTres = 62; - } - else{ - AddCustomSplit("mu24i:mu36:mu24"); - _ptTres = 37; - } - } - else if (_period == Period::Year2015) { // for Run2 - //if(_isEle){ // no trigger splitting for electrons - //} - if(!_isEle) { // for muons - AddCustomSplit("mu20_iloose_L1MU15:mu50:mu20_L1MU15"); - _ptTres = 51; - } - //AddCustomSplit(Form("%s:%s:%s",_trig1.c_str(),_trig2.c_str(),_trig3.c_str())); - } - else if (_period == Period::Year2016) { // for Run2 - if(_isEle){ // no trigger splitting for electrons - AddCustomSplit("e24_lhtight_nod0_ivarloose:e60_lhmedium_nod0:e24_lhmedium_L1EM20VH"); - _ptTres = 62; - } - if(!_isEle) { // for muons - AddCustomSplit("mu24_ivarmedium:mu50:mu24"); - _ptTres = 51; - } - //AddCustomSplit(Form("%s:%s:%s",_trig1.c_str(),_trig2.c_str(),_trig3.c_str())); - } - _splitBitMask |= (TRIGGER_MASK); -} - -// ... and combined -void MMEffSet::AddNumBtagAndTriggerSplit(){ - AddNumBtagSplit(); - AddTriggerSplit(); -} -void MMEffSet::AddNumBtagAndNumJetsSplit(){ - AddNumBtagSplit(); - AddNumJetsSplit(); -} -void MMEffSet::AddNumBtagAndNumJetsShortSplit(){ - AddNumBtagSplit(); - AddNumJetsShortSplit(); -} -void MMEffSet::AddNumJetsAndTriggerSplit(){ - AddNumJetsSplit(); - AddTriggerSplit(); -} -void MMEffSet::AddNumJetsShortAndTriggerSplit(){ - AddNumJetsShortSplit(); - AddTriggerSplit(); -} -void MMEffSet::AddNumBtagAndNumJetsAndTriggerSplit(){ - AddNumBtagSplit(); - AddNumJetsSplit(); - AddTriggerSplit(); -} -void MMEffSet::AddNumBtagAndNumJetsShortAndTriggerSplit(){ - AddNumBtagSplit(); - AddNumJetsShortSplit(); - AddTriggerSplit(); -} - -void MMEffSet::ReadEfficiency(MMEfficiency *eff,std::string aEff,std::string condition,bool isCorrection){ - string effFileName = Form("%s/%s_%s_%s.root", - _dataPath.c_str(), - isCorrection ? (_isReal ? "RCorr" : "FCorr") : (_isReal ? "R" : "F"), - _isEle ? "el" : "mu", - _optMap["Name"].c_str() - ); - if(_debug){ - if(_debug) std::cout << "------------------------------" << std::endl; - if(_isReal) std::cout << " --> Opening file for Real Eff: "; - else std::cout << " --> Opening file for Fake Eff: "; - std::cout << effFileName << std::endl; - } - TFile* effFile = TFile::Open(effFileName.c_str()); - - std::map<std::string,std::string> optMap; - ParseOptions(aEff,&optMap); - - string histoName; - int ndim = 1; - - bool status; - - // take average from histo - histoName = "av"; - if(condition=="") histoName = (string)(isCorrection ? "corr" : "eff")+"_" + histoName + "_" + optMap["Conditions"]; - else histoName = (string)(isCorrection ? "corr" : "eff")+"_" + histoName + "_" + condition; - if(_debug) std::cout << " --> Looking for histogram \"" << histoName << "\" inside file " << effFile->GetName() << std::endl; - eff->SetAverageHist(effFile,histoName); - - for(int i=0;;i++){ - histoName = optMap[Form("Histo%d",i)]; - if(histoName == "") break; - ndim = 1 + CountInString(histoName,'_'); - if(condition=="") histoName = (string)(isCorrection ? "corr" : "eff")+"_" + histoName + "_" + optMap["Conditions"]; - else histoName = (string)(isCorrection ? "corr" : "eff")+"_" + histoName + "_" + condition; - if(_debug){ - std::cout << " --> Looking for histogram \"" << histoName << "\" inside file " << effFile->GetName(); - std::cout << " " << (ndim==1 ?" (1D)" : (ndim==2 ? " (2D)" : " (3D)")); - std::cout << "..... "; - } - status = eff->AddHisto(effFile,histoName,ndim); - if(_debug){ - if(status) std::cout << "OK" << std::endl; - else std::cout << "NO" << std::endl << " MMEfficiency::INFO: Dummy Hstogram added." << std::endl; - } - } - - delete effFile; -} - -void MMEffSet::AddCorrection(){ - _useCorr = true; -} - -void MMEffSet::SetCustom(int value){ - _splitIdx = value; -} - -void MMEffSet::SetNumBtag(int nbtag){ - int value = -100; - value = NumBtagValue(nbtag); - SetCustom(value); -} - -void MMEffSet::SetNumJets(int njets){ - int value = -100; - value = NumJetsValue(njets); - SetCustom(value); -} - -void MMEffSet::SetNumJetsShort(int njets){ - int value = -100; - value = NumJetsShortValue(njets); - SetCustom(value); -} - -void MMEffSet::SetTrigger(int trigger,float pt){ - int value = -100; - value = TriggerValue(trigger, pt); - SetCustom(value); -} - -void MMEffSet::SetNumBtagAndNumJets(int nbtag,int njets){ - int value = -100; - value = NumJetsValue(njets); - value += 3*NumBtagValue(nbtag); - SetCustom(value); -} - -void MMEffSet::SetNumBtagAndNumJetsShort(int nbtag,int njets){ - int value = -100; - value = NumJetsShortValue(njets); - value += 2*NumBtagValue(nbtag); - SetCustom(value); -} - -void MMEffSet::SetNumBtagAndTrigger(int nbtag,int trigger,float pt){ - int value = -100; - value = TriggerValue(trigger, pt); - value += 3*NumBtagValue(nbtag); - SetCustom(value); -} - -void MMEffSet::SetNumJetsAndTrigger(int njets,int trigger,float pt){ - int value = -100; - value = TriggerValue(trigger, pt); - value += 3*NumJetsValue(njets); - SetCustom(value); -} - -void MMEffSet::SetNumJetsShortAndTrigger(int njets,int trigger,float pt){ - int value = -100; - value = TriggerValue(trigger, pt); - value += 3*NumJetsShortValue(njets); - SetCustom(value); -} - -void MMEffSet::SetNumBtagAndNumJetsAndTrigger(int nbtag,int njets,int trigger,float pt){ - int value = -100; - value = TriggerValue(trigger, pt); - value += 3*NumJetsValue(njets); - value += 9*NumBtagValue(nbtag); - SetCustom(value); -} - -void MMEffSet::SetNumBtagAndNumJetsShortAndTrigger(int nbtag,int njets,int trigger,float pt){ - int value = -100; - value = TriggerValue(trigger, pt); - value += 3*NumJetsShortValue(njets); - value += 6*NumBtagValue(nbtag); - SetCustom(value); -} - -void MMEffSet::SetTriggerNames(std::string trig1,std::string trig2,std::string trig3){ - _trig1 = trig1; - _trig2 = trig2; - _trig3 = trig3; -} - -void MMEffSet::SetPeriod(int period){ - _period = period; -} - -void MMEffSet::SetTriggerPrescales(float ps1,float ps2,float ps3){ - _ps1 = ps1; - _ps2 = ps2; - _ps3 = ps3; -} - -void MMEffSet::SetTriggerThreshold(float thres){ - _ptTres = thres; -} - -int MMEffSet::TriggerValue(int trigger,float pt){ - _trigger = -100; - if ((trigger & (1 << 0))>0 && (_ptTres<0 || pt < _ptTres)) _trigger = 0; // if matched to the low-pT isolated trigger - if ((trigger & (1 << 1))>0 && (_ptTres<0 || pt >= _ptTres)) _trigger = 1; // if matched to the high-pT trigger - if ((trigger & (1 << 2))>0 && (_ptTres<0 || pt < _ptTres)) _trigger = 2; // if matched to the low-pT non-iso trigger - if ((trigger & 3)==0) _trigger = 2; // if not matched to any trigger -> assign the low-pt non-iso eff - return _trigger; -} - -int MMEffSet::NumJetsValue(int njets){ - if(njets==1) return 0; - if(njets<=3) return 1; - else return 2; -} - -int MMEffSet::NumJetsShortValue(int njets){ - if(njets==1) return 0; - else return 1; -} - -int MMEffSet::NumBtagValue(int nbtag){ - if(nbtag==0) return 0; - else return 1; -} - -void MMEffSet::SetLepton(float v0,float v1,float v2,float v3,float v4,float v5,float v6,float v7,float v8,float v9){ - for(int i=0;i<_numCond;i++) _Eff[i]->SetParVars(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9); - if(_useCorr) - for(int i=0;i<_numCond;i++) _EffCorr[i]->SetParVars(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9); -} - -float MMEffSet::GetEff(bool isAverage){ - int idx = 0; - if(_numCond>0) idx = _splitIdx; - if(idx<0) return -1.; // added for events which are neglected by trigger splitting - float E; - if(isAverage){ - E = _Eff[idx]->GetAverageEfficiency(); - if(_useCorr) E *= _EffCorr[idx]->GetAverageEfficiency(); - } - else{ - E = _Eff[idx]->GetEfficiency(); - if(_useCorr) E *= _EffCorr[idx]->GetEfficiency(); - } - return E; -} - -// to be called after 'AddTriggerSplit' -void MMEffSet::SetPtThres(int thres){ - _ptTres = thres; -} - -void MMEffSet::SetLepton(MMEvent event,MMLepton lepton){ - _event = event; - _lepton = lepton; - // - int njets = _event.njets; - int ntag = _event.ntag; - float jetpt = _event.jetpt; - float sumet = _event.sumet; - // - float pt = _lepton.pt; - float eta = _lepton.eta; - float dR = _lepton.dR; - float dRpt = _lepton.dRpt; - float dPhi = _lepton.dPhi; - float d0sig = _lepton.d0sig; - int trigger = _lepton.trigger; - // - // set the correct splitting - if((_splitBitMask & NBTAG_MASK) && (_splitBitMask & NJETSSHORT_MASK) && (_splitBitMask & TRIGGER_MASK)) - SetNumBtagAndNumJetsShortAndTrigger(ntag,njets,trigger,pt); - else if((_splitBitMask & NBTAG_MASK) && (_splitBitMask & NJETS_MASK) && (_splitBitMask & TRIGGER_MASK)) - SetNumBtagAndNumJetsAndTrigger(ntag,njets,trigger,pt); - else if((_splitBitMask & NBTAG_MASK) && (_splitBitMask & TRIGGER_MASK)) - SetNumBtagAndTrigger(ntag,trigger,pt); - else if((_splitBitMask & NJETSSHORT_MASK) && (_splitBitMask & TRIGGER_MASK)) - SetNumJetsShortAndTrigger(njets,trigger,pt); - else if((_splitBitMask & NJETS_MASK) && (_splitBitMask & TRIGGER_MASK)) - SetNumJetsAndTrigger(njets,trigger,pt); - else if((_splitBitMask & NBTAG_MASK) && (_splitBitMask & NJETSSHORT_MASK)) - SetNumBtagAndNumJetsShort(ntag,njets); - else if((_splitBitMask & NBTAG_MASK) && (_splitBitMask & NJETS_MASK)) - SetNumBtagAndNumJets(ntag,njets); - else if((_splitBitMask & NBTAG_MASK)) - SetNumBtag(ntag); - else if((_splitBitMask & NJETSSHORT_MASK)) - SetNumJetsShort(njets); - else if((_splitBitMask & NJETS_MASK)) - SetNumJets(njets); - else if((_splitBitMask & TRIGGER_MASK)) - SetTrigger(trigger,pt); - // - // set the used variables - float input[] = {0,0,0,0,0,0,0,0,0,0}; - int k = 0; - if(_Estimate.find(":eta_dR")!=string::npos) { input[k] = eta; k++; input[k] = dR; k++; } - else if(_Estimate.find(":eta")!=string::npos) { input[k] = eta; k++; } - if(_Estimate.find(":pt_dR")!=string::npos) { input[k] = pt; k++; input[k] = dR; k++; } - else if(_Estimate.find(":pt_jetpt")!=string::npos) { input[k] = pt; k++; input[k] = jetpt; k++; } - else if(_Estimate.find(":pt")!=string::npos) { input[k] = pt; k++; } - if(_Estimate.find(":jetpt_dR")!=string::npos) { input[k] = jetpt; k++; input[k] = dR; k++; } - else if(_Estimate.find(":jetpt")!=string::npos){ input[k] = jetpt; k++; } - if(_Estimate.find(":sumet")!=string::npos) { input[k] = sumet; k++; } - if(_Estimate.find(":dR")!=string::npos && _Estimate.find(":dRpt")==string::npos) { input[k] = dR; k++; } - if(_Estimate.find(":dRpt")!=string::npos) { input[k] = dRpt; k++; } - if(_Estimate.find(":dPhi")!=string::npos) { input[k] = dPhi; k++; } - if(_Estimate.find(":d0sig")!=string::npos) { input[k] = d0sig; k++; } - if(_Estimate.find(":nbjets")!=string::npos) { input[k] = ntag; k++; } - - SetLepton(input[0],input[1],input[2],input[3],input[4],input[5],input[6],input[7],input[8],input[9]); -} - -float MMEffSet::GetPrescale(){ - if(_trigger==0) return _ps1; - if(_trigger==1) return _ps2; - if(_trigger==2) return _ps3; - return 1.; -} - - -// ------------------------------ - -// Internal methods / functions: - -int MMEffSet::CountInString(std::string s,char c){ - int n = 0; - for(int i=0;i<(int)s.size();i++){ - if(s[i]==c) n++; - } - return n; -} - -std::vector<std::string> MMEffSet::Tokenize(std::string s, std::string c){ - std::vector<std::string> v; - v.clear(); - std::string new_s; - while(true){ - new_s = s.substr(0,s.find(c)); - v.push_back(new_s); - if(new_s == s) break; - else s = s.substr(s.find(c)+1,s.size()); - } - return v; -} - -std::vector<std::string> MMEffSet::Combine(std::vector<std::string> v1,std::vector<std::string> v2){ - std::vector<std::string> v; - v.clear(); - for(int i=0;i<(int)v1.size();i++){ - for(int j=0;j<(int)v2.size();j++){ - v.push_back(v1[i]+"_"+v2[j]); - } - } - return v; -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MMEfficiency.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MMEfficiency.cxx deleted file mode 100644 index 64bbec0d5847e438dc689aeef3cfc477425e1a6f..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MMEfficiency.cxx +++ /dev/null @@ -1,313 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -/* - ** author: Michele Pinamonti <michele.pinamonti@cern.ch> - * * class used by FakesWeights.cxx -*/ - -#include "TopFakes/MMEfficiency.h" - -#define XXX std::cout << "I am here: " << __FILE__ << ":" << __LINE__ << std::endl; - -// ------------------------ Implementation ------------------------ // - -MMEfficiency::MMEfficiency() : - fAverage(-1), - fNvar(0) { - - for (int i = 0; i < MAXvar; ++i) { - fHist[i] = 0; - fHist2D[i] = 0; - fHist3D[i] = 0; - } -} - -MMEfficiency::~MMEfficiency(){ - for (int i = 0; i < MAXvar; ++i) { - delete fHist[i]; - delete fHist2D[i]; - delete fHist3D[i]; - } -} - -// ------------------------ AddHisto ------------------------ // - -bool MMEfficiency::AddHisto(TH1F *h){ - bool isDummy = false; - if(h==0) isDummy = true; - if(isDummy){ -// std::cout << " MMEfficiency::INFO: Dummy Hstogram added." << std::endl; - h = new TH1F("h_dummmy","h_dummy",1,0,1); - h->SetBinContent(1,1); - } - fHist[fNvar] = (TH1F*)h->Clone(); - fHist[fNvar]->SetDirectory(0); - fHist2D[fNvar] = 0; - fHist3D[fNvar] = 0; - if(fNvar>0 && fAverage<=0){ - std::cout << " MMEfficiency::INFO: No average efficiency set so far. Extracting it from current histogram... " << std::endl; - if(!isDummy) SetAverageFromHist((TH1F*)fHist[fNvar]->Clone()); - else fAverage = 1.; - } - fDim[fNvar] = 1; - fNvar += 1; - if(isDummy) delete h; - return !isDummy; -} - -bool MMEfficiency::AddHisto(TH2F *h){ - bool isDummy = false; - if(h==0) isDummy = true; - if(isDummy){ -// std::cout << " MMEfficiency::INFO: Dummy Hstogram added." << std::endl; - h = new TH2F("h_dummmy","h_dummy",1,0,1,1,0,1); - h->SetBinContent(1,1); - } - fHist[fNvar] = 0; - fHist2D[fNvar] = (TH2F*)h->Clone(); - fHist2D[fNvar]->SetDirectory(0); - fHist3D[fNvar] = 0; - if(fNvar>0 && fAverage<=0){ - std::cout << " MMEfficiency::INFO: No average efficiency set so far. Extracting it from current histogram... " << std::endl; - if(!isDummy) SetAverageFromHist((TH2F*)fHist2D[fNvar]->Clone()); - else fAverage = 1.; - } - fDim[fNvar] = 2; - fNvar += 2; - if(isDummy) delete h; - return !isDummy; -} - -bool MMEfficiency::AddHisto(TH3F *h){ - bool isDummy = false; - if(h==0) isDummy = true; - if(isDummy){ -// std::cout << " MMEfficiency::INFO: Dummy Hstogram added." << std::endl; - h = new TH3F("h_dummmy","h_dummy",1,0,1,1,0,1,1,0,1); - h->SetBinContent(1,1); - } - fHist[fNvar] = 0; - fHist2D[fNvar] = 0; - fHist3D[fNvar] = (TH3F*)h->Clone(); - fHist3D[fNvar]->SetDirectory(0); - if(fNvar>0 && fAverage<=0){ - std::cout << " MMEfficiency::INFO: No average efficiency set so far. Extracting it from current histogram... " << std::endl; - if(!isDummy) SetAverageFromHist((TH3F*)fHist3D[fNvar]->Clone()); - else fAverage = 1.; - } - fDim[fNvar] = 3; - fNvar += 3; - if(isDummy) delete h; - return !isDummy; -} - -bool MMEfficiency::AddHisto(TFile *f, std::string histoName, int ndim){ - f->cd(); - bool res = false; - if (ndim==1) res = AddHisto((TH1F*)f->Get(histoName.c_str())); - else if(ndim==2) res = AddHisto((TH2F*)f->Get(histoName.c_str())); - else if(ndim==3) res = AddHisto((TH3F*)f->Get(histoName.c_str())); - else{ - std::cout << " MMEfficiency::ERROR: ndim != 1,2,3" << std::endl; - return false; - } - return res; -} - -bool MMEfficiency::AddHisto(std::string fileName, std::string histoName, int ndim){ - bool res = false; - TFile *f = TFile::Open(fileName.c_str()); - res = AddHisto(f,histoName,ndim); - delete f; - return res; -} - -// ------------------------ SetAverage ------------------------ // - -void MMEfficiency::SetAverage(float value){ - fAverage = value; -} - -void MMEfficiency::SetAverageHist(std::string fileName, std::string histoName){ - TFile *f = TFile::Open(fileName.c_str()); - if(!f) return; - TH1F *h = (TH1F*)f->Get(histoName.c_str()); - if(!h){ - delete f; - return; - } - fAverage = h->GetBinContent(1); -// cout << "Setting Average Efficiency = " << fAverage << endl; - delete f; -} - -void MMEfficiency::SetAverageHist(TFile *f, std::string histoName){ - TH1F *h = (TH1F*)f->Get(histoName.c_str()); - if(!h) return; - fAverage = h->GetBinContent(1); -// cout << "Setting Average Efficiency = " << fAverage << endl; - delete h; -} - -float MMEfficiency::SetAverageFromHist(TH1F *h){ - TF1 *p = new TF1("p","pol0",h->GetXaxis()->GetBinLowEdge(1),h->GetXaxis()->GetBinUpEdge(h->GetNbinsX())); - h->Fit(p,"I0"); - fAverage = p->GetParameter(0); - delete p; - return fAverage; -} - -float MMEfficiency::SetAverageFromHist(TH2F *h){ - TF2 *p = new TF2("p","[0]+0*x+0*y", - h->GetXaxis()->GetBinLowEdge(1),h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()), - h->GetYaxis()->GetBinLowEdge(1),h->GetYaxis()->GetBinUpEdge(h->GetNbinsY()) - ); - h->Fit(p,"I0"); - fAverage = p->GetParameter(0); - delete p; - return fAverage; -} - -float MMEfficiency::SetAverageFromHist(TH3F *h){ - TF3 *p = new TF3("p","[0]+0*x+0*y+0*z", - h->GetXaxis()->GetBinLowEdge(1),h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()), - h->GetYaxis()->GetBinLowEdge(1),h->GetYaxis()->GetBinUpEdge(h->GetNbinsY()), - h->GetZaxis()->GetBinLowEdge(1),h->GetZaxis()->GetBinUpEdge(h->GetNbinsZ()) - ); - h->Fit(p,"I0"); - fAverage = p->GetParameter(0); - delete p; - return fAverage; -} - -float MMEfficiency::SetAverageFromHist(TFile *f, std::string histoName,int ndim){ - float av = -1; - TH1F *h1; - TH2F *h2; - TH3F *h3; - if(ndim==1){ - h1 = (TH1F*)f->Get(histoName.c_str()); - av = SetAverageFromHist(h1); - } - if(ndim==2){ - h2 = (TH2F*)f->Get(histoName.c_str()); - av = SetAverageFromHist(h2); - } - if(ndim==3){ - h3 = (TH3F*)f->Get(histoName.c_str()); - av = SetAverageFromHist(h3); - } - return av; -} - -float MMEfficiency::SetAverageFromHist(std::string fileName, std::string histoName,int ndim){ - float av = -1; - TFile *f = TFile::Open(fileName.c_str()); - av = SetAverageFromHist(f,histoName,ndim); - delete f; - return av; -} - -// ------------------------ GetEfficiency ------------------------ // - -float MMEfficiency::GetEfficiency(){ - float eff = 1; - float eff1 = 0; - float v0, v1, v2; - float xmin, ymin, zmin; - float xmax, ymax, zmax; - for(int i=0;i<fNvar;i+=fDim[i]){ - // ensure that x,y,z are inside hist range - if(fDim[i]==3){ - v0 = fVars[i]; - xmin = fHist3D[i]->GetXaxis()->GetXmin(); - xmax = fHist3D[i]->GetXaxis()->GetXmax(); - if(v0<xmin) v0 = xmin; - if(v0>xmax) v0 = xmax-0.001; - v1 = fVars[i+1]; - ymin = fHist3D[i]->GetYaxis()->GetXmin(); - ymax = fHist3D[i]->GetYaxis()->GetXmax(); - if(v1<ymin) v1 = ymin; - if(v1>ymax) v1 = ymax-0.001; - v2 = fVars[i+2]; - zmin = fHist3D[i]->GetZaxis()->GetXmin(); - zmax = fHist3D[i]->GetZaxis()->GetXmax(); - if(v2<zmin) v2 = zmin; - if(v2>zmax) v2 = zmax-0.001; - eff1 = fHist3D[i]->GetBinContent(fHist3D[i]->FindBin(v0,v1,v2)); - } - if(fDim[i]==2){ - v0 = fVars[i]; - xmin = fHist2D[i]->GetXaxis()->GetXmin(); - xmax = fHist2D[i]->GetXaxis()->GetXmax(); - if(v0<xmin) v0 = xmin; - if(v0>xmax) v0 = xmax-0.001; - v1 = fVars[i+1]; - ymin = fHist2D[i]->GetYaxis()->GetXmin(); - ymax = fHist2D[i]->GetYaxis()->GetXmax(); - if(v1<ymin) v1 = ymin; - if(v1>ymax) v1 = ymax-0.001; - eff1 = fHist2D[i]->GetBinContent(fHist2D[i]->FindBin(v0,v1)); - } - if(fDim[i]==1){ - v0 = fVars[i]; - xmin = fHist[i]->GetXaxis()->GetXmin(); - xmax = fHist[i]->GetXaxis()->GetXmax(); - if(v0<xmin) v0 = xmin; - if(v0>xmax) v0 = xmax-0.001; - // fix by Timothée Theveneaux-Pelzer - if ( fHist[i]->GetXaxis()->FindBin(v0) < fHist[i]->FindFirstBinAbove(0) ) { - int bin=fHist[i]->FindFirstBinAbove(0); - eff1 = fHist[i]->GetBinContent(bin); - } - else if ( fHist[i]->GetXaxis()->FindBin(v0) > fHist[i]->FindLastBinAbove(0) ) { - int bin=fHist[i]->FindLastBinAbove(0); - eff1 = fHist[i]->GetBinContent(bin); - } - else eff1 = fHist[i]->GetBinContent(fHist[i]->FindBin(v0)); -// cout << fHist[i]->GetTitle() << endl; - } - // - if(eff1>0 && eff1<1) eff *= eff1; // this is just to avoid crazy eff values going in - else eff *= fAverage; // ... and if the value is non-physica, just give the average eff - // - if(i>0) eff /= fAverage; // divide by average if it's an additional parametrization - } - return eff; -} - -float MMEfficiency::GetAverageEfficiency(){ - return fAverage; -} - -float MMEfficiency::GetEfficiency(float v0,float v1,float v2,float v3,float v4,float v5,float v6,float v7,float v8,float v9){ - SetParVars(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9); - return GetEfficiency(); -} - -// ------------------------ SetParVar(s) ------------------------ // - -void MMEfficiency::SetParVars(float v0,float v1,float v2,float v3,float v4,float v5,float v6,float v7,float v8,float v9){ - SetParVar(0,v0); - if(fNvar>=2) SetParVar(1,v1); - if(fNvar>=3) SetParVar(2,v2); - if(fNvar>=4) SetParVar(3,v3); - if(fNvar>=5) SetParVar(4,v4); - if(fNvar>=6) SetParVar(5,v5); - if(fNvar>=7) SetParVar(6,v6); - if(fNvar>=8) SetParVar(7,v7); - if(fNvar>=9) SetParVar(8,v8); - if(fNvar>=10) SetParVar(9,v9); -} - -void MMEfficiency::SetParVar(int idx,float value){ - fVars[idx] = value; -} - -// ------------------------ Other ------------------------ // - -int MMEfficiency::GetNvars(){ - return fNvar; -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MatrixUtils.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MatrixUtils.cxx deleted file mode 100644 index d20b2a59d9789d9c2bb51263f6cd3a5337f6f3c5..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/MatrixUtils.cxx +++ /dev/null @@ -1,486 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// -// Generic matrix methods fake lepton estimates for lepton and dilepton. -// -// Given loose/tight lepton ID, real efficiency r, -// and fake efficiency f builds the fake estimate event weight -// -// Authors: -// Karl Gellerstedt (kargel@fysik.su.se) -// Jorgen Sjolin (sjolin@fysik.su.se) -// - -#include "TopFakes/MatrixUtils.h" -#include <iostream> -using namespace std; - -MatrixUtils::MatrixUtils() : - ljets_matrix(2,2), - ljets_matrix_top_corr(2,2), - ll_matrix(4,4), - ll_matrix_top_corr(4,4), - lll_matrix(8,8), - i_ljets_matrix(2,2), - i_ljets_matrix_top_corr(2,2), - i_ll_matrix(4,4), - i_ll_matrix_top_corr(4,4), - i_lll_matrix(8,8) -{ - -} - -double MatrixUtils::lepton_weight(bool loose, double r, double f, - double &nf, double & /*nr*/) { - // fix to not return NaN - if(r == 0 && f == 0) - return nf; - - double nl=loose ? 1 :0; - double nt=!loose ? 1 :0; - double a=1./(r-f); - nf=a*f*r*nl + a*f*(r - 1.)*nt; - if(nf!=nf) nf = 0.; // protect against "nan" - return nf; -} - -void MatrixUtils::fill_matrix(double r, double f) -{ - ljets_matrix[0][0] = r; - ljets_matrix[0][1] = f; - ljets_matrix[1][0] = (1. - r); - ljets_matrix[1][1] = (1. - f); - i_ljets_matrix = ljets_matrix; - i_ljets_matrix.InvertFast(); - - ljets_matrix_top_corr[0][0] = r; - ljets_matrix_top_corr[0][1] = f; - ljets_matrix_top_corr[1][0] = (1. - r); - ljets_matrix_top_corr[1][1] = (1. - f); - i_ljets_matrix_top_corr = ljets_matrix_top_corr; - i_ljets_matrix_top_corr.InvertFast(); -} - -void MatrixUtils::fill_matrix(double r, double f, double t) -{ - ljets_matrix[0][0] = r; - ljets_matrix[0][1] = f; - ljets_matrix[1][0] = (1. - r); - ljets_matrix[1][1] = (1. - f); - i_ljets_matrix = ljets_matrix; - i_ljets_matrix.InvertFast(); - - ljets_matrix_top_corr[0][0] = r*t; - ljets_matrix_top_corr[0][1] = f; - ljets_matrix_top_corr[1][0] = (1. - r*t); - ljets_matrix_top_corr[1][1] = (1. - f); - i_ljets_matrix_top_corr = ljets_matrix_top_corr; - i_ljets_matrix_top_corr.InvertFast(); -} - -double MatrixUtils::lepton_tight_weight(bool loose) -{ - double nl=loose ? 1 :0; - double nt=!loose ? 1 :0; - double nf=i_ljets_matrix[1][0]*nt + i_ljets_matrix[1][1]*nl; - double nf_tight=ljets_matrix[0][1]*nf; - return nf_tight; -} - -double MatrixUtils::lepton_loose_weight(bool loose) -{ - double nl=loose ? 1 :0; - double nt=!loose ? 1 :0; - double nf=i_ljets_matrix[1][0]*nt + i_ljets_matrix[1][1]*nl; - double nf_loose=ljets_matrix[1][1]*nf; - return nf_loose; -} - -double MatrixUtils::lepton_tight_top_corr_weight(bool loose) -{ - double nl=loose ? 1 :0; - double nt=!loose ? 1 :0; - double nf=i_ljets_matrix_top_corr[1][0]*nt + i_ljets_matrix_top_corr[1][1]*nl; - double nf_tight=ljets_matrix_top_corr[0][1]*nf; - return nf_tight; -} - -double MatrixUtils::lepton_loose_top_corr_weight(bool loose) -{ - double nl=loose ? 1 :0; - double nt=!loose ? 1 :0; - double nf=i_ljets_matrix_top_corr[1][0]*nt + i_ljets_matrix_top_corr[1][1]*nl; - double nf_tight=ljets_matrix_top_corr[0][1]*nf; - return nf_tight; -} - - -double MatrixUtils::dilepton_weight(bool l1, double r1, double f1, - bool l2, double r2, double f2, - double &nrf, double &nfr, - double &nff) { - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double a=1./((r1-f1)*(r2-f2)); - - nrf= a*r1*f2*( -(1.-f1)*(1.-r2)*ntt + (1.-f1)*r2*ntl + f1*(1.-r2)*nlt - f1*r2*nll ); - - nfr= a*f1*r2*( -(1.-r1)*(1.-f2)*ntt + (1.-r1)*f2*ntl + r1*(1.-f2)*nlt - r1*f2*nll ); - - nff= a*f1*f2*( +(1.-r1)*(1.-r2)*ntt - (1.-r1)*r2*ntl - r1*(1.-r2)*nlt + r1*r2*nll ); - - if(nrf!=nrf) nrf = 0.; // protect against "nan" - if(nfr!=nfr) nfr = 0.; // protect against "nan" - if(nff!=nff) nff = 0.; // protect against "nan" - return nrf+nfr+nff; -} - -void MatrixUtils::fill_matrix(double r1, double f1, double r2, double f2) -{ - ll_matrix[0][0] = r1 * r2; - ll_matrix[0][1] = r1 * f2; - ll_matrix[0][2] = f1 * r2; - ll_matrix[0][3] = f1 * f2; - ll_matrix[1][0] = r1 * (1. - r2); - ll_matrix[1][1] = r1 * (1. - f2); - ll_matrix[1][2] = f1 * (1. - r2); - ll_matrix[1][3] = f1 * (1. - f2); - ll_matrix[2][0] = (1. - r1) * r2; - ll_matrix[2][1] = (1. - r1) * f2; - ll_matrix[2][2] = (1. - f1) * r2; - ll_matrix[2][3] = (1. - f1) * f2; - ll_matrix[3][0] = (1. - r1) * (1. - r2); - ll_matrix[3][1] = (1. - r1) * (1. - f2); - ll_matrix[3][2] = (1. - f1) * (1. - r2); - ll_matrix[3][3] = (1. - f1) * (1. - f2); - i_ll_matrix = ll_matrix; - i_ll_matrix.InvertFast(); - - ll_matrix_top_corr[0][0] = r1 * r2; // RR - ll_matrix_top_corr[0][1] = r1 * f2; - ll_matrix_top_corr[0][2] = f1 * r2; - ll_matrix_top_corr[0][3] = f1 * f2; - ll_matrix_top_corr[1][0] = r1 * (1. - r2); // RR - ll_matrix_top_corr[1][1] = r1 * (1. - f2); - ll_matrix_top_corr[1][2] = f1 * (1. - r2); - ll_matrix_top_corr[1][3] = f1 * (1. - f2); - ll_matrix_top_corr[2][0] = (1. - r1) * r2; // RR - ll_matrix_top_corr[2][1] = (1. - r1) * f2; - ll_matrix_top_corr[2][2] = (1. - f1) * r2; - ll_matrix_top_corr[2][3] = (1. - f1) * f2; - ll_matrix_top_corr[3][0] = (1. - r1) * (1. - r2); // RR - ll_matrix_top_corr[3][1] = (1. - r1) * (1. - f2); - ll_matrix_top_corr[3][2] = (1. - f1) * (1. - r2); - ll_matrix_top_corr[3][3] = (1. - f1) * (1. - f2); - i_ll_matrix_top_corr = ll_matrix_top_corr; - i_ll_matrix_top_corr.InvertFast(); -} - -void MatrixUtils::fill_matrix(double r1, double f1, double t1, double r2, double f2, double t2) -{ - ll_matrix[0][0] = r1 * r2; - ll_matrix[0][1] = r1 * f2; - ll_matrix[0][2] = f1 * r2; - ll_matrix[0][3] = f1 * f2; - ll_matrix[1][0] = r1 * (1. - r2); - ll_matrix[1][1] = r1 * (1. - f2); - ll_matrix[1][2] = f1 * (1. - r2); - ll_matrix[1][3] = f1 * (1. - f2); - ll_matrix[2][0] = (1. - r1) * r2; - ll_matrix[2][1] = (1. - r1) * f2; - ll_matrix[2][2] = (1. - f1) * r2; - ll_matrix[2][3] = (1. - f1) * f2; - ll_matrix[3][0] = (1. - r1) * (1. - r2); - ll_matrix[3][1] = (1. - r1) * (1. - f2); - ll_matrix[3][2] = (1. - f1) * (1. - r2); - ll_matrix[3][3] = (1. - f1) * (1. - f2); - i_ll_matrix = ll_matrix; - i_ll_matrix.InvertFast(); - - // This is to fill and invert the matrix using the correction applied only to the real/real column - ll_matrix_top_corr[0][0] = r1 * t1 * r2 * t2; // RR - ll_matrix_top_corr[0][1] = r1 * f2; - ll_matrix_top_corr[0][2] = f1 * r2; - ll_matrix_top_corr[0][3] = f1 * f2; - ll_matrix_top_corr[1][0] = r1 * t1 * (1. - r2 * t2); // RR - ll_matrix_top_corr[1][1] = r1 * (1. - f2); - ll_matrix_top_corr[1][2] = f1 * (1. - r2); - ll_matrix_top_corr[1][3] = f1 * (1. - f2); - ll_matrix_top_corr[2][0] = (1. - r1 * t1) * r2 * t2; // RR - ll_matrix_top_corr[2][1] = (1. - r1) * f2; - ll_matrix_top_corr[2][2] = (1. - f1) * r2; - ll_matrix_top_corr[2][3] = (1. - f1) * f2; - ll_matrix_top_corr[3][0] = (1. - r1 * t1) * (1. - r2 * t2); // RR - ll_matrix_top_corr[3][1] = (1. - r1) * (1. - f2); - ll_matrix_top_corr[3][2] = (1. - f1) * (1. - r2); - ll_matrix_top_corr[3][3] = (1. - f1) * (1. - f2); - i_ll_matrix_top_corr = ll_matrix_top_corr; - i_ll_matrix_top_corr.InvertFast(); -} - -double MatrixUtils::dilepton_TT_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix[1][0] * ntt + i_ll_matrix[1][1] * ntl + i_ll_matrix[1][2] * nlt + i_ll_matrix[1][3] * nll; - double nfr = i_ll_matrix[2][0] * ntt + i_ll_matrix[2][1] * ntl + i_ll_matrix[2][2] * nlt + i_ll_matrix[2][3] * nll; - double nff = i_ll_matrix[3][0] * ntt + i_ll_matrix[3][1] * ntl + i_ll_matrix[3][2] * nlt + i_ll_matrix[3][3] * nll; - - double nrf_TT = ll_matrix[0][1] * nrf; - double nfr_TT = ll_matrix[0][2] * nfr; - double nff_TT = ll_matrix[0][3] * nff; - - return nrf_TT + nfr_TT + nff_TT; -} - -double MatrixUtils::dilepton_TL_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix[1][0] * ntt + i_ll_matrix[1][1] * ntl + i_ll_matrix[1][2] * nlt + i_ll_matrix[1][3] * nll; - double nfr = i_ll_matrix[2][0] * ntt + i_ll_matrix[2][1] * ntl + i_ll_matrix[2][2] * nlt + i_ll_matrix[2][3] * nll; - double nff = i_ll_matrix[3][0] * ntt + i_ll_matrix[3][1] * ntl + i_ll_matrix[3][2] * nlt + i_ll_matrix[3][3] * nll; - - double nrf_TL = ll_matrix[1][1] * nrf; - double nfr_TL = ll_matrix[1][2] * nfr; - double nff_TL = ll_matrix[1][3] * nff; - - return nrf_TL + nfr_TL + nff_TL; -} - -double MatrixUtils::dilepton_LT_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix[1][0] * ntt + i_ll_matrix[1][1] * ntl + i_ll_matrix[1][2] * nlt + i_ll_matrix[1][3] * nll; - double nfr = i_ll_matrix[2][0] * ntt + i_ll_matrix[2][1] * ntl + i_ll_matrix[2][2] * nlt + i_ll_matrix[2][3] * nll; - double nff = i_ll_matrix[3][0] * ntt + i_ll_matrix[3][1] * ntl + i_ll_matrix[3][2] * nlt + i_ll_matrix[3][3] * nll; - - double nrf_LT = ll_matrix[2][1] * nrf; - double nfr_LT = ll_matrix[2][2] * nfr; - double nff_LT = ll_matrix[2][3] * nff; - - return nrf_LT + nfr_LT + nff_LT; -} - -double MatrixUtils::dilepton_LL_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix[1][0] * ntt + i_ll_matrix[1][1] * ntl + i_ll_matrix[1][2] * nlt + i_ll_matrix[1][3] * nll; - double nfr = i_ll_matrix[2][0] * ntt + i_ll_matrix[2][1] * ntl + i_ll_matrix[2][2] * nlt + i_ll_matrix[2][3] * nll; - double nff = i_ll_matrix[3][0] * ntt + i_ll_matrix[3][1] * ntl + i_ll_matrix[3][2] * nlt + i_ll_matrix[3][3] * nll; - - double nrf_LL = ll_matrix[3][1] * nrf; - double nfr_LL = ll_matrix[3][2] * nfr; - double nff_LL = ll_matrix[3][3] * nff; - - return nrf_LL + nfr_LL + nff_LL; -} - -double MatrixUtils::dilepton_TT_top_corr_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix_top_corr[1][0] * ntt + i_ll_matrix_top_corr[1][1] * ntl + i_ll_matrix_top_corr[1][2] * nlt + i_ll_matrix_top_corr[1][3] * nll; - double nfr = i_ll_matrix_top_corr[2][0] * ntt + i_ll_matrix_top_corr[2][1] * ntl + i_ll_matrix_top_corr[2][2] * nlt + i_ll_matrix_top_corr[2][3] * nll; - double nff = i_ll_matrix_top_corr[3][0] * ntt + i_ll_matrix_top_corr[3][1] * ntl + i_ll_matrix_top_corr[3][2] * nlt + i_ll_matrix_top_corr[3][3] * nll; - - double nrf_TT = ll_matrix_top_corr[0][1] * nrf; - double nfr_TT = ll_matrix_top_corr[0][2] * nfr; - double nff_TT = ll_matrix_top_corr[0][3] * nff; - - return nrf_TT + nfr_TT + nff_TT; -} - -double MatrixUtils::dilepton_TL_top_corr_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix_top_corr[1][0] * ntt + i_ll_matrix_top_corr[1][1] * ntl + i_ll_matrix_top_corr[1][2] * nlt + i_ll_matrix_top_corr[1][3] * nll; - double nfr = i_ll_matrix_top_corr[2][0] * ntt + i_ll_matrix_top_corr[2][1] * ntl + i_ll_matrix_top_corr[2][2] * nlt + i_ll_matrix_top_corr[2][3] * nll; - double nff = i_ll_matrix_top_corr[3][0] * ntt + i_ll_matrix_top_corr[3][1] * ntl + i_ll_matrix_top_corr[3][2] * nlt + i_ll_matrix_top_corr[3][3] * nll; - - double nrf_TL = ll_matrix_top_corr[1][1] * nrf; - double nfr_TL = ll_matrix_top_corr[1][2] * nfr; - double nff_TL = ll_matrix_top_corr[1][3] * nff; - - return nrf_TL + nfr_TL + nff_TL; -} - -double MatrixUtils::dilepton_LT_top_corr_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix_top_corr[1][0] * ntt + i_ll_matrix_top_corr[1][1] * ntl + i_ll_matrix_top_corr[1][2] * nlt + i_ll_matrix_top_corr[1][3] * nll; - double nfr = i_ll_matrix_top_corr[2][0] * ntt + i_ll_matrix_top_corr[2][1] * ntl + i_ll_matrix_top_corr[2][2] * nlt + i_ll_matrix_top_corr[2][3] * nll; - double nff = i_ll_matrix_top_corr[3][0] * ntt + i_ll_matrix_top_corr[3][1] * ntl + i_ll_matrix_top_corr[3][2] * nlt + i_ll_matrix_top_corr[3][3] * nll; - - double nrf_LT = ll_matrix_top_corr[2][1] * nrf; - double nfr_LT = ll_matrix_top_corr[2][2] * nfr; - double nff_LT = ll_matrix_top_corr[2][3] * nff; - - return nrf_LT + nfr_LT + nff_LT; -} - -double MatrixUtils::dilepton_LL_top_corr_weight(bool l1, bool l2) -{ - double ntt=((!l1)&&(!l2)?1.:0.); - double ntl=((!l1)&&( l2)?1.:0.); - double nlt=(( l1)&&(!l2)?1.:0.); - double nll=(( l1)&&( l2)?1.:0.); - - double nrf = i_ll_matrix_top_corr[1][0] * ntt + i_ll_matrix_top_corr[1][1] * ntl + i_ll_matrix_top_corr[1][2] * nlt + i_ll_matrix_top_corr[1][3] * nll; - double nfr = i_ll_matrix_top_corr[2][0] * ntt + i_ll_matrix_top_corr[2][1] * ntl + i_ll_matrix_top_corr[2][2] * nlt + i_ll_matrix_top_corr[2][3] * nll; - double nff = i_ll_matrix_top_corr[3][0] * ntt + i_ll_matrix_top_corr[3][1] * ntl + i_ll_matrix_top_corr[3][2] * nlt + i_ll_matrix_top_corr[3][3] * nll; - - double nrf_LL = ll_matrix_top_corr[3][1] * nrf; - double nfr_LL = ll_matrix_top_corr[3][2] * nfr; - double nff_LL = ll_matrix_top_corr[3][3] * nff; - - return nrf_LL + nfr_LL + nff_LL; -} - -void MatrixUtils::fill_lll_matrix(double r1, double f1, double r2, double f2, double r3, double f3) -{ - - lll_matrix[0][0] = r1 * r2 * r3; - lll_matrix[0][1] = r1 * r2 * f3; - lll_matrix[0][2] = r1 * f2 * r3; - lll_matrix[0][3] = r1 * f2 * f3; - lll_matrix[0][4] = f1 * r2 * r3; - lll_matrix[0][5] = f1 * r2 * f3; - lll_matrix[0][6] = f1 * f2 * r3; - lll_matrix[0][7] = f1 * f2 * f3; - - lll_matrix[1][0] = r1 * r2 * (1. - r3); - lll_matrix[1][1] = r1 * r2 * (1. - f3); - lll_matrix[1][2] = r1 * f2 * (1. - r3); - lll_matrix[1][3] = r1 * f2 * (1. - f3); - lll_matrix[1][4] = f1 * r2 * (1. - r3); - lll_matrix[1][5] = f1 * r2 * (1. - f3); - lll_matrix[1][6] = f1 * f2 * (1. - r3); - lll_matrix[1][7] = f1 * f2 * (1. - f3); - - lll_matrix[2][0] = r1 * (1. - r2) * r3; - lll_matrix[2][1] = r1 * (1. - r2) * f3; - lll_matrix[2][2] = r1 * (1. - f2) * r3; - lll_matrix[2][3] = r1 * (1. - f2) * f3; - lll_matrix[2][4] = f1 * (1. - r2) * r3; - lll_matrix[2][5] = f1 * (1. - r2) * f3; - lll_matrix[2][6] = f1 * (1. - f2) * r3; - lll_matrix[2][7] = f1 * (1. - f2) * f3; - - lll_matrix[3][0] = r1 * (1. - r2) * (1. - r3); - lll_matrix[3][1] = r1 * (1. - r2) * (1. - f3); - lll_matrix[3][2] = r1 * (1. - f2) * (1. - r3); - lll_matrix[3][3] = r1 * (1. - f2) * (1. - f3); - lll_matrix[3][4] = f1 * (1. - r2) * (1. - r3); - lll_matrix[3][5] = f1 * (1. - r2) * (1. - f3); - lll_matrix[3][6] = f1 * (1. - f2) * (1. - r3); - lll_matrix[3][7] = f1 * (1. - f2) * (1. - f3); - - lll_matrix[4][0] = (1. - r1) * r2 * r3; - lll_matrix[4][1] = (1. - r1) * r2 * f3; - lll_matrix[4][2] = (1. - r1) * f2 * r3; - lll_matrix[4][3] = (1. - r1) * f2 * f3; - lll_matrix[4][4] = (1. - f1) * r2 * r3; - lll_matrix[4][5] = (1. - f1) * r2 * f3; - lll_matrix[4][6] = (1. - f1) * f2 * r3; - lll_matrix[4][7] = (1. - f1) * f2 * f3; - - lll_matrix[5][0] = (1. - r1) * r2 * (1. - r3); - lll_matrix[5][1] = (1. - r1) * r2 * (1. - f3); - lll_matrix[5][2] = (1. - r1) * f2 * (1. - r3); - lll_matrix[5][3] = (1. - r1) * f2 * (1. - f3); - lll_matrix[5][4] = (1. - f1) * r2 * (1. - r3); - lll_matrix[5][5] = (1. - f1) * r2 * (1. - f3); - lll_matrix[5][6] = (1. - f1) * f2 * (1. - r3); - lll_matrix[5][7] = (1. - f1) * f2 * (1. - f3); - - lll_matrix[6][0] = (1. - r1) * (1. - r2) * r3; - lll_matrix[6][1] = (1. - r1) * (1. - r2) * f3; - lll_matrix[6][2] = (1. - r1) * (1. - f2) * r3; - lll_matrix[6][3] = (1. - r1) * (1. - f2) * f3; - lll_matrix[6][4] = (1. - f1) * (1. - r2) * r3; - lll_matrix[6][5] = (1. - f1) * (1. - r2) * f3; - lll_matrix[6][6] = (1. - f1) * (1. - f2) * r3; - lll_matrix[6][7] = (1. - f1) * (1. - f2) * f3; - - lll_matrix[7][0] = (1. - r1) * (1. - r2) * (1. - r3); - lll_matrix[7][1] = (1. - r1) * (1. - r2) * (1. - f3); - lll_matrix[7][2] = (1. - r1) * (1. - f2) * (1. - r3); - lll_matrix[7][3] = (1. - r1) * (1. - f2) * (1. - f3); - lll_matrix[7][4] = (1. - f1) * (1. - r2) * (1. - r3); - lll_matrix[7][5] = (1. - f1) * (1. - r2) * (1. - f3); - lll_matrix[7][6] = (1. - f1) * (1. - f2) * (1. - r3); - lll_matrix[7][7] = (1. - f1) * (1. - f2) * (1. - f3); - - i_lll_matrix = lll_matrix; - i_lll_matrix.InvertFast(); - -} - -double MatrixUtils::trilepton_weight(bool l1, bool l2, bool l3){ - - double nttt=(((!l1)&&(!l2)&&(!l3))?1.:0.); - double nttl=(((!l1)&&(!l2)&&( l3))?1.:0.); - double ntlt=(((!l1)&&( l2)&&(!l3))?1.:0.); - double ntll=(((!l1)&&( l2)&&( l3))?1.:0.); - double nltt=((( l1)&&(!l2)&&(!l3))?1.:0.); - double nltl=((( l1)&&(!l2)&&( l3))?1.:0.); - double nllt=((( l1)&&( l2)&&(!l3))?1.:0.); - double nlll=((( l1)&&( l2)&&( l3))?1.:0.); - - double nrrf = i_lll_matrix[1][0] * nttt + i_lll_matrix[1][1] * nttl + i_lll_matrix[1][2] * ntlt + i_lll_matrix[1][3] * ntll - + i_lll_matrix[1][4] * nltt + i_lll_matrix[1][5] * nltl + i_lll_matrix[1][6] * nllt + i_lll_matrix[1][7] * nlll; - double nrfr = i_lll_matrix[2][0] * nttt + i_lll_matrix[2][1] * nttl + i_lll_matrix[2][2] * ntlt + i_lll_matrix[2][3] * ntll - + i_lll_matrix[2][4] * nltt + i_lll_matrix[2][5] * nltl + i_lll_matrix[2][6] * nllt + i_lll_matrix[2][7] * nlll; - double nrff = i_lll_matrix[3][0] * nttt + i_lll_matrix[3][1] * nttl + i_lll_matrix[3][2] * ntlt + i_lll_matrix[3][3] * ntll - + i_lll_matrix[3][4] * nltt + i_lll_matrix[3][5] * nltl + i_lll_matrix[3][6] * nllt + i_lll_matrix[3][7] * nlll; - double nfrr = i_lll_matrix[4][0] * nttt + i_lll_matrix[4][1] * nttl + i_lll_matrix[4][2] * ntlt + i_lll_matrix[4][3] * ntll - + i_lll_matrix[4][4] * nltt + i_lll_matrix[4][5] * nltl + i_lll_matrix[4][6] * nllt + i_lll_matrix[4][7] * nlll; - double nfrf = i_lll_matrix[5][0] * nttt + i_lll_matrix[5][1] * nttl + i_lll_matrix[5][2] * ntlt + i_lll_matrix[5][3] * ntll - + i_lll_matrix[5][4] * nltt + i_lll_matrix[5][5] * nltl + i_lll_matrix[5][6] * nllt + i_lll_matrix[5][7] * nlll; - double nffr = i_lll_matrix[6][0] * nttt + i_lll_matrix[6][1] * nttl + i_lll_matrix[6][2] * ntlt + i_lll_matrix[6][3] * ntll - + i_lll_matrix[6][4] * nltt + i_lll_matrix[6][5] * nltl + i_lll_matrix[6][6] * nllt + i_lll_matrix[6][7] * nlll; - double nfff = i_lll_matrix[7][0] * nttt + i_lll_matrix[7][1] * nttl + i_lll_matrix[7][2] * ntlt + i_lll_matrix[7][3] * ntll - + i_lll_matrix[7][4] * nltt + i_lll_matrix[7][5] * nltl + i_lll_matrix[7][6] * nllt + i_lll_matrix[7][7] * nlll; - - double nrrf_TT = lll_matrix[0][1] * nrrf; - double nrfr_TT = lll_matrix[0][2] * nrfr; - double nrff_TT = lll_matrix[0][3] * nrff; - double nfrr_TT = lll_matrix[0][4] * nfrr; - double nfrf_TT = lll_matrix[0][5] * nfrf; - double nffr_TT = lll_matrix[0][6] * nffr; - double nfff_TT = lll_matrix[0][6] * nfff; - - return nrrf_TT + nrfr_TT + nrff_TT + nfrr_TT + nfrf_TT + nffr_TT + nfff_TT; - -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/TopFakesMMWeightCalculator.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/TopFakesMMWeightCalculator.cxx deleted file mode 100644 index 3612d0842b562a6019ad7b5acdd26d6e1f27c14c..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/TopFakesMMWeightCalculator.cxx +++ /dev/null @@ -1,864 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -////////////////////////////////////////////////////////////////////// -// -// Author : -// Timothée Theveneaux-Pelzer -// Creation : -// Purpose : helper to be used in analyses -// -// Updated : -// 2016-01-29 : FD: set default values for Run2 and 1st efficiencies -////////////////////////////////////////////////////////////////////// - -#include "TopFakes/TopFakesMMWeightCalculator.h" -#include "TopFakes/TopFakesxAODUtils.h" -#include "TopConfiguration/TopConfig.h" -#include "TopConfiguration/ConfigurationSettings.h" -// #include "TopEvent/Event.h" -#include "TopEvent/EventTools.h" -#include "TopEvent/TopEventMaker.h" -#include "TopFakes/FakesWeights.h" -#include "TopFakes/MMEfficiency.h" -#include "TopFakes/MatrixUtils.h" -#include "TopFakes/MMEffSet.h" -#define XXX std::cout << "I am here: " << __FILE__ << ":" << __LINE__ << std::endl; - -namespace top{ - - TopFakesMMWeightCalculator::TopFakesMMWeightCalculator( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr), - m_dir(""), - m_debug(false)//, -// m_leptonDefs(fakes::LeptonDefinitions::Standard) - { - ATH_MSG_INFO(" constructor of top::TopFakesMMWeightCalculator "+name ); - declareProperty( "config" , m_config ); - } - - TopFakesMMWeightCalculator::~TopFakesMMWeightCalculator() - { - } - - // ============================================================= - StatusCode TopFakesMMWeightCalculator::initialize() - { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator initialize" ); - - m_dir = m_config->FakesMMDir(); - m_debug = m_config->FakesMMDebug(); - ATH_MSG_INFO(" Directory for efficiencies: "+m_dir ); - if (std::find(m_config->bTagWP_available().begin(), m_config->bTagWP_available().end(), "FixedCutBEff_77") == m_config->bTagWP_available().end()) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator initialize" ); - std::cout<<"B-tagging WP FixedCutBEff_77 is needed to parametrise efficiencies."<<std::endl; - std::cout<<"Please set it up by writing \"BTaggingWP FixedCutBEff_77\" or \"BTaggingWP %77\" in your configuration file."<<std::endl; - return StatusCode::FAILURE; - } - - return StatusCode::SUCCESS; - } - - StatusCode TopFakesMMWeightCalculator::setSelectionConfigs(std::string selection, std::vector<std::string> configs) - { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - - auto* const settings = top::ConfigurationSettings::get(); - const std::vector<top::SelectionConfigurationData> selections = settings->selections(); - for(std::string config : configs){ - std::istringstream ss(config); - std::vector<std::string> listofkeys; - std::string token; - while(std::getline(ss, token, ',')) {//parameters are separated by commas - listofkeys.push_back(token); - } - // check if number of parameters is ok - if (listofkeys.size()<3 || listofkeys.size()>7) {//need at least 3 and no more than 7 parameters - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - return StatusCode::FAILURE; - } - - // check if configuration already defined for another selection - if (m_fakesWeightTools.count(selection) !=0) { - if (m_fakesWeightTools[selection].count(listofkeys.at(0)) !=0) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The configuration "<<listofkeys.at(0)<<"is already defined for selection "<<selection<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - } - - // first argument must define the period - check if it's valid - int period = getPeriod(listofkeys.at(1)); - if (period == -1) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"Can't recognise period "<<listofkeys.at(1)<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - } - - // second argument is the channel - if (listofkeys.at(2)=="EJETS") { - if (listofkeys.size()<3 || listofkeys.size()>5) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(2)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Correct syntax (1): <config name>,EJETS"<<std::endl; - std::cout<<"Correct syntax (2): <config name>,EJETS,<systematic variation>"<<std::endl; - std::cout<<"Correct syntax (3): <config name>,EJETS,<real eff configuration>,<fake eff configuration>"<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)] = std::shared_ptr<FakesWeights>(new FakesWeights()); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDebug(m_debug); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDataPath(m_dir); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetPeriod(period); - if (listofkeys.size()==3) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::EJETS); - } - else if (listofkeys.size()==4) { - if (listofkeys.at(3)!="MCup" && listofkeys.at(3)!="MCdown" && listofkeys.at(3)!="MCupel" && listofkeys.at(3)!="MCdownel" && listofkeys.at(3)!="CRfake" && listofkeys.at(3)!="CRfakeel" && listofkeys.at(3)!="CRreal" && listofkeys.at(3)!="CRrealel" && listofkeys.at(3)!="EffPar") { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Systematic variation "<<listofkeys.at(2)<<" not recognised."<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::EJETS,listofkeys.at(3)); - } - } - else if (listofkeys.size()==5) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighter(FakesWeights::EJETS,listofkeys.at(3),listofkeys.at(4)); - } - } - } - else if (listofkeys.at(2)=="MUJETS") { - if (listofkeys.size()<3 || listofkeys.size()>5) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Correct syntax (1): <config name>,MUJETS"<<std::endl; - std::cout<<"Correct syntax (2): <config name>,MUJETS,<systematic variation>"<<std::endl; - std::cout<<"Correct syntax (3): <config name>,MUJETS,<real eff configuration>,<fake eff configuration>"<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)] = std::shared_ptr<FakesWeights>(new FakesWeights()); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDebug(m_debug); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDataPath(m_dir); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetPeriod(period); - if (listofkeys.size()==3) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::MUJETS); - } - else if (listofkeys.size()==4) { - if (listofkeys.at(3)!="MCup" && listofkeys.at(3)!="MCdown" && listofkeys.at(3)!="MCupmu" && listofkeys.at(3)!="MCdownmu" && listofkeys.at(3)!="CRfake" && listofkeys.at(3)!="CRfakemu" && listofkeys.at(3)!="CRreal" && listofkeys.at(3)!="CRrealmu" && listofkeys.at(3)!="EffPar") { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Systematic variation "<<listofkeys.at(3)<<" not recognised."<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::MUJETS,listofkeys.at(3)); - } - } - else if (listofkeys.size()==5) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighter(FakesWeights::MUJETS,listofkeys.at(3),listofkeys.at(4)); - } - } - } - else if (listofkeys.at(2)=="EE") { - if (listofkeys.size()<3 || listofkeys.size()>5) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Correct syntax (1): <config name>,EE"<<std::endl; - std::cout<<"Correct syntax (2): <config name>,EE,<systematic variation>"<<std::endl; - std::cout<<"Correct syntax (3): <config name>,EE,<real eff configuration>,<fake eff configuration>"<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)] = std::shared_ptr<FakesWeights>(new FakesWeights()); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDebug(m_debug); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDataPath(m_dir); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetPeriod(period); - if (listofkeys.size()==3) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::EE); - } - else if (listofkeys.size()==4) { - if (listofkeys.at(3)!="MCup" && listofkeys.at(3)!="MCdown" && listofkeys.at(3)!="MCupel" && listofkeys.at(3)!="MCdownel" && listofkeys.at(3)!="CRfake" && listofkeys.at(3)!="CRfakeel" && listofkeys.at(3)!="CRreal" && listofkeys.at(3)!="CRrealel" && listofkeys.at(3)!="EffPar") { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Systematic variation "<<listofkeys.at(3)<<" not recognised."<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::EE,listofkeys.at(3)); - } - } - else if (listofkeys.size()==4) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighter(FakesWeights::EE,listofkeys.at(3),listofkeys.at(4)); - } - } - } - else if (listofkeys.at(2)=="EMU") { - if (listofkeys.size()!=3 && listofkeys.size()!=4 && listofkeys.size()!=7) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Correct syntax (1): <config name>,EMU"<<std::endl; - std::cout<<"Correct syntax (2): <config name>,EMU,<systematic variation>"<<std::endl; - std::cout<<"Correct syntax (3): <config name>,EMU,<electron real eff configuration>,<electron fake eff configuration>,<muon real eff configuration>,<muon fake eff configuration>"<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)] = std::shared_ptr<FakesWeights>(new FakesWeights()); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDebug(m_debug); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDataPath(m_dir); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetPeriod(period); - if (listofkeys.size()==3) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::EMU); - } - else if (listofkeys.size()==4) { - if (listofkeys.at(3)!="MCup" && listofkeys.at(3)!="MCdown" && listofkeys.at(3)!="MCupel" && listofkeys.at(3)!="MCdownel" && listofkeys.at(3)!="MCupmu" && listofkeys.at(3)!="MCdownmu" && listofkeys.at(3)!="CRfake" && listofkeys.at(3)!="CRfakeel" && listofkeys.at(3)!="CRfakemu" && listofkeys.at(3)!="CRreal" && listofkeys.at(3)!="CRrealel" && listofkeys.at(3)!="CRrealmu" && listofkeys.at(3)!="EffPar") { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Systematic variation "<<listofkeys.at(3)<<" not recognised."<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::EMU,listofkeys.at(3)); - } - } - else if (listofkeys.size()==7) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighter(FakesWeights::EMU,listofkeys.at(3),listofkeys.at(4),listofkeys.at(5),listofkeys.at(6)); - } - } - } - else if (listofkeys.at(2)=="MUMU") { - if (listofkeys.size()<3 || listofkeys.size()>5) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Correct syntax (1): <config name>,MUMU"<<std::endl; - std::cout<<"Correct syntax (2): <config name>,MUMU,<systematic variation>"<<std::endl; - std::cout<<"Correct syntax (3): <config name>,MUMU,<real eff configuration>,<fake eff configuration>"<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)] = std::shared_ptr<FakesWeights>(new FakesWeights()); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDebug(m_debug); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetDataPath(m_dir); - m_fakesWeightTools[selection][listofkeys.at(0)]->SetPeriod(period); - if (listofkeys.size()==3) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::MUMU); - } - else if (listofkeys.size()==4) { - if (listofkeys.at(3)!="MCup" && listofkeys.at(3)!="MCdown" && listofkeys.at(3)!="MCupmu" && listofkeys.at(3)!="MCdownmu" && listofkeys.at(3)!="CRfake" && listofkeys.at(3)!="CRfakemu" && listofkeys.at(3)!="CRreal" && listofkeys.at(3)!="CRrealmu" && listofkeys.at(3)!="EffPar") { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"The following "<<listofkeys.at(1)<<" configuration is ill-defined:"<<std::endl; - std::cout<<config<<std::endl; - std::cout<<"Systematic variation "<<listofkeys.at(3)<<" not recognised."<<std::endl; - std::cout<<"Exiting.... "<<std::endl; - return StatusCode::FAILURE; - } - else { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighterDefault(FakesWeights::MUMU,listofkeys.at(3)); - } - } - else if (listofkeys.size()==5) { - m_fakesWeightTools[selection][listofkeys.at(0)]->SetupWeighter(FakesWeights::MUMU,listofkeys.at(3),listofkeys.at(4)); - } - } - } - else { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator setSelectionConfigs" ); - std::cout<<"Unknown configuration type "<<listofkeys.at(1)<<" of configuration "<<listofkeys.at(0)<<" for selection "<<selection<<std::endl; - return StatusCode::FAILURE; - } - } - return StatusCode::SUCCESS; - } - - // =========================================================== - StatusCode TopFakesMMWeightCalculator::execute(top::Event* topEvent) - { - const xAOD::EventInfo* event_info = topEvent->m_info; - const xAOD::ElectronContainer* electrons = &topEvent->m_electrons; - const xAOD::MuonContainer* muons = &topEvent->m_muons; - const xAOD::JetContainer* jets = &topEvent->m_jets; - const xAOD::MissingET* MET = topEvent->m_met; - - if (event_info->eventType(xAOD::EventInfo::IS_SIMULATION)) {// no MM weight to be calculated for MC events - return StatusCode::SUCCESS; - } - else { - auto* const settings = top::ConfigurationSettings::get(); - const std::vector<top::SelectionConfigurationData> selections = settings->selections(); - for(auto scd : selections){//loop on selections - bool pass = false; - if (event_info->isAvailable<int>(scd.m_name)) - pass = event_info->auxdataConst<int>(scd.m_name); - if (!pass) - continue;// if the selection is not passed, don't decorate the event with MM weight - for(auto configs : m_fakesWeightTools[scd.m_name]) {// loop on the configurations associated to this selection - std::string config_name = configs.first; - std::string decorName = "MMWeight_"; decorName += scd.m_name; decorName += "_"; decorName += config_name; - if (event_info->isAvailable<float>(decorName)) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Current event already decorated with "<<decorName<<std::endl; - std::cout<<"Don't want to re-calculate it. Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - float mmweight = -999.; - auto weighter = m_fakesWeightTools[scd.m_name][config_name]; - if (weighter==nullptr) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Weighter is not defined for "<<scd.m_name<<" "<<config_name<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - if (m_debug) { - std::cout<<"=====================================>Selection: "<<scd.m_name<<" Configuration: "<<config_name<<std::endl; - } - if (weighter->Channel()==FakesWeights::EJETS) { - try { - mmweight = getMMweightE(weighter, *MET, *electrons, *jets, event_info); - } - catch(std::exception& e) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Could not calculate EJETS MM weight for "<<decorName<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - } - else if (weighter->Channel()==FakesWeights::MUJETS) { - try { - mmweight = getMMweightM(weighter, *MET, *muons, *jets, event_info); - } - catch(std::exception& e) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Could not calculate MUJETS weight for "<<decorName<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - } - else if (weighter->Channel()==FakesWeights::EE) { - try { - mmweight = getMMweightEE(weighter, *MET, *electrons, *jets, event_info); - } - catch(std::exception& e) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Could not calculate EE weight for "<<decorName<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - } - else if (weighter->Channel()==FakesWeights::MUMU) { - try { - mmweight = getMMweightMM(weighter, *MET, *muons, *jets, event_info); - } - catch(std::exception& e) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Could not calculate MUMU weight for "<<decorName<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - } - else if (weighter->Channel()==FakesWeights::EMU) { - try { - mmweight = getMMweightEM(weighter, *MET, *electrons, *muons, *jets, event_info); - } - catch(std::exception& e) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Could not calculate EMU weight for "<<decorName<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - } - else { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator execute" ); - std::cout<<"Unable to retrieve the channel of FakesWeights object while calculating weight "<<decorName<<std::endl; - std::cout<<"Exiting... "<<std::endl; - return StatusCode::FAILURE; - } - event_info->auxdecor<float>(decorName) = mmweight; - } - } - } - return StatusCode::SUCCESS; - } - - // ================================================================== - float TopFakesMMWeightCalculator::getMMweightE(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::ElectronContainer& els, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info) - { - // - // Compute weight for e+jets channel - // - float mmWeightE = 0; - - /// not used for the moment -// std::vector<unsigned int> good_els_index = fakes::GetGoodHighPtLeptons(els); - - if (els.size()<1) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator::getMMweightE" ); - throw std::runtime_error("Need at least one electron to calculate EJETS matrix-method weight"); - } - - // if more than 1 electron, just take the leading one (i.e. the first in the container) - MMLepton *lept = getLeptonMMInfo(*els[0], jets, met, event_info); - MMEvent *evt = getEventMMInfo(jets, met); - - if (lept==0 || evt==0) { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator::getMMweightE" ); - ATH_MSG_INFO(" Unable to define MMLepton or MMEvent object" ); - mmWeightE = -999.; - } - else { - weighter->SetLepton(*evt,*lept); - mmWeightE = weighter->GetFakesWeightLJets(els[0]->auxdataConst<char>("passPreORSelection")); - } - - delete lept; - delete evt; - - if (m_debug) { - std::cout<<"==============>mmWeightE="<<mmWeightE<<std::endl; - std::cout<<"====>r1="<<weighter->GetRealEff()<<" f1="<<weighter->GetFakeEff()<<std::endl; - } - - return mmWeightE; - } - - // ================================================================== - float TopFakesMMWeightCalculator::getMMweightM(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::MuonContainer& mus, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info) - { - // - // Compute weight for m+jets channel - // - float mmWeightM = 0; - - /// not used for the moment -// std::vector<unsigned int> good_mus_index = fakes::GetGoodHighPtLeptons(mus); - - if (mus.size()<1) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator::getMMweightM" ); - throw std::runtime_error("Need at least one muon to calculate MUJETS matrix-method weight"); - } - - // if more than 1 muon, just take the leading one (i.e. the first in the container) - MMLepton *lept = getLeptonMMInfo(*mus[0], jets, met, event_info); - MMEvent *evt = getEventMMInfo(jets, met); - - if (lept==0 || evt==0) { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator::getMMweightM" ); - ATH_MSG_INFO(" Unable to define MMLepton or MMEvent object" ); - mmWeightM = -999.; - } - else { - weighter->SetLepton(*evt,*lept); - mmWeightM = weighter->GetFakesWeightLJets(mus[0]->auxdataConst<char>("passPreORSelection")); - } - - delete lept; - delete evt; - - if (m_debug) { - std::cout<<"==============>mmWeightM="<<mmWeightM<<std::endl; - std::cout<<"====>r1="<<weighter->GetRealEff()<<" f1="<<weighter->GetFakeEff()<<std::endl; - } - - return mmWeightM; - } - - // ================================================================== - float TopFakesMMWeightCalculator::getMMweightEE(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::ElectronContainer& els, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info) - { - // - // Compute weight for ee channel - // - float mmWeightEE = 0; - - /// not used for the moment -// std::vector<unsigned int> good_els_index = fakes::GetGoodHighPtLeptons(els); - - if (els.size()<2) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator::getMMweightEE" ); - throw std::runtime_error("Need at least two electrons to calculate EE matrix-method weight"); - } - - // if more than 2 electrons, just take the two leading ones (i.e. the first in the container) - MMLepton *lept_e1 = getLeptonMMInfo(*els[0], jets, met, event_info); - MMLepton *lept_e2 = getLeptonMMInfo(*els[1], jets, met, event_info); - MMEvent *evt = getEventMMInfo(jets, met); - - if (lept_e1==0 || lept_e2==0 || evt==0) { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator::getMMweightEE" ); - ATH_MSG_INFO(" Unable to define MMLepton or MMEvent object" ); - mmWeightEE = 0.; - } - else { - weighter->SetLeptons(*evt,*lept_e1,*lept_e2); - mmWeightEE = weighter->GetFakesWeightDilep(els[0]->auxdataConst<char>("passPreORSelection"),els[1]->auxdataConst<char>("passPreORSelection")); - } - - delete lept_e1; - delete lept_e2; - delete evt; - - if (m_debug) { - std::cout<<"==============>mmWeightEE="<<mmWeightEE<<std::endl; - std::cout<<"====>r1="<<weighter->GetRealEff()<<" f1="<<weighter->GetFakeEff()<<" r2="<<weighter->GetRealEff2()<<" f2="<<weighter->GetFakeEff2()<<std::endl; - } - - return mmWeightEE; - } - - // ================================================================== - float TopFakesMMWeightCalculator::getMMweightMM(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::MuonContainer& mus, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info) - { - // - // Compute weight for mm channel - // - float mmWeightMM = 0; - - /// not used for the moment -// std::vector<unsigned int> good_mus_index = fakes::GetGoodHighPtLeptons(mus); - - if (mus.size()<2) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator::getMMweightMM" ); - throw std::runtime_error("Need at least two muons to calculate MUMU matrix-method weight"); - } - - // if more than 2 muons, just take the two leading ones (i.e. the first in the container) - MMLepton *lept_m1 = getLeptonMMInfo(*mus[0], jets, met, event_info); - MMLepton *lept_m2 = getLeptonMMInfo(*mus[1], jets, met, event_info); - MMEvent *evt = getEventMMInfo(jets, met); - - if (lept_m1==0 || lept_m2==0 || evt==0) { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator::getMMweightMM" ); - ATH_MSG_INFO(" Unable to define MMLepton or MMEvent object" ); - mmWeightMM = 0.; - } - else { - weighter->SetLeptons(*evt,*lept_m1,*lept_m2); - mmWeightMM = weighter->GetFakesWeightDilep(mus[0]->auxdataConst<char>("passPreORSelection"),mus[1]->auxdataConst<char>("passPreORSelection")); - } - - delete lept_m1; - delete lept_m2; - delete evt; - - if (m_debug) { - std::cout<<"==============>mmWeightMM="<<mmWeightMM<<std::endl; - std::cout<<"====>r1="<<weighter->GetRealEff()<<" f1="<<weighter->GetFakeEff()<<" r2="<<weighter->GetRealEff2()<<" f2="<<weighter->GetFakeEff2()<<std::endl; - } - - return mmWeightMM; - } - - // ================================================================== - float TopFakesMMWeightCalculator::getMMweightEM(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::ElectronContainer& els, const xAOD::MuonContainer& mus, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info) - { - // - // Compute weight for em channel - // - float mmWeightEM = 0; - - /// not used for the moment -// std::vector<unsigned int> good_els_index = fakes::GetGoodHighPtLeptons(els); -// std::vector<unsigned int> good_mus_index = fakes::GetGoodHighPtLeptons(mus); - - if (els.size()<1) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator::getMMweightEM" ); - throw std::runtime_error("Need at least one electron to calculate EMU matrix-method weight"); - } - if (mus.size()<1) { - ATH_MSG_ERROR(" top::TopFakesMMWeightCalculator::getMMweightEM" ); - throw std::runtime_error("Need at least one muon to calculate EMU matrix-method weight"); - } - - // if more than 1 electron or 1 muon, just take the two leading ones (i.e. the first in the container) - MMLepton *lept_e = getLeptonMMInfo(*els[0], jets, met, event_info); - MMLepton *lept_m = getLeptonMMInfo(*mus[0], jets, met, event_info); - MMEvent *evt = getEventMMInfo(jets, met); - - if (lept_e==0 || lept_m==0 || evt==0) { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator::getMMweightEMU" ); - ATH_MSG_INFO(" Unable to define MMLepton or MMEvent object" ); - mmWeightEM = 0.; - } - else { - weighter->SetLeptons(*evt,*lept_e,*lept_m); - mmWeightEM = weighter->GetFakesWeightDilep(els[0]->auxdataConst<char>("passPreORSelection"),mus[0]->auxdataConst<char>("passPreORSelection")); - } - - delete lept_e; - delete lept_m; - delete evt; - - if (m_debug) { - std::cout<<"==============>mmWeightEM="<<mmWeightEM<<std::endl; - std::cout<<"====>r1="<<weighter->GetRealEff()<<" f1="<<weighter->GetFakeEff()<<" r2="<<weighter->GetRealEff2()<<" f2="<<weighter->GetFakeEff2()<<std::endl; - } - - return mmWeightEM; - } - - // =============================================================== - MMLepton* TopFakesMMWeightCalculator::getLeptonMMInfo(const xAOD::Electron& el, const xAOD::JetContainer& jets, const xAOD::MissingET& met, const xAOD::EventInfo* event_info) - { - float eta_cl = el.caloCluster()->etaBE(2); -// float eta = el.eta(); -// float phi = el.phi(); - float pt = el.pt()/1.e3; // tool needs GeV - unsigned int runNumber = event_info -> runNumber(); - if (m_config->isMC() && m_config->doPileupReweighting()) { - if (event_info->isAvailable<unsigned int>("RandomRunNumber")) - runNumber = event_info->auxdataConst<unsigned int>("RandomRunNumber"); - } - int trigger = 0.; - top::fakes::GetTrigMatchVariable(el, trigger, runNumber); - - const xAOD::TrackParticle* eltrack = el.trackParticle(); - float d0 = eltrack->d0(); - const xAOD::ParametersCovMatrix_t elcov = eltrack->definingParametersCovMatrix(); - float d0signif = d0/sqrt(elcov(0,0)); - - float dR; - float pTj; - float dRCentral; - float pTjCentral; - float dRpt; - float dRptCentral; - fakes::GetClosestJet (el, jets, dR, pTj, dRpt, dRCentral, pTjCentral, dRptCentral); - - float dphilmet; - fakes::GetdPhiLepMET (el, met, dphilmet); - - MMLepton* lept = new MMLepton(); - lept->pt = pt; - lept->eta = std::fabs(eta_cl); - lept->dR = dR; - lept->dPhi = dphilmet; - lept->trigger = trigger; - lept->d0sig = d0signif; - - if (m_debug) { - std::cout<<"Electron"; - std::cout<<" pt="<<pt; - std::cout<<" eta="<<std::fabs(eta_cl); - std::cout<<" dR="<<dR; - std::cout<<" dPhi="<<dphilmet; - std::cout<<" trigger="<<trigger; - std::cout<<" d0sig="<<d0signif; - std::cout<<std::endl; - } - - return lept; - } - - // =========================================================== - MMLepton* TopFakesMMWeightCalculator::getLeptonMMInfo(const xAOD::Muon& mu, const xAOD::JetContainer& jets, const xAOD::MissingET& met, const xAOD::EventInfo* event_info) - { - float eta = mu.eta(); -// float phi = mu.phi(); - float pt = mu.pt()/1.e3; // tool needs GeV - unsigned int runNumber = event_info -> runNumber(); - if (m_config->isMC() && m_config->doPileupReweighting()) { - if (event_info->isAvailable<unsigned int>("RandomRunNumber")) - runNumber = event_info->auxdataConst<unsigned int>("RandomRunNumber"); - } - int trigger = 0.; - top::fakes::GetTrigMatchVariable(mu, trigger, runNumber); - - const xAOD::TrackParticle* mutrack = mu.primaryTrackParticle(); - float d0 = mutrack->d0(); - const xAOD::ParametersCovMatrix_t mucov=mutrack->definingParametersCovMatrix(); - float d0signif = d0/sqrt(mucov(0,0)); - - float dR; - float pTj; - float dRCentral; - float pTjCentral; - float dRpt; - float dRptCentral; - fakes::GetClosestJet (mu, jets, dR, pTj, dRpt, dRCentral, pTjCentral, dRptCentral); - - float dphilmet; - fakes::GetdPhiLepMET (mu, met, dphilmet); - - MMLepton* lept = new MMLepton(); - lept->pt = pt; - lept->eta = std::fabs(eta); - lept->dR = dR; - lept->dPhi = dphilmet; - lept->trigger = trigger; - lept->d0sig = d0signif; - - if (m_debug) { - std::cout<<"Muon"; - std::cout<<" pt="<<pt; - std::cout<<" eta="<<std::fabs(eta); - std::cout<<" dR="<<dR; - std::cout<<" dRpt="<<dRpt; - std::cout<<" dPhi="<<dphilmet; - std::cout<<" trigger="<<trigger; - std::cout<<" d0sig="<<d0signif; - std::cout<<std::endl; - } - - return lept; - } - - // ============================================================ - MMEvent* TopFakesMMWeightCalculator::getEventMMInfo(const xAOD::JetContainer& jets, const xAOD::MissingET& met) - { - float leadingJetpT = -999.; - float leadingCentralJetpT = -999.; - unsigned int Njets = 0; - unsigned int NCentraljets = 0; - unsigned int nbtag = 0; - for (const auto* const jetPtr : jets) { - if (jetPtr->pt()<25000.) continue; - Njets++; - if (jetPtr->pt()>leadingJetpT) leadingJetpT = jetPtr->pt(); - if (jetPtr->eta()<2.5) { - NCentraljets++; - if (jetPtr->pt()>leadingCentralJetpT) leadingCentralJetpT = jetPtr->pt()/1000.; - } - - if (jetPtr->isAvailable<char>("isbtagged_FixedCutBEff_77")) { - if (jetPtr->auxdataConst<char>("isbtagged_FixedCutBEff_77")) nbtag++; - } - } - - MMEvent* evnt = new MMEvent(); - evnt->njets = NCentraljets; - evnt->ntag = nbtag; - evnt->jetpt = leadingCentralJetpT; - evnt->sumet = met.sumet()/1e3;//tool needs GeV - - if (m_debug) { - std::cout<<"Event"; - std::cout<<" njets="<<NCentraljets; - std::cout<<" ntag="<<nbtag; - std::cout<<" jetpt="<<leadingCentralJetpT; - std::cout<<" sumet="<<met.sumet()/1e3;//tool needs GeV - std::cout<<" met="<<met.met()/1e3;//tool needs GeV - std::cout<<" metx="<<met.mpx()/1e3;//tool needs GeV - std::cout<<" mety="<<met.mpy()/1e3;//tool needs GeV - std::cout<<" metphi="<<met.phi(); - std::cout<<std::endl; - } - - return evnt; - } - - std::vector<std::string> TopFakesMMWeightCalculator::GetFakesMMConfigNames(std::string selection) const - { - std::vector<std::string> configs; - if (m_fakesWeightTools.count(selection) !=0) { - for (auto config : m_fakesWeightTools.at(selection)) - configs.push_back(config.first); - } - return configs; - } - - int TopFakesMMWeightCalculator::getPeriod( const std::string& period_string ) - { - if (period_string == "2012") { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator getPeriod: can't use 2012 fakes in xAOD framework - returning -1" ); - return -1; - } - else if (period_string == "2015") { - return MMEffSet::Period::Year2015; - } - else if (period_string == "2016") { - return MMEffSet::Period::Year2016; - } - else { - ATH_MSG_INFO(" top::TopFakesMMWeightCalculator getPeriod: can't recognise any valid period - returning -1" ); - return -1; - } - } - - // ============================================================= - ///This function checks if the lepton ID, isolation, etc... match one of those supported by Top-Fakes - ///Currently only the "standard" definition is supported - ///The list of definitions could be expanded in TopFakesxAODUtils (the top::fakes::LeptonDefinitions enum class) - ///The function also checks the pT range of the leptons - this allows users to have leptons with pT<25GeV (they are ignored) - and the eta range of the jets - this allows users to have forward jets (they are ignored too) -// void TopFakesMMWeightCalculator::CheckConfiguration() -// { -// if (m_config == nullptr) { -// m_leptonDefs = fakes::LeptonDefinitions::Other; -// std::cout<<"Warning: TopFakesMMWeightCalculator::CheckLeptonDefs() was unable to assess the configuration; therefore dummy matrix-method weights will be returned"<<std::endl; -// } -// else { -// if ( m_config->electronID() == "TightLH" -// && m_config->electronIDLoose() == "MediumLH" -// && m_config->electronIsolation() == "Gradient" -// && m_config->electronIsolationLoose() == "None" -// && m_config->muonQuality() == "Medium" -// && m_config->muonQualityLoose() == "Loose" -// && m_config->muonIsolation() == "Gradient" -// && m_config->muonIsolationLoose() == "None" ) { -// m_leptonDefs = fakes::LeptonDefinitions::Standard; -// //now do checks on object definitions -// //electrons -// if (m_config->electronPtcut() < 25000.) { -// std::cout<<"Warning: electrons below pT=25GeV are used (pT cut is at "<<m_config->electronPtcut()/1000.<<"GeV). This is non-standard and not yet supported by TopFakes; therefore all electrons below this threshold will be ignored in the calculation of matrix-method weights."<<std::endl; -// } -// else if (m_config->electronPtcut() != 25000.) { -// std::cout<<"Warning: non-standard electron pT cut of "<<m_config->electronPtcut()/1000.<<"GeV is used (standard is 25GeV). It may have unexpected behaviour for the calculation of matrix-method weights."<<std::endl; -// } -// if (!m_config->electronVetoLArCrack()) { -// std::cout<<"Warning: veto of electrons on LAr crack was disabled; this is non-standard and not yet supported by TopFakes"<<std::endl; -// } -// -// //muons -// if (m_config->muonPtcut() < 25000.) { -// std::cout<<"Warning: muons below pT=25GeV are used (pT cut is at "<<m_config->muonPtcut()/1000.<<"GeV). This is non-standard and not yet supported by TopFakes; therefore all muons below this threshold will be ignored in the calculation of matrix-method weights."<<std::endl; -// } -// else if (m_config->muonPtcut() != 25000.) { -// std::cout<<"Warning: non-standard muon pT cut of "<<m_config->muonPtcut()/1000.<<"GeV is used (standard is 25GeV). It may have unexpected behaviour for the calculation of matrix-method weights."<<std::endl; -// } -// if (m_config->muonEtacut() != 2.5) { -// std::cout<<"Warning: non-standard muon eta cut of "<<m_config->jetEtacut()<<" is used (standard is 2.5). It may have unexpected behaviour for the calculation of matrix-method weights."<<std::endl; -// } -// -// //jets -// if (m_config->jetEtacut() > 2.5) { -// std::cout<<"Warning: forward jets are used (eta cut is at "<<m_config->jetEtacut()<<"). This is non-standard and not yet supported by TopFakes; therefore all jets above |eta|=2.5 will be ignored in the calculation of matrix-method weights."<<std::endl; -// } -// else if (m_config->jetEtacut() != 2.5) { -// std::cout<<"Warning: non-standard jet eta cut of "<<m_config->jetEtacut()<<" is used (standard is 2.5). It may have unexpected behaviour for the calculation of matrix-method weights."<<std::endl; -// } -// if (m_config->jetPtcut() != 25000.) { -// std::cout<<"Warning: non-standard jet pT cut of "<<m_config->jetPtcut()/1000.<<"GeV is used (standard is 25GeV). It may have unexpected behaviour for the calculation of matrix-method weights."<<std::endl; -// } -// } -// else { -// std::cout<<"Warning: the used lepton definitions are not yet supported by TopFakes; therefore dummy matrix-method weights will be returned"<<std::endl; -// } -// -// -// } -// -// } -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/TopFakesxAODUtils.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/TopFakesxAODUtils.cxx deleted file mode 100644 index 3b897b603175ad39ad24ce5e4b572a34a6d66672..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/Root/TopFakesxAODUtils.cxx +++ /dev/null @@ -1,363 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -////////////////////////////////////////////////////////////////////// -// -// Author : -// Timothée Theveneaux-Pelzer -// Creation : -// Purpose : helper to be used in analyses -// -// Updated : -// 2016-02-12 : fixes for muon trigger splitting -// -////////////////////////////////////////////////////////////////////// -#include "TopFakes/TopFakesxAODUtils.h" - -#include "TopEvent/EventTools.h" -#include "TopFakes/FakesWeights.h" - - -void top::fakes::GetClosestJet (const xAOD::Electron& el, - const xAOD::JetContainer& jets, - float& dRClosetJet, - float& PtClosetJet, - float& dROverPtClosetJet, - float& dRClosetCentralJet, - float& PtClosetCentralJet, - float& dROverPtClosetCentralJet) -{ - //the dRs are initialised to a very high positive value - dRClosetJet = 999.; - dRClosetCentralJet = 999.; - //the pTs are initialised to a negative value - PtClosetJet = -999.; - PtClosetCentralJet = -999.; - // these variables are not used in fact! - dROverPtClosetJet = -999.; - dROverPtClosetCentralJet = -999.; - - for (const auto* const jetPtr : jets) { - if (jetPtr->pt()<25000.) continue; - double newdR = top::deltaR(*jetPtr,el); - if (jetPtr->eta()<2.5) { - if (newdR<dRClosetCentralJet) { - dRClosetCentralJet = newdR; - PtClosetCentralJet = jetPtr->pt()/1000.; // tool needs GeV - } - } - if (newdR<dRClosetJet) { - dRClosetJet = newdR; - PtClosetJet = jetPtr->pt()/1000.; // tool needs GeV - } - } - - // these variables are not used ! - if ((dRClosetJet!=999.) && (PtClosetJet!=-999.)) dROverPtClosetJet = dRClosetJet/PtClosetJet; - if ((dRClosetCentralJet!=999.) && (PtClosetCentralJet!=-999.)) dROverPtClosetCentralJet = dRClosetCentralJet/PtClosetCentralJet; - - //if the dRs are at their default value, give them a negative value - if (dRClosetJet == 999.) dRClosetJet = -999.; - if (dRClosetCentralJet == 999.) dRClosetCentralJet = -999.; -} - -// ============================================================ -void top::fakes::GetClosestJet (const xAOD::Muon& mu, - const xAOD::JetContainer& jets, - float& dRClosetJet, - float& PtClosetJet, - float& dROverPtClosetJet, - float& dRClosetCentralJet, - float& PtClosetCentralJet, - float& dROverPtClosetCentralJet) -{ - //the dRs are initialised to a very high positive value - dRClosetJet = 999.; - dRClosetCentralJet = 999.; - //the pTs are initialised to a negative value - PtClosetJet = -999.; - PtClosetCentralJet = -999.; - // these variables are not used - dROverPtClosetJet = -999.; - dROverPtClosetCentralJet = -999.; - - for (const auto* const jetPtr : jets) { - if (jetPtr->pt()<25000.) continue; - double newdR = top::deltaR(*jetPtr,mu); - double newdRCentral = newdR; - if (jetPtr->eta()<2.5) { - if (newdRCentral<dRClosetCentralJet) { - dRClosetCentralJet = newdRCentral; - PtClosetCentralJet = jetPtr->pt()/1000.; // tool needs GeV - } - } - if (newdR<dRClosetJet) { - dRClosetJet = newdR; - PtClosetJet = jetPtr->pt()/1000.; // tool needs GeV - } - } - - // these variables are not used - if ((dRClosetJet!=999.) && (PtClosetJet!=-999.)) dROverPtClosetJet = dRClosetJet/PtClosetJet; - if ((dRClosetCentralJet!=999.) && (PtClosetCentralJet!=-999.)) dROverPtClosetCentralJet = dRClosetCentralJet/PtClosetCentralJet; - - //if the dRs are at their default value, give them a negative value - if (dRClosetJet == 999.) dRClosetJet = -999.; - if (dRClosetCentralJet == 999.) dRClosetCentralJet = -999.; -} - -// ================================================= -void top::fakes::GetdPhiLepMET (const xAOD::Electron& el, const xAOD::MissingET& met, float& dPhi) -{ - dPhi = -999.; - if (met.mpx()!=0. && met.mpx()!=0.) { - TLorentzVector met_4vect; - met_4vect.SetPxPyPzE(met.mpx(),met.mpx(),0.,0.); - dPhi = el.p4().DeltaPhi(met_4vect); - } -} - -// ================================================== -void top::fakes::GetdPhiLepMET (const xAOD::Muon& mu, const xAOD::MissingET& met, float& dPhi) -{ - dPhi = -999.; - if (met.mpx()!=0. && met.mpx()!=0.) { - TLorentzVector met_4vect; - met_4vect.SetPxPyPzE(met.mpx(),met.mpx(),0.,0.); - dPhi = mu.p4().DeltaPhi(met_4vect); - } -} - -// ========================================================= -void top::fakes::GetTrigMatchVariable(const xAOD::Electron& el, int& trigmatch, const unsigned int runNumber) -{ - std::string release_series = ""; - const char* rel_temp = std::getenv("ROOTCORE_RELEASE_SERIES"); - if (rel_temp) { - release_series = std::string(rel_temp); - } else { - std::cerr<<"Can not access ROOTCORE_RELEASE_SERIES - exiting..."<<std::endl; - exit(1); - } - - trigmatch = 0; - bool trig_lowpTIso,trig_hightpTNoIso,trig_veryhightpTNoIso,trig_lowpTNoIso; - - if (release_series == "23") {// for 20.1 samples - try {//not really used - trig_lowpTIso is overriden below - trig_lowpTIso = el.auxdataConst<char>("TRIGMATCH_HLT_e24_lhmedium_iloose_L1EM20VH"); - } catch (std::exception& e) { - trig_lowpTIso = false; - } - try { - trig_hightpTNoIso = el.auxdataConst<char>("TRIGMATCH_HLT_e60_lhmedium"); - } catch (std::exception& e) { - trig_hightpTNoIso = false; - } - try { - trig_veryhightpTNoIso = el.auxdataConst<char>("TRIGMATCH_HLT_e120_lhloose"); - } catch (std::exception& e) { - trig_veryhightpTNoIso = false; - } - try { - trig_lowpTIso = trig_lowpTNoIso = ( el.auxdataConst<char>("TRIGMATCH_HLT_e24_lhmedium_L1EM18VH") || el.auxdataConst<char>("TRIGMATCH_HLT_e24_lhmedium_L1EM20VH") ); - } catch (std::exception& e) { - trig_lowpTIso = trig_lowpTNoIso = false; - } - } - else if (release_series == "24") {// for 20.7 samples - if (runNumber>=276262 && runNumber<=284484) { - try {//not really used - trig_lowpTIso is overriden below - trig_lowpTIso = el.auxdataConst<char>("TRIGMATCH_HLT_e24_lhmedium_iloose_L1EM20VH"); - } catch (std::exception& e) { - trig_lowpTIso = false; - } - try { - trig_hightpTNoIso = el.auxdataConst<char>("TRIGMATCH_HLT_e60_lhmedium"); - } catch (std::exception& e) { - trig_hightpTNoIso = false; - } - try { - trig_veryhightpTNoIso = el.auxdataConst<char>("TRIGMATCH_HLT_e120_lhloose"); - } catch (std::exception& e) { - trig_veryhightpTNoIso = false; - } - try { - trig_lowpTNoIso = trig_lowpTIso = el.auxdataConst<char>("TRIGMATCH_HLT_e24_lhmedium_L1EM20VH"); - } catch (std::exception& e) { - trig_lowpTNoIso = false; - } - } - else if (runNumber>=297730) { - try { - trig_lowpTIso = el.auxdataConst<char>("TRIGMATCH_HLT_HLT_e24_lhtight_nod0_ivarloose"); - } catch (std::exception& e) { - trig_lowpTIso = false; - } - try { - trig_hightpTNoIso = el.auxdataConst<char>("TRIGMATCH_HLT_HLT_e60_lhmedium_nod0"); - } catch (std::exception& e) { - trig_hightpTNoIso = false; - } - try { - trig_veryhightpTNoIso = el.auxdataConst<char>("TRIGMATCH_HLT_e140_lhloose_nod0"); - } catch (std::exception& e) { - trig_veryhightpTNoIso = false; - } - try { - trig_lowpTNoIso = ( el.auxdataConst<char>("TRIGMATCH_HLT_e24_lhmedium_L1EM20VH") ); - } catch (std::exception& e) { - trig_lowpTNoIso = false; - } - } - else { - std::cerr<<"Nothing is well-defined for runNumber "<<runNumber<<" - exiting..."<<std::endl; - exit(1); - } - } - else { - std::cerr<<"Unknown release series - exiting..."<<std::endl; - exit(1); - } - - //if (trig_lowpTIso) trigmatch |= 0x1 << 0; - //if (trig_hightpTNoIso || trig_veryhightpTNoIso) trigmatch |= 0x1 << 1; - - // NB note used for Run2 2015 as there is no trigger splitting - if (trig_lowpTIso) trigmatch |= 0x1 << 0; - if (trig_hightpTNoIso || trig_veryhightpTNoIso) trigmatch |= 0x1 << 1; - if (trig_lowpTNoIso) trigmatch |= 0x1 << 2; -} - -// =========================================================== -void top::fakes::GetTrigMatchVariable(const xAOD::Muon& mu, int& trigmatch, const unsigned int runNumber) -{ - std::string release_series = ""; - const char* rel_temp = std::getenv("ROOTCORE_RELEASE_SERIES"); - if (rel_temp) { - release_series = std::string(rel_temp); - } else { - std::cerr<<"Can not access ROOTCORE_RELEASE_SERIES - exiting..."<<std::endl; - exit(1); - } - - trigmatch = 0; - bool trig_lowpTIso,trig_hightpTNoIso,trig_lowpTNoIso; - - if (release_series == "23") {// for 20.1 samples - try { - trig_lowpTIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu20_iloose_L1MU15"); - } catch (std::exception& e) { - trig_lowpTIso = false; - } - try { - trig_hightpTNoIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu50"); - } catch (std::exception& e) { - trig_hightpTNoIso = false; - } - try { - trig_lowpTNoIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu20_L1MU15"); - } catch (std::exception& e) { - trig_lowpTNoIso = false; - } - } - else if (release_series == "24") {// for 20.7 samples - if (runNumber>=276262 && runNumber<=284484) { - try { - trig_lowpTIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu20_iloose_L1MU15"); - } catch (std::exception& e) { - trig_lowpTIso = false; - } - try { - trig_hightpTNoIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu50"); - } catch (std::exception& e) { - trig_hightpTNoIso = false; - } - try { - trig_lowpTNoIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu20_L1MU15"); - } catch (std::exception& e) { - trig_lowpTNoIso = false; - } - } - else if (runNumber>=297730) { - try { - trig_lowpTIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu24_ivarmedium"); - } catch (std::exception& e) { - trig_lowpTIso = false; - } - try { - trig_hightpTNoIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu50"); - } catch (std::exception& e) { - trig_hightpTNoIso = false; - } - try { - trig_lowpTNoIso = mu.auxdataConst<char>("TRIGMATCH_HLT_mu24"); - } catch (std::exception& e) { - trig_lowpTNoIso = false; - } - } - else { - std::cerr<<"Nothing is well-defined for runNumber "<<runNumber<<" - exiting..."<<std::endl; - exit(1); - } - } - else { - std::cerr<<"Unknown release series - exiting..."<<std::endl; - exit(1); - } - - //if (trig_lowpTIso) trigmatch |= 0x1 << 0; - //if (trig_hightpTNoIso) trigmatch |= 0x1 << 1; - - if (trig_lowpTIso) trigmatch |= 0x1 << 0; // mu20i - if (trig_hightpTNoIso) trigmatch |= 0x1 << 1; // mu50 - if (trig_lowpTNoIso) trigmatch |= 0x1 << 2; // mu20 - -} - -// ============================================================= -std::vector<unsigned int> top::fakes::GetGoodHighPtLeptons(const xAOD::ElectronContainer& els) -{ - unsigned int i(0); - std::vector<unsigned int> good_els_index; - for (const auto* const elPtr : els) {//loop on electrons - if ( elPtr->isAvailable<char>("passPreORSelectionLoose") ) {//count only leptons wigth pT>25GeV that pass selection - if ( elPtr->pt()> 25000. && (elPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) ) good_els_index.push_back(i); - } - i++; - }//loop on electrons - return good_els_index; -} - -// ============================================================= -std::vector<unsigned int> top::fakes::GetGoodHighPtLeptons(const xAOD::MuonContainer& mus) -{ - unsigned int i(0); - std::vector<unsigned int> good_mus_index; - for (const auto* const muPtr : mus) {//loop on muons - if ( muPtr->isAvailable<char>("passPreORSelectionLoose") ) {//count only leptons wigth pT>25GeV that pass selection - if ( muPtr->pt()> 25000. && (muPtr->auxdataConst<char>("passPreORSelectionLoose") == 1) ) good_mus_index.push_back(i); - } - i++; - }//loop on muons - return good_mus_index; -} - -// ============================================================ -int top::fakes::GetChannel(const xAOD::ElectronContainer& els, - const xAOD::MuonContainer& mus) -{ - // - // - // - - unsigned int iels = GetGoodHighPtLeptons(els).size(); - unsigned int imus = GetGoodHighPtLeptons(mus).size(); - if (iels==1 && imus==0) return FakesWeights::EJETS; - else if (iels==0 && imus==1) return FakesWeights::MUJETS; - else if (iels==2 && imus==0) return FakesWeights::EE; - else if (iels==0 && imus==2) return FakesWeights::MUMU; - else if (iels==1 && imus==1) return FakesWeights::EMU; - else return -1; -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/FakesWeights.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/FakesWeights.h deleted file mode 100644 index 589036ddcd0bee0f0be73bc0059560e7726cf1e6..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/FakesWeights.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -////////////////////////////////////////////////////////////////////// -// -// Author : -// Anna Henrichs <anna.henrichs@cern.ch> -// Michele Pinamonti <michele.pinamonti@cern.ch> -// Creation : -// Purpose : main method to retrieve event-by-event weights -// from the Matrix Method -// Updated : -// 2016-01-29 : FD: set _isRun1 = false -// set default weighter -// remove pt/dR variable, never used -////////////////////////////////////////////////////////////////////// - -#ifndef FAKESWEIGHTS_h -#define FAKESWEIGHTS_h - -#include <string> -#include <vector> -#include <map> - -#include "TopFakes/MMEffSet.h" - -class TFile; -class TH1F; -class TH2F; -class TH3F; -class MMEfficiency; -class MMEffSet; -class MatrixUtils; -class MMEvent; -class MMLepton; - -class FakesWeights{ - -public: - // CONSTRUCTOR - FakesWeights(); - // DESTRUCTOR - ~FakesWeights(); - - // channels - enum { - EJETS, // 0 - MUJETS, // 1 - EE, // 2 - MUMU, // 3 - EMU // 4 - }; - -// // estimates -// enum{ -// PARIS, // 0 -// UPPSALA -// }; - - // systematics - enum{ - NONE, // 0 - MCup, // fake eff with removal of real lepton contamination from W/Z MC +30% - totally correlated between electron and muon - MCdown, // fake eff with removal of real lepton contamination from W/Z MC -30% - totally correlated between electron and muon - MCupel, // fake eff with removal of real lepton contamination from W/Z MC +30% - only for electron - MCdownel, // fake eff with removal of real lepton contamination from W/Z MC -30% - only for electron - MCupmu, // fake eff with removal of real lepton contamination from W/Z MC +30% - only for muon - MCdownmu, // fake eff with removal of real lepton contamination from W/Z MC -30% - only for muon - CRfake, // fake eff from alternative region - returns nominal for emu channel, otherwise equivalent to CRfakeel (CRfakemu) for e+jets and ee (mu+jets and mumu) channels - CRfakeel, // fake eff from alternative region - only for electron - CRfakemu, // fake eff from alternative region - only for muon - CRreal, // real eff from alternative region - totally correlated between electron and muon - CRrealel, // real eff from alternative region - only for electron - CRrealmu, // real eff from alternative region - only for muon - EffPar //efficiencies with alternative parametrisation (only for l+jet) - }; - - //void SetProtection(bool protection); - - void SetDataPath(std::string path); - void SetDebug(bool debug); - - void SetPeriod(int period); - void SetTriggerNamesEl(std::string trig1,std::string trig2,std::string trig3); - void SetTriggerNamesMu(std::string trig1,std::string trig2,std::string trig3); - void SetTriggerPrescalesEl(float ps1,float ps2,float ps3); - void SetTriggerPrescalesMu(float ps1,float ps2,float ps3); - void SetTriggerThresholdEl(float thres); - void SetTriggerThresholdMu(float thres); - - // method to set up all tools (Weighters) - void SetupWeighter(int channel, std::string aReal, std::string aFake, std::string aReal2="", std::string aFake2=""); - - // method to set the MMEvent and MMLepton objects for l+jets - void SetLepton(MMEvent event, MMLepton lepton); - // method to set the MMEvent and MMLepton objects for dilepton - void SetLeptons(MMEvent event,MMLepton lep1, MMLepton lep2); - // method to get the weight for l+jets - float GetFakesWeightLJets(bool tight); - // method to get the weight for dilepton - float GetFakesWeightDilep(bool tight1,bool tight2); - - // methods to retrieve dilepton weight for loose-loose (LL), loose-tight (LT) - // tigh-loose (TL) and tight-tight (TT) events - float GetFakesWeightDilepLL(bool tight1,bool tight2); - float GetFakesWeightDilepLT(bool tight1,bool tight2); - float GetFakesWeightDilepTL(bool tight1,bool tight2); - float GetFakesWeightDilepTT(bool tight1,bool tight2); - - // method to set up the weighters by default - void SetupWeighterDefault(int channel, std::string name, std::string syst); - // method to set up the weighters by default - void SetupWeighterDefault(int channel, std::string syst=""); - - void SetLeptonDefault(float lep_pt, float lep_eta, float el_cl_eta, - float dR_lj_min, float dPhi_lnu, - float jet_pt0, int jet_n, int nJet_tagged, int trigger); - float GetFakesWeightLJetsDefault(bool tight, float lep_pt, float lep_eta, - float el_cl_eta, float dR_lj_min, - float dPhi_lnu, float jet_pt0, - int jet_n, int nJet_tagged, int trigger); - - // methods to get the real and fake efficiencies - float GetRealEff(); - float GetFakeEff(); - float GetRealEff2(); - float GetFakeEff2(); - - // method to retrieve the matrix - MatrixUtils* GetMatrixUtils(); - - // method to access the channel - int Channel() const {return _channel;}; - -private: - int _channel; - int _syst; - - bool _dataPathIsSet; - bool _isInitialized; - //bool _protection; - - bool _debug; - std::string _dataPath; - - MatrixUtils *_mmUtil; - - MMEffSet *_EffSet[4]; // real, fake, real2, fake2 - - int _period; - std::string _trig1_el; - std::string _trig2_el; - std::string _trig3_el; - std::string _trig1_mu; - std::string _trig2_mu; - std::string _trig3_mu; - float _ps1_el; - float _ps2_el; - float _ps3_el; - float _ps1_mu; - float _ps2_mu; - float _ps3_mu; - float _ptTres_el; - float _ptTres_mu; -}; - -#endif - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MMEffSet.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MMEffSet.h deleted file mode 100644 index 1cbbbbf701352c763cd8054bbaa518b228eaa29d..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MMEffSet.h +++ /dev/null @@ -1,181 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -/* - ** authors: - ** Michele Pinamonti <michele.pinamonti@cern.ch> -*/ - -#ifndef MMEFFSET_h -#define MMEFFSET_h - -#include <string> -#include <vector> -#include <map> - -class TFile; -class TH1F; -class TH2F; -class TH3F; -class MMEfficiency; -class MatrixUtils; - - -//---- -class MMLepton{ -public: - float pt; - float eta; - float cleta; - float dR; // min dR(jet-lepton) - float dRpt; // pT/dR (lepton-closest jet) - float dPhi; // dPhi(MET-lepton) - float d0sig; // d0 significance - int trigger; // trigger matching the lepton -}; - -class MMEvent{ -public: - float jetpt; // pT of the leading jet - float sumet; // met_sumet - float hthad; // sum of pT's of jets - float met; // met_et in the event - int njets; // number of jets - int ntag; // number of b-tagged jets (MV1 70%) -}; -//---- - - - -class MMEffSet{ - -public: - - enum{ - TRIGGER_MASK =1, - NJETSSHORT_MASK=2, - NJETS_MASK =4, - NBTAG_MASK =8 - }; - - // "period" - enum Period { - Year2012, // 0 - Year2015, - Year2016 - }; - - MMEffSet(bool isEle,bool isReal,bool debug=false); - ~MMEffSet(); - - void SetDataPath(std::string path="data"); - - void SetupEff(std::string aEff); - - void AddCustomSplit(std::string config); // config = "condition1:condition2:condition3_..." -> value = 0,1,2,... - void AddNumBtagSplit(); - void AddNumJetsSplit(); - void AddNumJetsShortSplit(); - void AddTriggerSplit(); - void AddNumBtagAndTriggerSplit(); - void AddNumBtagAndNumJetsSplit(); - void AddNumBtagAndNumJetsShortSplit(); - void AddNumJetsAndTriggerSplit(); - void AddNumJetsShortAndTriggerSplit(); - void AddNumBtagAndNumJetsAndTriggerSplit(); - void AddNumBtagAndNumJetsShortAndTriggerSplit(); - void ReadEfficiencies(); // to call after having set up and added splittings - - void AddCorrection(); - - void SetLepton(float v0,float v1=0,float v2=0,float v3=0,float v4=0,float v5=0,float v6=0,float v7=0,float v8=0,float v9=0); - - void SetCustom(int value); - void SetNumBtag(int nbtag); - void SetNumJets(int njets); - void SetNumJetsShort(int njets); - void SetTrigger(int trigger,float pt); // pT in GeV - - void SetNumBtagAndNumJets(int ntag,int njets); - void SetNumBtagAndNumJetsShort(int ntag,int njets); - void SetNumBtagAndTrigger(int nbtag,int trigger,float pt); - void SetNumJetsAndTrigger(int njets,int trigger,float pt); - void SetNumJetsShortAndTrigger(int njets,int trigger,float pt); - void SetNumBtagAndNumJetsAndTrigger(int nbtag,int njets,int trigger,float pt); - void SetNumBtagAndNumJetsShortAndTrigger(int nbtag,int njets,int trigger,float pt); - - void SetPtThres(int thres); // set the pT-threshold for trigger splitting (in GeV); set it to -1 to ignore it - void SetTriggerNames(std::string trig1,std::string trig2,std::string trig3); - - int TriggerValue(int trigger,float pt); - - int NumJetsValue(int njets); - int NumJetsShortValue(int njets); - int NumBtagValue(int nbtag); - - void SetLepton(MMEvent event,MMLepton lepton); - float GetEff(bool isAverage=false); - - void SetPeriod(int period); - void SetTriggerPrescales(float ps1,float ps2,float ps3); - void SetTriggerThreshold(float thres); - - float GetPrescale(); - -private: - void ReadEfficiency(MMEfficiency *eff,std::string aEff,std::string condition="",bool isCorrection=false); - void ParseOptions(std::string s,std::map<std::string,std::string> *m); - - MMEvent _event; - MMLepton _lepton; - - std::string _Estimate; - - std::string _dataPath; - - std::map<std::string,std::string> _optMap; - - int _numCond; - - int _splitIdx; - - int _splitBitMask; // nbtag-njet-njetshort-trigger (eg. 1000, 1010, 0011..) - - float _ptTres; - - std::vector<std::string> _condVec; - - // separate class for efficiencies - MMEfficiency *_Eff[10]; - MMEfficiency *_EffCorr[10]; - - bool _useCorr; - - bool _effIsRead; - - //int _estimate; - //int _syst; - - bool _isEle; - bool _isReal; - bool _debug; - - int _period; - std::string _trig1; - std::string _trig2; - std::string _trig3; - float _ps1; - float _ps2; - float _ps3; - int _trigger; - - // Internal methods / functions - int CountInString(std::string s,char c); - std::vector<std::string> Tokenize(std::string s, std::string c); - std::vector<std::string> Combine(std::vector<std::string> v1,std::vector<std::string> v2); -}; - -#endif - - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MMEfficiency.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MMEfficiency.h deleted file mode 100644 index 053c147d35c5ba70ba2c9841d0e63fbcc2a2d2a4..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MMEfficiency.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -/* - ** author: Michele Pinamonti <michele.pinamonti@cern.ch> - ** version: v1 - 23aug2013 -*/ - -#ifndef MMEfficiency_H_ -#define MMEfficiency_H_ - -#include "TFile.h" -#include "TH1F.h" -#include "TH2F.h" -#include "TH3F.h" -#include "TF1.h" -#include "TF2.h" -#include "TF3.h" - -#include <string> -#include <iostream> - - -const int MAXvar = 10; - - -class MMEfficiency{ - public: - MMEfficiency(); - ~MMEfficiency(); - - bool AddHisto(TH1F *h); - bool AddHisto(TH2F *h); - bool AddHisto(TH3F *h); - bool AddHisto(TFile *f, std::string histoName, int ndim=1); - bool AddHisto(std::string fileName, std::string histoName, int ndim=1); - - void SetAverage(float value); - void SetAverageHist(TFile* f, std::string histoName); // this should be a 1-D & 1-bin histogram - void SetAverageHist(std::string fileName, std::string histoName); // this should be a 1-D & 1-bin histogram - float SetAverageFromHist(TH1F *h); - float SetAverageFromHist(TH2F *h); - float SetAverageFromHist(TH3F *h); - float SetAverageFromHist(TFile *f, std::string histoName,int ndim=1); - float SetAverageFromHist(std::string fileName, std::string histoName,int ndim=1); - - float GetEfficiency(); - float GetAverageEfficiency(); - float GetEfficiency(float v0,float v1=0,float v2=0,float v3=0,float v4=0,float v5=0,float v6=0,float v7=0,float v8=0,float v9=0); - void SetParVar(int idx,float value); - void SetParVars(float v0,float v1=0,float v2=0,float v3=0,float v4=0,float v5=0,float v6=0,float v7=0,float v8=0,float v9=0); - - // control methods - int GetNvars(); - - private: - TH1F* fHist[MAXvar]; - TH2F* fHist2D[MAXvar]; - TH3F* fHist3D[MAXvar]; - float fAverage; - float fVars[MAXvar]; - int fNvar; - int fDim[MAXvar]; -}; - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MatrixUtils.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MatrixUtils.h deleted file mode 100644 index ad5721f03818fe1929385a7b15f87b017e66680f..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/MatrixUtils.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// -// Generic matrix methods fake lepton estimates for lepton and dilepton. -// -// Given loose/tight lepton ID, real efficiency r, -// and fake efficiency f builds the fake estimate event weight -// -// Authors: -// Karl Gellerstedt (kargel@fysik.su.se) -// Jorgen Sjolin (sjolin@fysik.su.se) -// - -#ifndef MATRIX_UTILS_H -#define MATRIX_UTILS_H - -#include "TMatrixD.h" - -class MatrixUtils { - - public: - MatrixUtils(); - - double lepton_weight(bool loose, double r, double f, - double &nf, double &nr); - - void fill_matrix(double r, double f); - void fill_matrix(double r, double f, double t); - - double lepton_tight_weight(bool loose); - double lepton_loose_weight(bool loose); - double lepton_tight_top_corr_weight(bool loose); - double lepton_loose_top_corr_weight(bool loose); - - double dilepton_weight(bool l1, double r1, double f1, - bool l2, double r2, double f2, - double &nrf, double &nfr, double &nff); - - void fill_matrix(double r1, double f1, double r2, double f2); - void fill_matrix(double r1, double f1, double t1, double r2, double f2, double t2); - - double dilepton_TT_weight(bool l1, bool l2); - double dilepton_TL_weight(bool l1, bool l2); - double dilepton_LT_weight(bool l1, bool l2); - double dilepton_LL_weight(bool l1, bool l2); - double dilepton_TT_top_corr_weight(bool l1, bool l2); - double dilepton_TL_top_corr_weight(bool l1, bool l2); - double dilepton_LT_top_corr_weight(bool l1, bool l2); - double dilepton_LL_top_corr_weight(bool l1, bool l2); - - void fill_lll_matrix(double r1, double f1, double r2, double f2, double r3, double f3); - double trilepton_weight(bool l1, bool l2, bool l3); - - private: - - TMatrixD ljets_matrix; - TMatrixD ljets_matrix_top_corr; - TMatrixD ll_matrix; - TMatrixD ll_matrix_top_corr; - TMatrixD lll_matrix; - - TMatrixD i_ljets_matrix; - TMatrixD i_ljets_matrix_top_corr; - TMatrixD i_ll_matrix; - TMatrixD i_ll_matrix_top_corr; - TMatrixD i_lll_matrix; -}; - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/TopFakesMMWeightCalculator.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/TopFakesMMWeightCalculator.h deleted file mode 100644 index 6bef6366541a7ca396beccf0bb9b1fc7e1a65558..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/TopFakesMMWeightCalculator.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// $Id: TopFakesMMWeightCalculator.h 762053 2016-07-15 04:39:49Z tpelzer $ -#ifndef TOPFAKESMMWEIGHTCALCULATOR_H -#define TOPFAKESMMWEIGHTCALCULATOR_H - -/** - * @author Timothée Theveneaux-Pelzer <tpelzer@cern.ch> - * - * @brief TopFakesMMWeightCalculator - * Calculate Matrix-Method Weights for fake prompt lepton background estimates - **/ - -// Framework include(s): -#include "AsgTools/AsgTool.h" -#include "AsgTools/ToolHandle.h" - -// For Object containers -#include "TopEvent/Event.h" - -#include <map> - -// Classes from fakesWeight framework -class FakesWeights; -class MMLepton; -class MMEvent; - -// Forward declaration(s): -namespace top{ - class TopConfig; - class Event; - namespace fakes { - enum class LeptonDefinitions; - } -} - -namespace top{ - - class TopFakesMMWeightCalculator final : public asg::AsgTool { - public: - explicit TopFakesMMWeightCalculator( const std::string& name = "MMWeightCalculator" ); - virtual ~TopFakesMMWeightCalculator(); - - // Delete Standard constructors - TopFakesMMWeightCalculator(const TopFakesMMWeightCalculator& rhs) = delete; - TopFakesMMWeightCalculator(TopFakesMMWeightCalculator&& rhs) = delete; - TopFakesMMWeightCalculator& operator=(const TopFakesMMWeightCalculator& rhs) = delete; - - StatusCode initialize(); - StatusCode setSelectionConfigs(std::string selection, std::vector<std::string> configs); - StatusCode execute(top::Event* topEvent); - - std::vector<std::string> GetFakesMMConfigNames(std::string selection) const; - - private: - std::shared_ptr<top::TopConfig> m_config; - - std::string m_dir; - - bool m_debug; - - // unordered_map of FakesWeight objects - // m_fakesWeightTools[selection][configuration] - std::unordered_map<std::string,std::unordered_map<std::string,std::shared_ptr<FakesWeights>>> m_fakesWeightTools; - - float getMMweightE(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::ElectronContainer& els, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info); - float getMMweightM(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::MuonContainer& mus, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info); - float getMMweightEE(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::ElectronContainer& els, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info); - float getMMweightMM(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::MuonContainer& mus, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info); - float getMMweightEM(std::shared_ptr<FakesWeights> weighter, const xAOD::MissingET& met, const xAOD::ElectronContainer& els, const xAOD::MuonContainer& mus, const xAOD::JetContainer jets, const xAOD::EventInfo* event_info); - - MMLepton* getLeptonMMInfo(const xAOD::Electron& el, const xAOD::JetContainer& jets, const xAOD::MissingET& met, const xAOD::EventInfo* event_info); - MMLepton* getLeptonMMInfo(const xAOD::Muon& mu, const xAOD::JetContainer& jets, const xAOD::MissingET& met, const xAOD::EventInfo* event_info); - MMEvent* getEventMMInfo( const xAOD::JetContainer& jets, const xAOD::MissingET& met); - - int getPeriod ( const std::string& period_string ); - -// fakes::LeptonDefinitions m_leptonDefs; -// void CheckConfiguration(); - - ///-- Tell RootCore to build a dictionary (we need this) --/// - ClassDef(top::TopFakesMMWeightCalculator, 0); - - }; -} // namespace -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/TopFakesxAODUtils.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/TopFakesxAODUtils.h deleted file mode 100644 index c975f6a9a703f8c66228b717f917ce81454c5abb..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/TopFakes/TopFakesxAODUtils.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef TOPFAKESXAODUTILS_H -#define TOPFAKESXAODUTILS_H - -#include "TopEvent/Event.h" - -#include <vector> - -namespace top { - /** @namespace fakes - * @brief namespace containing usefull functions for matrix-method fakes estimates - **/ - namespace fakes { - /** @brief calculates the jet-environment-related quantities for a given electron - * quantities are calculated with and without taking into account the forward jets - * default values are -999. - it can occur in 0-jet cases - * @param el the selected electron (const) - * @param jets the whole jet container (const) - * @param dRClosetJet reference to the deltaR(electron, closest jet), including forward jets (i.e. jets can have |eta|>2.5) - * @param PtClosetJet reference to the pT of the closest Jet, including forward jets (i.e. jets can have |eta|>2.5) - * @param dRClosetCentralJet reference to the deltaR(electron, closest jet), excluding forward jets (i.e. considering only jets with |eta|<2.5) - * @param PtClosetCentralJet reference to the pT of the closest Jet, excluding forward jets (i.e. considering only jets with |eta|<2.5) - **/ - void GetClosestJet (const xAOD::Electron& el, - const xAOD::JetContainer& jets, - float& dRClosetJet, - float& PtClosetJet, - float& dROverPtClosetJet, - float& dRClosetCentralJet, - float& PtClosetCentralJet, - float& dROverPtClosetCentralJet); - - /** @brief calculates the jet-enrivronment-related quantities for a given muon - * quantities are calculated with and without taking into account the forward jets - * default values are -999. - it can occur in 0-jet cases - * @param mu the selected muon (const) - * @param jets the whole jet container (const) - * @param dRClosetJet reference to the deltaR(muon, closest jet), including forward jets (i.e. jets can have |eta|>2.5) - * @param PtClosetJet reference to the pT of the closest Jet, including forward jets (i.e. jets can have |eta|>2.5) - * @param dRClosetCentralJet reference to the deltaR(muon, closest jet), excluding forward jets (i.e. considering only jets with |eta|<2.5) - * @param PtClosetCentralJet reference to the pT of the closest Jet, excluding forward jets (i.e. considering only jets with |eta|<2.5) - **/ - void GetClosestJet (const xAOD::Muon& mu, const xAOD::JetContainer& jets, - float& dRClosetJet, - float& PtClosetJet, - float& dROverPtClosetJet, - float& dRClosetCentralJet, - float& PtClosetCentralJet, - float& dROverPtClosetCentralJet); - - /** @brief calculates the deltaPhi between an electron and the MET - * @param el reference to the selected electron (const) - * @param met reference to the MET (const) - * @param dPhi reference to the deltaPhi - **/ - void GetdPhiLepMET (const xAOD::Electron& el, - const xAOD::MissingET& met, float& dPhi); - - /** @brief calculates the deltaPhi between a muon and the MET - * @param mu reference to the selected muon (const) - * @param met reference to the MET (const) - * @param dPhi reference to the deltaPhi - **/ - void GetdPhiLepMET (const xAOD::Muon& mu, - const xAOD::MissingET& met, float& dPhi); - - /** @brief calculates the trigger-matching variable of an electron - * FIXME convention could be updated with new trigger recommendations - * @param runNumber allows to distinguish 2015 and 2016 data for triggers - default is 2015 - **/ - void GetTrigMatchVariable(const xAOD::Electron& el, int& trigmatch, const unsigned int runNumber=276262); - - /** @brief calculates the trigger-matching variable of a muon - * FIXME convention could be updated with new trigger recommendations - * @param runNumber allows to distinguish 2015 and 2016 data for triggers - default is 2015 - **/ - void GetTrigMatchVariable(const xAOD::Muon& mu, int& trigmatch, const unsigned int runNumber=276262); - - /** @brief get the indexes of the good high pT electrons - * FIXME may not be needed - **/ - std::vector<unsigned int> GetGoodHighPtLeptons(const xAOD::ElectronContainer& els); - - /** @brief get the indexes of the good high pT muons - * FIXME may not be needed - **/ - std::vector<unsigned int> GetGoodHighPtLeptons(const xAOD::MuonContainer& mus); - - - /** @brief get the channel of the event, based on the good high pT electrons and muons - * FIXME may not be needed - **/ - int GetChannel(const xAOD::ElectronContainer& els, const xAOD::MuonContainer& mus); - - /** @brief enum class listing the possible lepton definitions supported by the TopFakes package - * FIXME need to add more definitions (e.g. SSDilepton, TTbarResonance) - **/ - enum class LeptonDefinitions { Standard, Other }; - } -} - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/cmt/Makefile.Standalone b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/cmt/Makefile.Standalone deleted file mode 100644 index b6a05f39b3aa6c0237cdcb8ed7a0d2269692c21c..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/cmt/Makefile.Standalone +++ /dev/null @@ -1,129 +0,0 @@ -# This make file is for building a standalone version of the -# FakesMacros package. -# (The make file is a modified version of the GoodRunsLists Makefile.) -# - -# --- External configuration ---------------------------------- -#include $(ROOTSYS)/test/Makefile.arch -include $(ROOTSYS)/etc/Makefile.arch - -# ------------------------------------------------------------- -# General flags -# ------------------------------------------------------------- -PACKAGE = TopFakes -OUTPUTDIR = ../lib - -MFLAGS = -MM -Wall -W -Woverloaded-virtual -DSTANDALONE -INCLUDES += -I$(shell root-config --incdir) -I.. - -# For debugging -CXXFLAGS += -g -DSTANDALONE - -# Need these to avoid loading dependent libraries when ROOT starts -LINKLIBS = -L$(shell root-config --libdir) -lHist - -# Library list for applications -#EXELIBS = -L../lib -l$(PACKAGE) -#EXELIBS += $(shell root-config --libs) -lTreePlayer -lHistPainter - -# ------------------------------------------------------------- -# ROOT CINT files -# ------------------------------------------------------------- -LDEFFILE = ../Root/LinkDef.h -CINTFILE = ../Root/$(PACKAGE)Dict.cxx -CINTFILEH = ../Root/$(PACKAGE)Dict.h -CINTOBJ = ../Root/$(PACKAGE)Dict.o - -# ------------------------------------------------------------- -# C++ source and header files -# ------------------------------------------------------------- -CCXAOD = ../Root/TopFakesMMWeightCalculator.cxx ../Root/TopFakesxAODUtils.cxx -HHXAOD = ../$(PACKAGE)/TopFakesMMWeightCalculator.h ../$(PACKAGE)/TopFakesxAODUtils.h - -CCLIST = $(patsubst ../Root/%cxx, %cxx, $(filter-out $(CINTFILE) $(CCXAOD), $(wildcard ../Root/*.cxx))) -CCLISTC = $(addprefix ../Root/,$(CCLIST)) $(CINTFILE) -HHEXCLUDE = $(CINTFILEH) $(LDEFFILE) -HHLIST = $(patsubst ../$(PACKAGE)/%h, %h, $(filter-out $(HHEXCLUDE) $(HHXAOD), $(wildcard ../$(PACKAGE)/*.h))) -HHLISTC = $(addprefix ../$(PACKAGE)/,$(HHLIST)) -OLISTC = $(patsubst %.cxx,%.o,$(CCLISTC)) - -#APPCCLIST = $(patsubst ../src/apps/%cxx, %cxx, $(wildcard ../src/apps/*.cxx)) -#APPCCLISTC = $(addprefix ../src/apps/,$(APPCCLIST)) -#APPOLISTC = $(patsubst %.cxx,%.o,$(APPCCLISTC)) -#APPEXELIST = $(addprefix ../bin/, $(patsubst %cxx, %exe, $(APPCCLIST))) - -# ------------------------------------------------------------- -# Libraries -# ------------------------------------------------------------- -SHLIBFILE = $(OUTPUTDIR)/lib$(PACKAGE).so - -ifeq ($(PLATFORM),macosx) -EXTRALDFLAGS = -install_name @rpath/$(SHLIBFILE) -endif - -# get libraries of ROOT -define ldlinksuffixROOT - $(addsuffix $(LDLINKSUFFIX),$(Lib)) $(shell if [ "$(findstring -Ldlink2,$(OPTIONS))" ]; then echo $(addsuffix _pkgid_$(ROOTVER),$(Lib)); fi) -endef - -# ------------------------------------------------------------- -# Compilation -# ------------------------------------------------------------- - -#all: shlib apps -all: shlib - -# Implicit rule making all dependency Makefiles included at the end of this makefile -%.d: %.cxx $(HLIST) - @echo "Making $@" - @set -e; $(CC) $(MFLAGS) $(CXXFLAGS) $< \ - | awk '{ sub("^$(notdir $*).o:","$*.o $@:") ; print }' > $@ ;\ - [ -s $@ ] || rm -f $@ - -# Implicit rule to compile all classes -%.o : %.cxx - @echo "Compiling $<" - @$(CXX) $(CXXFLAGS) $(INCLUDES) -c $< -o $*.o - -# Rule to make ROOTCINT output file -$(CINTOBJ) : $(HHLISTC) $(LDEFFILE) - @echo "Running rootcint" - @$(ROOTSYS)/bin/rootcint -f $(CINTFILE) -c -p $(CXXFLAGS) $(INCLUDES) $(HHLISTC) $(LDEFFILE) - @echo "Compiling $(CINTFILE)" - @$(CXX) $(CXXFLAGS) $(INCLUDES) -c $(CINTFILE) -o $@ - -rootcint : $(HHLISTC) $(LDEFFILE) - @echo "Running rootcint" - $(ROOTSYS)/bin/rootcint -f $(CINTFILE) -c -p $(CXXFLAGS) $(INCLUDES) $(HHLISTC) $(LDEFFILE) - -# Rule to combine objects into a shared library -$(SHLIBFILE): $(OLISTC) - @echo "Linking $(SHLIBFILE)" - @mkdir -p $(OUTPUTDIR) - @rm -f $(SHLIBFILE) - @$(LD) $(CXXFLAGS) $(SOFLAGS) $(LINKLIBS) $(EXTRALDFLAGS) $(OLISTC) -o $(SHLIBFILE) - -# Rule to build test applications -#../bin/test.exe : ../src/apps/test.o -# @echo "Building $@" -# @$(LD) $(CXXFLAGS) $(EXELIBS) $< -o ../bin/test.exe -# -#../bin: -# @mkdir -p ../bin - --include $(DLIST) - -cint: $(CINTOBJ) -shlib: $(SHLIBFILE) - -#apps: shlib ../bin $(APPEXELIST) - -clean: - @rm -f ../*/*~ - @rm -f ../*/*.o ../*/*.d ../*/*.pcm - @rm -f ../*/*/*.o ../*/*/*.d ../*/*/*.pcm - -veryclean: clean - @rm -f ../Root/$(CINTFILE) ../Root/$(CINTFILEH) - @rm -rf $(OUTPUTDIR) - @rm -rf ../bin diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default.root deleted file mode 100644 index aa8ed4a17e833e3220ba22092c1ba743d72df808..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_CRfake.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_CRfake.root deleted file mode 100644 index 1d60d363b5fc6e32cf74a03379b1591da5e9e639..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_CRfake.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_MCdown.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_MCdown.root deleted file mode 100644 index 01e8465945b5e98542abfc97ac6220a1f8f33f6f..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_MCdown.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_MCup.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_MCup.root deleted file mode 100644 index 0b7eb759f7aebba9f4ca4dade7c25e20cc7cd945..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_MCup.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_WZMG.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_WZMG.root deleted file mode 100644 index d9b5b80792e91bbdaeee6f2e28a50dfd23199c85..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_WZMG.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_WZPowheg.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_WZPowheg.root deleted file mode 100644 index e25cd6801cfb9e7cfaf2005ddd5837e993f87371..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/F_el_Default_WZPowheg.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default.root deleted file mode 100644 index 13d678bcf9379067e93e2d11599447a868483f6c..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default_CRreal.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default_CRreal.root deleted file mode 100644 index 5956a4bcfe93baccee5f9b13370b1cdbbb15c913..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default_CRreal.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default_TPNoCorr.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default_TPNoCorr.root deleted file mode 100644 index fbb0666ccab0d1575911f0d96f5ecb28c63fe07b..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_el_Default_TPNoCorr.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_mu_Default.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_mu_Default.root deleted file mode 100644 index 6293996d65b9c69138439f10b1b474934d008340..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p1/Standard/R_mu_Default.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/F_el_2015Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/F_el_2015Test.root deleted file mode 100644 index 164ccf1d6e63b8abc81a7c7b051f34a33ea145b9..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/F_el_2015Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/F_mu_2015Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/F_mu_2015Test.root deleted file mode 100644 index b25724ea4275f9aaf90c9ac7a916acfd068ec7be..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/F_mu_2015Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/R_el_2015Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/R_el_2015Test.root deleted file mode 100644 index 55401f2409f20cc8aac184cf6d9db3dcb8f1b8d7..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/R_el_2015Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/R_mu_2015Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/R_mu_2015Test.root deleted file mode 100644 index 3c023c3d648e9e6f2772471069b775c0fc030c64..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2015/R_mu_2015Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/F_el_2016Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/F_el_2016Test.root deleted file mode 100644 index f3f764b0fc7282c2b7f18aa1a538b3d039a1ff8b..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/F_el_2016Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/F_mu_2016Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/F_mu_2016Test.root deleted file mode 100644 index 326ae1414b3df298631d6eeefe926d6c163462c2..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/F_mu_2016Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/R_el_2016Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/R_el_2016Test.root deleted file mode 100644 index 189d69454d21fc9d32919add4e4f10d27448b03e..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/R_el_2016Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/R_mu_2016Test.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/R_mu_2016Test.root deleted file mode 100644 index 04fa25d8ff939f317ee22d0201f110fc8d8facac..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/2016/R_mu_2016Test.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/F_el_2016PSTest.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/F_el_2016PSTest.root deleted file mode 100644 index 2ff43ce2794a4dac8e752cd6953b1fd90727e7fe..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/F_el_2016PSTest.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/F_mu_2016PSTest.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/F_mu_2016PSTest.root deleted file mode 100644 index 81877818132326e2197fa44389f97333dd7d3095..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/F_mu_2016PSTest.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/R_el_2016PSTest.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/R_el_2016PSTest.root deleted file mode 100644 index c8b4c2d06ec3a1e058f31ec25a7b38825f2081e0..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/R_el_2016PSTest.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/R_mu_2016PSTest.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/R_mu_2016PSTest.root deleted file mode 100644 index 5b4e78f8883daca4fd389a13fb86698367b36369..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/PS2016/R_mu_2016PSTest.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/F_el_Nedaa2015_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/F_el_Nedaa2015_2412-fakesStd.root deleted file mode 100644 index 527c19f9d75176777f9af8b58de6c4c5533d70fb..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/F_el_Nedaa2015_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Fred2015_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Fred2015_2412-fakesStd.root deleted file mode 100644 index 8f388f06d0681f0d18725035abdf31362f0dbd18..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Fred2015_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Fred2016_2412-fakesStdNoTTVA.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Fred2016_2412-fakesStdNoTTVA.root deleted file mode 100644 index a7aaf9bf85baa5af8a1fb977ebdfe8e668854724..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Fred2016_2412-fakesStdNoTTVA.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Nedaa2015_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Nedaa2015_2412-fakesStd.root deleted file mode 100644 index fccf00697a3d328f6c6a6963a3678bf2a4637b1c..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Nedaa2015_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Nedaa2016_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Nedaa2016_2412-fakesStd.root deleted file mode 100644 index 929bb91cd5284ba72f82d1f0ebfd40cfca8adeff..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_el_Nedaa2016_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Fred2015_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Fred2015_2412-fakesStd.root deleted file mode 100644 index f7bf09faefc98ca4b3a4d191152821b04c9fea90..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Fred2015_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Fred2016_2412-fakesStdNoTTVA.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Fred2016_2412-fakesStdNoTTVA.root deleted file mode 100644 index b2413e4757ac6c9fac75ad277264fbffe78885ae..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Fred2016_2412-fakesStdNoTTVA.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Nedaa2015_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Nedaa2015_2412-fakesStd.root deleted file mode 100644 index 11feb6886c3a3c76a6014a999e8cb9a9c8962856..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Nedaa2015_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Nedaa2016_2412-fakesStd.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Nedaa2016_2412-fakesStd.root deleted file mode 100644 index f10330bd5929e2bea797b8b0f4367f5e37b3583a..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/Standard/R_mu_Nedaa2016_2412-fakesStd.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/F_el_Fred2015_AT2414-fakesOldOR_MCup.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/F_el_Fred2015_AT2414-fakesOldOR_MCup.root deleted file mode 100644 index 03a440673f48896299180195c64affb3c28ba262..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/F_el_Fred2015_AT2414-fakesOldOR_MCup.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_el_Fred2015_AT2414-fakesOldOR.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_el_Fred2015_AT2414-fakesOldOR.root deleted file mode 100644 index 93606bf4c6c8cd8bc786ecdf015e6cbbad1d8bc6..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_el_Fred2015_AT2414-fakesOldOR.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_el_Fred2016_AT2414-fakesOldOR.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_el_Fred2016_AT2414-fakesOldOR.root deleted file mode 100644 index aa809097468c25ca29eb789b04933bf7012e6179..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_el_Fred2016_AT2414-fakesOldOR.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_mu_Fred2015_AT2414-fakesOldOR.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_mu_Fred2015_AT2414-fakesOldOR.root deleted file mode 100644 index b48cd20f553fb785a48cfab536af68cc745200c2..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_mu_Fred2015_AT2414-fakesOldOR.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_mu_Fred2016_AT2414-fakesOldOR.root b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_mu_Fred2016_AT2414-fakesOldOR.root deleted file mode 100644 index 89c14708da9ccda819f2edf4b041d96bece1fe05..0000000000000000000000000000000000000000 Binary files a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/20p7/StandardOldOR/R_mu_Fred2016_AT2414-fakesOldOR.root and /dev/null differ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/mainpage.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/mainpage.h deleted file mode 100644 index 5cac0dedaff785292f3478c7365c451b9b631c89..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/data/mainpage.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -/** - * @page tfpage TopFakes - * - * @section intro Introduction - * - * Description of the purpose of this code and how to use it. - * - * Example for usage - * @code - * executable [options] - * @endcode - * - * - * @section addinfo Additional information - * - * Some useful code is: - * - top::TopFakesMMWeightCalculator - * - * - * - */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasExample.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasExample.C deleted file mode 100644 index 24870d823628effdd99ae99a7e11824e445b89e8..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasExample.C +++ /dev/null @@ -1,224 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include <iostream> -#include <cmath> - -#include "Rtypes.h" - -#include "AtlasUtils.h" -// #ifndef __CINT__ -#include "AtlasStyle.C" -#include "AtlasLabels.C" -// #endif - -#include "TCanvas.h" -#include "TFile.h" -#include "TROOT.h" -#include "TH1F.h" -#include "TRandom.h" -#include "TGraphErrors.h" - -using namespace std; - -const Int_t GMAX=864; - -const int nren=3; -static const double mur[nren] = {1.0,0.25,4.0}; -static const double muf[nren] = {1.0,0.25,4.0}; -const unsigned int NUMPDF=41; - -TGraphErrors* GetGraph(Int_t ir, Int_t ifs,Int_t icut, Int_t ipdf); - - -void AtlasExample() -{ - -#ifdef __CINT__ - gROOT->LoadMacro("AtlasUtils.C"); -#endif - - SetAtlasStyle(); - - Int_t icol1=5; - Int_t icol2=5; - - TCanvas* c1 = new TCanvas("c1","single inclusive jets",50,50,600,600); - // TCanvas* c1 = new TCanvas("c1","single inclusive jets"); - TPad* thePad = (TPad*)c1->cd(); - thePad->SetLogy(); - - Double_t ymin=1.e-3; Double_t ymax=2e7; - Double_t xmin=60.00; Double_t xmax=3500.; - TH1F *h1 = thePad->DrawFrame(xmin,ymin,xmax,ymax); - h1->SetYTitle("d#sigma_{jet}/dE_{T,jet} [fb/GeV]"); - h1->SetXTitle("E_{T,jet} [GeV]"); - h1->GetYaxis()->SetTitleOffset(1.4); - h1->GetXaxis()->SetTitleOffset(1.4); - //h1->GetXaxis()->SetNdivisions(5); - h1->Draw(); - - const Int_t ncut=1; - TGraphErrors *data[ncut]; - - for (Int_t icut=0; icut<ncut; icut++) { // loop over cuts - - TGraphErrors *g1[nren][ncut]; - for (Int_t ir=0; ir<nren; ir++) { // loop over ren scale - g1[ir][icut]= GetGraph(ir,ir,icut,0); - if (g1[ir][icut]) - cout << g1[ir][icut]->GetTitle() << " found " << g1[ir][icut]->GetName() << endl; - else { - cout << " g1 not found " << endl; - return; - } - g1[ir][icut]->SetLineColor(1); - g1[ir][icut]->SetMarkerStyle(0); - //g1[ir][icut]->Draw("C"); - } - - char daname[100]; - sprintf(daname,"data_%d",icut); - data[icut]=(TGraphErrors*)g1[0][icut]->Clone(daname); - data[icut]->SetMarkerStyle(20); - data[icut]->SetMarkerColor(1); - - // just invent some data - for (Int_t i=0; i< data[icut]->GetN(); i++) { - Double_t x1,y1,e,dx1=0.; - data[icut]->GetPoint(i,x1,y1); - Double_t r1 = 0.4*(gRandom->Rndm(1)+2); - Double_t r2 = 0.4*(gRandom->Rndm(1)+2); - //cout << " i= " << i << " x1= " << x1 << " y1= " << y1 << " r= " << r << endl; - Double_t y; - if (icut==0) y=r1*y1+r1*r2*r2*x1/50000.; - else y=r1*y1; - e=sqrt(y*1000)/200; - data[icut]->SetPoint(i, x1,y); - data[icut]->SetPointError(i,dx1,e); - } - //data[icut]->Print(); - - TGraphAsymmErrors* scale[ncut]; - TGraphAsymmErrors* scalepdf[ncut]; - - scale[icut]= myMakeBand(g1[0][icut],g1[1][icut],g1[2][icut]); - //printf(" band1: \n"); - //scale->Print(); - - scalepdf[icut]=(TGraphAsymmErrors* ) scale[icut]->Clone("scalepdf"); - - TGraphErrors *gpdf[NUMPDF][ncut]; - for (Int_t ipdf=0; ipdf<NUMPDF; ipdf++) { - gpdf[ipdf][icut]= GetGraph(0,0,icut,ipdf); - if (gpdf[ipdf][icut]) - cout << gpdf[ipdf][icut]->GetTitle() << " found " << gpdf[ipdf][icut]->GetName() << endl; - else { - cout << " gpdf not found " << endl; - return; - } - gpdf[ipdf][icut]->SetLineColor(2); - gpdf[ipdf][icut]->SetLineStyle(1); - gpdf[ipdf][icut]->SetMarkerStyle(0); - myAddtoBand(gpdf[ipdf][icut],scalepdf[icut]); - } - - scalepdf[icut]->SetFillColor(icol2); - scalepdf[icut]->Draw("zE2"); - scale[icut]->SetFillColor(icol1); - scale[icut]->Draw("zE2"); - g1[0][icut]->SetLineWidth(3); - g1[0][icut]->Draw("z"); - data[icut]->Draw("P"); - - } - - myText( 0.3,0.85,1,"#sqrt{s}= 14 TeV"); - myText( 0.57,0.85,1,"|#eta_{jet}|<0.5"); - myMarkerText(0.55,0.75,1,20,"Data 2009",1.3); - myBoxText( 0.55,0.67,0.05,icol1,"NLO QCD"); - - //ATLAS_LABEL(0.2,0.2); myText( 0.37,0.2,1,"Preliminary"); - - // new method for ATLAS labels. Use this! - //ATLASLabel(0.2,0.2); - ATLASLabel(0.2,0.2,"Preliminary"); - //ATLASLabel(0.2,0.2,"Work in progress"); - - c1->Print("AtlasExample.eps"); - c1->Print("AtlasExample.png"); - c1->Print("AtlasExample.pdf"); - -} - -TGraphErrors* GetGraph(Int_t ir, Int_t ifs,Int_t icut, Int_t ipdf) -{ - - const bool debug=0; - - char *cuts[5] = - {"0.0 <= |eta| < 0.5", - "0.5 <= |eta| < 1.0", - "1.0 <= |eta| < 1.5", - "1.5 <= |eta| < 2.0", - "2.0 <= |eta| < 3.0"}; - - const double mur[] = {1.0,0.25,4.0}; - const double muf[] = {1.0,0.25,4.0}; - - TFile *f1 = TFile::Open("nlofiles.root"); - if (f1&&debug) cout << " file opened " << endl; - - char gname[100]; - char tname[100]; - - if (debug) cout << " mur= " << mur[ir] << " muf= " << muf[ifs] - << " iut= " << icut << " ipdf= " << ipdf << endl; - - if (ipdf>=0) - sprintf(tname," E_T (mu_r=%g, mu_f=%g);%s Pdf: %d",mur[ir],muf[ifs],cuts[icut],ipdf); - else - sprintf(tname," E_T %s Ms= %d",cuts[icut],-ipdf); - - if (debug) cout << "**GetGraph: Look for: " << tname << endl; - - TGraphErrors* g1 = 0; - - for (int i=1; i<=GMAX; i++){ - sprintf(gname,"full_%d",i); - // sprintf(gname,"born_%d",i); - sprintf(gname,"full_%d",i); - g1=(TGraphErrors*) f1->Get(gname); - if (!g1) { cout << gname << " not found " << endl; return g1=0; } - - const char *title=g1->GetTitle(); - - if (debug){ - cout << " Title= " << title << endl; - cout << " tname= " << tname << endl; - cout << " strcmp: " << strcmp(title,tname) << endl; - } - - if (strcmp(title,tname)==0) break; - g1=0; - } - - if (!g1) return 0; - if (debug) cout << " found: " << g1->GetTitle() << endl; - - return g1; -} - - - -#ifndef __CINT__ - -int main() { - - AtlasExample(); - - return 0; -} - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasLabels.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasLabels.C deleted file mode 100644 index eb382c7759ed912038880a5626ac8213f147a597..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasLabels.C +++ /dev/null @@ -1,129 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "AtlasLabels.h" - -#include "TLatex.h" -#include "TLine.h" -#include "TPave.h" -#include "TMarker.h" - - -void ATLASLabel(Double_t x,Double_t y,char* text,Color_t color) -{ - TLatex l; //l.SetTextAlign(12); l.SetTextSize(tsize); - l.SetNDC(); - l.SetTextFont(72); - l.SetTextColor(color); - - //double delx = 0.115*696*gPad->GetWh()/(472*gPad->GetWw()); - double delx = 0.115*696*gPad->GetWh()/(472*gPad->GetWw()); - - //l.DrawLatex(x,y,"ATLAS Internal"); - l.DrawLatex(x,y,"ATLAS"); - if (text) { - TLatex p; - p.SetNDC(); - p.SetTextFont(42); - p.SetTextColor(color); - //p.DrawLatex(x+delx,y,text); - //p.DrawLatex(x+delx,y,text); - p.DrawLatex(x+0.16,y,text); - } -} - - -void ATLASLabelOld(Double_t x,Double_t y,bool Preliminary,Color_t color) -{ - TLatex l; //l.SetTextAlign(12); l.SetTextSize(tsize); - l.SetNDC(); - l.SetTextFont(72); - l.SetTextColor(color); - l.DrawLatex(x,y,"ATLAS"); - if (Preliminary) { - TLatex p; - p.SetNDC(); - p.SetTextFont(42); - p.SetTextColor(color); - p.DrawLatex(x+0.115,y,"Preliminary"); - } -} - - - -void ATLASVersion(char* version,Double_t x,Double_t y,Color_t color) -{ - - if (version) { - char versionString[100]; - sprintf(versionString,"Version %s",version); - TLatex l; - l.SetTextAlign(22); - l.SetTextSize(0.04); - l.SetNDC(); - l.SetTextFont(72); - l.SetTextColor(color); - l.DrawLatex(x,y,versionString); - } -} - - - -void myText(Double_t x,Double_t y,Color_t color,char *text,float size) -{ - Double_t tsize=size; - TLatex l; //l.SetTextAlign(12); - l.SetTextSize(tsize); - l.SetNDC(); - l.SetTextColor(color); - l.DrawLatex(x,y,text); -} - -void myBoxText(Double_t x, Double_t y,Double_t boxsize,Int_t mcolor,char *text) -{ - Double_t tsize=0.06; - - TLatex l; l.SetTextAlign(12); //l.SetTextSize(tsize); - l.SetNDC(); - l.DrawLatex(x,y,text); - - Double_t y1=y-0.25*tsize; - Double_t y2=y+0.25*tsize; - Double_t x2=x-0.3*tsize; - Double_t x1=x2-boxsize; - - printf("x1= %f x2= %f y1= %f y2= %f \n",x1,x2,y1,y2); - - TPave *mbox= new TPave(x1,y1,x2,y2,0,"NDC"); - - mbox->SetFillColor(mcolor); - mbox->SetFillStyle(1001); - mbox->Draw(); - - TLine mline; - mline.SetLineWidth(4); - mline.SetLineColor(1); - mline.SetLineStyle(1); - Double_t y_new=(y1+y2)/2.; - mline.DrawLineNDC(x1,y_new,x2,y_new); - -} - -void myMarkerText(Double_t x,Double_t y,Int_t color,Int_t mstyle,char *text) - // Float_t msize=2.,Float_t mytsize=0.05) -{ - // printf("**myMarker: text= %s\ m ",text); - - Double_t tsize=0.06; - TMarker *marker = new TMarker(x-(0.4*tsize),y,8); - marker->SetMarkerColor(color); marker->SetNDC(); - marker->SetMarkerStyle(mstyle); - marker->SetMarkerSize(2.0); - marker->Draw(); - - TLatex l; l.SetTextAlign(12); //l.SetTextSize(tsize); - l.SetNDC(); - l.DrawLatex(x,y,text); -} - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasLabels.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasLabels.h deleted file mode 100644 index 82b33cdbd0327c46dfe335c10e5fc3ed0a430d36..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasLabels.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// -// @file AtlasLabels.h -// -// @author M.Sutton -// -// -// $Id: AtlasLabels.h 726730 2016-02-29 08:41:06Z derue $ - - -#ifndef __ATLASLABELS_H -#define __ATLASLABELS_H - -#include "Rtypes.h" - -void ATLASLabel(Double_t x,Double_t y,char* text=NULL,Color_t color=1); - -void ATLASLabelOld(Double_t x,Double_t y,bool Preliminary=false,Color_t color=1); - -void ATLASVersion(char* version=NULL,Double_t x=0.88,Double_t y=0.975,Color_t color=1); - -void myText(Double_t x,Double_t y,Color_t color,char *text,float size=0.045); - -void myBoxText(Double_t x, Double_t y,Double_t boxsize,Int_t mcolor,char *text); - -void myMarkerText(Double_t x,Double_t y,Int_t color,Int_t mstyle,char *text); -// Float_t msize=2.,Float_t mytsize=0.05); - -#endif // __ATLASLABELS_H diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.C deleted file mode 100644 index 99515ac6c3650a0affe86d153c61d68e7c14305b..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.C +++ /dev/null @@ -1,98 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// -// ATLAS Style, based on a style file from BaBar -// - -#include <iostream> - -#include "AtlasStyle.h" - -#include "TROOT.h" - -void SetAtlasStyle () -{ - static TStyle* atlasStyle = 0; - std::cout << "\nApplying ATLAS style settings...\n" << std::endl ; - if ( atlasStyle==0 ) atlasStyle = AtlasStyle(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); -} - -TStyle* AtlasStyle() -{ - TStyle *atlasStyle = new TStyle("ATLAS","Atlas style"); - - // use plain black on white colors - Int_t icol=0; // WHITE - atlasStyle->SetFrameBorderMode(icol); - atlasStyle->SetFrameFillColor(icol); - atlasStyle->SetCanvasBorderMode(icol); - atlasStyle->SetCanvasColor(icol); - atlasStyle->SetPadBorderMode(icol); - atlasStyle->SetPadColor(icol); - atlasStyle->SetStatColor(icol); - //atlasStyle->SetFillColor(icol); // don't use: white fill color for *all* objects - - // set the paper & margin sizes - atlasStyle->SetPaperSize(20,26); - - // set margin sizes - atlasStyle->SetPadTopMargin(0.05); - atlasStyle->SetPadRightMargin(0.05); - atlasStyle->SetPadBottomMargin(0.16); - atlasStyle->SetPadLeftMargin(0.16); - - // set title offsets (for axis label) - atlasStyle->SetTitleXOffset(1.4); - atlasStyle->SetTitleYOffset(1.4); - - // use large fonts - //Int_t font=72; // Helvetica italics - Int_t font=42; // Helvetica - Double_t tsize=0.045; - atlasStyle->SetTextFont(font); - - atlasStyle->SetTextSize(tsize); - atlasStyle->SetLabelFont(font,"x"); - atlasStyle->SetTitleFont(font,"x"); - atlasStyle->SetLabelFont(font,"y"); - atlasStyle->SetTitleFont(font,"y"); - atlasStyle->SetLabelFont(font,"z"); - atlasStyle->SetTitleFont(font,"z"); - - atlasStyle->SetLabelSize(tsize,"x"); - atlasStyle->SetTitleSize(tsize,"x"); - atlasStyle->SetLabelSize(tsize,"y"); - atlasStyle->SetTitleSize(tsize,"y"); - atlasStyle->SetLabelSize(tsize,"z"); - atlasStyle->SetTitleSize(tsize,"z"); - - // use bold lines and markers - atlasStyle->SetMarkerStyle(20); - atlasStyle->SetMarkerSize(1.); - atlasStyle->SetHistLineWidth(1.5); - atlasStyle->SetLineStyleString(2,"[12 12]"); // postscript dashes - - // get rid of X error bars - //atlasStyle->SetErrorX(0.001); - // get rid of error bar caps - atlasStyle->SetEndErrorSize(0.); - - // do not display any of the standard histogram decorations - atlasStyle->SetOptTitle(0); - atlasStyle->SetOptStat("emr"); - //atlasStyle->SetOptStat(0); - //atlasStyle->SetOptFit(1111); - atlasStyle->SetOptFit(0); - - // put tick marks on top and RHS of plots - atlasStyle->SetPadTickX(1); - atlasStyle->SetPadTickY(1); - - return atlasStyle; - -} - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.h deleted file mode 100644 index 259bed79a7e100ef82a36182cce5d1a1511409ae..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// -// @file AtlasStyle.h -// -// ATLAS Style, based on a style file from BaBar -// -// -// @author M.Sutton -// -// -// $Id: AtlasStyle.h 726730 2016-02-29 08:41:06Z derue $ - -#ifndef __ATLASSTYLE_H -#define __ATLASSTYLE_H - -#include "TStyle.h" - -void SetAtlasStyle(); - -TStyle* AtlasStyle(); - -#endif // __ATLASSTYLE_H diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.py b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.py deleted file mode 100644 index 1113db98a72cff04732c4d3c5523b53c3094c4ed..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasStyle.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration - -from ROOT import * -ROOT.gROOT.LoadMacro("AtlasStyle.C") -#SetAtlasStyle() diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.C deleted file mode 100644 index e2e336e2ae5edcbc8d9af049ce8b8bfb36c8edef..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.C +++ /dev/null @@ -1,330 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - - -#include <iostream> -#include <cmath> - -#include "AtlasUtils.h" - -#include "TLine.h" -#include "TLatex.h" -#include "TMarker.h" -#include "TPave.h" -#include "TH1.h" - -void ATLAS_LABEL(Double_t x,Double_t y,Color_t color) -{ - TLatex l; //l.SetTextAlign(12); l.SetTextSize(tsize); - l.SetNDC(); - l.SetTextFont(72); - l.SetTextColor(color); - l.DrawLatex(x,y,"ATLAS"); -} - -TGraphErrors* myTGraphErrorsDivide(TGraphErrors* g1,TGraphErrors* g2) { - - const Int_t debug=0; - - if (!g1) printf("**myTGraphErrorsDivide: g1 does not exist ! \n"); - if (!g2) printf("**myTGraphErrorsDivide: g2 does not exist ! \n"); - - - Int_t n1=g1->GetN(); - Int_t n2=g2->GetN(); - - if (n1!=n2) { - printf("**myTGraphErrorsDivide: vector do not have same number of entries ! \n"); - } - - TGraphErrors* g3= new TGraphErrors(); - - Double_t x1=0., y1=0., x2=0., y2=0.; - Double_t dx1=0.,dy1=0., dy2=0.; - - Int_t iv=0; - for (Int_t i1=0; i1<n1; i1++) { - for (Int_t i2=0; i2<n2; i2++) { - //if (debug) printf("**myTGraphErrorsDivide: %d %d ! \n",i1,i2); - - g1->GetPoint(i1,x1,y1); - g2->GetPoint(i2,x2,y2); - if (x1!=x2) { - //printf("**myTGraphErrorsDivide: %d x1!=x2 %f %f ! \n",iv,x1,x2); - }else{ - //if (debug) printf("**myTGraphErrorsDivide: %d x1=x2 %f %f ! \n",iv,x1,x2); - dx1 = g1->GetErrorX(i1); - if (y1!=0) dy1 = g1->GetErrorY(i1)/y1; - if (y2!=0) dy2 = g2->GetErrorY(i2)/y2; - - if (debug) - printf("**myTGraphErrorsDivide: %d x1=%f x2=%f y1=%f y2=%f \n",iv,x1,x2,y1,y2); - - if (y2!=0.) g3->SetPoint(iv, x1,y1/y2); - else g3->SetPoint(iv, x1,y2); - - Double_t e=0.; - if (y1!=0 && y2!=0) e=std::sqrt(dy1*dy1+dy2*dy2)*(y1/y2); - g3->SetPointError(iv,dx1,e); - - - if (debug) { - //Double_t g3y, g3x,g3e; - //g3->GetPoint(iv, g3y,g3x); - //g3e=g3->GetErrorY(iv); - //printf("%d g3y= %f g3e=%f \n",iv,g3y,g3e); - } - iv++; - } - // printf("**myTGraphErrorsDivide: ...next \n"); - } - } - return g3; - -} - - -TGraphAsymmErrors* myTGraphErrorsDivide(TGraphAsymmErrors* g1,TGraphAsymmErrors* g2) { - - const Int_t debug=0; - - TGraphAsymmErrors* g3= new TGraphAsymmErrors(); - Int_t n1=g1->GetN(); - Int_t n2=g2->GetN(); - - if (n1!=n2) { - printf(" vectors do not have same number of entries ! \n"); - return g3; - } - - Double_t x1=0., y1=0., x2=0., y2=0.; - Double_t dx1h=0., dx1l=0.; - Double_t dy1h=0., dy1l=0.; - Double_t dy2h=0., dy2l=0.; - - Double_t* X1 = g1->GetX(); - Double_t* Y1 = g1->GetY(); - Double_t* EXhigh1 = g1->GetEXhigh(); - Double_t* EXlow1 = g1->GetEXlow(); - Double_t* EYhigh1 = g1->GetEYhigh(); - Double_t* EYlow1 = g1->GetEYlow(); - - Double_t* X2 = g2->GetX(); - Double_t* Y2 = g2->GetY(); - Double_t* EXhigh2 = g2->GetEXhigh(); - Double_t* EXlow2 = g2->GetEXlow(); - Double_t* EYhigh2 = g2->GetEYhigh(); - Double_t* EYlow2 = g2->GetEYlow(); - - for (Int_t i=0; i<g1->GetN(); i++) { - g1->GetPoint(i,x1,y1); - g2->GetPoint(i,x2,y2); - dx1h = EXhigh1[i]; - dx1l = EXlow1[i]; - if (y1!=0.) dy1h = EYhigh1[i]/y1; - else dy1h = 0.; - if (y2!=0.) dy2h = EYhigh2[i]/y2; - else dy2h = 0.; - if (y1!=0.) dy1l = EYlow1 [i]/y1; - else dy1l = 0.; - if (y2!=0.) dy2l = EYlow2 [i]/y2; - else dy2l = 0.; - - //if (debug) - //printf("%d x1=%f x2=%f y1=%f y2=%f \n",i,x1,x2,y1,y2); - if (debug) - printf("%d dy1=%f %f dy2=%f %f sqrt= %f %f \n",i,dy1l,dy1h,dy2l,dy2h, - std::sqrt(dy1l*dy1l+dy2l*dy2l), std::sqrt(dy1h*dy1h+dy2h*dy2h)); - - if (y2!=0.) g3->SetPoint(i, x1,y1/y2); - else g3->SetPoint(i, x1,y2); - Double_t el=0.; Double_t eh=0.; - - if (y1!=0. && y2!=0.) el=std::sqrt(dy1l*dy1l+dy2l*dy2l)*(y1/y2); - if (y1!=0. && y2!=0.) eh=std::sqrt(dy1h*dy1h+dy2h*dy2h)*(y1/y2); - - if (debug) printf("dx1h=%f dx1l=%f el=%f eh=%f \n",dx1h,dx1l,el,eh); - g3->SetPointError(i,dx1h,dx1l,el,eh); - - } - return g3; - -} - - - -TGraphAsymmErrors* myMakeBand(TGraphErrors* g0, TGraphErrors* g1,TGraphErrors* g2) { - // default is g0 - //const Int_t debug=0; - - TGraphAsymmErrors* g3= new TGraphAsymmErrors(); - - Double_t x1=0., y1=0., x2=0., y2=0., y0=0, x3=0.; - //Double_t dx1=0.; - Double_t dum; - for (Int_t i=0; i<g1->GetN(); i++) { - g0->GetPoint(i, x1,y0); - g1->GetPoint(i, x1,y1); - g2->GetPoint(i, x1,y2); - - // if (y1==0) y1=1; - //if (y2==0) y2=1; - - if (i==g1->GetN()-1) x2=x1; - else g2->GetPoint(i+1,x2,dum); - - if (i==0) x3=x1; - else g2->GetPoint(i-1,x3,dum); - - Double_t tmp=y2; - if (y1<y2) {y2=y1; y1=tmp;} - //Double_t y3=1.; - Double_t y3=y0; - g3->SetPoint(i,x1,y3); - - Double_t binwl=(x1-x3)/2.; - Double_t binwh=(x2-x1)/2.; - if (binwl==0.) binwl= binwh; - if (binwh==0.) binwh= binwl; - g3->SetPointError(i,binwl,binwh,(y3-y2),(y1-y3)); - - } - return g3; - -} - -void myAddtoBand(TGraphErrors* g1, TGraphAsymmErrors* g2) { - - Double_t x1=0., y1=0., y2=0., y0=0; - //Double_t dx1=0.; - //Double_t dum; - - if (g1->GetN()!=g2->GetN()) - std::cout << " graphs have not the same # of elements " << std::endl; - - Double_t* EYhigh = g2-> GetEYhigh(); - Double_t* EYlow = g2-> GetEYlow(); - - for (Int_t i=0; i<g1->GetN(); i++) { - g1->GetPoint(i, x1,y1); - g2->GetPoint(i, x1,y2); - - if (y1==0) y1=1; - if (y2==0) y2=1; - - // if (i==g1->GetN()-1) x2=x1; - // else g2->GetPoint(i+1,x2,dum); - // if (i==0) x3=x1; - // else g2->GetPoint(i-1,x3,dum); - - Double_t eyh=0., eyl=0.; - //if (y1<y2) {y2=y1; y1=tmp;} - //Double_t y3=1.; - - //printf("%d: y1=%f y2=%f Eyhigh= %f Eylow= %f \n",i,y1,y2,EYhigh[i],EYlow[i]); - - y0=y1-y2; - if (y0!=0) { - if (y0>0){ - eyh=EYhigh[i]; - eyh=std::sqrt(eyh*eyh+y0*y0); - //printf("high: %d: y0=%f eyh=%f \n",i,y0,eyh); - g2->SetPointEYhigh(i,eyh); - } else { - eyl=EYlow[i]; - eyl=std::sqrt(eyl*eyl+y0*y0); - // printf("low: %d: y0=%f eyl=%f \n",i,y0,eyl); - g2->SetPointEYlow (i,eyl); - } - } - } - return; - -} - -TGraphErrors* TH1TOTGraph(TH1 *h1){ - - - if (!h1) std::cout << "TH1TOTGraph: histogram not found !" << std::endl; - - TGraphErrors* g1= new TGraphErrors(); - - Double_t x, y, ex, ey; - for (Int_t i=0; i<h1->GetNbinsX(); i++) { - y=h1->GetBinContent(i); - ey=h1->GetBinError(i); - x=h1->GetBinCenter(i); - ex=h1->GetBinWidth(i); - - // cout << " x,y = " << x << " " << y << " ex,ey = " << ex << " " << ey << endl; - - g1->SetPoint(i,x,y); - g1->SetPointError(i,ex,ey); - - } - - //g1->Print(); - - return g1; -} - -void myText(Double_t x,Double_t y,Color_t color,char *text,float size) { - - Double_t tsize=size; - TLatex l; //l.SetTextAlign(12); - l.SetTextSize(tsize); - l.SetNDC(); - l.SetTextColor(color); - l.DrawLatex(x,y,text); -} - - -void myBoxText(Double_t x, Double_t y,Double_t boxsize,Int_t mcolor,char *text,Float_t mytsize) -{ - - Double_t tsize=0.06; - - TLatex l; l.SetTextAlign(12); l.SetTextSize(mytsize); - l.SetNDC(); - l.DrawLatex(x,y,text); - - Double_t y1=y-0.25*tsize; - Double_t y2=y+0.25*tsize; - Double_t x2=x-0.3*tsize; - Double_t x1=x2-boxsize; - - printf("x1= %f x2= %f y1= %f y2= %f \n",x1,x2,y1,y2); - - TPave *mbox= new TPave(x1,y1,x2,y2,0,"NDC"); - - mbox->SetFillColor(mcolor); - mbox->SetFillStyle(1001); - mbox->Draw(); - - TLine mline; - mline.SetLineWidth(4); - mline.SetLineColor(1); - mline.SetLineStyle(1); - Double_t y_new=(y1+y2)/2.; - mline.DrawLineNDC(x1,y_new,x2,y_new); - -} - - -void myMarkerText(Double_t x,Double_t y,Int_t color,Int_t mstyle,char *text, - Float_t msize,Float_t mytsize) -{ - Double_t tsize=0.06; - TMarker *marker = new TMarker(x-(0.4*tsize),y,8); - marker->SetMarkerColor(color); marker->SetNDC(); - marker->SetMarkerStyle(mstyle); - marker->SetMarkerSize(msize); - marker->Draw(); - - TLatex l; l.SetTextAlign(12); - l.SetTextSize(mytsize); - l.SetNDC(); - l.DrawLatex(x,y,text); -} - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.h b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.h deleted file mode 100644 index be71ac787fb65e47d4a661b7bd08cd47c896df63..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// -// @file AtlasUtils.h -// -// -// @author M.Sutton -// -// -// $Id: AtlasUtils.h 726730 2016-02-29 08:41:06Z derue $ - - -#ifndef __ATLASUTILS_H -#define __ATLASUTILS_H - -#include "TGraphErrors.h" -#include "TGraphAsymmErrors.h" - -void ATLAS_LABEL(Double_t x,Double_t y,Color_t color=1); - -TGraphErrors* myTGraphErrorsDivide(TGraphErrors* g1,TGraphErrors* g2); - -TGraphAsymmErrors* myTGraphErrorsDivide(TGraphAsymmErrors* g1,TGraphAsymmErrors* g2); - -TGraphAsymmErrors* myMakeBand(TGraphErrors* g0, TGraphErrors* g1,TGraphErrors* g2); - -void myAddtoBand(TGraphErrors* g1, TGraphAsymmErrors* g2); - -TGraphErrors* TH1TOTGraph(TH1 *h1); - -void myText(Double_t x,Double_t y,Color_t color,char *text,float size=0.1); - -void myBoxText(Double_t x, Double_t y,Double_t boxsize,Int_t mcolor,char *text, - Float_t mytsize=0.05); - -void myMarkerText(Double_t x,Double_t y,Int_t color,Int_t mstyle,char *text,Float_t msize=2., - Float_t mytsize=0.05); - -#endif // __ATLASUTILS_H - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.py b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.py deleted file mode 100644 index d19a7dc5b4454cc2b9dad94ddc4a323488add485..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/AtlasUtils.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration - -from ROOT import * -ROOT.gROOT.LoadMacro("AtlasUtils.C") - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/EffSummary.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/EffSummary.C deleted file mode 100644 index c72f3edbe5d443d59dc8743f698f8519a09ad4ae..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/EffSummary.C +++ /dev/null @@ -1,595 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TH1.h" -#include "TFile.h" -#include "TCanvas.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" - -#include <string> -#include <map> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Michele Pinamonti (Univ. Udine), Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot a summary of all efficiencies -// vs different variables -// It reads as input the default efficiencies of TopFakes package -// void EffSummary() is the core of this macro -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -class MMEffComparison { -public: - MMEffComparison(){ - // _c = new TCanvas("c","c",600,600); - _totH = 0; - _label = ""; - _dummyHist = 0; - _noYlabels = false; - }; - ~MMEffComparison(){}; - - - void SetIsReal(int isReal=0){ - _isReal = isReal; - }; - - void SetXaxis(float min=0,float max=1,string title,int njetbins=0){ - _dummyHist = new TH1F("h","h",1,min,max); - _dummyHist->GetXaxis()->SetTitle(title.c_str()); - if(njetbins>0){ - _dummyHist->GetXaxis()->SetNdivisions(njetbins); - _dummyHist->GetXaxis()->CenterLabels(); - } - }; - - void SetYaxis(float min=0,float max=1){ - _dummyHist = new TH1F("h","h",1,min,max); - //_dummyHist->GetYaxis()->SetTitle(title.c_str()); - /*if(njetbins>0){ - _dummyHist->GetYaxis()->SetNdivisions(njetbins); - _dummyHist->GetYaxis()->CenterLabels(); - }*/ - }; - - void Add(string filename,string histoname,string label,int color,int style,int color2=-1,int style2=-1){ - TFile *f = new TFile(filename.c_str()); - std::cout << " filename = " << filename << std::endl; - std::cout << " histoname = " << histoname << std::endl; - _h[_totH] = (TH1*)f->Get(histoname.c_str())->Clone(); - - // cout << "Adding " << filename << ", " << histoname << endl; - // cout << _h[_totH]->GetBinContent(1) << endl; - - if(!_dummyHist){ - _dummyHist = (TH1F*)_h[_totH]->Clone("h_dummy"); - for(int i_bin=1;i_bin<=_dummyHist->GetNbinsX();i_bin++){ - _dummyHist->SetBinContent(i_bin,0); - _dummyHist->SetBinError(i_bin,0); - } - } - - _h[_totH]->SetName(label.c_str()); - _h[_totH]->SetTitle(label.c_str()); - _h[_totH]->SetLineColor(color); - _h[_totH]->SetLineWidth(1); - // _h[_totH]->SetLineStyle(style); - - // _h[_totH]->SetMarkerSize(0); - _h[_totH]->SetMarkerSize(1.5); - _h[_totH]->SetMarkerStyle(style); - _h[_totH]->SetMarkerColor(color); - - // _h_syst_up[_totH] = (TH1*)_h[_totH]->Clone(Form("%s_syst_up",histoname.c_str())); - // _h_syst_down[_totH] = (TH1*)_h[_totH]->Clone(Form("%s_syst_down",histoname.c_str())); - - _h_syst[_totH] = new TGraphAsymmErrors(_h[_totH]->GetNbinsX()); - for(int i_bin=1;i_bin<=_h[_totH]->GetNbinsX();i_bin++){ - _h_syst[_totH]->SetPoint(i_bin-1,_h[_totH]->GetXaxis()->GetBinCenter(i_bin), _h[_totH]->GetBinContent(i_bin) ); - _h_syst[_totH]->SetPointEYhigh( i_bin-1, _h[_totH]->GetBinError(i_bin) ); - _h_syst[_totH]->SetPointEYlow( i_bin-1, _h[_totH]->GetBinError(i_bin) ); - _h_syst[_totH]->SetPointEXhigh( i_bin-1, _h[_totH]->GetXaxis()->GetBinWidth(i_bin)/2. ); - _h_syst[_totH]->SetPointEXlow( i_bin-1, _h[_totH]->GetXaxis()->GetBinWidth(i_bin)/2. ); - } - - _h_syst[_totH]->SetMarkerSize(0); - _h_syst[_totH]->SetLineColor(color); - _h_syst[_totH]->SetLineStyle(style); - - if(color2>=0) _h_syst[_totH]->SetFillColor(color2); - else _h_syst[_totH]->SetFillColor(color); - if(style2>=0) _h_syst[_totH]->SetFillStyle(style2);//3454); - else _h_syst[_totH]->SetFillStyle(3454); - // _h_syst[_totH]->SetLineWidth(2); - - _index[label] = _totH; - _totH ++; - }; - - void AddSyst(string filename,string histoname,string label){ - TFile *f = new TFile(filename.c_str()); - // cout << "Adding syst to " << filename << ", " << histoname << " -> " << _index[label] << endl; - AddSystToHist( (TH1*)f->Get(histoname.c_str()), _h_syst[_index[label]] ); - }; - - void SetLabel(string label){ - _label = label; - }; - - void Draw(){ - bool xaxisSet = false; - if(_dummyHist!=0) _dummyHist->Draw(); - for(int i=0;i<_totH;i++){ - // if(i==0 && _dummyHist==0) _h_syst[i]->Draw("E2 same"); - // else - _h_syst[i]->Draw("E2 same"); - // if(i==0 && _dummyHist==0) - // _h[i]->Draw("E same"); - // else - _h[i]->Draw("E same"); - // if(i>0 && !xaxisSet) _h[0]->GetXaxis()->SetTitle( _h[i]->GetXaxis()->GetTitle() ); - string s = _h[i]->GetXaxis()->GetTitle(); - if( s != "" ) xaxisSet = true; - } - - if(_noYlabels){ - _dummyHist->GetYaxis()->SetTitle(""); - _dummyHist->GetYaxis()->SetLabelSize(0); - } - else{ - if(_isReal==0) _dummyHist->GetYaxis()->SetTitle("#epsilon_{fake}"); - if(_isReal==1) _dummyHist->GetYaxis()->SetTitle("#epsilon_{real}"); - if(_isReal==2) _dummyHist->GetYaxis()->SetTitle("Efficiency"); - } - - // if(_isReal) _dummyHist->SetMaximum(1.65); - if(_isReal) _dummyHist->SetMaximum(1.3); - else _dummyHist->SetMaximum(1.00); - _dummyHist->SetMinimum(0); - - // fix empty bins and error bars... - for(int i=0;i<_totH;i++){ - for(int i_bin=1;i_bin<=_h[i]->GetNbinsX();i_bin++){ - // _h[i]->SetBinError(i_bin,0.0001); - if( _h[i]->GetBinContent(i_bin)<=0 ) _h_syst[i]->SetPointEYhigh(i_bin-1,0); - if( _h[i]->GetBinContent(i_bin)<=0 ) _h_syst[i]->SetPointEYlow(i_bin-1,0); - // if( _h[i]->GetTitle() ) - } - } - - gPad->RedrawAxis(); - }; - - void DrawLegend(float x0=0.2, float y0=0.7, float x1=0.9, float y1=0.9){ - TLegend *l; - if(_isReal==2) l = new TLegend(x0,y0,x1,y1); - if(_isReal==2) l->SetNColumns(3); - l->SetFillStyle(0); - l->SetBorderSize(0); - l->SetTextSize(0.06); - for(int i=0;i<_totH;i++){ - // l->AddEntry(_h_syst[i],_h[i]->GetTitle(),"lf"); - _h_forLegend[i] = (TH1F*)_h[i]->Clone(Form("histForLegend[%d]",i)); - _h_forLegend[i]->SetFillColor(_h_syst[i]->GetFillColor()); - _h_forLegend[i]->SetFillStyle(_h_syst[i]->GetFillStyle()); - l->AddEntry(_h_forLegend[i],_h[i]->GetTitle(),"lpf"); - } - l->Draw(); - } - - TH1* GetHist(int idx){ - return _h[idx]; - }; - - TH1F* GetDummyHist(){ - return _dummyHist; - }; - - bool _noYlabels; - -private: - TH1* _h[100]; - TH1* _h_forLegend[100]; - // TH1* _h_syst[100]; - TGraphAsymmErrors* _h_syst[100]; - // TH1* _h_syst_up[100]; - // TH1* _h_syst_down[100]; - int _totH; - string _label; - int _isReal; - TH1F* _dummyHist; - map<string,int> _index; -}; - -// -------------------------------------------------- - -class MMEffComparisonSet { -public: - MMEffComparisonSet(int w=600,int h=600){ - _c = new TCanvas("c","c",w,h); - _N = 0; - _idx = 0; - _ec[0] = new MMEffComparison(); - Cd(0); - }; - ~MMEffComparisonSet(){}; - - void Divide(int a=2, int b=1){ - _c->Divide(a,b, 0,0 ); - _N=a*b; - for(int i=0;i<_N;i++){ - _ec[i] = new MMEffComparison(); - if(i>0) _ec[i]->_noYlabels = true; - } - Cd(0); - }; - - void Cd(int i){ - _c->cd(i+1); - _idx = i; - }; - - void SaveAs(string name){ - _c->SaveAs(name.c_str()); - }; - - - // methods from MMEffComparison: - void SetIsReal(int isReal=0){ - _ec[_idx]->SetIsReal(isReal); - }; - - void SetXaxis(float min=0,float max=1,string title,int njetbins=0){ - _ec[_idx]->SetXaxis(min,max,title,njetbins); - }; - - void SetYaxis(float min=0,float max=1){ - _ec[_idx]->SetYaxis(min,max); - }; - - void Add(string filename,string histoname,string label,int color,int style,int color2=-1,int style2=-1){ - _ec[_idx]->Add(filename,histoname,label,color,style,color2,style2); - }; - - void AddSyst(string filename,string histoname,string label){ - _ec[_idx]->AddSyst(filename,histoname,label); - }; - - void SetLabel(string label){ - _ec[_idx]->SetLabel(label); - }; - - void Draw(){ - _ec[_idx]->Draw(); - }; - - void DrawLegend(float x0=0.2, float y0=0.7, float x1=0.9, float y1=0.9){ - _ec[_idx]->DrawLegend(x0,y0,x1,y1); - } - - TH1* GetHist(int idx){ - return _ec[_idx]->GetHist(idx); - }; - - TCanvas* GetCanvas(){ - return _c; - }; - - TH1F* GetDummyHist(){ - return _ec[_idx]->GetDummyHist(); - }; - -private: - TCanvas *_c; - - MMEffComparison *_ec[10]; - int _N; - int _idx; - -}; - -// -------------------------------------------------- - -void AddSystToHist(TH1* h, TGraphAsymmErrors* h_syst){ - float x; - int j; - float diff; - for(int i=0;i<h_syst->GetN();i++){ - x = h_syst->GetX()[i]; - j = h->GetXaxis()->FindBin(x); - diff = h->GetBinContent(j) - h_syst->GetY()[i]; - // syst cutoff ;) - //if(diff>0.2) diff = 0.2; - //if(diff<-0.2) diff = -0.2; - // -// if(x<h_syst->GetXaxis()->GetXmax() && j<=h_syst->GetN() && h_syst->GetY[j]>0 ){ - if(diff>0) h_syst->SetPointEYhigh( i, SqSum( h_syst->GetErrorYhigh(i), diff ) ); - if(diff<0) h_syst->SetPointEYlow( i, SqSum( h_syst->GetErrorYlow(i), diff ) ); -// } - } -}; - -float SqSum(float a,float b){ - return sqrt( pow(a,2) + pow(b,2) ); -}; - -// -------------------------------------------------- - - -void EffSummary(string ch="el",string var="all_1", - string jet="",string bjet="_ge1b",int isReal=2) -{ - // ch : "el" for electrons, "mu" for muons - // var: "all_1" for eta,pt,dR - // "all_2" for ptjet,njet,nbtag and dphi - // jet: jet bin - // bjet: b-jet bin - // isReal = 2 means both fake and real - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - - MMEffComparisonSet *c = new MMEffComparisonSet(1800,600*1800/1400); - - if(ch=="el"){ - string trig[] = {""}; // no trigger splitting - } - else{ - string trig[] = {"mu20i","mu50","mu20"} - } - - // define the variables - if(ch=="el"){ - if(var=="all_1"){ - // e channel - int Nvar = 3; - string vari[] = {"eta", "pt", "dR"}; - string label[] = {"|#eta(elec)| ","p_{T}(elec) [GeV] ","#DeltaR(elec,jet) "}; - float xmin[] = {0, 21, 0.}; - float xmax[] = {2.6, 149, 5.9}; - } - if(var=="all_2"){ - int Nvar = 4; - string vari[] = {"jetpt", "njet", "nbtag", "dPhi"}; - string label[] = {"p_{T}(leading jet) [GeV] ", "n_{jet} ", "n_{b-jet} ", "#Delta#phi(e,E_{T}^{miss}) " }; - float xmin[] = {0, 0.9, -0.1, -0.1}; - float xmax[] = {530, 6.1, 3.1, 3.3}; - } - } - - if(ch=="mu"){ - // mu channel - if(var=="all_1"){ - int Nvar = 3; - string vari[] = {"eta", "pt", "dR"}; - string label[] = {"|#eta(#mu)| ","p_{T}(#mu) [GeV] ","#DeltaR(#mu,jet) "}; - float xmin[] = {0, 21, 0.}; - float xmax[] = {2.6, 149, 5.9}; - } - if(var=="all_2"){ - int Nvar = 4; - string vari[] = {"jetpt", "njet", "nbtag", "dPhi"}; - string label[] = {"p_{T}(leading jet) [GeV] ", "n_{jet} ", "n_{b-jet} ", "#Delta#phi(#mu,E_{T}^{miss}) " }; - float xmin[] = {0, 0.9, -0.1, -0.1}; - float xmax[] = {530, 6.1, 3.1, 3.3}; - } - } - - - // ---- - - c->Divide(Nvar); - // c->GetCanvas()->GetPad(1)->SetRightMargin(0.3); - // c->GetCanvas()->GetPad(2)->SetRightMargin(0.5); - if(Nvar==4){ - c->GetCanvas()->GetPad(1)->SetPad(0, 0, 0.367672, 0.942544); - c->GetCanvas()->GetPad(2)->SetPad(0.367672,0, 0.57,0.942544); // w = 0.57 - 0.367672; origw = 0.983166 - 0.675419 - c->GetCanvas()->GetPad(3)->SetPad(0.57,0, 0.675419,0.942544); // w = 0.675419 - 0.57; origw = 0.983166 - 0.675419 - c->GetCanvas()->GetPad(4)->SetPad(0.675419, 0, 0.983166, 0.942544); - // 0.367672, 0, 0.675419, 0.942544 - } - else{ - cout << c->GetCanvas()->GetPad(1)->GetXlowNDC() << ", "; - cout << c->GetCanvas()->GetPad(1)->GetYlowNDC() << ", "; - cout << c->GetCanvas()->GetPad(1)->GetXlowNDC()+c->GetCanvas()->GetPad(1)->GetAbsWNDC() << ", "; - cout << c->GetCanvas()->GetPad(1)->GetYlowNDC()+c->GetCanvas()->GetPad(1)->GetAbsHNDC(); - cout << endl; - - cout << c->GetCanvas()->GetPad(2)->GetXlowNDC() << ", "; - cout << c->GetCanvas()->GetPad(2)->GetYlowNDC() << ", "; - cout << c->GetCanvas()->GetPad(2)->GetXlowNDC()+c->GetCanvas()->GetPad(2)->GetAbsWNDC() << ", "; - cout << c->GetCanvas()->GetPad(2)->GetYlowNDC()+c->GetCanvas()->GetPad(2)->GetAbsHNDC(); - cout << endl; - - cout << c->GetCanvas()->GetPad(3)->GetXlowNDC() << ", "; - cout << c->GetCanvas()->GetPad(3)->GetYlowNDC() << ", "; - cout << c->GetCanvas()->GetPad(3)->GetXlowNDC()+c->GetCanvas()->GetPad(3)->GetAbsWNDC() << ", "; - cout << c->GetCanvas()->GetPad(3)->GetYlowNDC()+c->GetCanvas()->GetPad(3)->GetAbsHNDC(); - cout << endl; - } - - for(int i=0;i<Nvar;i++){ - c->Cd(i); - c->SetYaxis(0.,1.5); - c->SetXaxis(xmin[i],xmax[i],label[i]); - if(vari[i]=="nbtag") c->SetXaxis(xmin[i],xmax[i],label[i],5); - if(vari[i]=="njet") c->SetXaxis(xmin[i],xmax[i],label[i],7); - - c->SetIsReal(isReal); - - // ================================================== - // case for electrons - if(ch=="el") { - //std::cout << " add real efficiencies " << std::endl; - // real efficiencies - c->Add("../data/R_"+ch+"_Default.root","eff_"+vari[i]+jet,"#varepsilon_{r} ",kBlack,kOpenTriangleUp,kBlack,3445); - // add systematics (CRreal) - //std::cout << " add CRreal " << std::endl; - c->AddSyst("../data/R_"+ch+"_Default_CRreal.root","eff_"+vari[i]+bjet+jet,"#varepsilon_{r} "); - - //std::cout << " add fake efficiencies " << std::endl; - // fake efficiencies - c->Add("../data/F_"+ch+"_Default.root","eff_"+vari[i]+bjet+jet,"#varepsilon_{f} ",kBlack,kFullTriangleUp,kBlack,3445); - // add systematics MCup - //std::cout << " add MCup " << std::endl; - c->AddSyst("../data/F_"+ch+"_Default_MCup.root","eff_"+vari[i]+bjet+jet,"#varepsilon_{f} "); - // add systematics MCdown - //std::cout << " add MCdown " << std::endl; - c->AddSyst("../data/F_"+ch+"_Default_MCdown.root","eff_"+vari[i]+bjet+jet,"#varepsilon_{f} "); - //std::cout << " add CRfake " << std::endl; - // add systematics CRfake - c->AddSyst("../data/F_"+ch+"_Default_CRfake.root","eff_"+vari[i]+bjet+jet,"#varepsilon_{f} "); - } - // ================================================== - // case for muons - if(ch=="mu") { - //std::cout << " add real efficiencies T&P" << std::endl; - // real efficiencies - c->Add("../data/R_"+ch+"_Default.root","eff_"+vari[i]+jet+"_"+trig[0],"#varepsilon_{r} "+trig[0],kRed,kOpenSquare,kRed-10,1001); - c->Add("../data/R_"+ch+"_Default.root","eff_"+vari[i]+jet+"_"+trig[1],"#varepsilon_{r} "+trig[1],kBlack,kOpenTriangleUp,kBlack,3445); - c->Add("../data/R_"+ch+"_Default.root","eff_"+vari[i]+jet+"_"+trig[2],"#varepsilon_{r} "+trig[2],kBlue,kOpenCircle,kBlue-7);//kAzure); - // add systematics (CRreal) - //std::cout << " add real efficiencies high MTW" << std::endl; - //std::cout << " file = " << "../data/R_"+ch+"_Default_CRreal.root" << std::endl; - c->AddSyst("../data/R_"+ch+"_Default_CRreal.root","eff_"+vari[i]+bjet+jet+"_"+trig[0],"#varepsilon_{r} "+trig[0]); - c->AddSyst("../data/R_"+ch+"_Default_CRreal.root","eff_"+vari[i]+bjet+jet+"_"+trig[1],"#varepsilon_{r} "+trig[1]); - c->AddSyst("../data/R_"+ch+"_Default_CRreal.root","eff_"+vari[i]+bjet+jet+"_"+trig[2],"#varepsilon_{r} "+trig[2]); - - //std::cout << " add fake efficiencies " << std::endl; - // fake efficiencies - c->Add("../data/F_"+ch+"_Default.root","eff_"+vari[i]+bjet+jet+"_"+trig[0],"#varepsilon_{f} "+trig[0],kRed,kFullSquare,kRed-10,1001); - c->Add("../data/F_"+ch+"_Default.root","eff_"+vari[i]+bjet+jet+"_"+trig[1],"#varepsilon_{f} "+trig[1],kBlack,kFullTriangleUp,kBlack,3445); - c->Add("../data/F_"+ch+"_Default.root","eff_"+vari[i]+bjet+jet+"_"+trig[2],"#varepsilon_{f} "+trig[2],kBlue,kFullCircle,kBlue-7); - - // add systematics MCup - c->AddSyst("../data/F_"+ch+"_Default_MCup.root","eff_"+vari[i]+bjet+jet+"_"+trig[0],"#varepsilon_{f} "+trig[0]); - c->AddSyst("../data/F_"+ch+"_Default_MCup.root","eff_"+vari[i]+bjet+jet+"_"+trig[1],"#varepsilon_{f} "+trig[1]); - c->AddSyst("../data/F_"+ch+"_Default_MCup.root","eff_"+vari[i]+bjet+jet+"_"+trig[2],"#varepsilon_{f} "+trig[2]); - - // add systematics MCdown - c->AddSyst("../data/F_"+ch+"_Default_MCdown.root","eff_"+vari[i]+bjet+jet+"_"+trig[0],"#varepsilon_{f} "+trig[0]); - c->AddSyst("../data/F_"+ch+"_Default_MCdown.root","eff_"+vari[i]+bjet+jet+"_"+trig[1],"#varepsilon_{f} "+trig[1]); - c->AddSyst("../data/F_"+ch+"_Default_MCdown.root","eff_"+vari[i]+bjet+jet+"_"+trig[2],"#varepsilon_{f} "+trig[2]); - - // add systematics CRfake - c->AddSyst("../data/F_"+ch+"_Default_CRfake.root","eff_"+vari[i]+bjet+jet+"_"+trig[0],"#varepsilon_{f} "+trig[0]); - c->AddSyst("../data/F_"+ch+"_Default_CRfake.root","eff_"+vari[i]+bjet+jet+"_"+trig[1],"#varepsilon_{f} "+trig[1]); - c->AddSyst("../data/F_"+ch+"_Default_CRfake.root","eff_"+vari[i]+bjet+jet+"_"+trig[2],"#varepsilon_{f} "+trig[2]); - } - c->Draw(); - - if(i==Nvar-1){ - if(ch=="el") c->DrawLegend(0.05,0.8, 0.95,0.95); - if(ch=="mu") c->DrawLegend(0.05,0.8, 0.95,0.95); - } - } - - // ------ - - if(Nvar==4){ - c->Cd(0); - c->GetDummyHist()->GetXaxis()->SetNdivisions(506); - // w = 0.57 - 0.367672; origw = 0.942544 - 0.367672 - c->Cd(1); - c->GetDummyHist()->GetXaxis()->SetLabelSize( ((0.983166 - 0.675419)/(0.57 - 0.367672)) * c->GetDummyHist()->GetXaxis()->GetLabelSize() ); - c->GetDummyHist()->GetXaxis()->SetTitleSize( ((0.983166 - 0.675419)/(0.57 - 0.367672)) * c->GetDummyHist()->GetXaxis()->GetTitleSize() ); - c->GetDummyHist()->GetXaxis()->SetLabelOffset(-0.015); - c->GetDummyHist()->GetXaxis()->SetTitleOffset(0.9); - // - c->Cd(2); - c->GetDummyHist()->GetXaxis()->SetLabelSize( ((0.983166 - 0.675419)/(0.675419 - 0.57)) * c->GetDummyHist()->GetXaxis()->GetLabelSize() ); - c->GetDummyHist()->GetXaxis()->SetTitleSize( ((0.983166 - 0.675419)/(0.675419 - 0.57)) * c->GetDummyHist()->GetXaxis()->GetTitleSize() ); - c->GetDummyHist()->GetXaxis()->SetLabelOffset(-0.065); - c->GetDummyHist()->GetXaxis()->SetTitleOffset(0.46); - } - - - // increase x-axis size - c->Cd(0); - c->GetDummyHist()->GetXaxis()->SetLabelSize( 0.85 * c->GetDummyHist()->GetXaxis()->GetLabelSize() ); - c->GetDummyHist()->GetXaxis()->SetTitleSize( 0.85 * c->GetDummyHist()->GetXaxis()->GetTitleSize() ); - c->GetDummyHist()->GetXaxis()->SetLabelOffset(0.012); - c->GetDummyHist()->GetXaxis()->SetTitleOffset(1.6); - for(int i=0;i<Nvar;i++){ - c->Cd(i); - c->GetDummyHist()->GetXaxis()->SetLabelSize( 1.2 * c->GetDummyHist()->GetXaxis()->GetLabelSize() ); - c->GetDummyHist()->GetXaxis()->SetTitleSize( 1.2 * c->GetDummyHist()->GetXaxis()->GetTitleSize() ); - } - - - c->Cd(0); - if(ch=="el"){ - ATLASLabel(0.25,0.93,"Work in progress"); - myText(0.25,0.87,1,"#sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - } - if(ch=="mu"){ - ATLASLabel(0.25,0.93,"Work in progress"); - myText(0.25,0.87,1,"#sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - } - - // adapt to your case - // for electrons - if (ch=="el") { - if (jet=="_1j") { - if (bjet=="_0b") - myText(0.65,0.87,1,"e+1 jet, 0 b-jet",0.045); - if (bjet=="_ge1b") - myText(0.65,0.87,1,"e+1 jet, #geq1 b-jet",0.045); - } - if (jet=="") { - if (bjet=="_0b") - myText(0.65,0.87,1,"e+#geq 1 jet, 0 b-jet",0.045); - if (bjet=="_ge1b") - myText(0.65,0.87,1,"e+#geq 1 jet, #geq1 b-jet",0.045); - } - if (jet=="_ge2j") { - if (bjet=="_0b") - myText(0.65,0.87,1,"e+#geq 2 jets, 0 b-jet",0.045); - if (bjet=="_ge1b") - myText(0.65,0.87,1,"e+#geq 2 jets, #geq1 b-jet",0.045); - } - } - // for muons - if (ch=="mu") { - if (jet=="_1j") { - if (bjet=="_0b") - myText(0.65,0.87,1,"#mu+1 jet, 0 b-jet",0.045); - if (bjet=="_ge1b") - myText(0.65,0.87,1,"#mu+1 jet, #geq1 b-jet",0.045); - } - if (jet=="") { - if (bjet=="_0b") - myText(0.65,0.87,1,"#mu+#geq 1 jet, 0 b-jet",0.045); - if (bjet=="_ge1b") - myText(0.65,0.87,1,"#mu+#geq 1 jet, #geq1 b-jet",0.045); - } - if (jet=="_ge2j") { - if (bjet=="_0b") - myText(0.65,0.87,1,"#mu+#geq 2 jets, 0 b-jet",0.045); - if (bjet=="_ge1b") - myText(0.65,0.87,1,"#mu+#geq 2 jets, #geq1 b-jet",0.045); - } - } - - string name; - if(isReal==0) name = "FakeEffComp_"+ch+"_"+var+bjet+jet; - if(isReal==1) name = "RealEffComp_"+ch+"_"+var+bjet+jet; - if(isReal==2) name = "EffComp_"+ch+"_"+var+bjet+jet; - c->SaveAs(("fig/"+name+".png").c_str()); - c->SaveAs(("fig/"+name+".eps").c_str()); - c->SaveAs(("fig/"+name+".pdf").c_str()); - - TFile *fNew = new TFile("Test.root","RECREATE"); - gPad->Write("",TObject::kOverwrite); - -} - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/FakeEffElec.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/FakeEffElec.C deleted file mode 100644 index 522561dcea07b335ef7dbfe3060a204451a3d39d..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/FakeEffElec.C +++ /dev/null @@ -1,501 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot fake efficiencies vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void FakeEffElec() -{ - // choice the option you want - in which control region - //int choice = 0; // CR1 - //int choice = 1; // CR1 vs CR2 0 b-tag - //int choice = 2; // CR1 vs CR2 b-tag - //int choice = 3; // CR1 MCup/down 0 b-tag - //int choice = 4; // CR1 MCup/down b-tag - //int choice = 5; // CR1 MC WZ 0 b-tag - //int choice = 6; // CR1 MC WZ b-tag - - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int choice==0;choice<=6;choice++) - for (int var==0;var<=8;var++) - my.execute(var,choice); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var, int choice) - { - TGraph* plot0; - TH1F* plot[10][10]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f[10]; - - // read input files - // CR1 - myname = "..//data/F_el_Default.root"; - f[0] = TFile::Open(myname,"old"); - // CR2 - myname = "../data/F_el_Default_CRfake.root"; - f[1] = TFile::Open(myname,"old"); - // CR1 MCup - myname = "../data/F_el_Default_MCup.root"; - f[2] = TFile::Open(myname,"old"); - // CR1 MCdown - myname = "../data/F_el_Default_MCdown.root"; - f[3] = TFile::Open(myname,"old"); - // CR1 Powheg - myname = "../data/F_el_Default_WZPowheg.root"; - f[4] = TFile::Open(myname,"old"); - // CR1 MadGraph - myname = "../data/F_el_Default_WZMG.root"; - f[5] = TFile::Open(myname,"old"); - - // loop on each files - for (int ifile=0;ifile<=5;ifile++) { - // loop on jet bins - for (int ijet=0;ijet<=3;ijet++) { - // check which variable to be used - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mtw"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (var!=7) { - if (ijet==0) mynamehist += "_0b_1j"; - if (ijet==1) mynamehist += "_0b_ge2j"; - if (ijet==2) mynamehist += "_ge1b_1j"; - if (ijet==3) mynamehist += "_ge1b_ge2j"; - } else { - if (ijet==0) mynamehist += "_0b"; - if (ijet==1) mynamehist += "_0b_ge2j"; - if (ijet==2) mynamehist += "_ge1b"; - if (ijet==3) mynamehist += "_ge1b_ge2j"; - } - - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ifile][ijet] = (TH1F*)f[ifile]->Get(mynamehist); - //std::cout << " plot = " << plot[ifile][ijet] << std::endl; - } - } - - // =============================================== - // set the TAxis ranges - m_nlines = 2; - m_eff[0] = 0.; - m_eff[1] = 0.8; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,choice,plot0,plot); - } - - // ============================================== - void plotGraph(int var,int choice,TGraph* plot0,TH1F* plot[10][10]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // plot the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("E_{T}(elec) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(elec)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (elec, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (elec,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(elec,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // plot the TGraph - if (choice==0) { // CR1 - myplot(plot[0][0],1,20); - if (var!=7) myplot(plot[0][1],2,21); // case for njet - myplot(plot[0][2],3,24); - if (var!=7) myplot(plot[0][3],4,25); // case for njet - - if (var==8) { // case for nbjet (use same colors) - myplot(plot[0][0],1,20); - myplot(plot[0][1],3,24); - myplot(plot[0][2],1,20); - myplot(plot[0][3],3,24); - } - } - if (choice==1) { // CR1 vs CR2 0 btag - myplot(plot[0][0],1,20); // 1j 0b - myplot(plot[1][0],1,24); - myplot(plot[0][1],2,21); // ge2j 0b - myplot(plot[1][1],2,25); - } - if (choice==2) { //CR1 vs CR2 btag - myplot(plot[0][2],1,20); // 1j ge1b - myplot(plot[1][2],1,24); - myplot(plot[0][3],2,21); // ge2j ge1b - myplot(plot[1][3],2,25); - } - if (choice==3) { // CR1 MCup/down 0 btag - myplot(plot[0][0],1,20); // 1j 0b - myplot(plot[2][0],1,21); - myplot(plot[3][0],1,22); - - myplot(plot[0][1],2,24); // ge2j 0b - myplot(plot[2][1],2,25); - myplot(plot[3][1],2,26); - } - if (choice==4) { // CR1 MCup/down btag - myplot(plot[0][2],1,20); // 1j b - myplot(plot[2][2],1,21); - myplot(plot[3][2],1,22); - - myplot(plot[0][3],2,24); // ge2j b - myplot(plot[2][3],2,25); - myplot(plot[3][3],2,26); - } - if (choice==5) { // CR1 MC WZ 0 btag - myplot(plot[0][0],1,20); // 1j 0b - myplot(plot[4][0],1,21); - myplot(plot[5][0],1,22); - - myplot(plot[0][1],2,24); // ge2j 0b - myplot(plot[4][1],2,25); - myplot(plot[5][1],2,26); - } - if (choice==6) { // CR1 MC WZ btag - myplot(plot[0][2],1,20); // 1j b - myplot(plot[4][2],1,21); - myplot(plot[5][2],1,22); - - myplot(plot[0][3],2,24); // ge2j b - myplot(plot[4][3],2,25); - myplot(plot[5][3],2,26); - } - - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,choice,plot); - c1->RedrawAxis(); - - // plot the output names - TString suffix = ""; - if (var==0) suffix = "_vsEt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - - if (choice==0) // CR1 - c1->SaveAs("fig/efffake_elec"+suffix+format); - if (choice==1) // CR1 vs CR2 0 btag - c1->SaveAs("fig/efffake_elec_CR12_0btag"+suffix+format); - if (choice==2) // CR1 vs CR2 ge1 btag - c1->SaveAs("fig/efffake_elec_CR12_btag"+suffix+format); - if (choice==3) // CR1 MCup/down 0 btag - c1->SaveAs("fig/efffake_elec_CR1_MCUpDown_0btag"+suffix+format); - if (choice==4) // CR1 MCup/down ge1 btag - c1->SaveAs("fig/efffake_elec_CR1_MCUpDown_btag"+suffix+format); - if (choice==5) // CR1 MC WZ 0 btag - c1->SaveAs("fig/efffake_elec_CR1_MCWZ_0btag"+suffix+format); - if (choice==6) // CR1 MC WZ ge1 btag - c1->SaveAs("fig/efffake_elec_CR1_MCWZ_btag"+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,int choice,TH1F* plot[10][10]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.1,ylabel-0.06,1,"e+jets, #sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - // ============================================================ - // set the TLegend (adapt to your own team) - if (choice==0) { - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var!=7 && var!=8) { - leg->AddEntry(plot[0][0],"#epsilon_{f} CR_{1}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[0][1],"#epsilon_{f} CR_{1}, #geq2 jets, 0 btag","ep"); - leg->AddEntry(plot[0][2],"#epsilon_{f} CR_{1}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[0][3],"#epsilon_{f} CR_{1}, #geq2 jets, #geq1 btag","ep"); - } else if (var==7) { // case for njet - leg->AddEntry(plot[0][0],"#epsilon_{f} CR_{1} 0 btag","ep"); - leg->AddEntry(plot[0][2],"#epsilon_{f} CR_{1} #geq1 btag","ep"); - } else if (var==8) { // case for nbjet - leg->AddEntry(plot[0][0],"#epsilon_{f} CR_{1}, 1 jet","ep"); - leg->AddEntry(plot[0][1],"#epsilon_{f} CR_{1}, #geq2 jets","ep"); - } - leg->Draw(); - } - - // ============================= - if (choice==1) { // for comparison CR1 CR2 - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - leg->AddEntry(plot[0][0],"#epsilon_{f} CR_{1}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[1][0],"#epsilon_{f} CR_{2}, 1 jet, 0 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.5,ymin2,0.6,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.04); - leg2->AddEntry(plot[0][1],"#epsilon_{f} CR_{1}, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[1][1],"#epsilon_{f} CR_{2}, #geq2 jets, 0 btag","ep"); - leg2->Draw(); - } - - // ============================= - if (choice==2) { // for comparison CR1 CR2 - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - leg->AddEntry(plot[0][2],"#epsilon_{f} CR_{1}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[1][2],"#epsilon_{f} CR_{2}, 1 jet, #geq1 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.5,ymin2,0.6,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.04); - leg2->AddEntry(plot[0][3],"#epsilon_{f} CR_{1}, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[1][3],"#epsilon_{f} CR_{2}, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - // ============================= - if (choice==3) { // for comparison CR1 MCup/down 0 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.035); - leg->AddEntry(plot[0][0],"#epsilon_{f} CR_{1}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[2][0],"#epsilon_{f} CR_{1} MCup, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[3][0],"#epsilon_{f} CR_{1} MCdown, 1 jet, 0 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.035); - leg2->AddEntry(plot[0][1],"#epsilon_{f} CR_{1}, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[2][1],"#epsilon_{f} CR_{1} MCup, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[3][1],"#epsilon_{f} CR_{1} down, #geq2 jets, 0 btag","ep"); - leg2->Draw(); - } - - // ============================= - if (choice==4) { // for comparison CR1 MCup/down >=1 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.035); - leg->AddEntry(plot[0][2],"#epsilon_{f} CR_{1}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[2][2],"#epsilon_{f} CR_{1} MCup, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[3][2],"#epsilon_{f} CR_{1} MCdown, 1 jet, #geq1 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.035); - leg2->AddEntry(plot[0][3],"#epsilon_{f} CR_{1}, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[2][3],"#epsilon_{f} CR_{1} MCup, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[3][3],"#epsilon_{f} CR_{1} down, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - // ============================= - if (choice==5) { // for comparison CR1 MC WZ 0 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.03); - leg->AddEntry(plot[0][0],"#epsilon_{f} CR_{1} Sherpa, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[4][0],"#epsilon_{f} CR_{1} Powheg, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[5][0],"#epsilon_{f} CR_{1} MadGraph, 1 jet, 0 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.03); - leg2->AddEntry(plot[0][1],"#epsilon_{f} CR_{1} Sherpa, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[4][1],"#epsilon_{f} CR_{1} Powheg, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[5][1],"#epsilon_{f} CR_{1} MadGraph, #geq2 jets, 0 btag","ep"); - leg2->Draw(); - } - - // ============================= - if (choice==6) { // for comparison CR1 MC WZ >=1 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.03); - leg->AddEntry(plot[0][2],"#epsilon_{f} CR_{1} Sherpa, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[4][2],"#epsilon_{f} CR_{1} Powheg, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[5][2],"#epsilon_{f} CR_{1} MadGraph, 1 jet, #geq1 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.03); - leg2->AddEntry(plot[0][3],"#epsilon_{f} CR_{1} Sherpa, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[4][3],"#epsilon_{f} CR_{1} Powheg, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[5][3],"#epsilon_{f} CR_{1} MadGraph, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/FakeEffMuon.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/FakeEffMuon.C deleted file mode 100644 index eb279ab2ad206873a78212f9def641050e429bb0..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/FakeEffMuon.C +++ /dev/null @@ -1,564 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot fake efficiencies vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void FakeEffMuon() -{ - // use these options to choose the control region - //int choice = 0; // CR1 - //int choice = 1; // CR1 vs CR2 0 b-tag - //int choice = 2; // CR1 vs CR2 b-tag - //int choice = 3; // CR1 MCup/down 0 b-tag - //int choice = 4; // CR1 MCup/down b-tag - //int choice = 5; // CR1 MC WZ 0 b-tag - //int choice = 6; // CR1 MC WZ b-tag - - // choose the trigger - //int trigger = 0; // mu20i - //int trigger = 1; // mu20 - //int trigger = 2; // mu50 - - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int choice=0;choice<=1;choice++) - for (int trigger=0;trigger<=2;trigger++) - for (int var=0;var<=8;var++) - my.execute(var,choice,trigger); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var, int choice, int trigger) - { - TGraph* plot0; - TH1F* plot[10][20]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f[10]; - - // read the input files - // CR1 - myname = "../data/F_mu_Default.root"; - f[0] = TFile::Open(myname,"old"); - // CR2 - myname = "../data/F_mu_Default_CRfake.root"; - f[1] = TFile::Open(myname,"old"); - // CR1 MCup - myname = "../data/F_mu_Default_MCup.root"; - f[2] = TFile::Open(myname,"old"); - // CR1 MCdown - myname = "../data/F_mu_Default_MCdown.root"; - f[3] = TFile::Open(myname,"old"); - // CR1 Powheg - myname = "../data/F_mu_Default_WZPowheg.root"; - f[4] = TFile::Open(myname,"old"); - // CR1 MadGraph - myname = "../data/F_mu_Default_WZMG.root"; - f[5] = TFile::Open(myname,"old"); - - // loop on each files - for (int ifile=0;ifile<=5;ifile++) { - // loop on all jet possibilities - for (int ijet=0;ijet<=11;ijet++) { - // check which variable to use - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mtw"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (var<7) { - // mu20i - if (ijet==0) mynamehist += "_0b_1j_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_1j_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_1j_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_1j_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_1j_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_1j_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } else if (var==7) { // njet - // mu20i - if (ijet==0) mynamehist += "_0b_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } else if (var==8) { // nbjet - // mu20i - if (ijet==0) mynamehist += "_0b_1j_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_1j_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_1j_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_1j_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_1j_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_1j_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } - - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ifile][ijet] = (TH1F*)f[ifile]->Get(mynamehist); - //std::cout << " plot = " << plot[ifile][ijet] << std::endl; - } - } - - // =============================================== - // set the TAxis ranges - m_nlines = 2; - m_eff[0] = 0.; - m_eff[1] = 1.4; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,choice,trigger,plot0,plot); - } - - // ============================================== - void plotGraph(int var,int choice,int trigger, - TGraph* plot0,TH1F* plot[10][20]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // plot the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("p_{T}(#mu) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(#mu)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (#mu, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (#mu,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(#mu,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // choose the trigger - int it1 = -1; int it2 = -1; int it3 = -1; int it4 = -1; - if (trigger==0) {it1 = 0; it2 = 1; it3 = 2; it4 = 3;} // mu20i - if (trigger==1) {it1 = 4; it2 = 5; it3 = 6; it4 = 7;} // mu20 - if (trigger==2) {it1 = 8; it2 = 9; it3 = 10; it4 = 11;} // mu50 - - if (choice==0) { // CR1 - myplot(plot[0][it1],1,20); - if (var!=7) myplot(plot[0][it2],2,21); // case for njet - myplot(plot[0][it3],3,24); - if (var!=7) myplot(plot[0][it4],4,25); // case for njet - - if (var==8) { // case for nbjet (use same colors) - myplot(plot[0][it1],1,20); - myplot(plot[0][it2],3,24); - myplot(plot[0][it3],1,20); - myplot(plot[0][it4],3,24); - } - } - if (choice==1) { // CR1 vs CR2 0 btag - myplot(plot[0][it1],1,20); // 1j 0b - myplot(plot[1][it1],1,24); - myplot(plot[0][it2],2,21); // ge2j 0b - myplot(plot[1][it2],2,25); - } - if (choice==2) { //CR1 vs CR2 btag - myplot(plot[0][it3],1,20); // 1j ge1b - myplot(plot[1][it3],1,24); - myplot(plot[0][it4],2,21); // ge2j ge1b - myplot(plot[1][it4],2,25); - } - if (choice==3) { // CR1 MCup/down 0 btag - myplot(plot[0][it1],1,20); // 1j 0b - myplot(plot[2][it1],1,21); - myplot(plot[3][it1],1,22); - - myplot(plot[0][it2],2,24); // ge2j 0b - myplot(plot[2][it2],2,25); - myplot(plot[3][it2],2,26); - } - if (choice==4) { // CR1 MCup/down btag - myplot(plot[0][it3],1,20); // 1j b - myplot(plot[2][it3],1,21); - myplot(plot[3][it3],1,22); - - myplot(plot[0][it4],2,24); // ge2j b - myplot(plot[2][it4],2,25); - myplot(plot[3][it4],2,26); - } - if (choice==5) { // CR1 MC WZ 0 btag - myplot(plot[0][it1],1,20); // 1j 0b - myplot(plot[4][it1],1,21); - myplot(plot[5][it1],1,22); - - myplot(plot[0][it2],2,24); // ge2j 0b - myplot(plot[4][it2],2,25); - myplot(plot[5][it2],2,26); - } - if (choice==6) { // CR1 MC WZ btag - myplot(plot[0][it3],1,20); // 1j b - myplot(plot[4][it3],1,21); - myplot(plot[5][it3],1,22); - - myplot(plot[0][it4],2,24); // ge2j b - myplot(plot[4][it4],2,25); - myplot(plot[5][it4],2,26); - } - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,choice,trigger,plot); - c1->RedrawAxis(); - - // set the output names - TString suffix = ""; - if (var==0) suffix = "_vsPt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - - TString st = ""; - if (trigger==0) st = "_mu20i"; - if (trigger==1) st = "_mu20"; - if (trigger==2) st = "_mu50"; - - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - - if (choice==0) // CR1 - c1->SaveAs("fig/efffake_muon"+st+suffix+format); - if (choice==1) // CR1 vs CR2 0 btag - c1->SaveAs("fig/efffake_muon"+st+"_CR12_0btag"+suffix+format); - if (choice==2) // CR1 vs CR2 ge1 btag - c1->SaveAs("fig/efffake_muon"+st+"_CR12_btag"+suffix+format); - if (choice==3) // CR1 MCup/down 0 btag - c1->SaveAs("fig/efffake_muon"+st+"_CR1_MCUpDown_0btag"+suffix+format); - if (choice==4) // CR1 MCup/down ge1 btag - c1->SaveAs("fig/efffake_muon"+st+"_CR1_MCUpDown_btag"+suffix+format); - if (choice==5) // CR1 MC WZ 0 btag - c1->SaveAs("fig/efffake_muon"+st+"_CR1_MCWZ_0btag"+suffix+format); - if (choice==6) // CR1 MC WZ ge1 btag - c1->SaveAs("fig/efffake_muon"+st+"_CR1_MCWZ_btag"+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,int choice,int trigger,TH1F* plot[10][20]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.2,ylabel-0.06,1,"#sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - if (trigger==0) myText(xlabel,ylabel-0.06,1,"#mu+jets mu20i",0.04); - if (trigger==1) myText(xlabel,ylabel-0.06,1,"#mu+jets mu20",0.04); - if (trigger==2) myText(xlabel,ylabel-0.06,1,"#mu+jets mu50",0.04); - - int it1 = -1; int it2 = -1; int it3 = -1; int it4 = -1; - if (trigger==0) {it1 = 0; it2 = 1; it3 = 2; it4 = 3;} // mu20i - if (trigger==1) {it1 = 4; it2 = 5; it3 = 6; it4 = 7;} // mu20 - if (trigger==2) {it1 = 8; it2 = 9; it3 = 10; it4 = 11;} // mu50 - - // ============================================================ - // set the TLegend (adapt to your own team) - if (choice==0) { - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var!=7 && var!=8) { - leg->AddEntry(plot[0][it1],"#epsilon_{f} CR_{1}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[0][it2],"#epsilon_{f} CR_{1}, #geq2 jets, 0 btag","ep"); - leg->AddEntry(plot[0][it3],"#epsilon_{f} CR_{1}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[0][it4],"#epsilon_{f} CR_{1}, #geq2 jets, #geq1 btag","ep"); - } else if (var==7) { // case for njet - leg->AddEntry(plot[0][it1],"#epsilon_{f} CR_{1} 0 btag","ep"); - leg->AddEntry(plot[0][it3],"#epsilon_{f} CR_{1} #geq1 btag","ep"); - } else if (var==8) { // case for nbjet - leg->AddEntry(plot[0][it1],"#epsilon_{f} CR_{1}, 1 jet","ep"); - leg->AddEntry(plot[0][it2],"#epsilon_{f} CR_{1}, #geq2 jets","ep"); - } - leg->Draw(); - } - - // ============================= - if (choice==1) { // for comparison CR1 CR2 - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - leg->AddEntry(plot[0][it1],"#epsilon_{f} CR_{1}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[1][it1],"#epsilon_{f} CR_{2}, 1 jet, 0 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.5,ymin2,0.6,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.04); - leg2->AddEntry(plot[0][it2],"#epsilon_{f} CR_{1}, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[1][it2],"#epsilon_{f} CR_{2}, #geq2 jets, 0 btag","ep"); - leg2->Draw(); - } - - // ============================= - if (choice==2) { // for comparison CR1 CR2 - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - leg->AddEntry(plot[0][it3],"#epsilon_{f} CR_{1}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[1][it3],"#epsilon_{f} CR_{2}, 1 jet, #geq1 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.5,ymin2,0.6,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.04); - leg2->AddEntry(plot[0][it4],"#epsilon_{f} CR_{1}, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[1][it4],"#epsilon_{f} CR_{2}, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - // ============================= - if (choice==3) { // for comparison CR1 MCup/down 0 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.035); - leg->AddEntry(plot[0][it1],"#epsilon_{f} CR_{1}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[2][it1],"#epsilon_{f} CR_{1} MCup, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[3][it1],"#epsilon_{f} CR_{1} MCdown, 1 jet, 0 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.035); - leg2->AddEntry(plot[0][it2],"#epsilon_{f} CR_{1}, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[2][it2],"#epsilon_{f} CR_{1} MCup, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[3][it2],"#epsilon_{f} CR_{1} down, #geq2 jets, 0 btag","ep"); - leg2->Draw(); - } - - // ============================= - if (choice==4) { // for comparison CR1 MCup/down >=1 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.035); - leg->AddEntry(plot[0][it3],"#epsilon_{f} CR_{1}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[2][it3],"#epsilon_{f} CR_{1} MCup, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[3][it3],"#epsilon_{f} CR_{1} MCdown, 1 jet, #geq1 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.035); - leg2->AddEntry(plot[0][it4],"#epsilon_{f} CR_{1}, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[2][it4],"#epsilon_{f} CR_{1} MCup, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[3][it4],"#epsilon_{f} CR_{1} down, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - // ============================= - if (choice==5) { // for comparison CR1 MC WZ 0 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.03); - leg->AddEntry(plot[0][it1],"#epsilon_{f} CR_{1} Sherpa, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[4][it1],"#epsilon_{f} CR_{1} Powheg, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[5][it1],"#epsilon_{f} CR_{1} MadGraph, 1 jet, 0 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.03); - leg2->AddEntry(plot[0][it2],"#epsilon_{f} CR_{1} Sherpa, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[4][it2],"#epsilon_{f} CR_{1} Powheg, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[5][it2],"#epsilon_{f} CR_{1} MadGraph, #geq2 jets, 0 btag","ep"); - leg2->Draw(); - } - - // ============================= - if (choice==6) { // for comparison CR1 MC WZ >=1 btag - float ymin = 0.65; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.03); - leg->AddEntry(plot[0][it3],"#epsilon_{f} CR_{1} Sherpa, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[4][it3],"#epsilon_{f} CR_{1} Powheg, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[5][it3],"#epsilon_{f} CR_{1} MadGraph, 1 jet, #geq1 btag","ep"); - leg->Draw(); - - float ymin2 = 0.65; - float ymax2 = 0.8; - leg2 = new TLegend(0.58,ymin2,0.68,ymax2); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.03); - leg2->AddEntry(plot[0][it4],"#epsilon_{f} CR_{1} Sherpa, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[4][it4],"#epsilon_{f} CR_{1} Powheg, #geq2 jets, #geq1 btag","ep"); - leg2->AddEntry(plot[5][it4],"#epsilon_{f} CR_{1} MadGraph, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecHighEtmiss.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecHighEtmiss.C deleted file mode 100644 index 068c1710385063917d254986f8f572b404711e3f..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecHighEtmiss.C +++ /dev/null @@ -1,281 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot real efficiencies obtained from high-MET/MTW -// method vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void RealEffElecHighEtmiss() -{ - // use this option to see results with different njet bins - //int choice = 0; - // use this option to see results with njet>=1 only - //int choice = 1; - - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int choice=0;choice<=1;choice++) - for (int var=0;var<=8;var++) - my.execute(var,choice); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var, int choice) - { - TGraph* plot0; - TH1F* plot[10]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f; - - // loop on input files - myname = "../data/R_el_Default_CRreal.root"; - std::cout << " myname = " << myname << std::endl; - f = TFile::Open(myname,"old"); - - // loop on jet bins - for (int ijet=0;ijet<=3;ijet++) { - // check which variable is read - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mtw"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (choice==0) { // with details on njet - if (var!=7) { // for all variables except njet - if (ijet==0) mynamehist += "_0b_1j"; - if (ijet==1) mynamehist += "_0b_ge2j"; - if (ijet==2) mynamehist += "_ge1b_1j"; - if (ijet==3) mynamehist += "_ge1b_ge2j"; - } else { // for njet - if (ijet==0) mynamehist += "_0b"; - if (ijet==1) mynamehist += "_0b_ge2j"; - if (ijet==2) mynamehist += "_ge1b"; - if (ijet==3) mynamehist += "_ge1b_ge2j"; - } - } else { // with ony njet>=1 - if (var!=7) { // for all variables except njet - if (ijet==0) mynamehist += ""; - if (ijet==1) mynamehist += ""; - if (ijet==2) mynamehist += ""; - if (ijet==3) mynamehist += ""; - } else { // for njet - if (ijet==0) mynamehist += ""; - if (ijet==1) mynamehist += ""; - if (ijet==2) mynamehist += ""; - if (ijet==3) mynamehist += ""; - } - } - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ijet] = (TH1F*)f->Get(mynamehist); - //std::cout << " plot = " << plot[ijet] << std::endl; - } - - // =============================================== - // define TAxis ranges - m_nlines = 2; - m_eff[0] = 0.75; - m_eff[1] = 1.1; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,choice,plot0,plot); - } - - // ============================================== - void plotGraph(int var,int choice,TGraph* plot0,TH1F* plot[10]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // plot the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("E_{T}(elec) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(elec)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (elec, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (elec,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(elec,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // plot the TGraph - if (choice==0) { // with details on njet - myplot(plot[0],1,20); - if (var!=7) myplot(plot[1],2,21); // case for njet - myplot(plot[2],3,24); - if (var!=7) myplot(plot[3],4,25); // case for njet - - if (var==8) { // case for nbjet (use same colors) - myplot(plot[0],1,20); - myplot(plot[1],3,24); - myplot(plot[2],1,20); - myplot(plot[3],3,24); - } - } else { // only njet>=1 - myplot(plot[0],1,20); - } - - - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,choice,plot); - c1->RedrawAxis(); - - // define the output name - TString suffix = ""; - if (var==0) suffix = "_vsEt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - if (choice==0) - c1->SaveAs("fig/effrealHighMET_elec"+suffix+format); - else - c1->SaveAs("fig/effrealHighMET_elec_ge1j"+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,int choice,TH1F* plot[10]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.1,ylabel-0.06,1,"e+jets, #sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - // ============================================================ - // set the TLegend (adapt to your own team) - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (choice==0) { // case with details on njet - if (var!=7 && var!=8) { - leg->AddEntry(plot[0],"#epsilon_{r} high E_{T}^{miss}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[1],"#epsilon_{r} high E_{T}^{miss}, #geq2 jets, 0 btag","ep"); - leg->AddEntry(plot[2],"#epsilon_{r} high E_{T}^{miss}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[3],"#epsilon_{r} high E_{T}^{miss}, #geq2 jets, #geq1 btag","ep"); - } else if (var==7) { // case for njet - leg->AddEntry(plot[0],"#epsilon_{r} high E_{T}^{miss}, 0 btag","ep"); - leg->AddEntry(plot[2],"#epsilon_{r} high E_{T}^{miss}, #geq1 btag","ep"); - } else if (var==8) { // case for nbjet - leg->AddEntry(plot[0],"#epsilon_{r} high E_{T}^{miss}, 1 jet","ep"); - leg->AddEntry(plot[1],"#epsilon_{r} high E_{T}^{miss}, #geq2 jets","ep"); - } - } else { - leg->AddEntry(plot[0],"#epsilon_{r} high E_{T}^{miss}, #geq1 jet","ep"); - } - leg->Draw(); - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecTP.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecTP.C deleted file mode 100644 index d4c3cad81daed13ea3357a30b1b91e97c71b06df..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecTP.C +++ /dev/null @@ -1,246 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot real efficiencies obtained from tag-and-probe -// method vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - - -void RealEffElecTP() -{ - // use this option to read tag-and-probe results on Z data - //int choice = 0; - // use this option to read tag-and-probe results on Z data + MC correction - //int choice = 1; - - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int choice=0;choice<=1;choice++) - for (int var=0;var<=8;var++) - my.execute(var,choice); - - return; -} - -class MyEff { - -public: - - MyEff(int choice){} - - // ======================================== - void execute(int var, int choice) - { - TGraph* plot0; - TH1F* plot[10]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f; - - // read input files - if (choice==0) - myname = "../data/R_el_Default_TPNoCorr.root"; - if (choice==1) - myname = "../data/R_el_Default.root"; - std::cout << " myname = " << myname << std::endl; - f = TFile::Open(myname,"old"); - - // loop on jet bins - for (int ijet=0;ijet<=1;ijet++) { - // check which variable is read - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mtw"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (var!=7) { // for all variables except njet - if (ijet==0) mynamehist += "_1j"; - if (ijet==1) mynamehist += "_ge2j"; - } else { // for njet - if (ijet==0) mynamehist += ""; - if (ijet==1) mynamehist += ""; - } - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ijet] = (TH1F*)f->Get(mynamehist); - //std::cout << " plot = " << plot[ijet] << std::endl; - } - - // =============================================== - // setup the TAxis ranges - m_nlines = 2; - m_eff[0] = 0.75; - m_eff[1] = 1.1; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,choice,plot0,plot); - } - - // ============================================== - void plotGraph(int var,int choice,TGraph* plot0,TH1F* plot[10]) - { - // define the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // set the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("E_{T}(elec) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(elec)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (elec, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (elec,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(elec,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // plot the TGraph - myplot(plot[0],1,20); // 1 jet - if (var!=7) { // for all variables except njet - myplot(plot[1],2,21); // >=2 jet - } - - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,choice,plot); - c1->RedrawAxis(); - - // define the name of the output - TString suffix = ""; - if (var==0) suffix = "_vsEt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - if (choice==0) c1->SaveAs("fig/effrealTPNoCorr_elec"+suffix+format); - if (choice==1) c1->SaveAs("fig/effrealTP_elec"+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,int choice,TH1F* plot[10]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel,ylabel-0.06,1,"e+jets, #sqrt{s}=13 TeV, 3.2 fb^{-1}",0.04); - - // ============================================================ - // set the TLegend (adapt to your own team) - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (choice==0) { - leg->AddEntry(plot[0],"#epsilon_{r} tag-and-probe (no MC Corr) 1 jet","ep"); - leg->AddEntry(plot[1],"#epsilon_{r} tag-and-probe (no MC corr) #geq2 jets","ep"); - } - if (choice==1) { - leg->AddEntry(plot[0],"#epsilon_{r} tag-and-probe 1 jet","ep"); - leg->AddEntry(plot[1],"#epsilon_{r} tag-and-probe #geq2 jets","ep"); - } - if (var!=7) leg->Draw(); - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecTPHighETmiss.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecTPHighETmiss.C deleted file mode 100644 index 34c8ded333f1bdf22dd5b95d24a9b393bad99c72..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffElecTPHighETmiss.C +++ /dev/null @@ -1,243 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot real efficiencies obtained both from -// tag-and-probe and high-MET/MTW methods vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void RealEffElecTPHighETmiss() -{ - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int var=0;var<=8;var++) - my.execute(var); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var) - { - TGraph* plot0; - TH1F* plot[2][10]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f[2]; - - // read the input files - // T&P - myname = "../data/R_el_Default.root"; - f[0] = TFile::Open(myname,"old"); - // High ETmiss - myname = "../data/R_el_Default_CRreal.root"; - f[1] = TFile::Open(myname,"old"); - - // loop on files - for (int ifile=0;ifile<=1;ifile++) { - // loop on jet bins - for (int ijet=0;ijet<=1;ijet++) { - // check which variables to use - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mtw"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (var!=7) { - if (ijet==0) mynamehist += "_1j"; - if (ifile==0) - if (ijet==1) mynamehist += "_ge2j"; - if (ifile==1) - if (ijet==1) mynamehist += ""; - } else { - if (ijet==0) mynamehist += ""; - if (ijet==1) mynamehist += ""; - } - - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ifile][ijet] = (TH1F*)f[ifile]->Get(mynamehist); - std::cout << " ifile = " << ifile << " ijet = " << ijet - << " plot = " << plot[ifile][ijet] << std::endl; - } - } - - // =============================================== - // set the TAxis ranges - m_nlines = 2; - m_eff[0] = 0.75; - m_eff[1] = 1.1; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,plot0,plot); - } - - // ============================================== - void plotGraph(int var,TGraph* plot0,TH1F* plot[2][10]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // set the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("E_{T}(elec) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(elec)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (elec, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (elec,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(elec,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // plot the TGraph - myplot(plot[0][0],1,20); - if (var!=7) { - myplot(plot[0][1],2,21); - } - myplot(plot[1][0],3,24); - - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,plot); - c1->RedrawAxis(); - - // set the output names - TString suffix = ""; - if (var==0) suffix = "_vsEt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - - c1->SaveAs("fig/effrealTPHighETmiss_elec"+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,TH1F* plot[2][10]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.1,ylabel-0.06,1,"e+jets, #sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - // ============================================================ - // set the TLegend (adapt to your own team) - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - leg->AddEntry(plot[0][0],"#epsilon_{r} tag-and-probe 1 jet","ep"); - leg->AddEntry(plot[0][1],"#epsilon_{r} tag-and-probe #geq2 jets","ep"); - leg->AddEntry(plot[1][0],"#epsilon_{r} #epsilon_{r} high E_{T}^{miss} #geq1 jet","ep"); - if (var!=7) leg->Draw(); - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonHighMTW.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonHighMTW.C deleted file mode 100644 index 7c566e79a88ffea1542d74b53faf1c8f4afa20de..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonHighMTW.C +++ /dev/null @@ -1,386 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot real efficiencies obtained from high-MET/MTW -// method vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void RealEffMuonHighMTW() -{ - // use this option to see results with different njet bins - //int choice = 0; - // use this option to see results with njet>=1 only - //int choice = 1; - - // choose the trigger - //int trigger = 0; // mu20i - //int trigger = 1; // mu20 - //int trigger = 2; // mu50 - - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int choice=0;choice<=1;choice++) - for (int trigger=0;trigger<=2;trigger++) - for (int var=0;var<=8;var++) - my.execute(var,choice,trigger); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var, int choice,int trigger) - { - TGraph* plot0; - TH1F* plot[20]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f; - - // read input files - myname = "../data/R_mu_Default_CRreal.root"; - std::cout << " myname = " << myname << std::endl; - f = TFile::Open(myname,"old"); - - // loop on jet bins - for (int ijet=0;ijet<=11;ijet++) { - // check which variables to use - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mwt"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (choice==0) { // with details on njet - if (var<7) { - // mu20i - if (ijet==0) mynamehist += "_0b_1j_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_1j_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_1j_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_1j_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_1j_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_1j_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } else if (var==7) { // njet - // mu20i - if (ijet==0) mynamehist += "_0b_mu20i"; - if (ijet==1) mynamehist += "_0b_mu20i"; - if (ijet==2) mynamehist += "_ge1b_mu20i"; - if (ijet==3) mynamehist += "_ge1b_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_mu20"; - if (ijet==5) mynamehist += "_0b_mu20"; - if (ijet==6) mynamehist += "_ge1b_mu20"; - if (ijet==7) mynamehist += "_ge1b_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_mu50"; - if (ijet==9) mynamehist += "_0b_mu50"; - if (ijet==10) mynamehist += "_ge1b_mu50"; - if (ijet==11) mynamehist += "_ge1b_mu50"; - } else if (var==8) { // nbjet - // mu20i - if (ijet==0) mynamehist += "_0b_1j_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_1j_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_1j_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_1j_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_1j_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_1j_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } - } - // case for njet>=1 - if (choice==1) { // with details on njet - // mu20i - if (ijet==0) mynamehist += "_0b_mu20i"; - if (ijet==1) mynamehist += "_0b_mu20i"; - if (ijet==2) mynamehist += "_ge1b_mu20i"; - if (ijet==3) mynamehist += "_ge1b_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_mu20"; - if (ijet==5) mynamehist += "_0b_mu20"; - if (ijet==6) mynamehist += "_ge1b_mu20"; - if (ijet==7) mynamehist += "_ge1b_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_mu50"; - if (ijet==9) mynamehist += "_0b_mu50"; - if (ijet==10) mynamehist += "_ge1b_mu50"; - if (ijet==11) mynamehist += "_ge1b_mu50"; - } - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ijet] = (TH1F*)f->Get(mynamehist); - std::cout << " ijet = " << ijet - << " plot = " << plot[ijet] << std::endl; - } - - // =============================================== - // set the TAxis ranges - m_nlines = 2; - m_eff[0] = 0.75; - m_eff[1] = 1.3; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,choice,trigger,plot0,plot); - } - - // ============================================== - void plotGraph(int var,int choice,int trigger,TGraph* plot0,TH1F* plot[20]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // plot the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("p_{T}(#mu) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(#mu)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (#mu, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (#mu,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(#mu,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // choose the trigger - int it1 = -1; int it2 = -1; int it3 = -1; int it4 = -1; - if (trigger==0) {it1 = 0; it2 = 1; it3 = 2; it4 = 3;} // mu20i - if (trigger==1) {it1 = 4; it2 = 5; it3 = 6; it4 = 7;} // mu20 - if (trigger==2) {it1 = 8; it2 = 9; it3 = 10; it4 = 11;} // mu50 - - // plot the TGraph - if (choice==0) { // for different jet - myplot(plot[it1],1,20); - if (var!=7) myplot(plot[it2],2,21); // case for njet - myplot(plot[it3],3,24); - if (var!=7) myplot(plot[it4],4,25); // case for njet - - if (var==8) { // case for nbjet (use same colors) - myplot(plot[it1],1,20); - myplot(plot[it2],3,24); - myplot(plot[it3],1,20); - myplot(plot[it4],3,24); - } - } - if (choice==1) { // for njet>=1 - myplot(plot[it1],1,20); - myplot(plot[it3],3,24); - - if (var==8) { // case for nbjet (use same colors) - myplot(plot[it1],1,20); - myplot(plot[it3],1,20); - } - } - - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,choice,trigger,plot); - c1->RedrawAxis(); - - // set the output names - TString suffix = ""; - if (var==0) suffix = "_vsPt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - - TString st = ""; - if (trigger==0) st = "_mu20i"; - if (trigger==1) st = "_mu20"; - if (trigger==2) st = "_mu50"; - - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - - if (choice==0) - c1->SaveAs("fig/effrealHighMTW_muon"+st+suffix+format); - if (choice==1) - c1->SaveAs("fig/effrealHighMTW_muon_ge1j"+st+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,int choice,int trigger,TH1F* plot[20]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.2,ylabel-0.06,1,"#sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - if (trigger==0) myText(xlabel,ylabel-0.06,1,"#mu+jets mu20i",0.04); - if (trigger==1) myText(xlabel,ylabel-0.06,1,"#mu+jets mu20",0.04); - if (trigger==2) myText(xlabel,ylabel-0.06,1,"#mu+jets mu50",0.04); - - int it1 = -1; int it2 = -1; int it3 = -1; int it4 = -1; - if (trigger==0) {it1 = 0; it2 = 1; it3 = 2; it4 = 3;} // mu20i - if (trigger==1) {it1 = 4; it2 = 5; it3 = 6; it4 = 7;} // mu20 - if (trigger==2) {it1 = 8; it2 = 9; it3 = 10; it4 = 11;} // mu50 - - // ============================================================ - // set the TLegend (adapt to your own team) - float ymin = 0.55; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - // ============================================================ - // set the TLegend (adapt to your own team) - - if (choice==0) { // with details on njet - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var!=7 && var!=8) { - leg->AddEntry(plot[it1],"#epsilon_{r} High m_{T}^{W}, 1 jet, 0 btag","ep"); - leg->AddEntry(plot[it2],"#epsilon_{r} High m_{T}^{W}, #geq2 jets, 0 btag","ep"); - leg->AddEntry(plot[it3],"#epsilon_{r} High m_{T}^{W}, 1 jet, #geq1 btag","ep"); - leg->AddEntry(plot[it4],"#epsilon_{r} High m_{T}^{W}, #geq2 jets, #geq1 btag","ep"); - } else if (var==7) { // case for njet - leg->AddEntry(plot[it1],"#epsilon_{r} High m_{T}^{W}, 0 btag","ep"); - leg->AddEntry(plot[it3],"#epsilon_{r} High m_{T}^{W}, #geq1 btag","ep"); - } else if (var==8) { // case for nbjet - leg->AddEntry(plot[it1],"#epsilon_{r} High m_{T}^{W}, 1 jet","ep"); - leg->AddEntry(plot[it2],"#epsilon_{r} High m_{T}^{W}, #geq2 jets","ep"); - } - leg->Draw(); - } - - if (choice==1) { // with njet>=1 - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var!=8) { - leg->AddEntry(plot[it1],"#epsilon_{r} High m_{T}^{W}, #geq 1 jet, 0 btag","ep"); - leg->AddEntry(plot[it3],"#epsilon_{r} High m_{T}^{W}, #geq 1 jet, #geq1 btag","ep"); - } - if (var==8) // for nbjet - leg->AddEntry(plot[it1],"#epsilon_{r} High m_{T}^{W}, #geq 1 jet","ep"); - leg->Draw(); - } - - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonTP.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonTP.C deleted file mode 100644 index 0f0a4a6e0c61c09a00a001c4e7bb82e49b252959..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonTP.C +++ /dev/null @@ -1,272 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot real efficiencies obtained from tag-and-probe -// method vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void RealEffMuonTP() -{ - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int var=0;var<=8;var++) - my.execute(var); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var) - { - TGraph* plot0; - TH1F* plot[10]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f; - - // read input files - myname = "../data/R_mu_Default.root"; - std::cout << " myname = " << myname << std::endl; - f = TFile::Open(myname,"old"); - - // loop on all jet possibilities - for (int ijet=0;ijet<=5;ijet++) { - // check which variable is read - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mwt"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - if (var<7) { // for all variables except njet and nbjet - if (ijet==0) mynamehist += "_1j_mu20i"; - if (ijet==1) mynamehist += "_ge2j_mu20i"; - if (ijet==2) mynamehist += "_1j_mu20"; - if (ijet==3) mynamehist += "_ge2j_mu20"; - if (ijet==4) mynamehist += "_1j_mu50"; - if (ijet==5) mynamehist += "_ge2j_mu50"; - } else if (var==7) { // njet - if (ijet==0) mynamehist += "_mu20i"; - if (ijet==1) mynamehist += "_ge2j_mu20i"; - if (ijet==2) mynamehist += "_mu20"; - if (ijet==3) mynamehist += "_ge2j_mu20"; - if (ijet==4) mynamehist += "_mu50"; - if (ijet==5) mynamehist += "_ge2j_mu50"; - } else if (var==8) { // nbjet - if (ijet==0) mynamehist += "_mu20i"; - if (ijet==1) mynamehist += "_mu20i"; - if (ijet==2) mynamehist += "_mu20"; - if (ijet==3) mynamehist += "_mu20"; - if (ijet==4) mynamehist += "_mu50"; - if (ijet==5) mynamehist += "_mu50"; - } - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ijet] = (TH1F*)f->Get(mynamehist); - //std::cout << " plot = " << plot[ijet] << std::endl; - } - // =============================================== - // setup the TAxis ranges - m_nlines = 2; - m_eff[0] = 0.85; - m_eff[1] = 1.2; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,plot0,plot); - } - - // ============================================== - void plotGraph(int var,TGraph* plot0,TH1F* plot[10]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // plot the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("p_{T}(#mu) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(#mu)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (#mu, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (#mu,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(#mu,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // plot the TGraph - myplot(plot[0],1,20); - if (var<7) { // for all variables except njet and nbjet - myplot(plot[0],1,20); // mu20i 1 jet - myplot(plot[1],1,24); // >=2 jet - myplot(plot[2],2,21); // mu20 1 jet - myplot(plot[3],2,25); // >=2 jet - myplot(plot[4],4,22); // mu50 1 jet - myplot(plot[5],4,26); // >=2 jet - } - if (var==7) { // njet - myplot(plot[0],1,20); - myplot(plot[2],2,24); - myplot(plot[4],3,25); - } - if (var==8) { // nbjet - myplot(plot[0],1,20); - myplot(plot[2],2,24); - myplot(plot[4],3,25); - } - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - - // plot the TLegend - plotLegend(var,plot); - c1->RedrawAxis(); - - // define the output name - TString suffix = ""; - if (var==0) suffix = "_vsPt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - c1->SaveAs("fig/effrealTP_muon"+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,TH1F* plot[10]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.1,ylabel-0.06,1,"#mu+jets, #sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - // ============================================================ - // set the TLegend (adapt to your own team) - float ymin = 0.55; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var<7) { - leg->AddEntry(plot[0],"#epsilon_{r} tag-and-probe 1 jet mu20i","ep"); - leg->AddEntry(plot[1],"#epsilon_{r} tag-and-probe #geq2 jets mu20i","ep"); - leg->AddEntry(plot[2],"#epsilon_{r} tag-and-probe 1 jet mu20","ep"); - leg->AddEntry(plot[3],"#epsilon_{r} tag-and-probe #geq2 jets mu20","ep"); - leg->AddEntry(plot[4],"#epsilon_{r} tag-and-probe 1 jet mu50","ep"); - leg->AddEntry(plot[5],"#epsilon_{r} tag-and-probe #geq2 jets mu50","ep"); - } else if (var==7) { // njet - leg->AddEntry(plot[0],"#epsilon_{r} tag-and-probe mu20i","ep"); - leg->AddEntry(plot[2],"#epsilon_{r} tag-and-probe mu20","ep"); - leg->AddEntry(plot[4],"#epsilon_{r} tag-and-probe mu50","ep"); - } else if (var==8) { // njet - leg->AddEntry(plot[0],"#epsilon_{r} tag-and-probe mu20i","ep"); - leg->AddEntry(plot[2],"#epsilon_{r} tag-and-probe mu20","ep"); - leg->AddEntry(plot[4],"#epsilon_{r} tag-and-probe mu50","ep"); - } - leg->Draw(); - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonTPHighMTW.C b/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonTPHighMTW.C deleted file mode 100644 index a3afcdbb8a601cb46d32a22388281f99e131faf5..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopFakes/macros/RealEffMuonTPHighMTW.C +++ /dev/null @@ -1,506 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TGraph.h" -#include "TString.h" -#include "AtlasUtils.C" -#include "AtlasStyle.C" -#include "AtlasLabels.C" -#include <vector> -#include <string> -#include <cmath> - -///////////////////////////////////////////////////////////////////// -// CREATED : 01/02/2016 -// AUTHOR : Frederic Derue (LPNHE Paris) -// PURPOSE : ROOT macro to plot real efficiencies obtained both from -// tag-and-probe and high-MET/MTW methods vs different variables -// It reads as input the default efficiencies of TopFakes package -// MODIFICATION : -// -///////////////////////////////////////////////////////////////////// - -void RealEffMuonTPHighMTW() -{ - // use this option to see results with different njet bins - //int choice = 0; - // use this.q - // option to see results with njet>=1 only - //int choice = 1; - - // choose the trigger - //int trigger = 0; // mu20i - //int trigger = 1; // mu20 - //int trigger = 2; // mu50 - - // set the variable one want to compare - //int var = 0; // pt - //int var = 1; // eta - //int var = 2; // dR - //int var = 3; // jetpt - //int var = 4; // dphi - //int var = 5; // met - //int var = 6; // mtw - //int var = 7; // njet - //int var = 8; // nbjet - - SetAtlasStyle(); - gROOT->Reset(); - gROOT->SetStyle("ATLAS"); - gROOT->ForceStyle(); - gStyle->SetOptStat(0); - gStyle->SetOptTitle(0); - gStyle->SetOptTitle(0); - - // define the class - MyEff my(1); - // uncomment if you want to do all plots in one go - for (int choice=0;choice<=1;choice++) - for (int trigger=0;trigger<=2;trigger++) - for (int var=0;var<=8;var++) - my.execute(var,choice,trigger); - - return; -} - -class MyEff { - -public: - - MyEff(int choice) {} - - // ======================================== - void execute(int var,int choice,int trigger) - { - TGraph* plot0; - TH1F* plot[2][20]; - TString myname=""; - TString name[100]; - TString mynamehist = ""; - TFile *f[2]; - - // read input files - // T&P - myname = "../data/R_mu_Default.root"; - f[0] = TFile::Open(myname,"old"); - // High ETmiss - myname = "../data/R_mu_Default_CRreal.root"; - f[1] = TFile::Open(myname,"old"); - - // loop on all files - for (int ifile=0;ifile<=1;ifile++) { - // loop on jet bins - for (int ijet=0;ijet<=11;ijet++) { - // check which variable to be used - if (var==0) mynamehist = "eff_pt"; - if (var==1) mynamehist = "eff_eta"; - if (var==2) mynamehist = "eff_dR"; - if (var==3) mynamehist = "eff_jetpt"; - if (var==4) mynamehist = "eff_dPhi"; - if (var==5) mynamehist = "eff_met"; - if (var==6) mynamehist = "eff_mwt"; - if (var==7) mynamehist = "eff_njet"; - if (var==8) mynamehist = "eff_nbtag"; - - // case for the tag-and-probe - if (ifile==0) { - if (choice==0) { // with details on njet - if (var<7) { - // mu20i - if (ijet==0) mynamehist += "_1j_mu20i"; - if (ijet==1) mynamehist += "_ge2j_mu20i"; - if (ijet==2) mynamehist += "_1j_mu20i"; - if (ijet==3) mynamehist += "_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_1j_mu20"; - if (ijet==5) mynamehist += "_ge2j_mu20"; - if (ijet==6) mynamehist += "_1j_mu20"; - if (ijet==7) mynamehist += "_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_1j_mu50"; - if (ijet==9) mynamehist += "_ge2j_mu50"; - if (ijet==10) mynamehist += "_1j_mu50"; - if (ijet==11) mynamehist += "_ge2j_mu50"; - } else if (var==7) { // njet - // mu20i - if (ijet==0) mynamehist += "_mu20i"; - if (ijet==1) mynamehist += "_mu20i"; - if (ijet==2) mynamehist += "_mu20i"; - if (ijet==3) mynamehist += "_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_mu20"; - if (ijet==5) mynamehist += "_mu20"; - if (ijet==6) mynamehist += "_mu20"; - if (ijet==7) mynamehist += "_mu20"; - // mu50 - if (ijet==8) mynamehist += "_mu50"; - if (ijet==9) mynamehist += "_mu50"; - if (ijet==10) mynamehist += "_mu50"; - if (ijet==11) mynamehist += "_mu50"; - } else if (var==8) { // nbjet - // mu20i - if (ijet==0) mynamehist += "_1j_mu20i"; - if (ijet==1) mynamehist += "_ge2j_mu20i"; - if (ijet==2) mynamehist += "_1j_mu20i"; - if (ijet==3) mynamehist += "_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_1j_mu20"; - if (ijet==5) mynamehist += "_ge2j_mu20"; - if (ijet==6) mynamehist += "_1j_mu20"; - if (ijet==7) mynamehist += "_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_1j_mu50"; - if (ijet==9) mynamehist += "_ge2j_mu50"; - if (ijet==10) mynamehist += "_1j_mu50"; - if (ijet==11) mynamehist += "_ge2j_mu50"; - } - } - // case for njet>=1 - if (choice==1) { // with details on njet - // mu20i - if (ijet==0) mynamehist += "_mu20i"; - if (ijet==1) mynamehist += "_mu20i"; - if (ijet==2) mynamehist += "_mu20i"; - if (ijet==3) mynamehist += "_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_mu20"; - if (ijet==5) mynamehist += "_mu20"; - if (ijet==6) mynamehist += "_mu20"; - if (ijet==7) mynamehist += "_mu20"; - // mu50 - if (ijet==8) mynamehist += "_mu50"; - if (ijet==9) mynamehist += "_mu50"; - if (ijet==10) mynamehist += "_mu50"; - if (ijet==11) mynamehist += "_mu50"; - } - } - - // case for the HighMTW - if (ifile==1) { - if (choice==0) { // with details on njet - if (var<7) { - // mu20i - if (ijet==0) mynamehist += "_0b_1j_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_1j_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_1j_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_1j_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_1j_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_1j_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } else if (var==7) { // njet - // mu20i - if (ijet==0) mynamehist += "_0b_mu20i"; - if (ijet==1) mynamehist += "_0b_mu20i"; - if (ijet==2) mynamehist += "_ge1b_mu20i"; - if (ijet==3) mynamehist += "_ge1b_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_mu20"; - if (ijet==5) mynamehist += "_0b_mu20"; - if (ijet==6) mynamehist += "_ge1b_mu20"; - if (ijet==7) mynamehist += "_ge1b_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_mu50"; - if (ijet==9) mynamehist += "_0b_mu50"; - if (ijet==10) mynamehist += "_ge1b_mu50"; - if (ijet==11) mynamehist += "_ge1b_mu50"; - } else if (var==8) { // nbjet - // mu20i - if (ijet==0) mynamehist += "_0b_1j_mu20i"; - if (ijet==1) mynamehist += "_0b_ge2j_mu20i"; - if (ijet==2) mynamehist += "_ge1b_1j_mu20i"; - if (ijet==3) mynamehist += "_ge1b_ge2j_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_0b_1j_mu20"; - if (ijet==5) mynamehist += "_0b_ge2j_mu20"; - if (ijet==6) mynamehist += "_ge1b_1j_mu20"; - if (ijet==7) mynamehist += "_ge1b_ge2j_mu20"; - // mu50 - if (ijet==8) mynamehist += "_0b_1j_mu50"; - if (ijet==9) mynamehist += "_0b_ge2j_mu50"; - if (ijet==10) mynamehist += "_ge1b_1j_mu50"; - if (ijet==11) mynamehist += "_ge1b_ge2j_mu50"; - } - } - // case for njet>=1 - if (choice==1) { // with details on njet - // mu20i - if (ijet==0) mynamehist += "_mu20i"; - if (ijet==1) mynamehist += "_mu20i"; - if (ijet==2) mynamehist += "_mu20i"; - if (ijet==3) mynamehist += "_mu20i"; - // mu20 - if (ijet==4) mynamehist += "_mu20"; - if (ijet==5) mynamehist += "_mu20"; - if (ijet==6) mynamehist += "_mu20"; - if (ijet==7) mynamehist += "_mu20"; - // mu50 - if (ijet==8) mynamehist += "_mu50"; - if (ijet==9) mynamehist += "_mu50"; - if (ijet==10) mynamehist += "_mu50"; - if (ijet==11) mynamehist += "_mu50"; - } - } - - std::cout << " ijet = " << ijet - << " namehist = " << mynamehist << std::endl; - plot[ifile][ijet] = (TH1F*)f[ifile]->Get(mynamehist); - std::cout << " ijet = " << ijet - << " plot = " << plot[ifile][ijet] << std::endl; - } - } - - // =============================================== - // set the TAxis range - m_nlines = 2; - m_eff[0] = 0.85; - m_eff[1] = 1.2; - if (var==0) {m_var[0] = 25.; m_var[1] = 150.;} // pt - if (var==1) {m_var[0] = 0.; m_var[1] = 2.3;} // eta - if (var==2) {m_var[0] = 0.; m_var[1] = 6.;} // dR - if (var==3) {m_var[0] = 25.; m_var[1] = 500.;} // jetpt - if (var==4) {m_var[0] = 0.; m_var[1] = 3.2;} // dphi - if (var==5) {m_var[0] = 0.; m_var[1] = 1000.;} // met - if (var==6) {m_var[0] = 0.; m_var[1] = 1000.;} // mtw - if (var==7) {m_var[0] = 0.; m_var[1] = 6.;} // njet - if (var==8) {m_var[0] = 0.; m_var[1] = 3.;} // nbjet - plot0 = new TGraph(m_nlines,m_var,m_eff); - - // plot the TGraph - plotGraph(var,choice,trigger,plot0,plot); - } - - // ============================================== - void plotGraph(int var,int choice,int trigger, - TGraph* plot0,TH1F* plot[2][20]) - { - // set the TCanvas - c1 = new TCanvas("c1"," ",0.,0.,800,600); - c1->SetFillColor(42); - c1->SetFillColor(10); - - // set the TAxis - plot0->SetFillColor(19); - plot0->SetLineColor(0); - plot0->SetLineWidth(4); - plot0->SetMarkerColor(0); - plot0->SetMarkerStyle(20); - //plot0->GetXaxis()->CenterLabels(true); - if (var==0) plot0->GetXaxis()->SetTitle("p_{T}(#mu) [GeV]"); - if (var==1) plot0->GetXaxis()->SetTitle("|#eta(#mu)|"); - if (var==2) plot0->GetXaxis()->SetTitle("#DeltaR (#mu, nearest jet)"); - if (var==3) plot0->GetXaxis()->SetTitle("p_{T}(leading jet) [GeV]"); - if (var==4) plot0->GetXaxis()->SetTitle("#Delta#phi (#mu,E_{T}^{miss})"); - if (var==5) plot0->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]"); - if (var==6) plot0->GetXaxis()->SetTitle("m_{T}(#mu,E_{T}^{miss}) [GeV]"); - if (var==7) plot0->GetXaxis()->SetTitle("n_{jet}"); - if (var==8) plot0->GetXaxis()->SetTitle("n_{b-jet}"); - plot0->GetYaxis()->SetTitle("Efficiency"); - plot0->Draw("AP"); - - // ================================================================ - // choose the trigger - int it1 = -1; int it2 = -1; int it3 = -1; int it4 = -1; - if (trigger==0) {it1 = 0; it2 = 1; it3 = 2; it4 = 3;} // mu20i - if (trigger==1) {it1 = 4; it2 = 5; it3 = 6; it4 = 7;} // mu20 - if (trigger==2) {it1 = 8; it2 = 9; it3 = 10; it4 = 11;} // mu50 - - // plot the TGraph - if (choice==0) { // for different jet - // T&P - myplot(plot[0][it1],1,20); - myplot(plot[0][it2],1,24); - // High MTWW - myplot(plot[1][it1],1,21); - if (var!=7) myplot(plot[1][it2],2,22); // case for njet - myplot(plot[1][it3],3,23); - if (var!=7) myplot(plot[1][it4],4,29); // case for njet - - if (var==8) { // case for nbjet (use same colors) - myplot(plot[0][it1],1,20); - myplot(plot[0][it2],1,24); - - myplot(plot[1][it1],1,21); - myplot(plot[1][it2],3,22); - myplot(plot[1][it3],1,23); - myplot(plot[1][it4],3,29); - } - } - if (choice==1) { // for njet>=1 - if (var!=8) { - myplot(plot[0][it1],1,20); // T&P - myplot(plot[1][it1],2,21); // high MTW - } - if (var==8) { // case for nbjet (use same colors) - myplot(plot[0][it1],1,20); - myplot(plot[1][it1],2,21); - } - } - - c1->Update(); - c1->GetFrame()->SetFillColor(0); - c1->GetFrame()->SetBorderSize(0); - c1->Modified(); - // plot the TLegend - plotLegend(var,choice,trigger,plot); - c1->RedrawAxis(); - - // set the output filename - TString suffix = ""; - if (var==0) suffix = "_vsPt"; - if (var==1) suffix = "_vsEta"; - if (var==2) suffix = "_vsdR"; - if (var==3) suffix = "_vsPtLeadingJet"; - if (var==4) suffix = "_vsdPhi"; - if (var==5) suffix = "_vsMET"; - if (var==6) suffix = "_vsMTW"; - if (var==7) suffix = "_vsnjet"; - if (var==8) suffix = "_vsnbjet"; - - TString st = ""; - if (trigger==0) st = "_mu20i"; - if (trigger==1) st = "_mu20"; - if (trigger==2) st = "_mu50"; - - TString format = ""; - for (int i=0;i<3;i++) { - if (i==0) format = ".eps"; - if (i==1) format = ".pdf"; - if (i==2) format = ".png"; - - if (choice==0) - c1->SaveAs("fig/effrealTPHighMTW_muon"+st+suffix+format); - if (choice==1) - c1->SaveAs("fig/effrealTPHighMTW_muon_ge1j"+st+suffix+format); - } - } - - // ============================================== - void myplot(TH1F* plot,int mkcolor, int mktype, float size=1.5) - { - plot->SetFillColor(19); - plot->SetLineColor(1); - plot->SetLineWidth(1.5); - plot->SetMarkerColor(mkcolor); - plot->SetMarkerStyle(mktype); - //plot->SetTitle("rel 16"); - plot->SetMarkerSize(size); - plot->Draw("P sames"); - } - - // ============================================== - void plotLegend(int var,int choice,int trigger,TH1F* plot[2][20]) - { - float xlabel = 0.2; - float ylabel = 0.88; - // set the ATLAS label - ATLASLabel(xlabel,ylabel,"Work in Progress"); - // set energy and luminosity (adapt to your own case) - myText(xlabel+0.2,ylabel-0.06,1,"#sqrt{s}=13 TeV, 3.2 fb^{-1}",0.045); - - if (choice==0) myText(xlabel,ylabel-0.06,1,"#mu+jets mu20i",0.04); - if (choice==1) myText(xlabel,ylabel-0.06,1,"#mu+jets mu20",0.04); - if (choice==2) myText(xlabel,ylabel-0.06,1,"#mu+jets mu50",0.04); - - int it1 = -1; int it2 = -1; int it3 = -1; int it4 = -1; - if (trigger==0) {it1 = 0; it2 = 1; it3 = 2; it4 = 3;} // mu20i - if (trigger==1) {it1 = 4; it2 = 5; it3 = 6; it4 = 7;} // mu20 - if (trigger==2) {it1 = 8; it2 = 9; it3 = 10; it4 = 11;} // mu50 - - // ============================= - if (choice==0) { // with details on njet - if (var<7) { - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.035); - leg->AddEntry(plot[0][it1],"#epsilon_{r} tag-and-probe, 1 jet","ep"); - leg->AddEntry(plot[0][it2],"#epsilon_{r} tag-and-probe, #geq2 jets","ep"); - leg->Draw(); - - leg2 = new TLegend(0.5,ymin,0.8,ymax); - leg2->SetFillColor(0); - leg2->SetFillStyle(0); - leg2->SetBorderSize(0); - leg2->SetTextSize(0.035); - leg2->AddEntry(plot[1][it1],"#epsilon_{r} High m_{T}^{W}, 1 jet, 0 btag","ep"); - leg2->AddEntry(plot[1][it2],"#epsilon_{r} High m_{T}^{W}, #geq2 jets, 0 btag","ep"); - leg2->AddEntry(plot[1][it3],"#epsilon_{r} High m_{T}^{W}, 1 jet, #geq1 btag","ep"); - leg2->AddEntry(plot[1][it4],"#epsilon_{r} High m_{T}^{W}, #geq2 jets, #geq1 btag","ep"); - leg2->Draw(); - } - } - - // ============================================================ - // set the TLegend (adapt to your own team) - float ymin = 0.55; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - // ============================================================ - // set the TLegend (adapt to your own team) - - if (choice==0) { // with details on njet - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var==7) { // case for njet - leg->AddEntry(plot[0][it1],"#epsilon_{r} tag-and-probe","ep"); - leg->AddEntry(plot[1][it1],"#epsilon_{r} High m_{T}^{W}, 0 btag","ep"); - leg->AddEntry(plot[1][it3],"#epsilon_{r} High m_{T}^{W}, #geq1 btag","ep"); - } else if (var==8) { // case for nbjet - leg->AddEntry(plot[0][it1],"#epsilon_{r} tag-and-probe, 1 jet","ep"); - leg->AddEntry(plot[0][it2],"#epsilon_{r} tag-and-probe, #geq2 jets","ep"); - leg->AddEntry(plot[1][it1],"#epsilon_{r} High m_{T}^{W}, 1 jet","ep"); - leg->AddEntry(plot[1][it2],"#epsilon_{r} High m_{T}^{W}, #geq2 jets","ep"); - } - leg->Draw(); - } - - if (choice==1) { // with njet>=1 - float ymin = 0.6; - float ymax = 0.8; - leg = new TLegend(0.2,ymin,0.3,ymax); - leg->SetFillColor(0); - leg->SetFillStyle(0); - leg->SetBorderSize(0); - leg->SetTextSize(0.04); - if (var!=8) { - leg->AddEntry(plot[0][it1],"#epsilon_{r} tag-and-probe, #geq 1 jet","ep"); - leg->AddEntry(plot[1][it1],"#epsilon_{r} High m_{T}^{W}, #geq 1 jet","ep"); - } - if (var==8) { // for nbjet - leg->AddEntry(plot[0][it1],"#epsilon_{r} tag-and-probe, #geq 1 jet","ep"); - leg->AddEntry(plot[1][it1],"#epsilon_{r} High m_{T}^{W}, #geq 1 jet","ep"); - } - leg->Draw(); - } - - } - -private: - - Float_t m_var[300]; - Float_t m_errvar[300]; - Float_t m_eff[300]; - Float_t m_erreff[300]; - - Int_t m_nlines; -}; diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/CMakeLists.txt deleted file mode 100644 index 6c3b0ad7cc72ced4707696435bf6ca2a4339d1a2..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/CMakeLists.txt +++ /dev/null @@ -1,38 +0,0 @@ -# Auto-generated on: 2017-03-08 14:47:37.415174 - -# Declare the name of this package: -atlas_subdir( TopHLUpgrade None ) - -# This package depends on other packages: -atlas_depends_on_subdirs( PUBLIC - TopConfiguration - TopEvent - xAODTruth - xAODJet - xAODMissingET - TopParticleLevel - UpgradePerformanceFunctions ) - -# This package uses ROOT: -find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) - -# Generate a CINT dictionary source file: -atlas_add_root_dictionary( TopHLUpgrade _cintDictSource - ROOT_HEADERS Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) - -# Build a library that other components can link against: -atlas_add_library( TopHLUpgrade Root/*.cxx Root/*.h Root/*.icc - TopHLUpgrade/*.h TopHLUpgrade/*.icc TopHLUpgrade/*/*.h - TopHLUpgrade/*/*.icc ${_cintDictSource} - PUBLIC_HEADERS TopHLUpgrade - LINK_LIBRARIES TopConfiguration - TopEvent - xAODTruth - xAODJet - xAODMissingET - TopParticleLevel - UpgradePerformanceFunctions - ${ROOT_LIBRARIES} - INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/LinkDef.h deleted file mode 100644 index f9fa452558b6689ef1035f603096f64ab7ab8510..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/LinkDef.h +++ /dev/null @@ -1,12 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifdef __CINT__ - -#pragma link off all globals; -#pragma link off all classes; -#pragma link off all functions; -#pragma link C++ nestedclass; - -#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradeLeptonObjectSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradeLeptonObjectSelector.cxx deleted file mode 100644 index 3775b5e013f9c5fa62b062ea603425d64b3bee3b..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradeLeptonObjectSelector.cxx +++ /dev/null @@ -1,39 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: UpgradeLeptonObjectSelector.cxx -// Description: -// Author: Mark Owen -// Created: Sun Feb 22 15:18:45 2015 - -#include "TopHLUpgrade/UpgradeLeptonObjectSelector.h" - -using namespace top; - -UpgradeLeptonObjectSelector::UpgradeLeptonObjectSelector( Options opt /* = Options() */ ) - : m_opt( opt ){ /* Deliberately Empty */ } - -/* virtual */ bool -UpgradeLeptonObjectSelector::apply( const xAOD::TruthParticle & truthParticle ) { - - // -------------------------------------------------- - // Always require 'reco' to pass - if( truthParticle.auxdata<int>("passReco") !=1 ) { return false; } - - // -------------------------------------------------- - // Apply kinematic cut on the (smeared) pT: - // must exceed 25 GeV - if ( truthParticle.pt() < m_opt.pt_min ){ return false; } - - // -------------------------------------------------- - // Apply kinematic cut on the eta: - // must be less than or equal to 2.5 - if ( std::abs( truthParticle.eta() ) > m_opt.eta_max ){ return false; } - - - // -------------------------------------------------- - // Everything that reaches this point has passed the selection - return true; - -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradeObjectLoader.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradeObjectLoader.cxx deleted file mode 100644 index 1e5caa1de8d40d1397a03d9413faacdab8f5f87b..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradeObjectLoader.cxx +++ /dev/null @@ -1,295 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TopHLUpgrade/UpgradeObjectLoader.h" - -#include "TopConfiguration/TopConfig.h" -#include "TopEvent/EventTools.h" -#include "TopHLUpgrade/UpgradeLeptonObjectSelector.h" - -#include "xAODTruth/TruthParticleContainer.h" -#include "xAODTruth/TruthParticleAuxContainer.h" -#include "xAODMissingET/MissingETContainer.h" -#include "xAODJet/JetContainer.h" -#include "xAODJet/JetAuxContainer.h" -#include "xAODCore/ShallowCopy.h" - -#include <algorithm> - -using namespace top; - -bool ptSort(const xAOD::IParticle* p1, const xAOD::IParticle* p2) { - return p1->pt() > p2->pt(); -} - -UpgradeObjectLoader::UpgradeObjectLoader( const std::shared_ptr<top::TopConfig> & cfg ) : - asg::AsgTool( "UpgradeObjectLoader" ), - m_config(cfg), - m_upgrade(), - // tool is active depending on config settings - m_active(m_config->isMC() && m_config->HLLHC()), - // object selection tools setup below - m_objectSelector_Electron( nullptr ), - m_objectSelector_Muon( nullptr ) - { - - if ( m_active ){ - std::cout << "Upgrade level reconstruction is enabled; telling you how I am configured:" << '\n'; - m_upgrade.reset(new UpgradePerformanceFunctionsxAOD(UpgradePerformanceFunctions::gold, 200.0)); //layout & mu hard coded for now - m_upgrade->setElectronWorkingPoint(UpgradePerformanceFunctions::looseElectron); - m_upgrade->setElectronRandomSeed(171); - m_upgrade->setMuonWorkingPoint(UpgradePerformanceFunctions::tightMuon); - m_upgrade->setMETRandomSeed(986); - m_upgrade->loadMETHistograms("UpgradePerformanceFunctions/sumetPU_mu200_ttbar_gold.root"); - m_upgrade->setPileupRandomSeed(121); - m_upgrade->setPileupRandomSeed(771); - m_upgrade->setPileupJetPtThresholdMeV(30000.); - m_upgrade->setPileupEfficiencyScheme(UpgradePerformanceFunctions::PileupEff::HS); - m_upgrade->setPileupEff(0.9); - m_upgrade->setPileupTemplatesPath("/cvmfs/atlas.cern.ch/repo/sw/database/GroupData/UpgradePerformanceFunctions/"); - m_upgrade->setFlavourTaggingCalibrationFilename("UpgradePerformanceFunctions/flavor_tags_v1.1.root"); - - // configure muon selector - auto optMu = UpgradeLeptonObjectSelector::Options{ - m_config->truth_muon_PtCut(), - m_config->truth_muon_EtaCut() - }; - - m_objectSelector_Muon.reset( new UpgradeLeptonObjectSelector( optMu ) ); - - // configure electron selector - auto optEl = UpgradeLeptonObjectSelector::Options{ - m_config->truth_electron_PtCut(), - m_config->truth_electron_EtaCut() - }; - - m_objectSelector_Electron.reset( new UpgradeLeptonObjectSelector( optEl ) ); - } - -}//UpgradeObjectLoader constructor - -UpgradeObjectLoader::~UpgradeObjectLoader( ) { - -} - -/*! - * The main function to do the heavy lifting - get the truth objects, smear them - * and apply efficiency corrections. - * @return ParticleLevelEvent object - */ -ParticleLevelEvent UpgradeObjectLoader::load() { - - // Create the ParticleLevelEvent object - ParticleLevelEvent particleEvent; - - // Load event info object directly into the particleEvent - top::check( evtStore()->retrieve( particleEvent.m_info, m_config->sgKeyEventInfo() ), - "xAOD::TEvent::retrieve failed for EventInfo" ); - - /* ------------------------------ Muons -----------------------------------------------------------*/ - // Get muons - const xAOD::TruthParticleContainer * origmuons(0); - top::check( evtStore()->retrieve( origmuons, m_config->sgKeyTruthMuons() ), - "xAOD::TEvent::retrieve failed for Truth Muons" ); - - // Shallow copy - std::pair< xAOD::TruthParticleContainer*, xAOD::ShallowAuxContainer* > muons_shallowCopy = xAOD::shallowCopyContainer( *origmuons ); - xAOD::TruthParticleContainer* muons = muons_shallowCopy.first; - - // container to put the selected muons in - use view container to avoid deep copies - m_selectedMuons.reset( new xAOD::TruthParticleContainer(SG::VIEW_ELEMENTS)); - - // Smear & efficiency correct muons - for(auto muon : *muons) { - // efficiency (assume pass unsmeared pT here) - const double eff = m_upgrade->getMuonEfficiency( muon->pt(), muon->eta()); - //std::cout << "Muon with pT " << muon->pt() << " has efficiency = " << eff << std::endl; - - // smear - m_upgrade->smearMuon( *muon ); - //std::cout << "\t smeared pT " << muon->pt() << std::endl; - - // store efficiency correction - if(m_upgrade->getRandom3()->Uniform() < eff) { - muon->auxdata<int>("passReco") = 1; - } - else muon->auxdata<int>("passReco") = 0; - - // apply all cuts - if( m_objectSelector_Muon->apply( *muon ) ) m_selectedMuons->push_back( muon ); - - } - - // sort the muons by pT - std::sort(m_selectedMuons->begin(), m_selectedMuons->end(), ptSort); - - // keep hold of the pointers in our private variables (also clears last event) - m_muons.reset(muons); - m_muonsShallowAux.reset(muons_shallowCopy.second); - - // pass the muons to the ParticleLevelEvent object - particleEvent.m_muons = m_selectedMuons.get(); - - /* ------------------------------ Electrons -----------------------------------------------------------*/ - // Get electrons - const xAOD::TruthParticleContainer * origelectrons(0); - top::check( evtStore()->retrieve( origelectrons, m_config->sgKeyTruthElectrons() ), - "xAOD::TEvent::retrieve failed for Truth Electrons" ); - - // Shallow copy - std::pair< xAOD::TruthParticleContainer*, xAOD::ShallowAuxContainer* > electrons_shallowCopy = xAOD::shallowCopyContainer( *origelectrons ); - xAOD::TruthParticleContainer* electrons = electrons_shallowCopy.first; - - // container to put the selected electrons in - use view container to avoid deep copies - m_selectedElectrons.reset( new xAOD::TruthParticleContainer(SG::VIEW_ELEMENTS)); - - // Smear & efficiency correct electrons - for(auto electron : *electrons) { - // efficiency (assume pass unsmeared pT here) - const double eff = m_upgrade->getElectronEfficiency( electron->pt(), electron->eta()); - //std::cout << "Electron with pT " << electron->pt() << " has efficiency = " << eff << std::endl; - - // smear - m_upgrade->smearElectron( *electron ); - //std::cout << "\t smeared pT " << electron->pt() << std::endl; - - // store efficiency result - if(m_upgrade->getRandom3()->Uniform() < eff) { - electron->auxdata<int>("passReco") = 1; - } - else electron->auxdata<int>("passReco") = 0; - - // apply all cuts - if( m_objectSelector_Electron->apply( *electron ) ) m_selectedElectrons->push_back( electron ); - } - - // sort the electrons by pT - std::sort(m_selectedElectrons->begin(), m_selectedElectrons->end(), ptSort); - - // keep hold of the pointers in our private variables (also clears last event) - m_electrons.reset(electrons); - m_electronsShallowAux.reset(electrons_shallowCopy.second); - - // pass the electrons to the ParticleLevelEvent object - particleEvent.m_electrons = m_selectedElectrons.get(); - - - /* ------------------------------ Jets-----------------------------------------------------------*/ - // Get jets - const xAOD::JetContainer * origjets(0); - top::check( evtStore()->retrieve( origjets, m_config->sgKeyTruthJets() ), - "xAOD::TEvent::retrieve failed for Truth Jets" ); - - // Shallow copy - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > jets_shallowCopy = xAOD::shallowCopyContainer( *origjets ); - xAOD::JetContainer* jets = jets_shallowCopy.first; - - // we are going to put selected 'good' jets in to a xAOD::JetContainer - xAOD::JetContainer* selectedJets = new xAOD::JetContainer(); - xAOD::JetAuxContainer* auxJetCont = new xAOD::JetAuxContainer(); - selectedJets->setStore(auxJetCont); // connect container & store - - // Smear & efficiency correct jets - for(auto jet : *jets) { - // smear - m_upgrade->smearJet( *jet ); - - // jets must be above minimum threshold - if ( jet->pt() < m_upgrade->getPileupJetPtThresholdMeV()) continue; - - jet->auxdata<int>("pileUp") = 0; // so we know this jet is not pileup later on - - const float trackEff = m_upgrade->getTrackJetConfirmEff(jet->pt(),jet->eta(), "HS"); - - if(m_upgrade->getRandom3()->Uniform() < trackEff) { - // mark that jet passed track confirmation - jet->auxdata<int>("passTrackConf") = 1; - - // store b-tagging efficiency - - // first work out jet flavour - char type = 'L'; - if(jet->auxdata<int>("GhostBQuarksFinalCount") > 0) type = 'B'; - else if(jet->auxdata<int>("GhostCQuarksFinalCount") > 0) type = 'C'; - - // now get b-tagging efficiency - const double MV1tagEff = m_upgrade->getFlavourTagEfficiency(jet->pt(), jet->eta(), type, "mv1", 70, m_upgrade->getPileupTrackConfSetting()); - jet->auxdata<float>("mv1TagEff") = MV1tagEff; - - // put jet in to selectedJets container, have to deep copy the jet - xAOD::Jet* newjet = new xAOD::Jet(*jet); - selectedJets->push_back( newjet ); - - } - else jet->auxdata<int>("passTrackConf") = 0; - - - //std::cout << "\t smeared pT " << jet->pt() << std::endl; - } - - // now get the pileup jets - std::vector<TLorentzVector> puJets = m_upgrade->getPileupJets(); - // loop over pileup jets - for(auto puJet : puJets) { - - const float trackEff = m_upgrade->getTrackJetConfirmEff(puJet.Pt(),puJet.Eta(),"PU"); - - if(m_upgrade->getRandom3()->Uniform() > trackEff) continue; // ignore jets failing track confirmation - - // jet 4 momentum stored as PtEtaPhiM (see xAODJet/JetTypes.h) - xAOD::JetFourMom_t mom( puJet.Pt(), puJet.Eta(), puJet.Phi(), puJet.M() ); - xAOD::Jet* jet = new xAOD::Jet(); - selectedJets->push_back( jet ); - selectedJets->back()->setJetP4( mom ); - selectedJets->back()->auxdata<int>("pileUp") = 1; // so we know this jet is pileup later on - // now get b-tagging efficiency - const double MV1tagEff = m_upgrade->getFlavourTagEfficiency(jet->pt(), jet->eta(), 'P', "mv1", 70, m_upgrade->getPileupTrackConfSetting()); - selectedJets->back()->auxdata<float>("mv1TagEff") = MV1tagEff; - - }// pileup jet loop - - // sort jets by pT - std::sort(selectedJets->begin(), selectedJets->end(), ptSort); - - // keep hold of the pointers in our private variables (also clears last event) - m_jets.reset(selectedJets); - m_jetsAux.reset(auxJetCont); - - // pass the jets to the ParticleLevelEvent object - particleEvent.m_jets = selectedJets; - - // clean up memory from the shallow copy of jets that is finished with now - delete jets; - delete jets_shallowCopy.second; - - - /* ----------------------------- MET ------------------------------------------*/ - const xAOD::MissingETContainer * origmetcont(0); - top::check( evtStore()->retrieve( origmetcont, m_config->sgKeyTruthMET() ), - "xAOD::TEvent::retrieve failed for Truth MET" ); - - ATH_MSG_DEBUG("N(MET) = " << origmetcont->size()); - - // Maybe we shouldn't hard code this, but probably it will not change.... - const xAOD::MissingET* origmet = (*origmetcont)["NonInt"]; - - // the MET type is just std::pair<double,double>, representing the smeared METx and METy - UpgradePerformanceFunctions::MET smearedMET = m_upgrade->getMETSmeared(origmet->sumet(), origmet->mpx(), origmet->mpy()); - - // Shallow copy - std::pair< xAOD::MissingETContainer*, xAOD::ShallowAuxContainer* > metcont_shallowCopy = xAOD::shallowCopyContainer( *origmetcont ); - xAOD::MissingETContainer* metcont = metcont_shallowCopy.first; - xAOD::MissingET* met = (*metcont)["NonInt"]; - met->setMpx(smearedMET.first); - met->setMpx(smearedMET.second); - - // keep hold of the pointers in our private variables (also clears last event) - m_metCont.reset(metcont); - m_metShallowAux.reset(metcont_shallowCopy.second); - - // pass the MET pointer to the ParticleLevelEvent object - particleEvent.m_met = met; - - return particleEvent; -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradePerformanceFunctionsxAOD.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradePerformanceFunctionsxAOD.cxx deleted file mode 100644 index 63fe0423de0d8a65c825231ad8cf472c5415cb6a..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/Root/UpgradePerformanceFunctionsxAOD.cxx +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TopHLUpgrade/UpgradePerformanceFunctionsxAOD.h" - -UpgradePerformanceFunctionsxAOD::UpgradePerformanceFunctionsxAOD() : - UpgradePerformanceFunctions(), - m_randgen(811) //fix random seed -{ - -} - -UpgradePerformanceFunctionsxAOD::UpgradePerformanceFunctionsxAOD(UpgradeLayout layout, double avgMu) : - UpgradePerformanceFunctions(layout, avgMu), - m_randgen(811) // fix random seed -{ - -} - -/** - * Get smeared electron energy from the UpgradePerformanceFunctions and then - * modify the input electron energy accordingly. - */ -void UpgradePerformanceFunctionsxAOD::smearElectron(xAOD::TruthParticle& electron) { - const double newE = getElectronSmearedEnergy( electron.e(), electron.eta() ); - const double newE2 = newE*newE; - const double m2 = electron.m() * electron.m(); - const double p2 = newE2 > m2 ? newE2 - m2 : 0.; - TLorentzVector newvec; - newvec.SetPtEtaPhiE( sqrt(p2) / cosh(electron.eta()), electron.eta(), electron.phi(), newE ); - - // no p4 setter in truth particle, have to set one-by-one - electron.setPx( newvec.Px() ); - electron.setPy( newvec.Py() ); - electron.setPz( newvec.Pz() ); - electron.setE( newvec.E() ); - electron.setM( newvec.M() ); -} - -/** - * Get smeared muon momentum from the UpgradePerformanceFunctions and then - * modify the input muon accordingly. Note, the PdgId will be changed - * if the muon smearing results in a charge flip (since the - * TruthParticle->charge() function uses the PdgId). - */ -void UpgradePerformanceFunctionsxAOD::smearMuon(xAOD::TruthParticle& muon) { - double qoverpt = muon.charge()/muon.pt(); - const double sigma_qoverpt = this->getMuonQOverPtResolution(muon.pt(), muon.eta()); - qoverpt += m_randgen.Gaus(0,sigma_qoverpt); - const double pt_smeared = fabs(1.0/qoverpt); - const double q_smeared = (qoverpt > 0) ? 1.0 : -1.0; - TLorentzVector newvec; - newvec.SetPtEtaPhiM( pt_smeared, muon.eta(), muon.phi(), muon.m() ); - - // no p4 setter in truth particle, have to set one-by-one - muon.setPx( newvec.Px() ); - muon.setPy( newvec.Py() ); - muon.setPz( newvec.Pz() ); - muon.setE( newvec.E() ); - muon.setM( newvec.M() ); - // set pdg id (which is used to get charge) - muon.setPdgId( -1.0 * q_smeared * muon.absPdgId()); -} - -/** - * Get smeared jet pT from the UpgradePerformanceFunctions and then - * modify the input jet accordingly. - */ -void UpgradePerformanceFunctionsxAOD::smearJet(xAOD::Jet& jet) { - // can only smear jets with 10 < pT < 1500 GeV (would be good not to hard code this....) - if(jet.pt() < 10.0*1000.0 or jet.pt() > 1500.0*1000.0) return; - - // function might be called 'SmearedEnergy', but apparently it gives smeared pT (https://twiki.cern.ch/twiki/bin/view/AtlasProtected/UpgradePerformanceFunctions) - const double smearedjetpt = this->getJetSmearedEnergy(jet.pt(), jet.eta(), true); - const double smearedjetE = jet.e() * smearedjetpt/jet.pt(); - // lazy way to calculate the mass after pT smearing - TLorentzVector newjet; - newjet.SetPtEtaPhiE( smearedjetpt, jet.eta(), jet.phi(), smearedjetE ); - // jet 4 momentum stored as PtEtaPhiM (see xAODJet/JetTypes.h) - xAOD::JetFourMom_t mom( smearedjetpt, jet.eta(), jet.phi(), newjet.M() ); - jet.setJetP4( mom ); -} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradeLeptonObjectSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradeLeptonObjectSelector.h deleted file mode 100644 index 547c51402c2e8a01f3e000e19ad673017508ebed..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradeLeptonObjectSelector.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: UpgradeLeptonObjectSelector.h -// Description: -// Author: Mark Owen -// Created: 19 Jan 2017 - -#ifndef _TOP_UPGRADE_LEPTONOBJECTSELECTOR_H_ -#define _TOP_UPGRADE_LEPTONOBJECTSELECTOR_H_ - -#include "TopParticleLevel/ObjectSelectorBase.h" - -#include "xAODTruth/TruthParticleContainer.h" - -namespace top { - - class UpgradeLeptonObjectSelector - : public ObjectSelectorBase<xAOD::TruthParticle> { - public: - // Struct used to store the cut values used by the object selector. It - // is important that the object has a sensible default config because it - // will be default constructed for the trivial constructor of the object - // selector. - struct Options { - Options( double ptMin = 25.e3, - double etaMax = 2.5 ) : - pt_min( ptMin ), - eta_max( etaMax ) {} - double pt_min; - double eta_max; - - }; - public: - UpgradeLeptonObjectSelector( Options opt = Options() ); - virtual bool apply( const xAOD::TruthParticle & truthParticle ); - private: - Options m_opt; - }; - -} - -#endif /* _TOP_UPGRADE_LEPTONOBJECTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradeObjectLoader.h b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradeObjectLoader.h deleted file mode 100644 index 49fa5a1efccfacd94919a2323467f59fe3865a30..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradeObjectLoader.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef _TOP_UPGRADEOBJECTLOADER_H_ -#define _TOP_UPGRADEOBJECTLOADER_H_ - -#include "AsgTools/AsgTool.h" - -#include "TopHLUpgrade/UpgradePerformanceFunctionsxAOD.h" -#include "TopParticleLevel/ParticleLevelEvent.h" -#include "TopParticleLevel/ObjectSelectorBase.h" - -#include "xAODTruth/TruthParticleContainer.h" -#include "xAODJet/JetContainer.h" -#include "xAODJet/JetAuxContainer.h" -#include "xAODEventInfo/EventInfo.h" -#include "xAODMissingET/MissingETContainer.h" -#include "xAODMuon/MuonContainer.h" -#include "xAODEgamma/Electron.h" -#include "xAODCore/ShallowCopy.h" - -// Forward Declarations -namespace top { - class TopConfig; -} - -namespace top { - - class UpgradeObjectLoader : public asg::AsgTool { - - public: - - /*! - * @brief Constructor of loader tool. - */ - UpgradeObjectLoader( const std::shared_ptr<top::TopConfig> & cfg ); - - /*! - * @brief Destructor of loader tool. - */ - ~UpgradeObjectLoader( ); - - /*! - * @brief Loading function. Does the actual work. This function will - * load the truth information from the #xaodEvent and return this data - * transformed into a smeared level event. The data stored in the - * SmearedLevel is owned by the truth event loader. - * @param xaodEvent The input data event object. - * @return ParticleLevelEvent object. - */ - ParticleLevelEvent load(); - - /*! - * @brief Function that can be used to test whether the UpgradeObjectLoader - * is active. The loader is set to inactive if the names of the truth - * collections are unavailable. This is determined at construction. - */ - bool active() const { return m_active; } - - private: - - // The global config object - const std::shared_ptr<top::TopConfig> & m_config; - - // pointer to smearing function object - std::unique_ptr<UpgradePerformanceFunctionsxAOD> m_upgrade; - - // Flag denoting whether the loader tool is active. Will be set by the - // constructor and remains unchanged afterwards. - const bool m_active; - - // muons - std::unique_ptr<xAOD::TruthParticleContainer> m_muons; - std::unique_ptr<xAOD::ShallowAuxContainer> m_muonsShallowAux; - std::unique_ptr<xAOD::TruthParticleContainer> m_selectedMuons; - - // electrons - std::unique_ptr<xAOD::TruthParticleContainer> m_electrons; - std::unique_ptr<xAOD::ShallowAuxContainer> m_electronsShallowAux; - std::unique_ptr<xAOD::TruthParticleContainer> m_selectedElectrons; - - // jets - std::unique_ptr<xAOD::JetContainer> m_jets; - std::unique_ptr<xAOD::JetAuxContainer> m_jetsAux; - - // MET - std::unique_ptr<xAOD::MissingETContainer> m_metCont; - std::unique_ptr<xAOD::ShallowAuxContainer> m_metShallowAux; - - // Electron selector tool - std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Electron; - - // Muon selector tool - std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Muon; - - };//class UpgradeObjectLoader - -}//namespace top - -#endif //_TOP_UPGRADEOBJECTLOADER_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradePerformanceFunctionsxAOD.h b/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradePerformanceFunctionsxAOD.h deleted file mode 100644 index 158af7891d6a26f9301e6f0851b2461fb68fc36e..0000000000000000000000000000000000000000 --- a/PhysicsAnalysis/TopPhys/xAOD/TopHLUpgrade/TopHLUpgrade/UpgradePerformanceFunctionsxAOD.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef UPGRADEPERFORMANCEFUNCTIONSXAOD_H -#define UPGRADEPERFORMANCEFUNCTIONSXAOD_H - -#include "UpgradePerformanceFunctions/UpgradePerformanceFunctions.h" - -#include "TRandom3.h" - -#include "xAODTruth/TruthParticle.h" -#include "xAODJet/Jet.h" - -/*! - * @brief Class to use the upgrade performance functions to smear xAOD objects. - * - * The class inherits from UpgradePerformanceFunctions and provides a few functions - * to smear electrons, muons and jets. - * - * @author Mark Owen <markowen@cern.ch> - */ -class UpgradePerformanceFunctionsxAOD : public UpgradePerformanceFunctions { - - public: - - /// Default constructor - UpgradePerformanceFunctionsxAOD(); - - /// Constructor specifing layout & mu - UpgradePerformanceFunctionsxAOD(UpgradeLayout layout, double avgMu); - - /// Destructor - ~UpgradePerformanceFunctionsxAOD() {}; - - /// Smear an Electron - void smearElectron(xAOD::TruthParticle& electron); - - /// Smear a Muon - void smearMuon(xAOD::TruthParticle& muon); - - /// Smear a Jet - void smearJet(xAOD::Jet& jet); - - /// Access to random number generator - inline TRandom3* getRandom3() {return &m_randgen;} - - private: - - TRandom3 m_randgen; - -};//class UpgradePerformanceFunctionsxAOD - -#endif //UPGRADEPERFORMANCEFUNCTIONSXAOD_H diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/CMakeLists.txt index 2dd9663462385280cbdeba3553c80534d4e345ab..cf1ffff012eeecb08c7e05b452ae3b92c4a2dd06 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/CMakeLists.txt @@ -1,7 +1,5 @@ -# Auto-generated on: 2017-03-08 14:47:37.639679 - # Declare the name of this package: -atlas_subdir( TopJetSubstructure None ) +atlas_subdir( TopJetSubstructure ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC @@ -24,9 +22,6 @@ find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) find_package( FastJet ) find_package( FastJetContrib ) -# Custom definitions needed for this package: -add_definitions( -g ) - # Build a library that other components can link against: atlas_add_library( TopJetSubstructure Root/*.cxx Root/*.h Root/*.icc TopJetSubstructure/*.h TopJetSubstructure/*.icc TopJetSubstructure/*/*.h @@ -49,6 +44,3 @@ atlas_add_library( TopJetSubstructure Root/*.cxx Root/*.h Root/*.icc ${FASTJET_INCLUDE_DIRS} ${FASTJETCONTRIB_INCLUDE_DIRS}) -# Install data files from the package: -atlas_install_data( share/* ) - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/ElectronInJetSubtractionAlgorithm.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/ElectronInJetSubtractionAlgorithm.cxx index ef63f2d9adce4cd9cc11655a1338c44d1e52c670..e9ffb27ae11ac8ecdb112c375fdff42fa9002cde 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/ElectronInJetSubtractionAlgorithm.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/ElectronInJetSubtractionAlgorithm.cxx @@ -1,26 +1,23 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: ElectronInJetSubtractionAlgorithm.cxx 654856 2015-03-17 19:00:30Z dferreir $ #include "TopJetSubstructure/ElectronInJetSubtractionAlgorithm.h" #include <iostream> -namespace top{ - +namespace top { ElectronInJetSubtractionAlgorithm::ElectronInJetSubtractionAlgorithm() : m_doLooseCuts(false), m_passPreORSelection("passPreORSelection"), - m_passPreORSelectionLoose("passPreORSelectionLoose") - { - + m_passPreORSelectionLoose("passPreORSelectionLoose") { } - - void ElectronInJetSubtractionAlgorithm::apply( xAOD::ElectronContainer* electrons , xAOD::JetContainer* jets , const bool useLooseElectrons ) - { + + void ElectronInJetSubtractionAlgorithm::apply(xAOD::ElectronContainer* electrons, xAOD::JetContainer* jets, + const bool useLooseElectrons) { std::string leptonDef; - if (!useLooseElectrons){ + if (!useLooseElectrons) { leptonDef = m_passPreORSelection; } if (useLooseElectrons) { @@ -33,7 +30,7 @@ namespace top{ ++passedElectronsBefore; } } - + m_o.Load(jets, electrons, leptonDef); m_o.AnalyzeEvent(leptonDef); @@ -43,11 +40,11 @@ namespace top{ ++passedElectrons; } } - + bool debug(false); if (debug) { - std::cout<<"Total number of electrons = "<<electrons->size()<<" that pass cuts = "<<passedElectrons<<"/" << passedElectronsBefore << " :: Total number of jets = "<<jets->size()<<std::endl; + std::cout << "Total number of electrons = " << electrons->size() << " that pass cuts = " << passedElectrons << + "/" << passedElectronsBefore << " :: Total number of jets = " << jets->size() << std::endl; } } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/LargeJetTrimmer.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/LargeJetTrimmer.cxx index 9ef40ba675d33667fb9a004f742233eb54062823..b36599dcaec69c6272d4ac734f75cab3582a7eff 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/LargeJetTrimmer.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/LargeJetTrimmer.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopJetSubstructure/LargeJetTrimmer.h" @@ -27,12 +27,13 @@ top::LargeJetTrimmer::~LargeJetTrimmer() { void top::LargeJetTrimmer::correctJet(xAOD::Jet& jet) { JetConstituentVector vec = jet.getConstituents(); + std::vector<fastjet::PseudoJet> p_c; xAOD::JetConstituentVector::iterator it = vec.begin(); xAOD::JetConstituentVector::iterator itE = vec.end(); - for( ; it != itE; it++){ - PseudoJet p(0,0,0,0); + for (; it != itE; it++) { + PseudoJet p(0, 0, 0, 0); float pt = (*it)->pt(); float y = (*it)->rapidity(); float phi = (*it)->phi(); @@ -40,7 +41,7 @@ void top::LargeJetTrimmer::correctJet(xAOD::Jet& jet) { p.reset_PtYPhiM(pt, y, phi, m); p_c.push_back(p); } - + JetDefinition jet_def_large = JetDefinition(antikt_algorithm, 1.0, fastjet::E_scheme, fastjet::Best); ClusterSequence cs_large(p_c, jet_def_large); std::vector<PseudoJet> ljets = sorted_by_pt(cs_large.inclusive_jets(50e3)); @@ -55,4 +56,3 @@ void top::LargeJetTrimmer::correctJet(xAOD::Jet& jet) { void top::LargeJetTrimmer::print(std::ostream& o) const { o << "LargeJetTrimmer" << std::endl; } - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/SubjetMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/SubjetMaker.cxx index 67745de04259fec2f5a2cc3264c919f3e23cf521..78e7429733875d4c5d78a577addff69ffb81f6b4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/SubjetMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/SubjetMaker.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopJetSubstructure/SubjetMaker.h" @@ -29,20 +29,18 @@ void top::SubjetMaker::correctJet(xAOD::Jet& jet) { xAOD::JetConstituentVector vec = jet.getConstituents(); std::vector<fastjet::PseudoJet> p_c; - for(auto it : vec){ - PseudoJet p(0,0,0,0); + for (auto it : vec) { + PseudoJet p(0, 0, 0, 0); float pt = (*it)->pt(); float y = (*it)->rapidity(); float phi = (*it)->phi(); float m = (*it)->m(); if (y != y) { continue; + } else { + p.reset_PtYPhiM(pt, y, phi, m); + p_c.push_back(p); } - else { - p.reset_PtYPhiM(pt, y, phi, m); - p_c.push_back(p); - } - } JetDefinition jet_def_small = JetDefinition(cambridge_algorithm, 0.2, fastjet::E_scheme, fastjet::Best); @@ -51,18 +49,17 @@ void top::SubjetMaker::correctJet(xAOD::Jet& jet) { if (ljets.size() == 0) { return; } - std::vector<float> sje,sjpx,sjpy,sjpz; + std::vector<float> sje, sjpx, sjpy, sjpz; for (size_t z = 0; z < ljets.size(); ++z) { sje.push_back(ljets[z].e()); sjpx.push_back(ljets[z].px()); sjpy.push_back(ljets[z].py()); sjpz.push_back(ljets[z].pz()); } - jet.auxdata<std::vector<float> >("Subjet_E") = sje; - jet.auxdata<std::vector<float> >("Subjet_Px") = sjpx; - jet.auxdata<std::vector<float> >("Subjet_Py") = sjpy; - jet.auxdata<std::vector<float> >("Subjet_Pz") = sjpz; - + jet.auxdata<std::vector<float> >("Subjet_E") = sje; + jet.auxdata<std::vector<float> >("Subjet_Px") = sjpx; + jet.auxdata<std::vector<float> >("Subjet_Py") = sjpy; + jet.auxdata<std::vector<float> >("Subjet_Pz") = sjpz; } void top::SubjetMaker::print(std::ostream& o) const { diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TTBarElectronJetOverlap.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TTBarElectronJetOverlap.cxx index 99421df6c3fc3615abc284030e72dd7cd09e76ca..606633128db08ba3326772ecaece0ebce57dcaa0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TTBarElectronJetOverlap.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TTBarElectronJetOverlap.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopJetSubstructure/TTBarElectronJetOverlap.h" @@ -13,336 +13,349 @@ using namespace std; -void TTBarElectronJetOverlap::Load(xAOD::JetContainer *jets, xAOD::ElectronContainer *electrons, const std::string &leptonDef) { - m_jets = jets; - m_electrons = electrons; - fDebug = false; - - size_t se = m_electrons->size(); - fElClTLVs.resize(se); - fElTLVs.resize(se); - fElGood.resize(se); - - size_t sj = m_jets->size(); - fJetTLVs.resize(sj); - fOrigJetTLVs.resize(sj); - fJetJVFs.resize(sj); - fJetD3PDTrkPtSums.resize(sj); - fJetD3PDTrkPtPVSums.resize(sj); - - for (size_t i = 0; i < sj; i++) { - fJetTLVs[i].SetPtEtaPhiE(m_jets->at(i)->pt(), m_jets->at(i)->eta(), m_jets->at(i)->phi(), m_jets->at(i)->e()); - fOrigJetTLVs[i].SetPtEtaPhiE(m_jets->at(i)->pt(), m_jets->at(i)->eta(), m_jets->at(i)->phi(), m_jets->at(i)->e()); - - //std::vector<float> JVF = m_jets->at(i)->getAttribute<std::vector<float> >("JVF"); - //fJetJVFs[i] = JVF.size() > 0 ? JVF[0] : -1; // (TODO) NOTA BENE: Assumes PV is the first vertex - //std::vector<float> trkPtSumVec = m_jets->at(i)->getAttribute<std::vector<float> >("SumPtTrkPt500"); - //float trkPtSum = trkPtSumVec.size() > 0 ? trkPtSumVec[0] : 0; // (TODO) NOTA BENE: Assumes PV is the first vertex - //fJetD3PDTrkPtSums[i] = fJetJVFs[i] ? trkPtSum/JVF[0] : -1; - //fJetD3PDTrkPtPVSums[i] = trkPtSum; - if (fDebug) { - cout << " - (pre-OR) Jet # " << i << - " Pt Eta Phi: " << - fJetTLVs[i].Pt() << " " << - fJetTLVs[i].Eta() << " " << - fJetTLVs[i].Phi() << endl; - } +void TTBarElectronJetOverlap::Load(xAOD::JetContainer* jets, xAOD::ElectronContainer* electrons, + const std::string& leptonDef) { + m_jets = jets; + m_electrons = electrons; + fDebug = false; + + size_t se = m_electrons->size(); + fElClTLVs.resize(se); + fElTLVs.resize(se); + fElGood.resize(se); + + size_t sj = m_jets->size(); + fJetTLVs.resize(sj); + fOrigJetTLVs.resize(sj); + fJetJVFs.resize(sj); + fJetD3PDTrkPtSums.resize(sj); + fJetD3PDTrkPtPVSums.resize(sj); + + for (size_t i = 0; i < sj; i++) { + fJetTLVs[i].SetPtEtaPhiE(m_jets->at(i)->pt(), m_jets->at(i)->eta(), m_jets->at(i)->phi(), m_jets->at(i)->e()); + fOrigJetTLVs[i].SetPtEtaPhiE(m_jets->at(i)->pt(), m_jets->at(i)->eta(), m_jets->at(i)->phi(), m_jets->at(i)->e()); + + //std::vector<float> JVF = m_jets->at(i)->getAttribute<std::vector<float> >("JVF"); + //fJetJVFs[i] = JVF.size() > 0 ? JVF[0] : -1; // (TODO) NOTA BENE: Assumes PV is the first vertex + //std::vector<float> trkPtSumVec = m_jets->at(i)->getAttribute<std::vector<float> >("SumPtTrkPt500"); + //float trkPtSum = trkPtSumVec.size() > 0 ? trkPtSumVec[0] : 0; // (TODO) NOTA BENE: Assumes PV is the first vertex + //fJetD3PDTrkPtSums[i] = fJetJVFs[i] ? trkPtSum/JVF[0] : -1; + //fJetD3PDTrkPtPVSums[i] = trkPtSum; + if (fDebug) { + cout << " - (pre-OR) Jet # " << i << + " Pt Eta Phi: " << + fJetTLVs[i].Pt() << " " << + fJetTLVs[i].Eta() << " " << + fJetTLVs[i].Phi() << endl; + } + } + + for (size_t i = 0; i < se; i++) { + fElGood[i] = m_electrons->at(i)->auxdataConst<char>(leptonDef.c_str()); + + if (m_electrons->at(i)->caloCluster()) { + fElClTLVs[i].SetPtEtaPhiM(m_electrons->at(i)->caloCluster()->e() / + std::cosh(m_electrons->at(i)->caloCluster()->eta()), + m_electrons->at(i)->caloCluster()->eta(), m_electrons->at( + i)->caloCluster()->phi(), 0.511); + } else { + fElClTLVs[i] = m_electrons->at(i)->p4(); } - for (size_t i = 0; i < se; i++) { - fElGood[i] = m_electrons->at(i)->auxdataConst<char>(leptonDef.c_str()); - - if (m_electrons->at(i)->caloCluster()) { - fElClTLVs[i].SetPtEtaPhiM(m_electrons->at(i)->caloCluster()->e()/std::cosh(m_electrons->at(i)->caloCluster()->eta()), - m_electrons->at(i)->caloCluster()->eta(), m_electrons->at(i)->caloCluster()->phi(), 0.511); - } else { - fElClTLVs[i] = m_electrons->at(i)->p4(); - } - - if (m_electrons->at(i)->trackParticle() && m_electrons->at(i)->caloCluster()) { - fElTLVs[i].SetPtEtaPhiM(m_electrons->at(i)->caloCluster()->e()/std::cosh(m_electrons->at(i)->trackParticle()->eta()), - m_electrons->at(i)->trackParticle()->eta(), m_electrons->at(i)->trackParticle()->phi(), 0.511); - } else { - fElTLVs[i] = m_electrons->at(i)->p4(); - } - if (fDebug) { - cout << " - (pre-OR) El # " << i << - " Pt Eta Phi: " << - fElTLVs[i].Pt() << " " << - fElTLVs[i].Eta() << " " << - fElTLVs[i].Phi() << endl; - } + if (m_electrons->at(i)->trackParticle() && m_electrons->at(i)->caloCluster()) { + fElTLVs[i].SetPtEtaPhiM(m_electrons->at(i)->caloCluster()->e() / + std::cosh(m_electrons->at(i)->trackParticle()->eta()), + m_electrons->at(i)->trackParticle()->eta(), m_electrons->at( + i)->trackParticle()->phi(), 0.511); + } else { + fElTLVs[i] = m_electrons->at(i)->p4(); + } + if (fDebug) { + cout << " - (pre-OR) El # " << i << + " Pt Eta Phi: " << + fElTLVs[i].Pt() << " " << + fElTLVs[i].Eta() << " " << + fElTLVs[i].Phi() << endl; } + } } void TTBarElectronJetOverlap::FindAssocEls() { - size_t nJets = m_jets->size(); - fJetAssocElCls = vector<set<int> >(nJets); - size_t nEls = m_electrons->size(); - fElClAssocJet = vector<int>(nEls, -1); - - // find the associated electron clusters in each jet - double drmin, dr; - TLorentzVector elcl, jet; - for (size_t z = 0 ; z < nEls; ++z) { - if (!fElGood[z]) continue; - elcl = fElClTLVs[z]; - drmin = 0.4; - int drmin_idx = -1; - for (size_t y = 0 ; y < nJets; ++y) { - jet = fJetTLVs[y]; - dr = elcl.DeltaR(jet); - // attempt to match the jet to the electron. - if (dr < drmin) { - drmin = dr; - drmin_idx = y; - } - } - if (drmin_idx == -1) - continue; - fJetAssocElCls[drmin_idx].insert(z); - fElClAssocJet[z] = drmin_idx; + size_t nJets = m_jets->size(); + + fJetAssocElCls = vector<set<int> >(nJets); + size_t nEls = m_electrons->size(); + fElClAssocJet = vector<int>(nEls, -1); + + // find the associated electron clusters in each jet + double drmin, dr; + TLorentzVector elcl, jet; + for (size_t z = 0; z < nEls; ++z) { + if (!fElGood[z]) continue; + elcl = fElClTLVs[z]; + drmin = 0.4; + int drmin_idx = -1; + for (size_t y = 0; y < nJets; ++y) { + jet = fJetTLVs[y]; + dr = elcl.DeltaR(jet); + // attempt to match the jet to the electron. + if (dr < drmin) { + drmin = dr; + drmin_idx = y; + } } + if (drmin_idx == -1) continue; + fJetAssocElCls[drmin_idx].insert(z); + fElClAssocJet[z] = drmin_idx; + } } void TTBarElectronJetOverlap::SubtractEls() { - size_t nJets = m_jets->size(); - size_t nEls = m_electrons->size(); - int ElIdx; - - fSubJets.resize(nJets); - for (int k=0; k<nJets; ++k) { - fSubJets[k] = 0; - } - - for (size_t iJet = 0; iJet < nJets; iJet++) { - TLorentzVector originalJet = fOrigJetTLVs[iJet]; - for (set<int>::iterator iEl = fJetAssocElCls[iJet].begin(); iEl != fJetAssocElCls[iJet].end(); iEl++) { - ElIdx = *iEl; - TLorentzVector elcorr = fElTLVs[ElIdx]; - fJetTLVs[iJet] -= elcorr; - fSubJets[iJet] = 1; - } + size_t nJets = m_jets->size(); + int ElIdx; + + fSubJets.resize(nJets); + for (unsigned int k = 0; k < nJets; ++k) { + fSubJets[k] = 0; + } + + for (size_t iJet = 0; iJet < nJets; iJet++) { + TLorentzVector originalJet = fOrigJetTLVs[iJet]; + for (set<int>::iterator iEl = fJetAssocElCls[iJet].begin(); iEl != fJetAssocElCls[iJet].end(); iEl++) { + ElIdx = *iEl; + TLorentzVector elcorr = fElTLVs[ElIdx]; + fJetTLVs[iJet] -= elcorr; + fSubJets[iJet] = 1; } + } } void TTBarElectronJetOverlap::FindGoodObjects() { - size_t nEls = m_electrons->size(); - fGoodEls = vector<bool>(nEls, true); - - size_t nJets = fJetTLVs.size(); - vector<TLorentzVector> TmpJetTLVs = fJetTLVs; - vector<TLorentzVector> TmpOrigJetTLVs = fOrigJetTLVs; - TLorentzVector el, jet, jetOrig; - - for (size_t iEl = 0; iEl < nEls; iEl++) { - if (!fElGood[iEl]) continue; - - el = fElTLVs[iEl]; - - if (fDebug) { - cout << " - (good) El # " << iEl << - " Pt Eta Phi: " << - el.Pt() << " " << - el.Eta() << " " << - el.Phi() << endl; - } + size_t nEls = m_electrons->size(); - for (size_t iJet = 0; iJet < nJets; iJet++) { - jet = fJetTLVs[iJet]; - jetOrig = fOrigJetTLVs[iJet]; - if (fDebug) { - cout << " - (good) Jet # " << iJet << - " Pt Eta Phi M: " << - jet.Pt() << " " << - jet.Eta() << " " << - jet.Phi() << " " << - jet.M() << endl; - } - - //if (jet.Pt() < 25e3) - //continue; - - // New overlap removal procedure: - // subtracted ets failing the pT cut are assumed to be a result of electron energy deposits. Continue to the next jet. - - if ((jetOrig.Pt() >= 30e3 && jetOrig.Pt() < 50e3) && jet.Pt() < 20e3) { - continue; - } else if (( jetOrig.Pt() >= 50e3 && jetOrig.Pt() < 100e3) && jet.Pt() <30e3) { - continue; - } else if ((jetOrig.Pt() >= 100e3 && jetOrig.Pt() < 400e3) && jet.Pt() <90e3) { - continue; - } else if ((jetOrig.Pt() >= 400e3 && jetOrig.Pt() < 800e3) && jet.Pt() <130e3) { - continue; - } else if ((jetOrig.Pt() >= 800e3 && jetOrig.Pt() <1200e3) && jet.Pt() <230e3) { - continue; - } else if ((jetOrig.Pt() >=1200e3 && jetOrig.Pt() <1600e3) && jet.Pt() <700e3) { - continue; - } else if ((jetOrig.Pt() >=1600e3 && jetOrig.Pt() <2000e3) && jet.Pt() < 1250e3) { - continue; - } else if ((jetOrig.Pt() >=2000e3 && jetOrig.Pt()<2200e3) && jet.Pt() < 1300e3) { - continue; - } else if (jetOrig.Pt()>2200e3 && jet.Pt()<1350e3) { - continue; - } - - // if the electron is too close to a subtracted jet... - if (jet.DeltaR(el) < 0.2) { - - if (fDebug) - cout << " El too close to jet. Removing." << endl; - - // remove from good electrons list. - fGoodEls[iEl] = false; - - if (fElClAssocJet[iEl] >= 0) { - // add electron 4-vector back to jet. - TmpJetTLVs[fElClAssocJet[iEl]] += el; - //remove from subtracted jets list - fSubJets[iJet] = 0; - // remove this electron from the association. - fJetAssocElCls[iJet].erase(iEl); - } - } - } - } - - fJetTLVs = TmpJetTLVs; - fOrigJetTLVs = TmpOrigJetTLVs; - fGoodJets = vector<bool>(nJets,true); - - for (size_t iJet = 0; iJet < nJets; iJet++) { - jetOrig = fOrigJetTLVs[iJet]; - - if (jetOrig.Pt() >= 30e3 && jetOrig.Pt() < 50e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 20e3; - } else if (jetOrig.Pt() >= 50e3 && jetOrig.Pt() < 100e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 30e3; - } else if (jetOrig.Pt() >= 100e3 && jetOrig.Pt() < 400e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 90e3; - } else if (jetOrig.Pt() >= 400e3 && jetOrig.Pt() < 800e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 130e3; - } else if (jetOrig.Pt() >= 800e3 && jetOrig.Pt() < 1200e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 230e3; - } else if (jetOrig.Pt() >= 1200e3 && jetOrig.Pt() < 1600e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 700e3; - } else if (jetOrig.Pt() >= 1600e3 && jetOrig.Pt() < 2000e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 1250e3; - } else if (jetOrig.Pt() >= 2000e3 && jetOrig.Pt() < 2200e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 1300e3; - } else if (jetOrig.Pt() > 2200e3) { - fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 1350e3; - } - } -} - -void TTBarElectronJetOverlap::RecalcJVF() { + fGoodEls = vector<bool>(nEls, true); - size_t nJets = m_jets->size(); - int ElIdx; - //int TrkIdx; - TLorentzVector trk; + size_t nJets = fJetTLVs.size(); + vector<TLorentzVector> TmpJetTLVs = fJetTLVs; + vector<TLorentzVector> TmpOrigJetTLVs = fOrigJetTLVs; + TLorentzVector el, jet, jetOrig; - for (size_t iJet = 0; iJet < nJets; iJet++) { + for (size_t iEl = 0; iEl < nEls; iEl++) { + if (!fElGood[iEl]) continue; - // if jvf == 0 or -1, no need to recalulate... - if (!fJetJVFs[iJet] || - fJetJVFs[iJet] < 0) - continue; + el = fElTLVs[iEl]; - for (set<int>::iterator iEl = fJetAssocElCls[iJet].begin(); - iEl != fJetAssocElCls[iJet].end(); iEl++) { + if (fDebug) { + cout << " - (good) El # " << iEl << + " Pt Eta Phi: " << + el.Pt() << " " << + el.Eta() << " " << + el.Phi() << endl; + } - ElIdx = *iEl; + for (size_t iJet = 0; iJet < nJets; iJet++) { + jet = fJetTLVs[iJet]; + jetOrig = fOrigJetTLVs[iJet]; + if (fDebug) { + cout << " - (good) Jet # " << iJet << + " Pt Eta Phi M: " << + jet.Pt() << " " << + jet.Eta() << " " << + jet.Phi() << " " << + jet.M() << endl; + } - trk.SetPtEtaPhiE(m_electrons->at(ElIdx)->trackParticle()->pt(), - m_electrons->at(ElIdx)->trackParticle()->eta(), m_electrons->at(ElIdx)->trackParticle()->phi(), m_electrons->at(ElIdx)->trackParticle()->e()); + //if (jet.Pt() < 25e3) + //continue; + + // New overlap removal procedure: + // subtracted ets failing the pT cut are assumed to be a result of electron energy deposits. Continue to the next + // jet. + + if ((jetOrig.Pt() >= 30e3 && jetOrig.Pt() < 50e3) && jet.Pt() < 20e3) { + continue; + } else if ((jetOrig.Pt() >= 50e3 && jetOrig.Pt() < 100e3) && jet.Pt() < 30e3) { + continue; + } else if ((jetOrig.Pt() >= 100e3 && jetOrig.Pt() < 400e3) && jet.Pt() < 90e3) { + continue; + } else if ((jetOrig.Pt() >= 400e3 && jetOrig.Pt() < 800e3) && jet.Pt() < 130e3) { + continue; + } else if ((jetOrig.Pt() >= 800e3 && jetOrig.Pt() < 1200e3) && jet.Pt() < 230e3) { + continue; + } else if ((jetOrig.Pt() >= 1200e3 && jetOrig.Pt() < 1600e3) && jet.Pt() < 700e3) { + continue; + } else if ((jetOrig.Pt() >= 1600e3 && jetOrig.Pt() < 2000e3) && jet.Pt() < 1250e3) { + continue; + } else if ((jetOrig.Pt() >= 2000e3 && jetOrig.Pt() < 2200e3) && jet.Pt() < 1300e3) { + continue; + } else if (jetOrig.Pt() > 2200e3 && jet.Pt() < 1350e3) { + continue; + } - // not in the associated tracks. - bool foundMatch = false; - std::vector<const xAOD::TrackParticle*> jetTracks; - //bool haveJetTracks = m_jets->at(iJet)->getAssociatedObjects(xAOD::JetAttribute::GhostTrack, jetTracks); - for (size_t t = 0; t < jetTracks.size(); ++t) { - TLorentzVector jet_trk; - jet_trk.SetPtEtaPhiE(jetTracks[t]->pt(), jetTracks[t]->eta(), jetTracks[t]->phi(), jetTracks[t]->e()); - if (jet_trk.DeltaR(trk) < 0.01) { - foundMatch = true; - } - } + // if the electron is too close to a subtracted jet... + if (jet.DeltaR(el) < 0.2) { + if (fDebug) cout << " El too close to jet. Removing." << endl; - if (!foundMatch) - continue; + // remove from good electrons list. + fGoodEls[iEl] = false; - // recompute JVF. - fJetD3PDTrkPtSums[iJet] -= trk.Pt(); + if (fElClAssocJet[iEl] >= 0) { + // add electron 4-vector back to jet. + TmpJetTLVs[fElClAssocJet[iEl]] += el; + //remove from subtracted jets list + fSubJets[iJet] = 0; + // remove this electron from the association. + fJetAssocElCls[iJet].erase(iEl); + } + } + } + } + + fJetTLVs = TmpJetTLVs; + fOrigJetTLVs = TmpOrigJetTLVs; + fGoodJets = vector<bool>(nJets, true); + + for (size_t iJet = 0; iJet < nJets; iJet++) { + jetOrig = fOrigJetTLVs[iJet]; + + if (jetOrig.Pt() >= 30e3 && jetOrig.Pt() < 50e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 20e3; + } else if (jetOrig.Pt() >= 50e3 && jetOrig.Pt() < 100e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 30e3; + } else if (jetOrig.Pt() >= 100e3 && jetOrig.Pt() < 400e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 90e3; + } else if (jetOrig.Pt() >= 400e3 && jetOrig.Pt() < 800e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 130e3; + } else if (jetOrig.Pt() >= 800e3 && jetOrig.Pt() < 1200e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 230e3; + } else if (jetOrig.Pt() >= 1200e3 && jetOrig.Pt() < 1600e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 700e3; + } else if (jetOrig.Pt() >= 1600e3 && jetOrig.Pt() < 2000e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 1250e3; + } else if (jetOrig.Pt() >= 2000e3 && jetOrig.Pt() < 2200e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 1300e3; + } else if (jetOrig.Pt() > 2200e3) { + fGoodJets[iJet] = fJetTLVs[iJet].Pt() > 1350e3; + } + } +} - if (std::fabs(std::sin(m_electrons->at(ElIdx)->trackParticle()->theta())*m_electrons->at(ElIdx)->trackParticle()->z0()) < 1.0 && - std::fabs(m_electrons->at(ElIdx)->trackParticle()->d0()) < 1.0) - fJetD3PDTrkPtPVSums[iJet] -= trk.Pt(); +void TTBarElectronJetOverlap::RecalcJVF() { + size_t nJets = m_jets->size(); + int ElIdx; + //int TrkIdx; + TLorentzVector trk; + + for (size_t iJet = 0; iJet < nJets; iJet++) { + // if jvf == 0 or -1, no need to recalulate... + if (!fJetJVFs[iJet] || + fJetJVFs[iJet] < 0) continue; + + for (set<int>::iterator iEl = fJetAssocElCls[iJet].begin(); + iEl != fJetAssocElCls[iJet].end(); iEl++) { + ElIdx = *iEl; + + trk.SetPtEtaPhiE(m_electrons->at(ElIdx)->trackParticle()->pt(), + m_electrons->at(ElIdx)->trackParticle()->eta(), m_electrons->at( + ElIdx)->trackParticle()->phi(), m_electrons->at(ElIdx)->trackParticle()->e()); + + // not in the associated tracks. + bool foundMatch = false; + std::vector<const xAOD::TrackParticle*> jetTracks; + //bool haveJetTracks = m_jets->at(iJet)->getAssociatedObjects(xAOD::JetAttribute::GhostTrack, jetTracks); + for (size_t t = 0; t < jetTracks.size(); ++t) { + TLorentzVector jet_trk; + jet_trk.SetPtEtaPhiE(jetTracks[t]->pt(), jetTracks[t]->eta(), jetTracks[t]->phi(), jetTracks[t]->e()); + if (jet_trk.DeltaR(trk) < 0.01) { + foundMatch = true; } + } + + if (!foundMatch) continue; - // we subtracted too much for some reason? - if (fJetD3PDTrkPtSums[iJet] < 0 || - fJetD3PDTrkPtPVSums[iJet] < 0) - fJetJVFs[iJet] = 0; - // no tracks associated with the jet. - else if (fJetD3PDTrkPtSums[iJet] == 0) - fJetJVFs[iJet] = -1; - // all good. recalculate JVF. - else - fJetJVFs[iJet] = fJetD3PDTrkPtPVSums[iJet]/fJetD3PDTrkPtSums[iJet]; + // recompute JVF. + fJetD3PDTrkPtSums[iJet] -= trk.Pt(); + + if (std::fabs(std::sin(m_electrons->at(ElIdx)->trackParticle()->theta()) * + m_electrons->at(ElIdx)->trackParticle()->z0()) < 1.0 && + std::fabs(m_electrons->at(ElIdx)->trackParticle()->d0()) < 1.0) fJetD3PDTrkPtPVSums[iJet] -= trk.Pt(); } + + // we subtracted too much for some reason? + if (fJetD3PDTrkPtSums[iJet] < 0 || + fJetD3PDTrkPtPVSums[iJet] < 0) fJetJVFs[iJet] = 0; + // no tracks associated with the jet. + else if (fJetD3PDTrkPtSums[iJet] == 0) fJetJVFs[iJet] = -1; + // all good. recalculate JVF. + else fJetJVFs[iJet] = fJetD3PDTrkPtPVSums[iJet] / fJetD3PDTrkPtSums[iJet]; + } } -void TTBarElectronJetOverlap::AnalyzeEvent(const std::string &leptonDef) { +void TTBarElectronJetOverlap::AnalyzeEvent(const std::string& leptonDef) { FindAssocEls(); SubtractEls(); FindGoodObjects(); //RecalcJVF(); - // put the results back in place - size_t se = m_electrons->size(); - size_t sj = m_jets->size(); - for (size_t i = 0; i < sj; i++) { - m_jets->at(i)->setJetP4(xAOD::JetFourMom_t(fJetTLVs[i].Perp(), fJetTLVs[i].Eta(), fJetTLVs[i].Phi(), fJetTLVs[i].M())); - - if (fGoodJets[i]) m_jets->at(i)->auxdata<char>("passesFancyOR") = 1; // Subtracted jets that pass the OR test and are kept. - else m_jets->at(i)->auxdata<char>("passesFancyOR") = 0; - - if (fSubJets[i]==1) m_jets->at(i)->auxdata<char>("subtractedJet") = 1; // Jets close to electrons that undergo the OR test. - else m_jets->at(i)->auxdata<char>("subtractedJet") = 0; - - - //std::vector<float> newJVF; - //newJVF.push_back(fJetJVFs[i]); - //m_jets->at(i)->setAttribute<std::vector<float> >("JVF", newJVF); - if (fDebug) { - cout << " - (final) Jet # " << i << - " Pt Eta Phi M: " << - m_jets->at(i)->pt() << " " << - m_jets->at(i)->eta() << " " << - m_jets->at(i)->phi() << " " << - m_jets->at(i)->m() << " good " << (int) m_jets->at(i)->auxdata<char>(leptonDef.c_str())<< endl; - } + // put the results back in place + size_t se = m_electrons->size(); + size_t sj = m_jets->size(); + for (size_t i = 0; i < sj; i++) { + m_jets->at(i)->setJetP4(xAOD::JetFourMom_t(fJetTLVs[i].Perp(), fJetTLVs[i].Eta(), fJetTLVs[i].Phi(), + fJetTLVs[i].M())); + + if (fGoodJets[i]) m_jets->at(i)->auxdata<char>("passesFancyOR") = 1; // Subtracted + // jets + // that + // pass + // the + // OR + // test + // and + // are + // kept. + else m_jets->at(i)->auxdata<char>("passesFancyOR") = 0; + + if (fSubJets[i] == 1) m_jets->at(i)->auxdata<char>("subtractedJet") = 1; // Jets + // close + // to + // electrons + // that + // undergo + // the + // OR + // test. + else m_jets->at(i)->auxdata<char>("subtractedJet") = 0; + + + //std::vector<float> newJVF; + //newJVF.push_back(fJetJVFs[i]); + //m_jets->at(i)->setAttribute<std::vector<float> >("JVF", newJVF); + if (fDebug) { + cout << " - (final) Jet # " << i << + " Pt Eta Phi M: " << + m_jets->at(i)->pt() << " " << + m_jets->at(i)->eta() << " " << + m_jets->at(i)->phi() << " " << + m_jets->at(i)->m() << " good " << (int) m_jets->at(i)->auxdata<char>(leptonDef.c_str()) << endl; } + } - for (size_t j = 0; j < se; j++) { - if (!fGoodEls[j] || !fElGood[j]) { - m_electrons->at(j)->auxdata<char>(leptonDef.c_str()) = 0; - } else { - m_electrons->at(j)->auxdata<char>(leptonDef.c_str()) = 1; - } - - if (fDebug) { - cout << " - (final) El # " << j << - " Pt Eta Phi M: " << - m_electrons->at(j)->pt() << " " << - m_electrons->at(j)->eta() << " " << - m_electrons->at(j)->phi() << " " << - m_electrons->at(j)->m() << " good " << (int) m_electrons->at(j)->auxdata<char>(leptonDef.c_str()) << endl; - } + for (size_t j = 0; j < se; j++) { + if (!fGoodEls[j] || !fElGood[j]) { + m_electrons->at(j)->auxdata<char>(leptonDef.c_str()) = 0; + } else { + m_electrons->at(j)->auxdata<char>(leptonDef.c_str()) = 1; } -} - + if (fDebug) { + cout << " - (final) El # " << j << + " Pt Eta Phi M: " << + m_electrons->at(j)->pt() << " " << + m_electrons->at(j)->eta() << " " << + m_electrons->at(j)->phi() << " " << + m_electrons->at(j)->m() << " good " << (int) m_electrons->at(j)->auxdata<char>(leptonDef.c_str()) << endl; + } + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TopJetSubstructure.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TopJetSubstructure.cxx index d0ab71ef6c220fe734ec1ea134498c175cfc5dbc..ff7816b9ac69718ae433b4cebd15893f3fc7edb0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TopJetSubstructure.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/Root/TopJetSubstructure.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopJetSubstructure/TopJetSubstructure.h" @@ -17,4 +17,3 @@ top::TopJetSubstructure::~TopJetSubstructure() { void top::TopJetSubstructure::print(std::ostream& o) const { o << "TopJetSubstructure empty calss" << std::endl; } - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/ElectronInJetSubtractionAlgorithm.h b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/ElectronInJetSubtractionAlgorithm.h index 86161df3042d64c7cfea2265de29c9efc387fd85..584995d195f4b8a5ede0afb572ea18b282690675 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/ElectronInJetSubtractionAlgorithm.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/ElectronInJetSubtractionAlgorithm.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: ElectronInJetSubtractionAlgorithm.h 654856 2015-03-17 19:00:30Z dferreir $ #ifndef ANALYSISTOP_TOPJETSUBSTRUCTURE_ELECTRONINJETSUBTRACTIONALGORITHM_H @@ -10,25 +10,24 @@ #include "xAODJet/JetContainer.h" #include "TopJetSubstructure/TTBarElectronJetOverlap.h" -namespace top{ +namespace top { class ElectronInJetSubtractionAlgorithm final { - public: - ElectronInJetSubtractionAlgorithm(); - virtual ~ElectronInJetSubtractionAlgorithm(){} - - ElectronInJetSubtractionAlgorithm(const ElectronInJetSubtractionAlgorithm& rhs) = delete; - ElectronInJetSubtractionAlgorithm(ElectronInJetSubtractionAlgorithm&& rhs) = delete; - ElectronInJetSubtractionAlgorithm& operator=(const ElectronInJetSubtractionAlgorithm& rhs) = delete; - - void apply( xAOD::ElectronContainer* electrons , xAOD::JetContainer* jets , const bool useLooseElectrons=false ); - - private: - bool m_doLooseCuts; - // Pass selection strings - const std::string m_passPreORSelection; - const std::string m_passPreORSelectionLoose; + public: + ElectronInJetSubtractionAlgorithm(); + virtual ~ElectronInJetSubtractionAlgorithm() {} - TTBarElectronJetOverlap m_o; + ElectronInJetSubtractionAlgorithm(const ElectronInJetSubtractionAlgorithm& rhs) = delete; + ElectronInJetSubtractionAlgorithm(ElectronInJetSubtractionAlgorithm&& rhs) = delete; + ElectronInJetSubtractionAlgorithm& operator = (const ElectronInJetSubtractionAlgorithm& rhs) = delete; + + void apply(xAOD::ElectronContainer* electrons, xAOD::JetContainer* jets, const bool useLooseElectrons = false); + private: + bool m_doLooseCuts; + // Pass selection strings + const std::string m_passPreORSelection; + const std::string m_passPreORSelectionLoose; + + TTBarElectronJetOverlap m_o; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/LargeJetTrimmer.h b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/LargeJetTrimmer.h index a2e72fea55b66bc89351fcdf642ce196e4eafec5..b9005b8b2996a7e3b2107d0b6f17b978cd638f41 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/LargeJetTrimmer.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/LargeJetTrimmer.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef LARGEJETTRIMMER_H #define LARGEJETTRIMMER_H @@ -9,13 +9,12 @@ #include "TopJetSubstructure/TopJetSubstructure.h" namespace top { - /** * @brief JetCorrection-derived class that trims large-R jets while derivations are not ready. */ -class LargeJetTrimmer : public TopJetSubstructure { -public: + class LargeJetTrimmer: public TopJetSubstructure { + public: LargeJetTrimmer(); ~LargeJetTrimmer(); @@ -23,11 +22,8 @@ public: ///Useful messages on the screen. void print(std::ostream&) const; - -private: -}; - + private: + }; } #endif - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/SubjetMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/SubjetMaker.h index 9bf729325d3664e97a7fd780bca69779d69a8a10..d87d56bfc71d5ddc27515f8fdf3618d83b2b053f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/SubjetMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/SubjetMaker.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef SUBJETMAKER_H #define SUBJETMAKER_H @@ -9,13 +9,12 @@ #include "TopJetSubstructure/TopJetSubstructure.h" namespace top { - /** * @brief Derived class that constructs subjets while derivations are not ready. */ -class SubjetMaker : public TopJetSubstructure { -public: + class SubjetMaker: public TopJetSubstructure { + public: SubjetMaker(); ~SubjetMaker(); @@ -23,11 +22,8 @@ public: ///Useful messages on the screen. void print(std::ostream&) const; - -private: -}; - + private: + }; } #endif - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TTBarElectronJetOverlap.h b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TTBarElectronJetOverlap.h index d3a2c02772b33bee03c0eab0eb11b095a0fbfe69..e8221e3c9ddd49743ac44c220d69a9b4125ba637 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TTBarElectronJetOverlap.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TTBarElectronJetOverlap.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef __TTBARELECTRONJETOVERLAP_H__ #define __TTBARELECTRONJETOVERLAP_H__ @@ -14,60 +14,58 @@ #include "xAODEgamma/ElectronContainer.h" class TTBarElectronJetOverlap { - private: - std::vector<TLorentzVector> fJetTLVs; - std::vector<float> fJetJVFs; - std::vector<float> fJetD3PDTrkPtPVSums; - std::vector<float> fJetD3PDTrkPtSums; - - std::vector<bool> fGoodJets; - std::vector<int> fSubJets; - std::vector<std::set<int> > fJetAssocElCls; - - std::vector<TLorentzVector> fElTLVs; - std::vector<TLorentzVector> fOrigJetTLVs; - std::vector<TLorentzVector> fElClTLVs; - std::vector<bool> fElGood; // this registers if the electron passed the object definition - - std::vector<bool> fGoodEls; - std::vector<int> fElClAssocJet; - - bool fDebug; - - void FindAssocEls(); - void SubtractEls(); - void FindGoodObjects(); - void RecalcJVF(); - - - xAOD::JetContainer *m_jets; //! - xAOD::ElectronContainer *m_electrons; //! - - public: - TTBarElectronJetOverlap() : fDebug(false), m_jets(nullptr), m_electrons(nullptr) { - } - - ~TTBarElectronJetOverlap() { } - - void AnalyzeEvent(const std::string &leptonDef); - - // sets the debug level (info will print if set true). - void SetDebug(bool db) { - fDebug = db; - } - - bool GetDebug() { - return fDebug; - } - - // load all anti-kt 0.4 LCTopo jets in the event. - // these variables should correspond to the *corrected* jet - // quantities. Every jet in the D3PD should be passed. - // load selected electrons. - // these variables should only be filled for /selected/ - // electrons (i.e. pass ID and isolation cuts). - void Load(xAOD::JetContainer *jets, xAOD::ElectronContainer *electrons, const std::string &leptonDef); - +private: + std::vector<TLorentzVector> fJetTLVs; + std::vector<float> fJetJVFs; + std::vector<float> fJetD3PDTrkPtPVSums; + std::vector<float> fJetD3PDTrkPtSums; + + std::vector<bool> fGoodJets; + std::vector<int> fSubJets; + std::vector<std::set<int> > fJetAssocElCls; + + std::vector<TLorentzVector> fElTLVs; + std::vector<TLorentzVector> fOrigJetTLVs; + std::vector<TLorentzVector> fElClTLVs; + std::vector<bool> fElGood; // this registers if the electron passed the object definition + + std::vector<bool> fGoodEls; + std::vector<int> fElClAssocJet; + + bool fDebug; + + void FindAssocEls(); + void SubtractEls(); + void FindGoodObjects(); + void RecalcJVF(); + + + xAOD::JetContainer* m_jets; //! + xAOD::ElectronContainer* m_electrons; //! +public: + TTBarElectronJetOverlap() : fDebug(false), m_jets(nullptr), m_electrons(nullptr) { + } + + ~TTBarElectronJetOverlap() { } + + void AnalyzeEvent(const std::string& leptonDef); + + // sets the debug level (info will print if set true). + void SetDebug(bool db) { + fDebug = db; + } + + bool GetDebug() { + return fDebug; + } + + // load all anti-kt 0.4 LCTopo jets in the event. + // these variables should correspond to the *corrected* jet + // quantities. Every jet in the D3PD should be passed. + // load selected electrons. + // these variables should only be filled for /selected/ + // electrons (i.e. pass ID and isolation cuts). + void Load(xAOD::JetContainer* jets, xAOD::ElectronContainer* electrons, const std::string& leptonDef); }; #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TopJetSubstructure.h b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TopJetSubstructure.h index c9a916c747c536054df12f49f3f0cce9d0a8fe61..271b76074c4b17b47967475a066aeb4471b712cc 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TopJetSubstructure.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure/TopJetSubstructure/TopJetSubstructure.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPJETSUBSTRUCTURE_H #define TOPJETSUBSTRUCTURE_H @@ -8,25 +8,21 @@ #include "xAODJet/JetContainer.h" namespace top { - /** * @brief JetCorrection-derived class that applies a jet substructure action on the object */ -class TopJetSubstructure { -public: + class TopJetSubstructure { + public: TopJetSubstructure(); - ~TopJetSubstructure(); + virtual ~TopJetSubstructure(); virtual void correctJet(xAOD::Jet& /*jet*/) = 0; ///Useful messages on the screen. void print(std::ostream&) const; - -private: -}; - + private: + }; } #endif - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/CMakeLists.txt index 421048d9bed4a809e74359fd5e77c4154d8fbf36..139045ae49939d7bc94c4bd364e11580f0cbe6f7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopObjectSelectionTools ) @@ -11,29 +10,38 @@ atlas_depends_on_subdirs( PUBLIC xAODMuon xAODTau xAODTracking + FourMomUtils ElectronPhotonSelectorTools - MuonSelectorTools + TopDataPreparation TopEvent TopSystematicObjectMaker AssociationUtils + TrigBunchCrossingTool TrigConfInterfaces TrigDecisionTool TriggerMatchingTool TrigTauMatching + TriggerAnalysisInterfaces + #TrigGlobalEfficiencyCorrection GoodRunsLists - JetJvtEfficiency - xAODBTaggingEfficiency + InDetTrackSelectionTool + JetAnalysisInterfaces JetSubStructureMomentTools JetSubStructureUtils - JetReclustering ) + JetReclustering + #BoostedJetTaggers + MuonAnalysisInterfaces + FTagAnalysisInterfaces + JetAnalysisInterfaces + PATCore) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopObjectSelectionTools _cintDictSource - ROOT_HEADERS TopObjectSelectionTools/RCJetMC15.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopObjectSelectionTools Root/*.cxx Root/*.h Root/*.icc @@ -47,22 +55,29 @@ atlas_add_library( TopObjectSelectionTools Root/*.cxx Root/*.h Root/*.icc xAODMuon xAODTau xAODTracking + FourMomUtils ElectronPhotonSelectorToolsLib - MuonSelectorToolsLib TopEvent TopSystematicObjectMaker AssociationUtilsLib + TrigBunchCrossingTool TrigConfInterfaces TrigDecisionToolLib TriggerMatchingToolLib TrigTauMatchingLib + #TrigGlobalEfficiencyCorrectionLib GoodRunsListsLib - JetJvtEfficiencyLib - xAODBTaggingEfficiencyLib + InDetTrackSelectionToolLib + JetAnalysisInterfacesLib JetSubStructureMomentToolsLib JetSubStructureUtils JetReclusteringLib - ${ROOT_LIBRARIES} + #BoostedJetTaggersLib + MuonAnalysisInterfacesLib + FTagAnalysisInterfacesLib + JetAnalysisInterfacesLib + PATCoreLib + ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) # Install data files from the package: diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/AntiMuonMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/AntiMuonMC15.cxx index aee050b03609b73aa818bcf0263f8457ec3420df..979bd53901cd55562e1a374f29ea2eb4957be8fe 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/AntiMuonMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/AntiMuonMC15.cxx @@ -1,69 +1,61 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -#include "TopObjectSelectionTools/AntiMuonMC15.h" - -#include "TopEvent/EventTools.h" - -namespace top { - -AntiMuonMC15::AntiMuonMC15(const double ptcut, IsolationBase* /* isolation */) : - m_ptcut(ptcut), - m_muonSelectionTool("CP::MuonSelectionTool") - //m_muonSelectionToolLoose("CP::MuonSelectionToolLoose"), - //m_isolation(isolation) -{ - top::check( m_muonSelectionTool.retrieve() , "Failed to retrieve muonSelectionTool" ); -// top::check( m_muonSelectionToolLoose.retrieve() , "Failed to retrieve muonSelectionToolLoose" ); -} - -bool AntiMuonMC15::passSelection(const xAOD::Muon& mu) const -{ - if (mu.pt() < m_ptcut) - return false; - - ///-- https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15 --/// - if (!m_muonSelectionTool->accept(mu)) - return false; - - - if (mu.energyLossType()!=xAOD::Muon::NotIsolated) return false; - float eloss=0; - bool ok=mu.parameter(eloss,xAOD::Muon::EnergyLoss); - if (ok && eloss>6000) return false; - float etcone20=0,ptvarcone40=0; - ok=mu.isolation(etcone20,xAOD::Iso::etcone20); - if (ok && etcone20/mu.pt()<0.03) return false; - //if (mu.auxdataConst<float>("miniIso")/mu.pt() > .1) return false; - ok=mu.isolation(ptvarcone40,xAOD::Iso::ptvarcone40); - if (ok && ptvarcone40/mu.pt()>0.1) return false; - - return true; -} - -bool AntiMuonMC15::passSelectionLoose(const xAOD::Muon& /*mu*/) const -{ - - // code does not compile without this function - - return true; -} - - void AntiMuonMC15::print(std::ostream& os) const { - os << "AntiMuonMC15\n" - << " * pT > " << m_ptcut << "\n" -// << " * |eta| < " << m_etamax << "\n" -// << " * quality=" << m_quality << " (tight=0, medium=1, loose=2, v.loose=3)\n" - << " * Everything else from muon tool - fill this in?\n"; - -// if (!m_isolation) -// os << " * No isolation requirement\n"; -// else -// m_isolation->print(os); - } - - - -} - +#include "TopObjectSelectionTools/AntiMuonMC15.h" + +#include "TopEvent/EventTools.h" + +namespace top { + AntiMuonMC15::AntiMuonMC15(const double ptcut, IsolationBase* /* isolation */) : + m_ptcut(ptcut), + m_muonSelectionTool("CP::MuonSelectionTool") { + //m_muonSelectionToolLoose("CP::MuonSelectionToolLoose"), + //m_isolation(isolation) + top::check(m_muonSelectionTool.retrieve(), "Failed to retrieve muonSelectionTool"); +// top::check( m_muonSelectionToolLoose.retrieve() , "Failed to retrieve muonSelectionToolLoose" ); + } + + bool AntiMuonMC15::passSelection(const xAOD::Muon& mu) const { + if (mu.pt() < m_ptcut) return false; + + ///-- https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15 --/// + if (!m_muonSelectionTool->accept(mu)) return false; + + + if (mu.energyLossType() != xAOD::Muon::NotIsolated) return false; + + float eloss = 0; + bool ok = mu.parameter(eloss, xAOD::Muon::EnergyLoss); + if (ok && eloss > 6000) return false; + + float etcone20 = 0, ptvarcone40 = 0; + ok = mu.isolation(etcone20, xAOD::Iso::etcone20); + if (ok && etcone20 / mu.pt() < 0.03) return false; + + //if (mu.auxdataConst<float>("miniIso")/mu.pt() > .1) return false; + ok = mu.isolation(ptvarcone40, xAOD::Iso::ptvarcone40); + if (ok && ptvarcone40 / mu.pt() > 0.1) return false; + + return true; + } + + bool AntiMuonMC15::passSelectionLoose(const xAOD::Muon& /*mu*/) const { + // code does not compile without this function + + return true; + } + + void AntiMuonMC15::print(std::ostream& os) const { + os << "AntiMuonMC15\n" + << " * pT > " << m_ptcut << "\n" +// << " * |eta| < " << m_etamax << "\n" +// << " * quality=" << m_quality << " (tight=0, medium=1, loose=2, v.loose=3)\n" + << " * Everything else from muon tool - fill this in?\n"; + +// if (!m_isolation) +// os << " * No isolation requirement\n"; +// else +// m_isolation->print(os); + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronCutBasedMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronCutBasedMC15.cxx index ce47f1b7edb7e893f3450d303182e9203c4ae397..c9f99cc96ef4f5828575085fab5a502bccdaf9a4 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronCutBasedMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronCutBasedMC15.cxx @@ -1,53 +1,44 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/ElectronCutBasedMC15.h" namespace top { - -ElectronCutBasedMC15::ElectronCutBasedMC15(double ptcut, bool vetoCrack, const std::string& quality, const std::string& qualityLoose, IsolationBase* isolation) : + ElectronCutBasedMC15::ElectronCutBasedMC15(double ptcut, bool vetoCrack, const std::string& quality, + const std::string& qualityLoose, IsolationBase* isolation) : m_ptcut(ptcut), m_vetoCrack(vetoCrack), m_quality(quality), m_qualityLoose(qualityLoose), - m_isolation(isolation) -{ -} + m_isolation(isolation) { + } -bool ElectronCutBasedMC15::passSelection(const xAOD::Electron& el) const { + bool ElectronCutBasedMC15::passSelection(const xAOD::Electron& el) const { + if (!passSelectionNoIsolation(el, m_quality)) return false; - if (!passSelectionNoIsolation(el, m_quality)) - return false; + if (m_isolation && !m_isolation->passSelection(el)) return false; - if (m_isolation && !m_isolation->passSelection(el)) - return false; - return true; -} - -bool ElectronCutBasedMC15::passSelectionLoose(const xAOD::Electron& el) const { + } - if (!passSelectionNoIsolation(el, m_qualityLoose)) - return false; + bool ElectronCutBasedMC15::passSelectionLoose(const xAOD::Electron& el) const { + if (!passSelectionNoIsolation(el, m_qualityLoose)) return false; - if (m_isolation && !m_isolation->passSelectionLoose(el)) - return false; + if (m_isolation && !m_isolation->passSelectionLoose(el)) return false; return true; -} + } -bool ElectronCutBasedMC15::passSelectionNoIsolation(const xAOD::Electron& el, const std::string& quality) const { + bool ElectronCutBasedMC15::passSelectionNoIsolation(const xAOD::Electron& el, const std::string& quality) const { // if (el.author() != xAOD::EgammaParameters::AuthorElectron && el.author() != xAOD::EgammaParameters::AuthorSofte) // return false; - if (el.pt() < m_ptcut) - return false; + if (el.pt() < m_ptcut) return false; // This will be replaced with the proper AsgElectronIsEMSelector // Once the calib files are on afs (cvmfs?) - not there yet..... - if (!el.passSelection(quality)) - return false; + if (!el.passSelection(quality)) return false; //WARNING: Not all electrons keep clusters in the derivation //i.e. bad electrons (which is why we moved the check on the quality @@ -55,26 +46,22 @@ bool ElectronCutBasedMC15::passSelectionNoIsolation(const xAOD::Electron& el, co //Good electrons should always have a cluster, if not then crash to warn us //Better than checking and silently doing nothing... //This stops a crash - if (std::fabs(el.caloCluster()->etaBE(2)) > 2.47) - return false; + if (std::fabs(el.caloCluster()->etaBE(2)) > 2.47) return false; - if (m_vetoCrack && std::fabs(el.caloCluster()->etaBE(2)) > 1.37 && std::fabs(el.caloCluster()->etaBE(2)) < 1.52) - return false; + if (m_vetoCrack && std::fabs(el.caloCluster()->etaBE(2)) > 1.37 && + std::fabs(el.caloCluster()->etaBE(2)) < 1.52) return false; return true; -} + } -void ElectronCutBasedMC15::print(std::ostream& os) const { + void ElectronCutBasedMC15::print(std::ostream& os) const { os << "ElectronCutBasedMC15\n"; os << " * pT > " << m_ptcut << "\n"; os << " * Currently disabled --- |cluster_eta| < 2.47 \n"; os << " * Veto 1.37 < |cluster_eta| < 1.52? " << std::boolalpha << m_vetoCrack << "\n"; os << " * Quality " << m_quality << "\n"; - if (!m_isolation) - os << " * No isolation requirement\n"; - else - m_isolation->print(os); -} - + if (!m_isolation) os << " * No isolation requirement\n"; + else m_isolation->print(os); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronLikelihoodMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronLikelihoodMC15.cxx index b8bf1093b8eda3c2cf170977ef89792c2c370a6e..7ebaf17b876794f0da3e80b72027574130db67eb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronLikelihoodMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronLikelihoodMC15.cxx @@ -1,16 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/ElectronLikelihoodMC15.h" #include "TopEvent/EventTools.h" -#include "ElectronPhotonSelectorTools/AsgElectronChargeIDSelectorTool.h" +//#include "ElectronPhotonSelectorTools/AsgElectronChargeIDSelectorTool.h" +#include "ElectronPhotonSelectorTools/ElectronSelectorHelpers.h" #include <iostream> -namespace top { +#include "TopObjectSelectionTools/MsgCategory.h" +using namespace TopObjectSelectionTools; - ElectronLikelihoodMC15::ElectronLikelihoodMC15(const double ptcut, const bool vetoCrack, const std::string& operatingPoint, - const std::string& operatingPointLoose, StandardIsolation* isolation, const bool applyTTVACut) : +namespace top { + ElectronLikelihoodMC15::ElectronLikelihoodMC15(const double ptcut, const bool vetoCrack, + const std::string& operatingPoint, + const std::string& operatingPointLoose, StandardIsolation* isolation, + const bool applyTTVACut, const bool applyChargeIDCut) : m_ptcut(ptcut), m_vetoCrack(vetoCrack), m_operatingPoint("SetMe"), @@ -19,192 +24,195 @@ namespace top { m_operatingPointLoose_DF("SetMe"), m_isolation(isolation), m_applyTTVACut(applyTTVACut), - m_applyChargeIDCut(false) - { + m_applyChargeIDCut(applyChargeIDCut) { /** Egamma use different naming styles for the likelihood in: - * Trigger = HLT_e24_lhmedium_iloose_L1EM20VH HLT_e60_lhmedium - * Derivation Framework = DFCommonElectronsLHMedium - * ElectronPhotonSelectionTools (the LLH tools) = ElectronLikelihoodMediumOfflineConfig2015.conf - * Trigger SF = efficiencySF.e24vhi_medium1_e60_medium1.MediumLLH.2015.13TeV.rel20p0.v02.root - * Trigger SF = efficiencySF.AnyElectronTrigger.MediumLH.2015.13TeV.rel20p0.v01.root - * ID SF = efficiencySF.offline.MediumLH.2015.13TeV.rel20p0.v01.root - * - * It's a bit of a mess - */ - + * Trigger = HLT_e24_lhmedium_iloose_L1EM20VH HLT_e60_lhmedium + * Derivation Framework = DFCommonElectronsLHMedium + * ElectronPhotonSelectionTools (the LLH tools) = ElectronLikelihoodMediumOfflineConfig2015.conf + * Trigger SF = efficiencySF.e24vhi_medium1_e60_medium1.MediumLLH.2015.13TeV.rel20p0.v02.root + * Trigger SF = efficiencySF.AnyElectronTrigger.MediumLH.2015.13TeV.rel20p0.v01.root + * ID SF = efficiencySF.offline.MediumLH.2015.13TeV.rel20p0.v01.root + * + * It's a bit of a mess + */ + std::string egammaNamesAreNotConsistantAnywhere("LikelihoodNotSetProperly"); std::string egammaNamesAreNotConsistantAnywhereLoose("LikelihoodNotSetProperly"); - if (operatingPoint == "LooseLH") {egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHLoose";} - if (operatingPoint == "LooseAndBLayerLH") {egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHLoose";} - if (operatingPoint == "MediumLH") {egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHMedium";} - if (operatingPoint == "TightLH") {egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHTight";} - - if (operatingPointLoose == "LooseLH") {egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHLoose";} - if (operatingPointLoose == "LooseAndBLayerLH") {egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHLoose";} - if (operatingPointLoose == "MediumLH") {egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHMedium";} - if (operatingPointLoose == "TightLH") {egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHTight";} - - m_operatingPoint_DF = egammaNamesAreNotConsistantAnywhere; - m_operatingPointLoose_DF = egammaNamesAreNotConsistantAnywhereLoose; - m_operatingPoint = operatingPoint; - m_operatingPointLoose = operatingPointLoose; + if (operatingPoint == "LooseLH") { + egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHLoose"; + } + if (operatingPoint == "LooseAndBLayerLH") { + egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHLooseBL"; + } + if (operatingPoint == "MediumLH") { + egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHMedium"; + } + if (operatingPoint == "TightLH") { + egammaNamesAreNotConsistantAnywhere = "DFCommonElectronsLHTight"; + } + + if (operatingPointLoose == "LooseLH") { + egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHLoose"; + } + if (operatingPointLoose == "LooseAndBLayerLH") { + egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHLooseBL"; + } + if (operatingPointLoose == "MediumLH") { + egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHMedium"; + } + if (operatingPointLoose == "TightLH") { + egammaNamesAreNotConsistantAnywhereLoose = "DFCommonElectronsLHTight"; + } - // currently implemented only for this working point - if (m_operatingPoint == "MediumLH" && m_isolation->tightLeptonIsolation() == "FixedCutTight") - m_applyChargeIDCut = true; + m_operatingPoint_DF = egammaNamesAreNotConsistantAnywhere; + m_operatingPointLoose_DF = egammaNamesAreNotConsistantAnywhereLoose; + m_operatingPoint = operatingPoint; + m_operatingPointLoose = operatingPointLoose; } ElectronLikelihoodMC15::ElectronLikelihoodMC15(const bool, - const double ptcut, const bool vetoCrack, const std::string& operatingPoint, - const std::string& operatingPointLoose, StandardIsolation* isolation, const bool applyTTVACut) : - ElectronLikelihoodMC15::ElectronLikelihoodMC15(ptcut, vetoCrack, operatingPoint, - operatingPointLoose, isolation, applyTTVACut) {} + const double ptcut, const bool vetoCrack, + const std::string& operatingPoint, + const std::string& operatingPointLoose, StandardIsolation* isolation, + const bool applyTTVACut, const bool applyChargeIDCut) : + ElectronLikelihoodMC15::ElectronLikelihoodMC15(ptcut, vetoCrack, operatingPoint, + operatingPointLoose, isolation, applyTTVACut, applyChargeIDCut) {} bool ElectronLikelihoodMC15::passSelection(const xAOD::Electron& el) const { - if (!passSelectionNoIsolation(el, m_operatingPoint_DF, m_operatingPoint)) - return false; + if (!passSelectionNoIsolation(el, m_operatingPoint_DF, m_operatingPoint)) return false; - if (m_isolation && !m_isolation->passSelection(el)) - return false; + if (m_isolation && !m_isolation->passSelection(el)) return false; return true; } bool ElectronLikelihoodMC15::passSelectionLoose(const xAOD::Electron& el) const { - if (!passSelectionNoIsolation(el, m_operatingPointLoose_DF, m_operatingPointLoose)) - return false; + if (!passSelectionNoIsolation(el, m_operatingPointLoose_DF, m_operatingPointLoose)) return false; - if (m_isolation && !m_isolation->passSelectionLoose(el)) - return false; + if (m_isolation && !m_isolation->passSelectionLoose(el)) return false; return true; } - bool ElectronLikelihoodMC15::passSelectionNoIsolation(const xAOD::Electron& el, const std::string& operatingPoint_DF, const std::string& operatingPoint) const { + bool ElectronLikelihoodMC15::passSelectionNoIsolation(const xAOD::Electron& el, const std::string& operatingPoint_DF, + const std::string& operatingPoint) const { + if (el.pt() < m_ptcut) return false; - if (el.pt() < m_ptcut) - return false; + // removing bad electron cluser - see + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/EGammaIdentificationRun2#Bad_Electron_Photon_Cluster + if (!el.isGoodOQ(xAOD::EgammaParameters::BADCLUSELECTRON)) return false; - // removing bad electron cluser - see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/EGammaIdentificationRun2#Bad_Electron_Photon_Cluster - if( !el.isGoodOQ(xAOD::EgammaParameters::BADCLUSELECTRON) ) return false; + // Try to catch instances for derivations using a different type for this variable + try { + if (el.auxdataConst<int>(operatingPoint_DF) != 1) return false; + } + catch (const SG::ExcAuxTypeMismatch& e) { + if (el.auxdataConst<char>(operatingPoint_DF) != 1) return false; + } + + if (operatingPoint == "LooseAndBLayerLH") { + if (!passBLayerCuts(el)) return false; + } + //WARNING: There has been a bug previously in our derivations where looseLH failed, but tighter WP succeed + //WARNING: This results in a "good" electron with no clusters (due to thinning), and then we crash and burn + //WARNING: We are therefore going to test whether the looseLH WP is also passed before we check the cluster eta + //WARNING: If it does not (and we passed ID checks above) then this is a dodgy electron + //WARNING: So we print a warning to alert the user that this was found, but then we proceed as normal + //WARNING: and this electron is vetoed from the selection try { - if (el.auxdataConst<int>(operatingPoint_DF) != 1) + if (el.auxdataConst<int>("DFCommonElectronsLHLoose") != 1) { + ATH_MSG_ERROR("This electron fails the DFCommonElectronsLHLoose and has an incorrect decoration.\n pt (" + << el.pt() << "), eta (" << el.eta() << ")"); return false; - } catch(std::exception& e) { - if (el.auxdataConst<char>(operatingPoint_DF) != 1) + } + } + catch (const SG::ExcAuxTypeMismatch& e) { + if (el.auxdataConst<char>("DFCommonElectronsLHLoose") != 1) { + ATH_MSG_ERROR("This electron fails the DFCommonElectronsLHLoose and has an incorrect decoration.\n pt (" + << el.pt() << "), eta (" << el.eta() << ")"); return false; + } } - if(operatingPoint == "LooseAndBLayerLH"){ - - if(!passBLayerCuts(el)) - return false; - - } - //WARNING: Not all electrons keep clusters in the derivation //i.e. bad electrons (which is why we moved the check on the likelihood //before the check on the calo cluster) //This stops a crash //Good electrons should always have a cluster, if not then crash to warn us //Better than checking and silently doing nothing... - if (std::fabs(el.caloCluster()->etaBE(2)) > 2.47) - return false; + if (std::fabs(el.caloCluster()->etaBE(2)) > 2.47) return false; - if (m_vetoCrack && std::fabs(el.caloCluster()->etaBE(2)) > 1.37 && std::fabs(el.caloCluster()->etaBE(2)) < 1.52) - return false; + //Veto electrons suffering from the 2015+2016/mc16a crack+topocluster association bug + //See https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/HowToCleanJets2017#EGamma_Crack_Electron_topocluste for details + if (el.isAvailable<char>("DFCommonCrackVetoCleaning")) + if (!el.auxdataConst<char>("DFCommonCrackVetoCleaning")) return false; + + if (m_vetoCrack && std::fabs(el.caloCluster()->etaBE(2)) > 1.37 && + std::fabs(el.caloCluster()->etaBE(2)) < 1.52) return false; // Track-to-vertex association - if (m_applyTTVACut){ - if (!passTTVACuts(el)) - return false; + if (m_applyTTVACut) { + if (!passTTVACuts(el)) return false; } // Electron Charge ID Selector Tool // apply decoration only - if (m_applyChargeIDCut && !passChargeIDCut(el)) - el.auxdecor<char>("passChargeID") = 0; - else - el.auxdecor<char>("passChargeID") = 1; - + if (m_applyChargeIDCut && !passChargeIDCut(el)) el.auxdecor<char>("passChargeID") = 0; + else el.auxdecor<char>("passChargeID") = 1; + return true; } -bool ElectronLikelihoodMC15::passBLayerCuts(const xAOD::Electron& el) const -{ - - // this is taken from ElectronPhotonSelectorTools/Root/AsgElectronLikelihoodTool.cxx - const xAOD::TrackParticle* t = el.trackParticle(); - - if (!t) return false; - - uint8_t expectBlayer(true); - uint8_t nBlayerHits(0); - uint8_t nBlayerOutliers(0); - - t -> summaryValue(expectBlayer, xAOD::expectBLayerHit); - t -> summaryValue(nBlayerHits, xAOD::numberOfBLayerHits); - t -> summaryValue(nBlayerOutliers, xAOD::numberOfBLayerOutliers); - - if(expectBlayer && (nBlayerHits+nBlayerOutliers) < 1) return false; - else return true; - -} - -bool ElectronLikelihoodMC15::passTTVACuts(const xAOD::Electron& el) const -{ + bool ElectronLikelihoodMC15::passBLayerCuts(const xAOD::Electron& el) const { - // TTVA: - // see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TrackingCPEOYE2015#Track_to_Vertex_Association - if( !el.isAvailable<float>("d0sig") ){ - std::cout << "d0 significance not found for electron. " - << "Maybe no primary vertex? Won't accept." << std::endl; - return false; + const xAOD::TrackParticle* t = el.trackParticle(); + return ElectronSelectorHelpers::passBLayerRequirement(t); } - - float d0sig = el.auxdataConst<float>("d0sig"); - if( std::abs(d0sig) >= 5 ) - return false; - - if( !el.isAvailable<float>("delta_z0_sintheta") ){ - std::cout << "delta z0*sin(theta) not found for electron. " - << "Maybe no primary vertex? Won't accept." << std::endl; - return false; + + bool ElectronLikelihoodMC15::passTTVACuts(const xAOD::Electron& el) const { + // TTVA: + // see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TrackingCPEOYE2015#Track_to_Vertex_Association + if (!el.isAvailable<float>("d0sig")) { + ATH_MSG_WARNING("d0 significance not found for electron. Maybe no primary vertex? Won't accept."); + return false; + } + + float d0sig = el.auxdataConst<float>("d0sig"); + if (std::abs(d0sig) >= 5) return false; + + if (!el.isAvailable<float>("delta_z0_sintheta")) { + ATH_MSG_WARNING("delta z0*sin(theta) not found for electron. Maybe no primary vertex? Won't accept."); + return false; + } + + float delta_z0_sintheta = el.auxdataConst<float>("delta_z0_sintheta"); + if (std::abs(delta_z0_sintheta) >= 0.5) return false; + + return true; } - - float delta_z0_sintheta = el.auxdataConst<float>("delta_z0_sintheta"); - if( std::abs(delta_z0_sintheta) >= 0.5 ) - return false; - - return true; - -} -bool ElectronLikelihoodMC15::passChargeIDCut(const xAOD::Electron& el) const -{ + bool ElectronLikelihoodMC15::passChargeIDCut(const xAOD::Electron& el) const { + static const SG::AuxElement::ConstAccessor<char> acc_ECIDS("DFCommonElectronsECIDS"); - // Electron Charge ID Selector Tool - // see https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/ElectronChargeFlipTaggerTool - if ( asg::ToolStore::contains<AsgElectronChargeIDSelectorTool> ("ECIDS_medium") ) { - AsgElectronChargeIDSelectorTool* electronChargeIDSelectorTool = asg::ToolStore::get<AsgElectronChargeIDSelectorTool> ("ECIDS_medium"); - if (!electronChargeIDSelectorTool->accept(el)) return false; + top::check(acc_ECIDS.isAvailable( + el), "ElectronLikelihoodMC15::passChargeIDCut: DFCommonElectronsECIDS is not available"); + return acc_ECIDS(el) ? true : false; } - return true; -} void ElectronLikelihoodMC15::print(std::ostream& os) const { - os << "ElectronLikelihoodMC15\n"; - os << " * pT > " << m_ptcut << "\n"; - os << " * Currently disabled --- |cluster_eta| < 2.47 \n"; - os << " * Veto 1.37 < |cluster_eta| < 1.52? " << std::boolalpha << m_vetoCrack << "\n"; - if (!m_isolation) { - os << " * No isolation requirement\n"; - } else { - m_isolation->print(os); - } - os << " * LH Tool Operating Point: " << m_operatingPoint_DF << " \t\t LH Tool Loose Operating Point: " <<m_operatingPointLoose_DF << " \n"; + os << "ElectronLikelihoodMC15\n"; + os << " * pT > " << m_ptcut << "\n"; + os << " * Currently disabled --- |cluster_eta| < 2.47 \n"; + os << " * Veto 1.37 < |cluster_eta| < 1.52? " << std::boolalpha << m_vetoCrack << "\n"; + if (!m_isolation) { + os << " * No isolation requirement\n"; + } else { + m_isolation->print(os); + } + os << " * LH Tool Operating Point: " << m_operatingPoint_DF << " \t\t LH Tool Loose Operating Point: " << + m_operatingPointLoose_DF << " \n"; } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronSelectionBase.cxx index a4aed6c324cf7fb44911ddef60a0138d630632f0..0c9df9486517aee67dfd5970c34b0fb9ce05affd 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronSelectionBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/ElectronSelectionBase.cxx @@ -1,22 +1,20 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/ElectronSelectionBase.h" #include <iostream> namespace top { + ElectronSelectionBase::ElectronSelectionBase() { + } -ElectronSelectionBase::ElectronSelectionBase() { -} - -ElectronSelectionBase::~ElectronSelectionBase() { -} - -} + ElectronSelectionBase::~ElectronSelectionBase() { + } -std::ostream& operator<<(std::ostream& os, const top::ElectronSelectionBase& selection) { + std::ostream& operator << (std::ostream& os, const top::ElectronSelectionBase& selection) { selection.print(os); return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/EventCleaningSelection.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/EventCleaningSelection.cxx index f5c228878c0ee0f8b063b8edcfca9924b00ab81a..0e9dbd615759ccc78f6fdfd61f00b0b5597cf57f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/EventCleaningSelection.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/EventCleaningSelection.cxx @@ -1,8 +1,7 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ -// $Id: EventCleaningSelection.cxx 802748 2017-04-11 20:29:03Z iconnell $ #include "TopObjectSelectionTools/EventCleaningSelection.h" #include "TopEvent/EventTools.h" #include "TopConfiguration/TopConfig.h" @@ -13,15 +12,17 @@ #include "xAODMuon/MuonContainer.h" #include "xAODTau/TauJetContainer.h" #include "xAODTracking/VertexContainer.h" +//#include "TrigGlobalEfficiencyCorrection/ImportData.h" +#include <algorithm> #include <sstream> #include <list> +#include <boost/algorithm/string.hpp> namespace top { - - EventCleaningSelection::EventCleaningSelection( const std::string& name ) : - asg::AsgTool( name ), + EventCleaningSelection::EventCleaningSelection(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), m_grlTool("GoodRunsListSelectionTool"), @@ -30,99 +31,288 @@ namespace top { m_trigDecisionTool("Trig::TrigDecisionTool"), m_trigMatchTool("Trig::MatchingTool"), m_trigMatchTauTool("Trig::TrigTauMatchingTool"), + m_globalTriggerSF("TrigGlobalEfficiencyCorrectionTool::TrigGlobal"), + m_globalTriggerSFLoose("TrigGlobalEfficiencyCorrectionTool::TrigGlobalLoose"), m_vetoEventsTrigger(false), m_vetoEventsGRL(false), m_vetoEventsGoodCalo(false), - m_vetoEventsPriVtx(false) { - declareProperty( "config" , m_config ); + m_vetoEventsPriVtx(true) { + declareProperty("config", m_config); - declareProperty( "GRLTool" , m_grlTool ); + declareProperty("GRLTool", m_grlTool); - declareProperty( "TrigConfigTool", m_trigConfTool ); - declareProperty( "TrigDecisionTool", m_trigDecisionTool ); - declareProperty( "TrigMatchTool", m_trigMatchTool ); - declareProperty( "TrigMatchTauTool" , m_trigMatchTauTool ); + declareProperty("TrigConfigTool", m_trigConfTool); + declareProperty("TrigDecisionTool", m_trigDecisionTool); + declareProperty("TrigMatchTool", m_trigMatchTool); + declareProperty("TrigMatchTauTool", m_trigMatchTauTool); } - StatusCode EventCleaningSelection::initilize() - { + StatusCode EventCleaningSelection::initialize() { // If running on a Truth DxAOD we don't need anything so // just return successfully... if (m_config->isTruthDxAOD()) return StatusCode::SUCCESS; - top::check( m_trigConfTool.retrieve() , "Failed to retrieve TrigConfTool" ); - top::check( m_trigDecisionTool.retrieve() , "Failed to retrieve TrigDecisionTool" ); - top::check( m_trigMatchTool.retrieve(), - "Failed to retrieve trigger matching tool"); - if (m_config->useTaus()) - top::check(m_trigMatchTauTool.retrieve(), - "Failed to retrieve TrigMatchTauTool" ); + top::check(m_trigConfTool.retrieve(), "Failed to retrieve TrigConfTool"); + top::check(m_trigDecisionTool.retrieve(), "Failed to retrieve TrigDecisionTool"); + top::check(m_trigMatchTool.retrieve(), + "Failed to retrieve trigger matching tool"); + if (m_config->useTaus()) top::check(m_trigMatchTauTool.retrieve(), + "Failed to retrieve TrigMatchTauTool"); if (!m_config->isMC()) { - top::check( m_grlTool.retrieve() , "Failed to retrieve TrigDecisionTool" ); + top::check(m_grlTool.retrieve(), "Failed to retrieve TrigDecisionTool"); } + m_vetoEventsPriVtx = m_config->demandPriVtx(); + return StatusCode::SUCCESS; } - void EventCleaningSelection::setEventSelections( const std::vector<top::SelectionConfigurationData>& selections ) - { - std::list<std::string> tmpAllTriggers; + void EventCleaningSelection::setEventSelections(const std::vector<top::SelectionConfigurationData>& selections) { + std::unordered_set<std::string> tmpAllTriggers_Tight; + std::unordered_set<std::string> tmpAllTriggers_Loose; + + // get full list of global triggers + std::vector<std::string> globalTriggers_Tight; + std::vector<std::string> globalTriggers_Loose; + std::vector<std::string> globalElectronTriggers_Tight; + std::vector<std::string> globalElectronTriggers_Loose; + std::vector<std::string> globalMuonTriggers_Tight; + std::vector<std::string> globalMuonTriggers_Loose; + if (m_config->useGlobalTrigger()) { + std::set<std::string> tmp; + for (auto const& triggermap : {m_config->getGlobalTriggers()}) { + for (auto const& pair : triggermap) { + auto const& triggers = getIndividualFromGlobalTriggers(pair.second); + tmp.insert(triggers.begin(), triggers.end()); + } + } + globalTriggers_Tight.assign(tmp.begin(), tmp.end()); + for (std::string const& trigger : globalTriggers_Tight) { + if (isElectronTrigger(trigger)) globalElectronTriggers_Tight.push_back(trigger); + if (isMuonTrigger(trigger)) globalMuonTriggers_Tight.push_back(trigger); + } + tmp.clear(); + // and the usual copy-paste-s/Tight/Loose/g story: + for (auto const& triggermap : {m_config->getGlobalTriggersLoose()}) { + for (auto const& pair : triggermap) { + auto const& triggers = getIndividualFromGlobalTriggers(pair.second); + tmp.insert(triggers.begin(), triggers.end()); + } + } + globalTriggers_Loose.assign(tmp.begin(), tmp.end()); + for (std::string const& trigger : globalTriggers_Loose) { + if (isElectronTrigger(trigger)) globalElectronTriggers_Loose.push_back(trigger); + if (isMuonTrigger(trigger)) globalMuonTriggers_Loose.push_back(trigger); + } + } - m_allTriggers.clear(); - m_electronTriggers.clear(); - m_muonTriggers.clear(); - m_tauTriggers.clear(); + m_allTriggers_Tight.clear(); + m_electronTriggers_Tight.clear(); + m_muonTriggers_Tight.clear(); + m_tauTriggers_Tight.clear(); + m_allTriggers_Loose.clear(); + m_electronTriggers_Loose.clear(); + m_muonTriggers_Loose.clear(); + m_tauTriggers_Loose.clear(); // Trigger maps for TopConfig - to be used by individual selectors - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> allTriggers_perSelector - ( new std::unordered_map<std::string,std::vector<std::string>> ); - - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> electronTriggers_perSelector - ( new std::unordered_map<std::string,std::vector<std::string>> ); - - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> muonTriggers_perSelector - ( new std::unordered_map<std::string,std::vector<std::string>> ); - - std::shared_ptr<std::unordered_map<std::string,std::vector<std::string>>> tauTriggers_perSelector - ( new std::unordered_map<std::string,std::vector<std::string>> ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > allTriggers_perSelector_Tight + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > electronTriggers_perSelector_Tight + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > muonTriggers_perSelector_Tight + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > tauTriggers_perSelector_Tight + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > allTriggers_perSelector_Loose + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > electronTriggers_perSelector_Loose + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > muonTriggers_perSelector_Loose + (new std::unordered_map<std::string, std::vector<std::string> > ); + std::shared_ptr<std::unordered_map<std::string, std::vector<std::string> > > tauTriggers_perSelector_Loose + (new std::unordered_map<std::string, std::vector<std::string> > ); // Loop over all selections m_vetoEventsTrigger = true; m_vetoEventsGRL = true; m_vetoEventsGoodCalo = true; - m_vetoEventsPriVtx = true; for (auto sel : selections) { - - std::list<std::string> listAllTriggers_thisSelector; - std::vector<std::string> allTriggers_thisSelector; - std::vector<std::string> electronTriggers_thisSelector; - std::vector<std::string> muonTriggers_thisSelector; - std::vector<std::string> tauTriggers_thisSelector; + std::list<std::string> listAllTriggers_thisSelector_Tight; + std::vector<std::string> allTriggers_thisSelector_Tight; + std::vector<std::string> electronTriggers_thisSelector_Tight; + std::vector<std::string> muonTriggers_thisSelector_Tight; + std::vector<std::string> tauTriggers_thisSelector_Tight; + std::list<std::string> listAllTriggers_thisSelector_Loose; + std::vector<std::string> allTriggers_thisSelector_Loose; + std::vector<std::string> electronTriggers_thisSelector_Loose; + std::vector<std::string> muonTriggers_thisSelector_Loose; + std::vector<std::string> tauTriggers_thisSelector_Loose; // Loop over cut names and look for TRIGDEC, GRL, GOODCALO, PRIVTX - bool selectionHasTriggerCut(false),selectionHasGRLCut(false); - bool selectionHasGOODCALOCut(false),selectionHasPRIVTXCut(false); - for (auto cut : sel.m_cutnames) { - - if (cut.find("GRL") != std::string::npos) { + bool selectionHasTriggerCut(false); + bool selectionHasTriggerCut_Tight(false); + bool selectionHasTriggerCut_Loose(false); + bool selectionHasGRLCut(false); + bool selectionHasGOODCALOCut(false); + for (std::string cut : sel.m_cutnames) { + using boost::algorithm::starts_with; + cut.append(" "); + + if (starts_with(cut, "GRL ")) { selectionHasGRLCut = true; } - if (cut.find("GOODCALO") != std::string::npos) { + if (starts_with(cut, "GOODCALO ")) { selectionHasGOODCALOCut = true; } - if (cut.find("PRIVTX") != std::string::npos) { - selectionHasPRIVTXCut = true; + if (starts_with(cut, "GTRIGDEC ")) { + if (selectionHasTriggerCut || selectionHasTriggerCut_Loose || selectionHasTriggerCut_Tight) { + throw std::runtime_error("You have multiple TRIGDEC selectors for selection " + + sel.m_name + ". Only one per selection is allowed."); + } + if (!m_config->useGlobalTrigger()) { + throw std::runtime_error("The GTRIGDEC selector cannot be used without UseGlobalLeptonTriggerSF option."); + } + selectionHasTriggerCut = true; + allTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, + std::vector<std::string>(globalTriggers_Tight.begin(), + globalTriggers_Tight.end()))); + allTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, + std::vector<std::string>(globalTriggers_Loose.begin(), + globalTriggers_Loose.end()))); + electronTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, + std::vector<std::string>( + globalElectronTriggers_Tight.begin(), + globalElectronTriggers_Tight.end()))); + electronTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, + std::vector<std::string>( + globalElectronTriggers_Loose.begin(), + globalElectronTriggers_Loose.end()))); + muonTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, + std::vector<std::string>(globalMuonTriggers_Tight.begin(), + globalMuonTriggers_Tight.end()))); + muonTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, + std::vector<std::string>(globalMuonTriggers_Loose.begin(), + globalMuonTriggers_Loose.end()))); } - if (cut.find("TRIGDEC") != std::string::npos) { + if (starts_with(cut, "TRIGDEC_TIGHT ")) { + if (selectionHasTriggerCut_Tight) { + throw std::runtime_error("You have multiple TRIGDEC_TIGHT selectors for selection " + + sel.m_name + ". Only one per selection is allowed."); + } + if (selectionHasTriggerCut) { + throw std::runtime_error("Both TRIGDEC and TRIGDEC_TIGHT selectors used for selection " + + sel.m_name + ". Only one of the two per selection is allowed."); + } + selectionHasTriggerCut_Tight = true; + ATH_MSG_INFO("Tight Triggers for Selection \t" << sel.m_name << "\tare " << cut); + + //split the trigger string at spaces + std::stringstream ss(cut); + std::string item; + char delim = ' '; + while (std::getline(ss, item, delim)) { + if (item.size() > 0 && item.find("TRIGDEC_TIGHT") == std::string::npos) { + tmpAllTriggers_Tight.insert(item); + listAllTriggers_thisSelector_Tight.push_back(item); + } + } + listAllTriggers_thisSelector_Tight.sort(); + listAllTriggers_thisSelector_Tight.unique(); + + // Turn list into vector + for (auto trigger : listAllTriggers_thisSelector_Tight) { + allTriggers_thisSelector_Tight.push_back(trigger); + } + + // Split triggers into electron, muon and tau + for (const auto& trigger : allTriggers_thisSelector_Tight) { + if (isElectronTrigger(trigger)) { + electronTriggers_thisSelector_Tight.push_back(trigger); + } + if (isMuonTrigger(trigger)) { + muonTriggers_thisSelector_Tight.push_back(trigger); + } + if ((trigger.find("_tau") != std::string::npos)) { + tauTriggers_thisSelector_Tight.push_back(trigger); + } + } + + allTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, allTriggers_thisSelector_Tight)); + electronTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, electronTriggers_thisSelector_Tight)); + muonTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, muonTriggers_thisSelector_Tight)); + tauTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, tauTriggers_thisSelector_Tight)); + } // Cut requested is TRIGDEC_TIGHT + else if (starts_with(cut, "TRIGDEC_LOOSE ")) { + if (selectionHasTriggerCut_Loose) { + throw std::runtime_error("You have multiple TRIGDEC_LOOSE selectors for selection " + + sel.m_name + ". Only one per selection is allowed."); + } + if (selectionHasTriggerCut) { + throw std::runtime_error("Both TRIGDEC and TRIGDEC_LOOSE selectors used for selection " + + sel.m_name + ". Only one of the two per selection is allowed."); + } + selectionHasTriggerCut_Loose = true; + ATH_MSG_INFO("Loose Triggers for Selection \t" << sel.m_name << "\tare " << cut); + + //split the trigger string at spaces + std::stringstream ss(cut); + std::string item; + char delim = ' '; + while (std::getline(ss, item, delim)) { + if (item.size() > 0 && item.find("TRIGDEC_LOOSE") == std::string::npos) { + tmpAllTriggers_Loose.insert(item); + listAllTriggers_thisSelector_Loose.push_back(item); + } + } + listAllTriggers_thisSelector_Loose.sort(); + listAllTriggers_thisSelector_Loose.unique(); + + // Turn list into vector + for (auto trigger : listAllTriggers_thisSelector_Loose) { + allTriggers_thisSelector_Loose.push_back(trigger); + } + + // Split triggers into electron, muon and tau + for (const auto& trigger : allTriggers_thisSelector_Loose) { + if (isElectronTrigger(trigger)) { + electronTriggers_thisSelector_Loose.push_back(trigger); + } + if (isMuonTrigger(trigger)) { + muonTriggers_thisSelector_Loose.push_back(trigger); + } + if ((trigger.find("_tau") != std::string::npos)) { + tauTriggers_thisSelector_Loose.push_back(trigger); + } + } + + allTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, allTriggers_thisSelector_Loose)); + electronTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, electronTriggers_thisSelector_Loose)); + muonTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, muonTriggers_thisSelector_Loose)); + tauTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, tauTriggers_thisSelector_Loose)); + } // Cut requested is TRIGDEC_LOOSE + else if (starts_with(cut, "TRIGDEC ")) { + if (selectionHasTriggerCut) { + throw std::runtime_error("GTRIGDEC/TRIGDEC already used for selection " + + sel.m_name + ". Cannot be used multiple times."); + } + if (selectionHasTriggerCut_Tight) { + throw std::runtime_error("Both TRIGDEC and TRIGDEC_TIGHT already used for selection " + + sel.m_name + ". Cannot be used simultaneously."); + } + if (selectionHasTriggerCut_Loose) { + throw std::runtime_error("Both TRIGDEC and TRIGDEC_LOOSE already used for selection " + + sel.m_name + ". Cannot be used simultaneously."); + } selectionHasTriggerCut = true; - ATH_MSG_INFO("Triggers for Selection \t"<<sel.m_name<<"\tare "<<cut); + ATH_MSG_INFO("Triggers for Selection \t" << sel.m_name << "\tare " << cut); //split the trigger string at spaces std::stringstream ss(cut); @@ -130,37 +320,58 @@ namespace top { char delim = ' '; while (std::getline(ss, item, delim)) { if (item.size() > 0 && item.find("TRIGDEC") == std::string::npos) { - tmpAllTriggers.push_back(item); - listAllTriggers_thisSelector.push_back(item); + tmpAllTriggers_Tight.insert(item); + listAllTriggers_thisSelector_Tight.push_back(item); + tmpAllTriggers_Loose.insert(item); + listAllTriggers_thisSelector_Loose.push_back(item); } } - tmpAllTriggers.sort(); - tmpAllTriggers.unique(); - listAllTriggers_thisSelector.sort(); - listAllTriggers_thisSelector.unique(); + listAllTriggers_thisSelector_Tight.sort(); + listAllTriggers_thisSelector_Tight.unique(); + listAllTriggers_thisSelector_Loose.sort(); + listAllTriggers_thisSelector_Loose.unique(); // Turn list into vector - for (auto trigger : listAllTriggers_thisSelector) { - allTriggers_thisSelector.push_back( trigger ); + for (auto trigger : listAllTriggers_thisSelector_Tight) { + allTriggers_thisSelector_Tight.push_back(trigger); + } + for (auto trigger : listAllTriggers_thisSelector_Loose) { + allTriggers_thisSelector_Loose.push_back(trigger); } // Split triggers into electron, muon and tau - for (const auto& trigger : allTriggers_thisSelector) { - if ( (trigger.find("HLT_e") != std::string::npos) || (trigger.find("HLT_2e") != std::string::npos) ) { - electronTriggers_thisSelector.push_back(trigger); + for (const auto& trigger : allTriggers_thisSelector_Tight) { + if (isElectronTrigger(trigger)) { + electronTriggers_thisSelector_Tight.push_back(trigger); + } + if (isMuonTrigger(trigger)) { + muonTriggers_thisSelector_Tight.push_back(trigger); + } + if ((trigger.find("_tau") != std::string::npos)) { + tauTriggers_thisSelector_Tight.push_back(trigger); } - if ( (trigger.find("HLT_mu") != std::string::npos) || (trigger.find("HLT_2mu") != std::string::npos) || (trigger.find("_mu") != std::string::npos) ) { - muonTriggers_thisSelector.push_back(trigger); + } + + for (const auto& trigger : allTriggers_thisSelector_Loose) { + if (isElectronTrigger(trigger)) { + electronTriggers_thisSelector_Loose.push_back(trigger); } - if ( (trigger.find("_tau") != std::string::npos) ) { - tauTriggers_thisSelector.push_back(trigger); + if (isMuonTrigger(trigger)) { + muonTriggers_thisSelector_Loose.push_back(trigger); + } + if ((trigger.find("_tau") != std::string::npos)) { + tauTriggers_thisSelector_Loose.push_back(trigger); } } - allTriggers_perSelector->insert( std::make_pair( sel.m_name , allTriggers_thisSelector ) ); - electronTriggers_perSelector->insert( std::make_pair( sel.m_name , electronTriggers_thisSelector ) ); - muonTriggers_perSelector->insert( std::make_pair( sel.m_name , muonTriggers_thisSelector ) ); - tauTriggers_perSelector->insert( std::make_pair( sel.m_name , tauTriggers_thisSelector ) ); + allTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, allTriggers_thisSelector_Tight)); + electronTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, electronTriggers_thisSelector_Tight)); + muonTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, muonTriggers_thisSelector_Tight)); + tauTriggers_perSelector_Tight->insert(std::make_pair(sel.m_name, tauTriggers_thisSelector_Tight)); + allTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, allTriggers_thisSelector_Loose)); + electronTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, electronTriggers_thisSelector_Loose)); + muonTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, muonTriggers_thisSelector_Loose)); + tauTriggers_perSelector_Loose->insert(std::make_pair(sel.m_name, tauTriggers_thisSelector_Loose)); } // Cut requested is TRIGDEC } // Loop over all cuts @@ -172,50 +383,77 @@ namespace top { m_vetoEventsGoodCalo = false; } - if (!selectionHasPRIVTXCut) { - m_vetoEventsPriVtx = false; - } - if (!selectionHasTriggerCut) { m_vetoEventsTrigger = false; - ATH_MSG_INFO("Selection "<<sel.m_name<<" Does not request a trigger. No event veto will be applied"); + ATH_MSG_INFO("Selection " << sel.m_name << " Does not request a trigger. No event veto will be applied"); } } // Loop over all selections + // Add triggers configured for the global trigger SF tool + tmpAllTriggers_Tight.insert(globalTriggers_Tight.begin(), globalTriggers_Tight.end()); + tmpAllTriggers_Loose.insert(globalTriggers_Loose.begin(), globalTriggers_Loose.end()); + // Turn list into vector - for (auto trigger : tmpAllTriggers) { - m_allTriggers.push_back( trigger ); + { + std::vector<std::string> tmp; + tmp.assign(tmpAllTriggers_Tight.begin(), tmpAllTriggers_Tight.end()); + std::sort(tmp.begin(), tmp.end()); + m_allTriggers_Tight.swap(tmp); + tmp.clear(); + tmp.assign(tmpAllTriggers_Loose.begin(), tmpAllTriggers_Loose.end()); + std::sort(tmp.begin(), tmp.end()); + m_allTriggers_Loose.swap(tmp); } - ATH_MSG_INFO("All requested triggers are:"); - for (const auto& trigger : m_allTriggers) { - ATH_MSG_INFO(" "<<trigger); + ATH_MSG_INFO("All requested Tight triggers are:"); + for (const auto& trigger : m_allTriggers_Tight) { + ATH_MSG_INFO(" " << trigger); + } + ATH_MSG_INFO("All requested Loose triggers are:"); + for (const auto& trigger : m_allTriggers_Loose) { + ATH_MSG_INFO(" " << trigger); } std::string outputInfoString("True"); if (!m_vetoEventsTrigger) { outputInfoString = "False"; } - ATH_MSG_INFO("Apply event veto on trigger decision = "<<outputInfoString); + ATH_MSG_INFO("Apply event veto on trigger decision = " << outputInfoString); // Split triggers into electron, muon and tau - for (const auto& trigger : m_allTriggers) { - if ( (trigger.find("HLT_e") != std::string::npos) || (trigger.find("HLT_2e") != std::string::npos) ) { - m_electronTriggers.push_back(trigger); + for (const auto& trigger : m_allTriggers_Tight) { + if (isElectronTrigger(trigger)) { + m_electronTriggers_Tight.push_back(trigger); } - if ( (trigger.find("HLT_mu") != std::string::npos) || (trigger.find("HLT_2mu") != std::string::npos) || (trigger.find("_mu") != std::string::npos) ) { - m_muonTriggers.push_back(trigger); + if (isMuonTrigger(trigger)) { + m_muonTriggers_Tight.push_back(trigger); } - if ( (trigger.find("_tau") != std::string::npos) ) { - m_tauTriggers.push_back(trigger); + if ((trigger.find("_tau") != std::string::npos)) { + m_tauTriggers_Tight.push_back(trigger); + } + } + // Split triggers into electron, muon and tau + for (const auto& trigger : m_allTriggers_Loose) { + if (isElectronTrigger(trigger)) { + m_electronTriggers_Loose.push_back(trigger); + } + if (isMuonTrigger(trigger)) { + m_muonTriggers_Loose.push_back(trigger); + } + if ((trigger.find("_tau") != std::string::npos)) { + m_tauTriggers_Loose.push_back(trigger); } } // Tell TopConfig about the triggers - m_config->allTriggers( allTriggers_perSelector ); - m_config->electronTriggers( electronTriggers_perSelector ); - m_config->muonTriggers( muonTriggers_perSelector ); - m_config->tauTriggers( tauTriggers_perSelector ); + m_config->allTriggers_Tight(allTriggers_perSelector_Tight); + m_config->electronTriggers_Tight(electronTriggers_perSelector_Tight); + m_config->muonTriggers_Tight(muonTriggers_perSelector_Tight); + m_config->tauTriggers_Tight(tauTriggers_perSelector_Tight); + m_config->allTriggers_Loose(allTriggers_perSelector_Loose); + m_config->electronTriggers_Loose(electronTriggers_perSelector_Loose); + m_config->muonTriggers_Loose(muonTriggers_perSelector_Loose); + m_config->tauTriggers_Loose(tauTriggers_perSelector_Loose); // If the user has requested that all events are saved, then we'd better turn off the vetos if (!m_config->saveOnlySelectedEvents()) { @@ -223,22 +461,21 @@ namespace top { m_vetoEventsGoodCalo = false; m_vetoEventsTrigger = false; } - } - bool EventCleaningSelection::applyGRL() const - { + bool EventCleaningSelection::applyGRL() const { const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()),"Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); ///-- Apply GRL to data --/// char passGRL(1); if (!m_config->isMC() && asg::ToolStore::contains<IGoodRunsListSelectionTool> ("GoodRunsListSelectionTool")) { - if (!m_grlTool->passRunLB( *eventInfo )) { + if (!m_grlTool->passRunLB(*eventInfo)) { passGRL = 0; } } - eventInfo->auxdecor<char>("AnalysisTop_GRL") = passGRL; + eventInfo->auxdecor<char>("AnalysisTop_GRL") = passGRL; // Do we veto events? Only if ALL selectors request GRL and GRL fails if (m_vetoEventsGRL) { @@ -254,10 +491,10 @@ namespace top { return true; } - bool EventCleaningSelection::applyGoodCalo() const - { + bool EventCleaningSelection::applyGoodCalo() const { const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()),"Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); ///-- Apply GoodCalo tests to data --/// ///-- https://twiki.cern.ch/twiki/bin/view/AtlasProtected/PhysicsAnalysisWorkBookRel20CPRec --/// @@ -266,12 +503,12 @@ namespace top { bool badTile(false), badLAr(false), badSCT(false), incompleteEvent(false); ///-- Remove bad events due to problems in TileCal --/// - if (eventInfo->errorState(xAOD::EventInfo::Tile)==xAOD::EventInfo::Error) { + if (eventInfo->errorState(xAOD::EventInfo::Tile) == xAOD::EventInfo::Error) { badTile = true; } ///-- Remove bad events due to problems in LAr --/// - if (eventInfo->errorState(xAOD::EventInfo::LAr)==xAOD::EventInfo::Error) { + if (eventInfo->errorState(xAOD::EventInfo::LAr) == xAOD::EventInfo::Error) { badLAr = true; } @@ -289,13 +526,13 @@ namespace top { passGoodCalo = 0; } } - eventInfo->auxdecor<char>("AnalysisTop_GOODCALO") = passGoodCalo; + eventInfo->auxdecor<char>("AnalysisTop_GOODCALO") = passGoodCalo; // Do we veto events? Only if ALL selectors request GOODCALO and GOODCALO fails if (m_vetoEventsGoodCalo) { if (passGoodCalo == 1) { return true; - } + } if (passGoodCalo == 0) { return false; } @@ -305,14 +542,14 @@ namespace top { return true; } - bool EventCleaningSelection::applyPrimaryVertex() const - { + bool EventCleaningSelection::applyPrimaryVertex() const { ///-- https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/InDetTrackingPerformanceGuidelines#Vertexing --/// const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()),"Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); const xAOD::VertexContainer* vertices(nullptr); - top::check(evtStore()->retrieve(vertices,m_config->sgKeyPrimaryVertices()), "Failed to retrieve Primary Vertices"); + top::check(evtStore()->retrieve(vertices, m_config->sgKeyPrimaryVertices()), "Failed to retrieve Primary Vertices"); char passPriVtx(0); float pri_vtx_z(0); @@ -320,13 +557,12 @@ namespace top { for (auto vtx : *vertices) { if (vtx->vertexType() == xAOD::VxType::PriVtx) { passPriVtx = 1; - pri_vtx_z = vtx->z(); + pri_vtx_z = vtx->z(); break; // No need to loop over all vertices, we only need one } } eventInfo->auxdecor<char>("AnalysisTop_PRIVTX") = passPriVtx; - if( passPriVtx == 1 ) - eventInfo->auxdecor<float>("AnalysisTop_PRIVTX_z_position") = pri_vtx_z; + if (passPriVtx == 1) eventInfo->auxdecor<float>("AnalysisTop_PRIVTX_z_position") = pri_vtx_z; // Do we veto events? Only if ALL selectors request PRIVTX and PRIVTX fails if (m_vetoEventsPriVtx) { @@ -342,25 +578,27 @@ namespace top { return true; } - bool EventCleaningSelection::applyTrigger() - { + bool EventCleaningSelection::applyTrigger() { const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()),"Failed to retrieve EventInfo"); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); bool orOfAllTriggers(false); - for (const auto& trigger : m_allTriggers) { + std::unordered_set<std::string> triggers; + triggers.insert(m_allTriggers_Tight.begin(), m_allTriggers_Tight.end()); + triggers.insert(m_allTriggers_Loose.begin(), m_allTriggers_Loose.end()); + for (const auto& trigger : triggers) { //decorating event with trigger decision - bool passThisTrigger = m_trigDecisionTool->isPassed(trigger); + bool passThisTrigger = m_trigDecisionTool->isPassed(trigger); char decoration = passThisTrigger ? 1 : 0; - eventInfo->auxdecor<char>( "TRIGDEC_" + trigger ) = decoration; + eventInfo->auxdecor<char>("TRIGDEC_" + trigger) = decoration; orOfAllTriggers |= passThisTrigger; //decorating event with trigger prescale (on Data) if (!m_config->isMC()) { auto cg = m_trigDecisionTool->getChainGroup(trigger); float prescale = cg->getPrescale(); - eventInfo->auxdecor<float>( "TRIGPS_" + trigger ) = prescale; + eventInfo->auxdecor<float>("TRIGPS_" + trigger) = prescale; } } @@ -371,82 +609,102 @@ namespace top { // Do we veto events? Only if ALL selectors request TRIGDEC and no trigger passes if (m_vetoEventsTrigger) { - return orOfAllTriggers; + return orOfAllTriggers; } // otherwise, we don't veto the event return true; } - void EventCleaningSelection::matchElectrons() - { + void EventCleaningSelection::matchElectrons() { const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()),"Failed to retrieve EventInfo"); - // Take muons from input file. Decorate these before doing any calibration/shallow copies + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + + // Take electrons from input file. Decorate these before doing any calibration/shallow copies const xAOD::ElectronContainer* electrons(nullptr); - top::check(evtStore()->retrieve(electrons,m_config->sgKeyElectrons()),"Failed to retrieve electrons"); + if(m_config->useElectrons()) top::check(evtStore()->retrieve(electrons, m_config->sgKeyElectrons()), "Failed to retrieve electrons"); - // Loop over muons + // Loop over electrons + std::unordered_set<std::string> triggers; + triggers.insert(m_electronTriggers_Tight.begin(), m_electronTriggers_Tight.end()); + triggers.insert(m_electronTriggers_Loose.begin(), m_electronTriggers_Loose.end()); for (const auto* el : *electrons) { - // Loop over muon triggers - for (const auto& trigger : m_electronTriggers) { + // Loop over electron triggers + for (const auto& trigger : triggers) { bool match(false); // Match even if event fails trigger decistion - it's important in case of pre-scaled menus - if (el->isAvailable<char>(m_config->getDerivationStream() + "_" + trigger)) { - match = el->auxdataConst<char>( m_config->getDerivationStream() + "_" + trigger); + if (!m_config->useGlobalTrigger() && el->isAvailable<char>(m_config->getDerivationStream() + "_" + trigger)) { + match = el->auxdataConst<char>(m_config->getDerivationStream() + "_" + trigger); } else { match = m_trigMatchTool->match(*el, trigger); } char decoration = match ? 1 : 0; - el->auxdecor<char>("TRIGMATCH_" + trigger ) = decoration; + el->auxdecor<char>("TRIGMATCH_" + trigger) = decoration; } } } - void EventCleaningSelection::matchMuons() - { + void EventCleaningSelection::matchMuons() { const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()),"Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); // Take muons from input file. Decorate these before doing any calibration/shallow copies const xAOD::MuonContainer* muons(nullptr); - top::check(evtStore()->retrieve(muons,m_config->sgKeyMuons()),"Failed to retrieve muons"); + if(m_config->useMuons()) top::check(evtStore()->retrieve(muons, m_config->sgKeyMuons()), "Failed to retrieve muons in EventCleaningSelection::matchMuons() "); // Loop over muons + std::unordered_set<std::string> triggers; + triggers.insert(m_muonTriggers_Tight.begin(), m_muonTriggers_Tight.end()); + triggers.insert(m_muonTriggers_Loose.begin(), m_muonTriggers_Loose.end()); for (const auto* mu : *muons) { // Loop over muon triggers - for (const auto& trigger : m_muonTriggers) { + for (const auto& trigger : triggers) { bool match(false); // Match even if event fails trigger decistion - it's important in case of pre-scaled menus - if (mu->isAvailable<char>(m_config->getDerivationStream() + "_" + trigger)) { + if (!m_config->useGlobalTrigger() && mu->isAvailable<char>(m_config->getDerivationStream() + "_" + trigger)) { match = mu->auxdataConst<char>(m_config->getDerivationStream() + "_" + trigger); } else { match = m_trigMatchTool->match(*mu, trigger); } char decoration = match ? 1 : 0; - mu->auxdecor<char>("TRIGMATCH_" + trigger ) = decoration; + mu->auxdecor<char>("TRIGMATCH_" + trigger) = decoration; } } } - void EventCleaningSelection::matchTaus() - { - + void EventCleaningSelection::matchTaus() { const xAOD::EventInfo* eventInfo(nullptr); - top::check(evtStore()->retrieve(eventInfo,m_config->sgKeyEventInfo()), - "Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), + "Failed to retrieve EventInfo"); // Take taus from input file. // Decorate these before doing any calibration/shallow copies const xAOD::TauJetContainer* taus(nullptr); - top::check(evtStore()->retrieve(taus,m_config->sgKeyTaus()), - "Failed to retrieve taus"); + top::check(evtStore()->retrieve(taus, m_config->sgKeyTaus()), + "Failed to retrieve taus"); // Loop over taus for (const auto* tau : *taus) { // Loop over tau triggers - for (const auto& trigger : m_tauTriggers) { + for (const auto& trigger : m_tauTriggers_Tight) { + bool match(false); + // Match even if event fails trigger decistion - it's important in case of pre-scaled menus + match = m_trigMatchTauTool->match(tau, trigger); + if (tau->isAvailable<char>(m_config->getDerivationStream() + "_" + trigger)) { + match = tau->auxdataConst<char>(m_config->getDerivationStream() + "_" + trigger); + } else { + match = m_trigMatchTool->match(*tau, trigger); + } + char decoration = match ? 1 : 0; + tau->auxdecor<char>("TRIGMATCH_" + trigger) = decoration; + } + // Loop over tau triggers + for (const auto& trigger : m_tauTriggers_Loose) { + // let's make sure this isn't done twice + if (tau->isAvailable<char>("TRIGMATCH_" + trigger)) continue; bool match(false); // Match even if event fails trigger decistion - it's important in case of pre-scaled menus match = m_trigMatchTauTool->match(tau, trigger); @@ -456,23 +714,56 @@ namespace top { match = m_trigMatchTool->match(*tau, trigger); } char decoration = match ? 1 : 0; - tau->auxdecor<char>("TRIGMATCH_" + trigger ) = decoration; + tau->auxdecor<char>("TRIGMATCH_" + trigger) = decoration; } } } - void EventCleaningSelection::addExtraBranches( std::vector<std::string>& extraBranchList) { - - for (const auto& trigger : m_allTriggers) - extraBranchList.push_back( "TRIGDEC_" + trigger ); - + void EventCleaningSelection::addExtraBranches(std::vector<std::string>& extraBranchList) { + for (const auto& trigger : m_allTriggers_Tight) + extraBranchList.push_back("TRIGDEC_" + trigger); + for (const auto& trigger : m_allTriggers_Loose) { + if (std::find(extraBranchList.begin(), extraBranchList.end(), + std::string {"TRIGDEC_"} +trigger) == extraBranchList.end()) { // to not add them twice + extraBranchList.push_back("TRIGDEC_" + trigger); + } + } } - void EventCleaningSelection::printTriggers() const - { + void EventCleaningSelection::printTriggers() const { // printout all HLT chains // Debug only - this is very verbose - m_trigConfTool->chainList()->print("",10); + m_trigConfTool->chainList()->print("", 10); } + std::vector<std::string> EventCleaningSelection::getIndividualFromGlobalTriggers( + std::vector<std::string> const& triggers) { + std::vector<std::string> result; + std::string const delim("_OR_"); + for (std::string const& trigger : triggers) { + size_t cur = 0; + while (true) { + size_t next = trigger.find(delim, cur); + bool last = (next == std::string::npos); + result.emplace_back(std::string("HLT_") + trigger.substr(cur, (last ? std::string::npos : next - cur))); + if (last) break; + cur = next + delim.size(); + } + } + return result; + } + + bool EventCleaningSelection::isElectronTrigger(std::string const& trigger) const { + top::check(trigger.find("HLT_") == 0, "Expected trigger name to start with `HLT_'"); + //bool success; + return true; + // return(TrigGlobEffCorr::ImportData::associatedLeptonFlavour(trigger.substr(4), success) == xAOD::Type::Electron); + } + + bool EventCleaningSelection::isMuonTrigger(std::string const& trigger) const { + top::check(trigger.find("HLT_") == 0, "Expected trigger name to start with `HLT_'"); + //bool success; + return true; + //return(TrigGlobEffCorr::ImportData::associatedLeptonFlavour(trigger.substr(4), success) == xAOD::Type::Muon); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/FwdElectronSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/FwdElectronSelectionBase.cxx new file mode 100644 index 0000000000000000000000000000000000000000..050a440d01b5de7d41120626e6a43aaa747d5b20 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/FwdElectronSelectionBase.cxx @@ -0,0 +1,20 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopObjectSelectionTools/FwdElectronSelectionBase.h" + +#include <iostream> + +namespace top { + FwdElectronSelectionBase::FwdElectronSelectionBase() { + } + + FwdElectronSelectionBase::~FwdElectronSelectionBase() { + } + + std::ostream& operator << (std::ostream& os, const top::FwdElectronSelectionBase& selection) { + selection.print(os); + return os; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/IsolationTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/IsolationTools.cxx index 43345d31a4a4ba47ccd407220c29563d915fb14a..ece125b44f9b17cc7f6ab6c5e7abce7513f85fa5 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/IsolationTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/IsolationTools.cxx @@ -1,73 +1,69 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/IsolationTools.h" +#include "TopConfiguration/ConfigurationSettings.h" #include "TopEvent/EventTools.h" #include "xAODEgamma/Photon.h" #include "xAODEgamma/Electron.h" #include "xAODMuon/Muon.h" -namespace top { - -IsolationBase::IsolationBase() { -} +#include "TopObjectSelectionTools/MsgCategory.h" +using namespace TopObjectSelectionTools; -IsolationBase::~IsolationBase() { -} +namespace top { + IsolationBase::IsolationBase() { + } + IsolationBase::~IsolationBase() { + } -AbsoluteIsolationDC14::AbsoluteIsolationDC14(const xAOD::Iso::IsolationType type, double cutvalue) : - m_type(type), - m_cutvalue(cutvalue) { -} + AbsoluteIsolationDC14::AbsoluteIsolationDC14(const xAOD::Iso::IsolationType type, double cutvalue) : + m_type(type), + m_cutvalue(cutvalue) { + } -bool AbsoluteIsolationDC14::passSelection(const xAOD::IParticle& p) const { + bool AbsoluteIsolationDC14::passSelection(const xAOD::IParticle& p) const { //electrons if (p.type() == xAOD::Type::Electron) { - float iso = 0.; - const xAOD::Electron* el = dynamic_cast<const xAOD::Electron*>(&p); - bool exists = el->isolationValue(iso, m_type); - return exists && iso > m_cutvalue; + float iso = 0.; + const xAOD::Electron* el = dynamic_cast<const xAOD::Electron*>(&p); + bool exists = el->isolationValue(iso, m_type); + return exists && iso > m_cutvalue; } //muons if (p.type() == xAOD::Type::Muon) { - float iso = 0.; - const xAOD::Muon* mu = dynamic_cast<const xAOD::Muon*>(&p); - bool exists = mu->isolation(iso, m_type); - return exists && iso > m_cutvalue; + float iso = 0.; + const xAOD::Muon* mu = dynamic_cast<const xAOD::Muon*>(&p); + bool exists = mu->isolation(iso, m_type); + return exists && iso > m_cutvalue; } - std::cout << "IsolationDC14::Not an electron or muon" << std::endl; - exit(1); - - //should never happen (famous last words for a comment, no?) - return false; -} + throw std::runtime_error("TopObjectSelectionTools::IsolationTools::AbsoluteIsolationDC14: Not an electron or muon"); + } ///Implement me! -bool AbsoluteIsolationDC14::passSelectionLoose(const xAOD::IParticle& /*p*/) const { + bool AbsoluteIsolationDC14::passSelectionLoose(const xAOD::IParticle& /*p*/) const { return true; -} + } -void AbsoluteIsolationDC14::print(std::ostream& os) const { + void AbsoluteIsolationDC14::print(std::ostream& os) const { os << " * AbsoluteIsolationDC14\n"; os << " * " << m_type << " > " << m_cutvalue << " MeV\n"; - //missing in xaodprimities-00-00-02 os << " * " << xAOD::Iso::toString(m_type) << " > " << m_cutvalue << " MeV\n"; -} - - + //missing in xaodprimities-00-00-02 os << " * " << xAOD::Iso::toString(m_type) << " > " << m_cutvalue << " + // MeV\n"; + } -RelativePTVarCone::RelativePTVarCone(unsigned int size, double fraction, unsigned int sizeLoose, double fractionLoose) : + RelativePTVarCone::RelativePTVarCone(unsigned int size, double fraction, unsigned int sizeLoose, + double fractionLoose) : m_fraction(fraction), m_fractionLoose(fractionLoose) { - if (size != 20 && size != 30 && size != 40) { - std::cout << "ptvarcone only supports cone sizes of 20, 30, 40" << std::endl; - std::cout << "and you asked for " << size << ". why?" << std::endl; - exit(1); + throw std::runtime_error("TopObjectSelectionTools::IsolationTools::RelativePTVarCone: " + "ptvarcone only supports cone sizes of 20, 30, 40\n and you asked for " + std::to_string (size)); } std::stringstream ss; @@ -77,105 +73,123 @@ RelativePTVarCone::RelativePTVarCone(unsigned int size, double fraction, unsigne ss.str(""); ss << "ptvarcone" << sizeLoose; m_sizeLoose = ss.str(); -} + } -bool RelativePTVarCone::passSelection(const xAOD::IParticle& p) const { - return (p.auxdataConst<float>(m_size) / p.pt() < m_fraction); -} + bool RelativePTVarCone::passSelection(const xAOD::IParticle& p) const { + return(p.auxdataConst<float>(m_size) / p.pt() < m_fraction); + } -bool RelativePTVarCone::passSelectionLoose(const xAOD::IParticle& p) const { - return (p.auxdataConst<float>(m_sizeLoose) / p.pt() < m_fractionLoose); -} + bool RelativePTVarCone::passSelectionLoose(const xAOD::IParticle& p) const { + return(p.auxdataConst<float>(m_sizeLoose) / p.pt() < m_fractionLoose); + } -void RelativePTVarCone::print(std::ostream& os) const { + void RelativePTVarCone::print(std::ostream& os) const { os << " * RelativePTVarCone\n"; os << " * " << m_size << " /pT > " << m_fraction << "\n"; -} - + } -ApproxPTVarCone::ApproxPTVarCone(double fraction, double fractionLoose) : + ApproxPTVarCone::ApproxPTVarCone(double fraction, double fractionLoose) : m_fraction(fraction), m_fractionLoose(fractionLoose) { -} + } -bool ApproxPTVarCone::passSelection(const xAOD::IParticle& p) const { - return (p.auxdataConst<float>("miniIso") / p.pt() < m_fraction); -} + bool ApproxPTVarCone::passSelection(const xAOD::IParticle& p) const { + return(p.auxdataConst<float>("miniIso") / p.pt() < m_fraction); + } -bool ApproxPTVarCone::passSelectionLoose(const xAOD::IParticle& p) const { - return (p.auxdataConst<float>("miniIso") / p.pt() < m_fractionLoose); -} + bool ApproxPTVarCone::passSelectionLoose(const xAOD::IParticle& p) const { + return(p.auxdataConst<float>("miniIso") / p.pt() < m_fractionLoose); + } -void ApproxPTVarCone::print(std::ostream& os) const { + void ApproxPTVarCone::print(std::ostream& os) const { os << " * Approximate Mini Isolation\n"; os << " * iso/pT > " << m_fraction << "\n"; -} - - + } -StandardIsolation::StandardIsolation(const std::string& tightLeptonIsolation,const std::string& looseLeptonIsolation) : - m_tightLeptonDecoration("AnalysisTop_Isol_"+tightLeptonIsolation), - m_looseLeptonDecoration("AnalysisTop_Isol_"+looseLeptonIsolation), - m_doTightIsolation(true), - m_doLooseIsolation(true) -{ - if (tightLeptonIsolation == "None") - m_doTightIsolation = false; - - if (looseLeptonIsolation == "None") - m_doLooseIsolation = false; -} + StandardIsolation::StandardIsolation(const std::string& tightLeptonIsolation, + const std::string& looseLeptonIsolation) : + m_tightLeptonDecoration("AnalysisTop_Isol_" + tightLeptonIsolation), + m_looseLeptonDecoration("AnalysisTop_Isol_" + looseLeptonIsolation), + m_tightLeptonIsolation(tightLeptonIsolation), + m_looseLeptonIsolation(looseLeptonIsolation), + m_doTightIsolation(true), + m_doLooseIsolation(true), + m_doTightPromptLeptonIso(false), + m_doLoosePromptLeptonIso(false), + m_skipUnavailable(!ConfigurationSettings::get()->feature("AbortOnUnavailableIsolation")) { + if (tightLeptonIsolation == "PromptLepton") m_doTightPromptLeptonIso = true; + if (looseLeptonIsolation == "PromptLepton") m_doLoosePromptLeptonIso = true; + + if (tightLeptonIsolation == "None") m_doTightIsolation = false; + + if (looseLeptonIsolation == "None") m_doLooseIsolation = false; + } -bool StandardIsolation::passSelection(const xAOD::IParticle& p) const -{ - // Are we doing isolation? - if (!m_doTightIsolation) - return true; - - // If we get this far then we are doing isolation - if ( p.type() == xAOD::Type::Photon || - p.type() == xAOD::Type::Electron || - p.type() == xAOD::Type::Muon ) - { - if (p.isAvailable<char>(m_tightLeptonDecoration)) { - if (p.auxdataConst<char>(m_tightLeptonDecoration) == 1) { - return true; + bool StandardIsolation::passSelection(const xAOD::IParticle& p) const { + // Are we doing isolation? + if (!m_doTightIsolation) return true; + + // If we get this far then we are doing isolation + if (p.type() == xAOD::Type::Photon || + p.type() == xAOD::Type::Electron || + p.type() == xAOD::Type::Muon) { + if (!m_doTightPromptLeptonIso) { + if (!m_skipUnavailable || p.isAvailable<char>(m_tightLeptonDecoration)) { + if (p.auxdataConst<char>(m_tightLeptonDecoration) == 1) { + return true; + } + } + } else { + // Hardcoded a bit - With PLI we need to check that it passes Loose isolation AND passes the BDT cut + if (!m_skipUnavailable || + (p.isAvailable<char>(m_tightLeptonDecoration) && p.isAvailable<char>("AnalysisTop_Isol_Loose"))) { + if (p.auxdataConst<char>(m_tightLeptonDecoration) == 1 && + p.auxdataConst<char>("AnalysisTop_Isol_Loose") == 1) { + return true; + } + } } } + + // Not a photon, electron or muon? + // Didn't pass isolation? + return false; } - - // Not a photon, electron or muon? - // Didn't pass isolation? - return false; -} -bool StandardIsolation::passSelectionLoose(const xAOD::IParticle& p) const -{ - // Are we doing isolation? - if (!m_doLooseIsolation) - return true; - - // If we get this far then we are doing isolation - if ( p.type() == xAOD::Type::Photon || - p.type() == xAOD::Type::Electron || - p.type() == xAOD::Type::Muon ) - { - if (p.isAvailable<char>(m_looseLeptonDecoration)) { - if (p.auxdataConst<char>(m_looseLeptonDecoration) == 1) { - return true; + bool StandardIsolation::passSelectionLoose(const xAOD::IParticle& p) const { + // Are we doing isolation? + if (!m_doLooseIsolation) return true; + + // If we get this far then we are doing isolation + if (p.type() == xAOD::Type::Photon || + p.type() == xAOD::Type::Electron || + p.type() == xAOD::Type::Muon) { + if (!m_doLoosePromptLeptonIso) { + if (!m_skipUnavailable || p.isAvailable<char>(m_looseLeptonDecoration)) { + if (p.auxdataConst<char>(m_looseLeptonDecoration) == 1) { + return true; + } + } + } else { + // Hardcoded a bit - With PLI we need to check that it passes Loose isolation AND passes the BDT cut + if (!m_skipUnavailable || + (p.isAvailable<char>(m_looseLeptonDecoration) && p.isAvailable<char>("AnalysisTop_Isol_Loose"))) { + if (p.auxdataConst<char>(m_looseLeptonDecoration) == 1 && + p.auxdataConst<char>("AnalysisTop_Isol_Loose") == 1) { + return true; + } + } } } + + // Not a photon, electron or muon? + // Didn't pass isolation? + return false; } - - // Not a photon, electron or muon? - // Didn't pass isolation? - return false; -} -void StandardIsolation::print(std::ostream& os) const { + void StandardIsolation::print(std::ostream& os) const { os << " * Standard Isolation\n"; - os << " * Tight lepton isolation = "<<m_tightLeptonDecoration<< "\n"; - os << " * Loose lepton isolation = "<<m_looseLeptonDecoration<< "\n"; -} - + os << " * Tight lepton isolation = " << m_tightLeptonDecoration << "\n"; + os << " * Loose lepton isolation = " << m_looseLeptonDecoration << "\n"; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetGhostTrackSelection.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetGhostTrackSelection.cxx new file mode 100644 index 0000000000000000000000000000000000000000..1a069fb779bd1e47defbddf5e96028abdc406b39 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetGhostTrackSelection.cxx @@ -0,0 +1,90 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopObjectSelectionTools/JetGhostTrackSelection.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" + +#include "xAODTracking/TrackParticle.h" +#include "xAODTracking/Vertex.h" + +#include "TopEvent/EventTools.h" + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +#include "TopObjectSelectionTools/MsgCategory.h" +using namespace TopObjectSelectionTools; + +namespace top { + + JetGhostTrackSelection::JetGhostTrackSelection(const double ptcut, const double etamax, const std::string vertexassociation, const double ptcut_jet, const double etacut_jet ) : + m_ptcut(ptcut), + m_etamax(etamax), + m_ptcut_jet(ptcut_jet), + m_etamax_jet(etacut_jet), + m_vertexassociation(vertexassociation), + m_trkseltool("top::GhostTrackCPTools::TrkSelTool") + { + + top::check(m_trkseltool.retrieve(), "Failed to retrieve InDetTrackSelectionTool"); + + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TrackingCPRecsRun2Final + if (m_vertexassociation == "nominal"){ + m_d0=2; + m_z0sintheta=3; + } + else if(m_vertexassociation == "tight"){ + m_d0=0.5; + m_z0sintheta=0.5; + } + else { + ATH_MSG_INFO("Not applying any vertex association for GA tracks"); + m_d0=10000; + m_z0sintheta=10000; + + } + + } + + JetGhostTrackSelection::~JetGhostTrackSelection() { + } + +// bool JetGhostTrackSelection::passSelection(const xAOD::TrackParticle& track, const xAOD::Vertex& primaryVertex) const { + +// // Track quality requirements +// if (track.pt() < m_ptcut) return false; +// +// if (std::fabs(track.eta()) > m_etamax) return false; +// +// if ( !m_trkseltool->accept(track, &primaryVertex ) ) return false; +// +// // Vertex association requirements +// float deltaz0 = track.z0() + track.vz() - primaryVertex.z(); +// +// if ((std::fabs(track.d0()) > m_d0) || (std::fabs(sin(track.theta()) * deltaz0) > m_z0sintheta)) +// return false; + +// return true; +// } + + bool JetGhostTrackSelection::JetConsideredForGhostTrackSelection(double pt, const double eta) const{ + if ( (pt > m_ptcut_jet) && (std::abs(eta) < m_etamax_jet) ){ + return true; + } + else { + return false; + } + + } + + void JetGhostTrackSelection::print(std::ostream& os) const { + os << "Ghost Associated Track \n" + << " * pT > " << m_ptcut << "\n" + << " * |eta| < " << m_etamax + << " * |d0| < " << m_d0 + << " * |z0sintheta| < " << m_z0sintheta; + } + + +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetGhostTrackSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetGhostTrackSelectionBase.cxx new file mode 100644 index 0000000000000000000000000000000000000000..7a20491934a6714aac1e39b8a176abd3789fc8b0 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetGhostTrackSelectionBase.cxx @@ -0,0 +1,18 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration +*/ + +#include "TopObjectSelectionTools/JetGhostTrackSelectionBase.h" + +namespace top { + JetGhostTrackSelectionBase::JetGhostTrackSelectionBase() { + } + + JetGhostTrackSelectionBase::~JetGhostTrackSelectionBase() { + } + + std::ostream& operator << (std::ostream& os, const top::JetGhostTrackSelectionBase& selection) { + selection.print(os); + return os; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetMC15.cxx index 0121920e039c3dcba83dc943c3616ceaaebce7e3..d44c06f5c5211cdd2210d86bed28ab9697d097ac 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetMC15.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/JetMC15.h" @@ -9,24 +9,25 @@ #include "TopEvent/EventTools.h" namespace top { - JetMC15::JetMC15(const double ptcut, const double etamax, - const bool doJVTCut, - const std::string fwdJetSel) : + const bool doJVTCut): m_ptcut(ptcut), m_etamax(etamax), m_applyJVTCut(doJVTCut), - m_fwdJetSel(fwdJetSel), m_jvt_tool("JetJvtEfficiencyTool") { top::check(m_jvt_tool.retrieve(), "Failed to retrieve JVT tool"); } - // This version of the constructor always perform JVT cut + // This version of the constructor always perform JVT cut + JetMC15::JetMC15(const double ptcut, + const double etamax) : JetMC15::JetMC15(ptcut, etamax, true) {} + + // DEPRECIATED - fwdJetSel string now defunct, keeping blank string input for backwards compatibility JetMC15::JetMC15(const double ptcut, const double etamax, - const std::string fwdJetSel) : JetMC15::JetMC15(ptcut, etamax, true, fwdJetSel) {} + const std::string) : JetMC15::JetMC15(ptcut, etamax, true) {} // DEPRECATED - only kept for backward compatibility JetMC15::JetMC15(const double ptcut, @@ -34,31 +35,16 @@ namespace top { const double) : JetMC15::JetMC15(ptcut, etamax) {} bool JetMC15::passSelection(const xAOD::Jet& jet) { - if (jet.pt() < m_ptcut) - return false; - - if (std::fabs(jet.eta()) > m_etamax) - return false; - if (m_applyJVTCut) { - if (!m_jvt_tool->passesJvtCut(jet)) { - jet.auxdecor<char>("passJVT") = 0; - } - else { - jet.auxdecor<char>("passJVT") = 1; - } + jet.auxdecor<char>("passJVT") = (m_jvt_tool->passesJvtCut(jet) ? 1 : 0); } + //fJVT pass/fail decision already attatched in CP tools - if (m_fwdJetSel == "fJVT") { - if (!jet.getAttribute<char>("passFJVT")) - return false; - } - else if (m_fwdJetSel == "Tight") { - if (std::fabs(jet.eta()) > 2.5 && jet.pt() < 30e3) - return false; - } + if (jet.pt() < m_ptcut) return false; - jet.auxdecor<char>("good") = 1; + if (std::fabs(jet.eta()) > m_etamax) return false; + + jet.auxdecor<char>("good") = 1; jet.auxdecor<char>("closeToLepton") = 0; return true; @@ -68,5 +54,5 @@ namespace top { os << "JetMC15\n" << " * pT > " << m_ptcut << "\n" << " * |eta| < " << m_etamax << "\n"; - } + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetSelectionBase.cxx index 475c55f4c93e7f6528fc9bd3914d785cc28ae42f..559ad72d6b03403ea9e95ee51269eaa3a17f708c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetSelectionBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/JetSelectionBase.cxx @@ -1,20 +1,18 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/JetSelectionBase.h" namespace top { + JetSelectionBase::JetSelectionBase() { + } -JetSelectionBase::JetSelectionBase() { -} - -JetSelectionBase::~JetSelectionBase() { -} - -} + JetSelectionBase::~JetSelectionBase() { + } -std::ostream& operator<<(std::ostream& os, const top::JetSelectionBase& selection) { + std::ostream& operator << (std::ostream& os, const top::JetSelectionBase& selection) { selection.print(os); return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/LinkDef.h index 12b00eda063d7c2c84deb7b002b9446bcf76046c..8496427036cc7b44d40a9d1ff2df653e7a51c5a7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/LinkDef.h @@ -1,18 +1,12 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -#include "TopObjectSelectionTools/RCJetMC15.h" + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #ifdef __CINT__ -#pragma extra_include "TopObjectSelectionTools/RCJetMC15.h"; - #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ nestedclass; -#pragma link C++ class RCJetMC15+; - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MsgCategory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MsgCategory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e8b69082a9b1686d282b62dac1822ee9e5800175 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MsgCategory.cxx @@ -0,0 +1,6 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#include "TopObjectSelectionTools/MsgCategory.h" + +ANA_MSG_SOURCE(TopObjectSelectionTools, "TopObjectSelectionTools") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonMC15.cxx index 0ded97d78d1e0cb4a9b5fc31d184e72c17a238ea..6e9cfe9c1441b92e0eb58f6f41ce68201d631863 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonMC15.cxx @@ -1,111 +1,91 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/MuonMC15.h" #include "TopEvent/EventTools.h" -namespace top { +#include "TopObjectSelectionTools/MsgCategory.h" +using namespace TopObjectSelectionTools; +namespace top { MuonMC15::MuonMC15(const double ptcut, IsolationBase* isolation, const bool applyTTVACut) : m_ptcut(ptcut), m_muonSelectionTool("CP::MuonSelectionTool"), m_muonSelectionToolLoose("CP::MuonSelectionToolLoose"), m_isolation(isolation), - m_applyTTVACut(applyTTVACut) -{ - top::check( m_muonSelectionTool.retrieve() , "Failed to retrieve muonSelectionTool" ); - top::check( m_muonSelectionToolLoose.retrieve() , "Failed to retrieve muonSelectionToolLoose" ); - -} + m_applyTTVACut(applyTTVACut) { + top::check(m_muonSelectionTool.retrieve(), "Failed to retrieve muonSelectionTool"); + top::check(m_muonSelectionToolLoose.retrieve(), "Failed to retrieve muonSelectionToolLoose"); + } -bool MuonMC15::passSelection(const xAOD::Muon& mu) const -{ - if (mu.pt() < m_ptcut) - return false; + bool MuonMC15::passSelection(const xAOD::Muon& mu) const { + if (mu.pt() < m_ptcut) return false; ///-- https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15 --/// - if (!m_muonSelectionTool->accept(mu)) - return false; + if (!m_muonSelectionTool->accept(mu)) return false; //isolation, if m_isolation != nullptr - if (m_isolation && !m_isolation->passSelection(mu)) - return false; + if (m_isolation && !m_isolation->passSelection(mu)) return false; // Track-to-vertex association - if (m_applyTTVACut){ - if (!passTTVACuts(mu)) - return false; + if (m_applyTTVACut) { + if (!passTTVACuts(mu)) return false; } return true; -} + } -bool MuonMC15::passSelectionLoose(const xAOD::Muon& mu) const -{ - if (mu.pt() < m_ptcut) - return false; + bool MuonMC15::passSelectionLoose(const xAOD::Muon& mu) const { + if (mu.pt() < m_ptcut) return false; ///-- https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15 --/// - if (!m_muonSelectionToolLoose->accept(mu)) - return false; + if (!m_muonSelectionToolLoose->accept(mu)) return false; //isolation, if m_isolation != nullptr - if (m_isolation && !m_isolation->passSelectionLoose(mu)) - return false; + if (m_isolation && !m_isolation->passSelectionLoose(mu)) return false; // Track-to-vertex association - if (m_applyTTVACut){ - if (!passTTVACuts(mu)) - return false; + if (m_applyTTVACut) { + if (!passTTVACuts(mu)) return false; } return true; -} - -bool MuonMC15::passTTVACuts(const xAOD::Muon& mu) const -{ - - // TTVA: - // see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TrackingCPEOYE2015#Track_to_Vertex_Association - if( !mu.isAvailable<float>("d0sig") ){ - std::cout << "d0 significance not found for muon. " - << "Maybe no primary vertex? Won't accept." << std::endl; - return false; } - float d0sig = mu.auxdataConst<float>("d0sig"); - if( std::abs(d0sig) >= 3 ) - return false; + bool MuonMC15::passTTVACuts(const xAOD::Muon& mu) const { + // TTVA: + // see https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TrackingCPEOYE2015#Track_to_Vertex_Association + if (!mu.isAvailable<float>("d0sig")) { + ATH_MSG_WARNING("d0 significance not found for muon. " + << "Maybe no primary vertex? Won't accept."); + return false; + } - if( !mu.isAvailable<float>("delta_z0_sintheta") ){ - std::cout << "delta z0*sin(theta) not found for muon. " - << "Maybe no primary vertex? Won't accept." << std::endl; - return false; - } + float d0sig = mu.auxdataConst<float>("d0sig"); + if (std::abs(d0sig) >= 3) return false; - float delta_z0_sintheta = mu.auxdataConst<float>("delta_z0_sintheta"); - if( std::abs(delta_z0_sintheta) >= 0.5 ) - return false; + if (!mu.isAvailable<float>("delta_z0_sintheta")) { + ATH_MSG_WARNING("delta z0*sin(theta) not found for muon. " + << "Maybe no primary vertex? Won't accept."); + return false; + } - return true; + float delta_z0_sintheta = mu.auxdataConst<float>("delta_z0_sintheta"); + if (std::abs(delta_z0_sintheta) >= 0.5) return false; -} + return true; + } void MuonMC15::print(std::ostream& os) const { - os << "MuonMC15\n" - << " * pT > " << m_ptcut << "\n" + os << "MuonMC15\n" + << " * pT > " << m_ptcut << "\n" // << " * |eta| < " << m_etamax << "\n" // << " * quality=" << m_quality << " (tight=0, medium=1, loose=2, v.loose=3)\n" - << " * Everything else from muon tool - fill this in?\n"; + << " * Everything else from muon tool - fill this in?\n"; - if (!m_isolation) - os << " * No isolation requirement\n"; - else - m_isolation->print(os); + if (!m_isolation) os << " * No isolation requirement\n"; + else m_isolation->print(os); } - - - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonSelectionBase.cxx index f6dbfdff46c972f74e511dc266da216a1e02a241..e30d3bcbcd75a8694818a5257c65428fa84cc2a7 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonSelectionBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/MuonSelectionBase.cxx @@ -1,20 +1,18 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/MuonSelectionBase.h" namespace top { + MuonSelectionBase::MuonSelectionBase() { + } -MuonSelectionBase::MuonSelectionBase() { -} - -MuonSelectionBase::~MuonSelectionBase() { -} - -} + MuonSelectionBase::~MuonSelectionBase() { + } -std::ostream& operator<<(std::ostream& os, const top::MuonSelectionBase& selection) { + std::ostream& operator << (std::ostream& os, const top::MuonSelectionBase& selection) { selection.print(os); return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalASG.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalASG.cxx index 4d099c3457ba863e2b23cbf25bb505e2cb6adad5..2ffbfe2cdf7121b01ed0966713c07697ed815c48 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalASG.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalASG.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id$ #include "TopObjectSelectionTools/OverlapRemovalASG.h" @@ -9,72 +9,60 @@ #include <list> namespace top { - OverlapRemovalASG::OverlapRemovalASG(bool dolargeJet) : m_overlapRemovalTool("OverlapRemovalTool"), m_overlapRemovalToolLoose("OverlapRemovalToolLoose"), m_passPreORSelection("passPreORSelection"), m_passPreORSelectionLoose("passPreORSelectionLoose"), m_overlaps("overlaps"), - m_doLargeJet(dolargeJet) - { - - top::check( m_overlapRemovalTool.retrieve() , "Failed to retrieve overlap removal tool" ); - top::check( m_overlapRemovalToolLoose.retrieve() , "Failed to retrieve (loose) overlap removal tool" ); - + m_doLargeJet(dolargeJet) { + top::check(m_overlapRemovalTool.retrieve(), "Failed to retrieve overlap removal tool"); + top::check(m_overlapRemovalToolLoose.retrieve(), "Failed to retrieve (loose) overlap removal tool"); } - OverlapRemovalASG::~OverlapRemovalASG() - { + OverlapRemovalASG::~OverlapRemovalASG() { } - void OverlapRemovalASG::overlapremoval(const xAOD::PhotonContainer* photon , - const xAOD::ElectronContainer* el , - const xAOD::MuonContainer* mu , - const xAOD::TauJetContainer* tau , - const xAOD::JetContainer* jet , - const xAOD::JetContainer* ljet, + void OverlapRemovalASG::overlapremoval(const xAOD::PhotonContainer* photon, + const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::TauJetContainer* tau, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, std::vector<unsigned int>& goodPhotons, std::vector<unsigned int>& goodElectrons, std::vector<unsigned int>& goodMuons, std::vector<unsigned int>& goodTaus, std::vector<unsigned int>& goodJets, std::vector<unsigned int>& goodLargeRJets, - const bool isLoose ) - { + const bool isLoose) { std::string passTopCuts(""); if (!isLoose) { - if (m_doLargeJet) - top::check( m_overlapRemovalTool->removeOverlaps( el, mu, jet, tau, photon, ljet ) , "Failed to remove overlaps" ); - else - top::check( m_overlapRemovalTool->removeOverlaps( el, mu, jet, tau, photon ) , "Failed to remove overlaps" ); + if (m_doLargeJet) top::check(m_overlapRemovalTool->removeOverlaps(el, mu, jet, tau, photon, + ljet), "Failed to remove overlaps"); + else top::check(m_overlapRemovalTool->removeOverlaps(el, mu, jet, tau, photon), "Failed to remove overlaps"); passTopCuts = m_passPreORSelection; } if (isLoose) { - if (m_doLargeJet) - top::check( m_overlapRemovalToolLoose->removeOverlaps( el, mu, jet, tau, photon, ljet ) , "Failed to remove overlaps" ); - else - top::check( m_overlapRemovalToolLoose->removeOverlaps( el, mu, jet, tau, photon ) , "Failed to remove overlaps" ); + if (m_doLargeJet) top::check(m_overlapRemovalToolLoose->removeOverlaps(el, mu, jet, tau, photon, + ljet), "Failed to remove overlaps"); + else top::check(m_overlapRemovalToolLoose->removeOverlaps(el, mu, jet, tau, photon), "Failed to remove overlaps"); + passTopCuts = m_passPreORSelectionLoose; } - removeObjectOverlap( photon, goodPhotons, passTopCuts ); - removeObjectOverlap( el, goodElectrons, passTopCuts ); - removeObjectOverlap( mu, goodMuons, passTopCuts ); - removeObjectOverlap( tau, goodTaus, passTopCuts ); - removeObjectOverlap( jet, goodJets, passTopCuts ); - if (m_doLargeJet) - removeObjectOverlap( ljet, goodLargeRJets, passTopCuts ); - else - removeObject( ljet, goodLargeRJets, passTopCuts ); - - + removeObjectOverlap(photon, goodPhotons, passTopCuts); + removeObjectOverlap(el, goodElectrons, passTopCuts); + removeObjectOverlap(mu, goodMuons, passTopCuts); + removeObjectOverlap(tau, goodTaus, passTopCuts); + removeObjectOverlap(jet, goodJets, passTopCuts); + if (m_doLargeJet) removeObjectOverlap(ljet, goodLargeRJets, passTopCuts); + else removeObject(ljet, goodLargeRJets, passTopCuts); } - void OverlapRemovalASG::removeObjectOverlap( const xAOD::IParticleContainer* xaod, - std::vector<unsigned int>& OUT_vec, - const std::string passTopCuts) { - + void OverlapRemovalASG::removeObjectOverlap(const xAOD::IParticleContainer* xaod, + std::vector<unsigned int>& OUT_vec, + const std::string passTopCuts) { OUT_vec.clear(); unsigned int index(0); @@ -89,10 +77,9 @@ namespace top { } } - void OverlapRemovalASG::removeObject( const xAOD::IParticleContainer* xaod, - std::vector<unsigned int>& OUT_vec, - const std::string passTopCuts) { - + void OverlapRemovalASG::removeObject(const xAOD::IParticleContainer* xaod, + std::vector<unsigned int>& OUT_vec, + const std::string passTopCuts) { OUT_vec.clear(); unsigned int index(0); @@ -107,12 +94,11 @@ namespace top { } } -void OverlapRemovalASG::print(std::ostream& os) const { + void OverlapRemovalASG::print(std::ostream& os) const { os << "OverlapRemovalASG\n"; os << " (1) remove electron that sharing track with muon\n"; os << " (2) remove single jet closest to an electron (within dR < 0.2)\n"; os << " (3) remove electron with dR < 0.4 of jet\n"; os << " (4) remove muon within dR < 0.4 of any jet\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalBase.cxx index 84b3c250edf0f5f4df9180ebf3112fc69e1c8888..ac0db026190744c5d96c0394e73f2962df37eeb0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalBase.cxx @@ -1,20 +1,18 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/OverlapRemovalBase.h" namespace top { + OverlapRemovalBase::OverlapRemovalBase() { + } -OverlapRemovalBase::OverlapRemovalBase() { -} - -OverlapRemovalBase::~OverlapRemovalBase() { -} - -} + OverlapRemovalBase::~OverlapRemovalBase() { + } -std::ostream& operator<<(std::ostream& os, const top::OverlapRemovalBase& overlapremoval) { + std::ostream& operator << (std::ostream& os, const top::OverlapRemovalBase& overlapremoval) { overlapremoval.print(os); return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalIndices.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalIndices.cxx index fa90456dfa5cfa26e145d5a1227e149eaf9d5809..467ec7c50b75873fcdc8beee399af9bc5a6c680e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalIndices.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/OverlapRemovalIndices.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: OverlapRemovalIndices.cxx 661110 2015-04-17 00:03:39Z morrisj $ #include "TopObjectSelectionTools/OverlapRemovalIndices.h" @@ -9,111 +9,108 @@ #include <list> namespace top { + OverlapRemovalIndices::OverlapRemovalIndices() { + } -OverlapRemovalIndices::OverlapRemovalIndices() { -} + OverlapRemovalIndices::~OverlapRemovalIndices() { + } -OverlapRemovalIndices::~OverlapRemovalIndices() { -} + void OverlapRemovalIndices::overlapremoval(const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, + std::vector<unsigned int>& OUT_el, + std::vector<unsigned int>& OUT_mu, + std::vector<unsigned int>& OUT_jet, + std::vector<unsigned int>& OUT_ljet, + const bool isLoose) { + std::string passTopCuts(""); + if (!isLoose) { + passTopCuts = "passPreORSelection"; + } + if (isLoose) { + passTopCuts = "passPreORSelectionLoose"; + } -void OverlapRemovalIndices::overlapremoval(const xAOD::ElectronContainer* el, - const xAOD::MuonContainer* mu, - const xAOD::JetContainer* jet, - const xAOD::JetContainer* ljet, - std::vector<unsigned int>& OUT_el, - std::vector<unsigned int>& OUT_mu, - std::vector<unsigned int>& OUT_jet, - std::vector<unsigned int>& OUT_ljet, - const bool isLoose ) -{ - std::string passTopCuts(""); - if (!isLoose) { - passTopCuts = "passPreORSelection"; - } - if (isLoose) { - passTopCuts = "passPreORSelectionLoose"; - } - // Work internally with std::list // What passed the pre-overlap removal selection? - std::vector<unsigned int> IN_el,IN_mu,IN_jet,IN_ljet; - std::list<unsigned int> l_el,l_mu,l_jet,l_ljet; - unsigned int index_el(0),index_mu(0),index_jet(0),index_ljet(0); + std::vector<unsigned int> IN_el, IN_mu, IN_jet, IN_ljet; + std::list<unsigned int> l_el, l_mu, l_jet, l_ljet; + unsigned int index_el(0), index_mu(0), index_jet(0), index_ljet(0); if (el) { - for( auto x : *el ){ - if( x->auxdataConst< char >(passTopCuts) == 1 ){ - IN_el.push_back(index_el); - l_el.push_back(index_el); - } - ++index_el; + for (auto x : *el) { + if (x->auxdataConst< char >(passTopCuts) == 1) { + IN_el.push_back(index_el); + l_el.push_back(index_el); } + ++index_el; + } } if (mu) { - for( auto x : *mu ){ - if( x->auxdataConst< char >(passTopCuts) == 1 ){ - IN_mu.push_back(index_mu); - l_mu.push_back(index_mu); - } - ++index_mu; + for (auto x : *mu) { + if (x->auxdataConst< char >(passTopCuts) == 1) { + IN_mu.push_back(index_mu); + l_mu.push_back(index_mu); } + ++index_mu; + } } if (jet) { - for( auto x : *jet ){ - if( x->auxdataConst< char >(passTopCuts) == 1 ){ - IN_jet.push_back(index_jet); - l_jet.push_back(index_jet); - } - ++index_jet; + for (auto x : *jet) { + if (x->auxdataConst< char >(passTopCuts) == 1) { + IN_jet.push_back(index_jet); + l_jet.push_back(index_jet); } + ++index_jet; + } } if (ljet) { - for( auto x : *ljet ){ - if( x->auxdataConst< char >(passTopCuts) == 1 ){ - IN_ljet.push_back(index_ljet); - l_ljet.push_back(index_ljet); - } - ++index_ljet; + for (auto x : *ljet) { + if (x->auxdataConst< char >(passTopCuts) == 1) { + IN_ljet.push_back(index_ljet); + l_ljet.push_back(index_ljet); } + ++index_ljet; + } } // Jets and Muons - remove muon with dR < 0.4 - for( auto j : IN_jet ){ - for( auto m : IN_mu ){ - if( top::deltaR( *(jet->at(j) ) , *(mu->at(m)) ) < 0.4 ){ - l_mu.remove( m ); - } + for (auto j : IN_jet) { + for (auto m : IN_mu) { + if (top::deltaR(*(jet->at(j)), *(mu->at(m))) < 0.4) { + l_mu.remove(m); } + } } // Jets and Electrons - remove single closest jet with dR < 0.2 for (auto e : IN_el) { - double closestdr = 100.; - int closestJetIndex = -1; - for (auto j : IN_jet) { - const double ejetdr = top::deltaR(*(jet->at(j)) , *(el->at(e))); - - if (ejetdr < 0.2 && ejetdr < closestdr) { - closestdr = ejetdr; - closestJetIndex = j; - } + double closestdr = 100.; + int closestJetIndex = -1; + for (auto j : IN_jet) { + const double ejetdr = top::deltaR(*(jet->at(j)), *(el->at(e))); + + if (ejetdr < 0.2 && ejetdr < closestdr) { + closestdr = ejetdr; + closestJetIndex = j; } + } - if (closestJetIndex > -1) - l_jet.remove(closestJetIndex); + if (closestJetIndex > -1) l_jet.remove(closestJetIndex); } // Electrons and Jets - remove electrons with dR < 0.4 - for( auto j : l_jet ){ - for( auto e : IN_el ){ - if( top::deltaR( *(el->at(e)) , *(jet->at(j)) ) < 0.4 ){ - l_el.remove( e ); - } + for (auto j : l_jet) { + for (auto e : IN_el) { + if (top::deltaR(*(el->at(e)), *(jet->at(j))) < 0.4) { + l_el.remove(e); } + } } // Save what's left of the std::lists into the OUT vectors; @@ -122,36 +119,40 @@ void OverlapRemovalIndices::overlapremoval(const xAOD::ElectronContainer* el, OUT_jet.clear(); OUT_ljet.clear(); - for( auto i : l_el ){OUT_el.push_back(i); } - for( auto i : l_mu ){OUT_mu.push_back(i); } - for( auto i : l_jet ){OUT_jet.push_back(i);} - for( auto i : l_ljet ){OUT_ljet.push_back(i);} -} - -void OverlapRemovalIndices::overlapremoval(const xAOD::PhotonContainer* /*photon*/ , - const xAOD::ElectronContainer* el , - const xAOD::MuonContainer* mu , - const xAOD::TauJetContainer* /*tau*/ , - const xAOD::JetContainer* jet , - const xAOD::JetContainer* ljet, - std::vector<unsigned int>& /*goodPhotons*/, - std::vector<unsigned int>& goodElectrons, - std::vector<unsigned int>& goodMuons, - std::vector<unsigned int>& /*goodTaus*/, - std::vector<unsigned int>& goodJets, - std::vector<unsigned int>& goodLargeRJets, - const bool isLoose ) -{ - - overlapremoval(el, mu, jet, ljet, goodElectrons, goodMuons, goodJets, goodLargeRJets, isLoose ); + for (auto i : l_el) { + OUT_el.push_back(i); + } + for (auto i : l_mu) { + OUT_mu.push_back(i); + } + for (auto i : l_jet) { + OUT_jet.push_back(i); + } + for (auto i : l_ljet) { + OUT_ljet.push_back(i); + } + } -} + void OverlapRemovalIndices::overlapremoval(const xAOD::PhotonContainer* /*photon*/, + const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::TauJetContainer* /*tau*/, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, + std::vector<unsigned int>& /*goodPhotons*/, + std::vector<unsigned int>& goodElectrons, + std::vector<unsigned int>& goodMuons, + std::vector<unsigned int>& /*goodTaus*/, + std::vector<unsigned int>& goodJets, + std::vector<unsigned int>& goodLargeRJets, + const bool isLoose) { + overlapremoval(el, mu, jet, ljet, goodElectrons, goodMuons, goodJets, goodLargeRJets, isLoose); + } -void OverlapRemovalIndices::print(std::ostream& os) const { + void OverlapRemovalIndices::print(std::ostream& os) const { os << "OverlapRemovalIndices\n"; os << " (1) remove muon within dR < 0.4 of any jet\n"; os << " (2) remove single jet closest to an electron (within dR < 0.2)\n"; os << " (3) remove electron with dR < 0.4 of jet\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonMC16.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonMC16.cxx new file mode 100644 index 0000000000000000000000000000000000000000..d79c46fa82d32c3e6e46ae8ef74fd6207d43b8d5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonMC16.cxx @@ -0,0 +1,118 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopObjectSelectionTools/PhotonMC16.h" + +// Include what you use! +#include <map> +#include <string> + +#include "TopEvent/EventTools.h" + +#include "TopObjectSelectionTools/MsgCategory.h" +using namespace TopObjectSelectionTools; + +namespace top { + PhotonMC16::PhotonMC16(double ptcut, double etamax, IsolationBase* isolation, bool usePhotonShowerShapeVariables) : + m_ptcut(ptcut), + m_etamax(etamax), + m_photon_selection("DFCommonPhotonsIsEMTight"), + m_loose_photon_selection("DFCommonPhotonsIsEMLoose"), + m_isolation(isolation), + m_usePhotonShowerShapeVariables(usePhotonShowerShapeVariables) { + } + + PhotonMC16::PhotonMC16(double ptcut, double etamax, + const std::string& tightID, + const std::string& looseID, + IsolationBase* isolation, + bool usePhotonShowerShapeVariables) : + m_ptcut(ptcut), + m_etamax(etamax), + m_photon_selection(tightID), + m_loose_photon_selection(looseID), + m_isolation(isolation), + m_usePhotonShowerShapeVariables(usePhotonShowerShapeVariables) { + // Make a map of shortcuts e.g "Tight = DFCommonPhotonsIsEMTight" + std::map<std::string, std::string> id_map; + id_map["Tight"] = "DFCommonPhotonsIsEMTight"; + id_map["Loose"] = "DFCommonPhotonsIsEMLoose"; + id_map["None"] = "None"; + // If ID in map then set it to full name, else keep as is. + if (id_map.find(tightID) != id_map.end()) m_photon_selection = id_map[tightID]; + if (id_map.find(looseID) != id_map.end()) m_loose_photon_selection = id_map[looseID]; + } + + bool PhotonMC16::passSelection(const xAOD::Photon& ph) const { + if (!passSelectionNoIsolation(ph, m_photon_selection)) return false; + + if (m_isolation && !m_isolation->passSelection(ph)) return false; + + return true; + } + + bool PhotonMC16::passSelectionLoose(const xAOD::Photon& ph) const { + if (!passSelectionNoIsolation(ph, m_loose_photon_selection)) return false; + + if (m_isolation && !m_isolation->passSelectionLoose(ph)) return false; + + return true; + } + + bool PhotonMC16::passSelectionNoIsolation(const xAOD::Photon& ph, + const std::string& photon_selection) const { + // Photon author : AuthorPhoton/AuthorAmbiguous. + // Also, for special-case recovery of soft photons: + // xAOD::EgammaParameters::AuthorCaloTopo35. + if (ph.author() != xAOD::EgammaParameters::AuthorPhoton + && ph.author() != xAOD::EgammaParameters::AuthorAmbiguous) return false; + + if (ph.pt() < m_ptcut) return false; + + // removing bad photon cluser [http://cern.ch/go/kp8F] + if (!ph.isGoodOQ(xAOD::EgammaParameters::BADCLUSPHOTON)) return false; + + // Photon selection using derivation decorations + if (photon_selection != "None") + if (!ph.auxdataConst<char>(photon_selection)) return false; + + if (!ph.caloCluster()) return false; + + float abs_eta = std::abs(ph.caloCluster()->etaBE(2)); + if (abs_eta > m_etamax) return false; + + // Remove crack region + if (abs_eta > 1.37 && abs_eta < 1.52) return false; + + // Photon cleaning [http://cern.ch/go/8RdK] + // <tom.neep@cern.ch>: This is madness!! I *think* this is the right way + // to do this but there should really be a helper function supplied by egamma! + // <iconnell@cern.ch>: Updating the cleaning for R21, using similar options... + if (m_usePhotonShowerShapeVariables) { + try { + if ((ph.OQ() & 1073741824) != 0 || + ((ph.OQ() & 134217728) != 0 && + (ph.showerShapeValue(xAOD::EgammaParameters::Reta) > 0.98 + || ph.showerShapeValue(xAOD::EgammaParameters::f1) > 0.4 + || (ph.OQ() & 67108864) != 0))) return false; + } + catch (const SG::ExcBadAuxVar& e) { + ATH_MSG_WARNING("Didn't find the necessary photon shower shapes variables for photon cleaning! This might be a derivation issue, skipping from now on."); + m_usePhotonShowerShapeVariables = false; + } + } + + return true; + } + + void PhotonMC16::print(std::ostream& os) const { + os << "PhotonMC16\n"; + os << " * pT > " << m_ptcut << "\n"; + os << " * |eta| < " << m_etamax << "\n"; + os << " * Photon PID: " << m_photon_selection << "\n"; + os << " * Loose Photon PID: " << m_loose_photon_selection << "\n"; + if (!m_isolation) os << " * No isolation requirement\n"; + else m_isolation->print(os); + } +} // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonSelectionBase.cxx index 20527343eeee379386f635b14b004db67690c75a..08db6326c80c23462aa10bbf01d2083bff760a48 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonSelectionBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/PhotonSelectionBase.cxx @@ -1,22 +1,20 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/PhotonSelectionBase.h" #include <iostream> namespace top { + PhotonSelectionBase::PhotonSelectionBase() { + } -PhotonSelectionBase::PhotonSelectionBase() { -} - -PhotonSelectionBase::~PhotonSelectionBase() { -} - -} + PhotonSelectionBase::~PhotonSelectionBase() { + } -std::ostream& operator<<(std::ostream& os, const top::PhotonSelectionBase& selection) { + std::ostream& operator << (std::ostream& os, const top::PhotonSelectionBase& selection) { selection.print(os); return os; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/SoftMuonMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/SoftMuonMC15.cxx new file mode 100644 index 0000000000000000000000000000000000000000..306fd89d235a6cfaa64f1f742793e4b14827c51c --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/SoftMuonMC15.cxx @@ -0,0 +1,30 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopObjectSelectionTools/SoftMuonMC15.h" + +#include "TopEvent/EventTools.h" + +namespace top { + SoftMuonMC15::SoftMuonMC15(const double ptcut) : + m_ptcut(ptcut), + m_softmuonSelectionTool("CP::SoftMuonSelectionTool") { + top::check(m_softmuonSelectionTool.retrieve(), "Failed to retrieve softmuonSelectionTool"); + } + + bool SoftMuonMC15::passSelection(const xAOD::Muon& mu) const { + if (mu.pt() < m_ptcut) return false; + + ///-- https://twiki.cern.ch/twiki/bin/view/AtlasProtected/MCPAnalysisGuidelinesMC15 --/// + if (!m_softmuonSelectionTool->accept(mu)) return false; + + return true; + } + + void SoftMuonMC15::print(std::ostream& os) const { + os << "SoftMuonMC15\n" + << " * pT > " << m_ptcut << "\n" + << " * Everything else from muon tool - fill this in?\n"; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/SoftMuonSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/SoftMuonSelectionBase.cxx new file mode 100644 index 0000000000000000000000000000000000000000..bc9cdf7979b164bf5a5c8fb881301461f857d48e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/SoftMuonSelectionBase.cxx @@ -0,0 +1,18 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopObjectSelectionTools/SoftMuonSelectionBase.h" + +namespace top { + SoftMuonSelectionBase::SoftMuonSelectionBase() { + } + + SoftMuonSelectionBase::~SoftMuonSelectionBase() { + } + + std::ostream& operator << (std::ostream& os, const top::SoftMuonSelectionBase& selection) { + selection.print(os); + return os; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauMC15.cxx index df9cbe62f0e3322ebccc384ce43804aaa2056abd..c169e6a3243e527d959cb3ba636ede935a85aa75 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauMC15.cxx @@ -1,54 +1,51 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/TauMC15.h" #include "TopEvent/EventTools.h" namespace top { - -TauMC15::TauMC15() : m_tauSelection("TauAnalysisTools::TauSelectionTool"), - m_tauSelectionLoose - ("TauAnalysisTools::TauSelectionToolLoose") { - top::check(m_tauSelection.retrieve(), - "Failed to retrieve tau selection tool"); - top::check(m_tauSelectionLoose.retrieve(), - "Failed to retrieve loose tau selection tool"); -} - -bool TauMC15::passSelection(const xAOD::TauJet& tau) const { - // Get the WP related decisions from TauSelectionTool - - // HIGG8D1 derivations (and possibly others) skim away - // tau tracks with pT<15 GeV. The tau selector tool - // returns an exception in this case. These taus should - // NOT be selected so return false if an exception is raised. - try { - return m_tauSelection->accept(tau); - } catch (std::runtime_error& e) { - // If an exception is raised (possibly due to no tau track) - // then return false - return false; + TauMC15::TauMC15() : m_tauSelection("TauAnalysisTools::TauSelectionTool"), + m_tauSelectionLoose + ("TauAnalysisTools::TauSelectionToolLoose") { + top::check(m_tauSelection.retrieve(), + "Failed to retrieve tau selection tool"); + top::check(m_tauSelectionLoose.retrieve(), + "Failed to retrieve loose tau selection tool"); } -} -bool TauMC15::passSelectionLoose(const xAOD::TauJet& tau) const { - // get the WP related decisions from TauSelectionTool - // For the reasoning behind try/catch see above... - try { - return m_tauSelectionLoose->accept(tau); - } catch (std::runtime_error& e) { - return false; + bool TauMC15::passSelection(const xAOD::TauJet& tau) const { + // Get the WP related decisions from TauSelectionTool + + // HIGG8D1 derivations (and possibly others) skim away + // tau tracks with pT<15 GeV. The tau selector tool + // returns an exception in this case. These taus should + // NOT be selected so return false if an exception is raised. + try { + return static_cast<bool>(m_tauSelection->accept(tau)); + } catch (std::runtime_error& e) { + // If an exception is raised (possibly due to no tau track) + // then return false + return false; + } } -} - -void TauMC15::print(std::ostream& os) const { - os << "TauMC15\n"; - os << " * Taus are now selected using the TauSelectionTool"<< "\n"; - os << " * Either you have supplied a tau configuration file (expert)\n"; - os << " or set pT, JetIDWP and EleOLR options in your top-xaod\n"; - os << " configuration file."; -} + bool TauMC15::passSelectionLoose(const xAOD::TauJet& tau) const { + // get the WP related decisions from TauSelectionTool + // For the reasoning behind try/catch see above... + try { + return static_cast<bool>(m_tauSelectionLoose->accept(tau)); + } catch (std::runtime_error& e) { + return false; + } + } + void TauMC15::print(std::ostream& os) const { + os << "TauMC15\n"; + os << " * Taus are now selected using the TauSelectionTool" << "\n"; + os << " * Either you have supplied a tau configuration file (expert)\n"; + os << " or set pT, JetIDWP and EleOLR options in your top-xaod\n"; + os << " configuration file."; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauSelectionBase.cxx index 99f9366c8bd450511eaa2c1582af8a0c3f62900a..ce8206b962f1d24183d85da0d847d790b15ece7f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauSelectionBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TauSelectionBase.cxx @@ -1,20 +1,18 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/TauSelectionBase.h" namespace top { + TauSelectionBase::TauSelectionBase() { + } -TauSelectionBase::TauSelectionBase() { + TauSelectionBase::~TauSelectionBase() { + } } -TauSelectionBase::~TauSelectionBase() { -} - -} - -std::ostream& operator<<(std::ostream& os, const top::TauSelectionBase& selection) { - selection.print(os); - return os; +std::ostream& operator << (std::ostream& os, const top::TauSelectionBase& selection) { + selection.print(os); + return os; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TopObjectSelection.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TopObjectSelection.cxx index 2842e20c999a9c6f36309748d9259f17f9aecfb3..def7388b3c7566bec12e7cab11da11b3797b3495 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TopObjectSelection.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TopObjectSelection.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/TopObjectSelection.h" @@ -14,640 +14,1217 @@ #include "xAODMuon/MuonContainer.h" #include "xAODTau/TauJetContainer.h" #include "xAODJet/JetContainer.h" +#include "xAODTracking/TrackParticleContainer.h" #include "xAODMissingET/MissingETContainer.h" +#include "xAODEventInfo/EventInfo.h" -namespace top { - -TopObjectSelection::TopObjectSelection( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr), +#include "FourMomUtils/xAODP4Helpers.h" +//#include "PATCore/TAccept.h" - m_electronSelection(nullptr), - m_muonSelection(nullptr), - m_tauSelection(nullptr), - m_jetSelection(nullptr), - m_photonSelection(nullptr), - m_largeJetSelection(nullptr), - m_trackJetSelection(nullptr), +#include "TopParticleLevel/TruthTools.h" +#include "xAODTruth/TruthParticle.h" +#include "xAODTruth/TruthParticleContainer.h" - m_overlapRemovalToolPostSelection(nullptr), - - m_electronInJetSubtractor(nullptr), - - m_passPreORSelection("passPreORSelection"), - m_passPreORSelectionLoose("passPreORSelectionLoose"), - // the following two are used to give failing JVT jets a lower priority in the OR - m_ORToolDecoration("ORToolDecoration"), - m_ORToolDecorationLoose("ORToolDecorationLoose"), - - m_doLooseCuts(false) -{ - declareProperty( "config" , m_config ); -} +#include "TopDataPreparation/SampleXsection.h" - StatusCode TopObjectSelection::initialize() +namespace top { + TopObjectSelection::TopObjectSelection(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + m_electronSelection(nullptr), + m_fwdElectronSelection(nullptr), + m_muonSelection(nullptr), + m_softmuonSelection(nullptr), + m_tauSelection(nullptr), + m_jetSelection(nullptr), + m_photonSelection(nullptr), + m_largeJetSelection(nullptr), + m_trackJetSelection(nullptr), + m_jetGhostTrackSelection(nullptr), + m_trackSelection(nullptr), + m_overlapRemovalToolPostSelection(nullptr), + m_electronInJetSubtractor(nullptr), + m_passPreORSelection("passPreORSelection"), + m_passPreORSelectionLoose("passPreORSelectionLoose"), + // the following two are used to give failing JVT and failing fJVT jets a lower priority in the OR + m_ORToolDecoration("ORToolDecoration"), + m_ORToolDecorationLoose("ORToolDecorationLoose"), + m_doLooseCuts(false), + m_overlapRemovalTool_softMuons_PFjets("OverlapRemovalTool_softMuons_PFjets"), + m_overlapRemovalTool_softMuons_Alljets("OverlapRemovalTool_softMuons_Alljets") { - // If there are loose selection requirements, then we need additional computations - // Tight leptons are not constrained to be a sub-set of loose - // We will call the selections in the following order: - // (1) passSelection(); - // (2) passSelectionLoose(); - // - // If your tight is not a sub-set of your loose, then you have 2 different functions - // If your tight is a sub-set of your loose, then I suggest you set a loose flag - // when calling passSelection(), then have passSelectionLoose() return this flag - // - // Requests to process loose selections can come from: - // (1) Data event - // (2) User request overlap removal be done on loose objects - // - The top recommendation is that you do OR on tight objects - // (3) Determination of Fakes control regions in MC - expert fakes mode - // - - if (!m_config->isMC()) - m_doLooseCuts = true; - - if (m_config->doOverlapRemovalOnLooseLeptonDef()) - m_doLooseCuts = true; - - if (m_config->doLooseEvents()) - m_doLooseCuts = true; - - if (m_config->applyElectronInJetSubtraction()) { - m_electronInJetSubtractor = std::unique_ptr<top::ElectronInJetSubtractionCollectionMaker> - ( new top::ElectronInJetSubtractionCollectionMaker( "top::ElectronInJetSubtractionCollectionMaker" ) ); - top::check( m_electronInJetSubtractor->setProperty( "config" , m_config ) , "Failed to setProperty of top::ElectronInJetSubtractionCollectionMaker" ); - top::check( m_electronInJetSubtractor->initialize() , "Failed to initialize top::ElectronInJetSubtractionCollectionMaker" ); + declareProperty("config", m_config); } - - // b-tagging stuff - // for calo jets - std::vector<std::string> availableWPs = m_config->bTagWP_available(); - for (auto& WP : availableWPs) { - m_btagSelTools[WP] = "BTaggingSelectionTool_"+WP+"_"+m_config->sgKeyJets(); - top::check( m_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool" ); - } - // for track jets - availableWPs = m_config->bTagWP_available_trkJet(); - for (auto& WP : availableWPs) { - m_trkjet_btagSelTools[WP] = "BTaggingSelectionTool_"+WP+"_"+m_config->sgKeyTrackJets(); - top::check( m_trkjet_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool" ); - } - - return StatusCode::SUCCESS; -} + StatusCode TopObjectSelection::initialize() { + // If there are loose selection requirements, then we need additional computations + // Tight leptons are not constrained to be a sub-set of loose + // We will call the selections in the following order: + // (1) passSelection(); + // (2) passSelectionLoose(); + // + // If your tight is not a sub-set of your loose, then you have 2 different functions + // If your tight is a sub-set of your loose, then I suggest you set a loose flag + // when calling passSelection(), then have passSelectionLoose() return this flag + // + // Requests to process loose selections can come from: + // (1) Data event + // (2) User request overlap removal be done on loose objects + // - The top recommendation is that you do OR on tight objects + // (3) Determination of Fakes control regions in MC - expert fakes mode + // + + if (m_config->useSoftMuons()) { + top::check(m_overlapRemovalTool_softMuons_PFjets.retrieve(), "Failed to retrieve overlap removal tool for soft muons - PF jets"); + top::check(m_overlapRemovalTool_softMuons_Alljets.retrieve(), "Failed to retrieve overlap removal tool for soft muons - all jets"); + } + + if (!m_config->isMC()) m_doLooseCuts = true; + + if (m_config->doOverlapRemovalOnLooseLeptonDef()) m_doLooseCuts = true; + + if (m_config->doLooseEvents()) m_doLooseCuts = true; + + if(m_config->useLooseObjectsInMETInLooseTree() || m_config->useLooseObjectsInMETInNominalTree() || m_config->writeMETBuiltWithLooseObjects()) m_doLooseCuts = true; + + if (m_config->applyElectronInJetSubtraction()) { + m_electronInJetSubtractor = std::unique_ptr<top::ElectronInJetSubtractionCollectionMaker> + (new top::ElectronInJetSubtractionCollectionMaker( + "top::ElectronInJetSubtractionCollectionMaker")); + top::check(m_electronInJetSubtractor->setProperty("config", + m_config), + "Failed to setProperty of top::ElectronInJetSubtractionCollectionMaker"); + top::check( + m_electronInJetSubtractor->initialize(), "Failed to initialize top::ElectronInJetSubtractionCollectionMaker"); + } + + // b-tagging stuff + // for calo jets + std::vector<std::string> availableWPs = m_config->bTagWP_available(); + for (auto& WP : availableWPs) { + m_btagSelTools[WP] = "BTaggingSelectionTool_" + WP + "_" + m_config->sgKeyJets(); + top::check(m_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool"); + } + // for track jets + availableWPs = m_config->bTagWP_available_trkJet(); + for (auto& WP : availableWPs) { + m_trkjet_btagSelTools[WP] = "BTaggingSelectionTool_" + WP + "_" + m_config->sgKeyTrackJets(); + top::check(m_trkjet_btagSelTools[WP].retrieve(), "Failed to retrieve b-tagging Selection tool"); + } + return StatusCode::SUCCESS; + } -void TopObjectSelection::electronSelection(ElectronSelectionBase* ptr) { + void TopObjectSelection::electronSelection(ElectronSelectionBase* ptr) { m_electronSelection.reset(ptr); -} + } + + void TopObjectSelection::fwdElectronSelection(FwdElectronSelectionBase* ptr) { + m_fwdElectronSelection.reset(ptr); + } -void TopObjectSelection::muonSelection(MuonSelectionBase* ptr) { + void TopObjectSelection::muonSelection(MuonSelectionBase* ptr) { m_muonSelection.reset(ptr); -} + } -void TopObjectSelection::tauSelection(TauSelectionBase* ptr) { + void TopObjectSelection::softmuonSelection(SoftMuonSelectionBase* ptr) { + m_softmuonSelection.reset(ptr); + } + + void TopObjectSelection::tauSelection(TauSelectionBase* ptr) { m_tauSelection.reset(ptr); -} + } -void TopObjectSelection::jetSelection(JetSelectionBase* ptr) { + void TopObjectSelection::jetSelection(JetSelectionBase* ptr) { m_jetSelection.reset(ptr); -} + } -void TopObjectSelection::photonSelection(PhotonSelectionBase* ptr) { - m_photonSelection.reset(ptr); -} - -void TopObjectSelection::largeJetSelection(JetSelectionBase* ptr) { + void TopObjectSelection::photonSelection(PhotonSelectionBase* ptr) { + m_photonSelection.reset(ptr); + } + + void TopObjectSelection::largeJetSelection(JetSelectionBase* ptr) { m_largeJetSelection.reset(ptr); -} + } -void TopObjectSelection::trackJetSelection(JetSelectionBase* ptr) { + void TopObjectSelection::trackJetSelection(JetSelectionBase* ptr) { m_trackJetSelection.reset(ptr); -} + } + + void TopObjectSelection::jetGhostTrackSelection(JetGhostTrackSelectionBase* ptr) { + m_jetGhostTrackSelection.reset(ptr); + } + + void TopObjectSelection::trackSelection(TrackSelectionBase* ptr) { + m_trackSelection.reset(ptr); + } + -void TopObjectSelection::overlapRemovalPostSelection(OverlapRemovalBase* ptr) { + void TopObjectSelection::overlapRemovalPostSelection(OverlapRemovalBase* ptr) { m_overlapRemovalToolPostSelection.reset(ptr); -} + } -StatusCode TopObjectSelection::execute() -{ - applySelectionPreOverlapRemoval(); - top::check( applyOverlapRemoval() , "Failed to apply overlap removal" ); - return StatusCode::SUCCESS; -} + StatusCode TopObjectSelection::execute(bool executeNominal) { + // Set variable to tell us if we are doing this execution on nominal or systematic events + m_executeNominal = executeNominal; + applySelectionPreOverlapRemoval(); + top::check(applyOverlapRemoval(), "Failed to apply overlap removal"); -void TopObjectSelection::applySelectionPreOverlapRemoval() -{ + return StatusCode::SUCCESS; + } + + void TopObjectSelection::applySelectionPreOverlapRemoval() { + // If we are doing Electron in Jet subtraction, + // We need to: + // (1) Apply object selection to the electrons + // (2) Subtract the electron from the jet, which: + // - Changes the jet 4-momentum + // - Reject additional electrons + // (3) Apply object selection to the modified jets + + if (m_config->useElectrons()) { + applySelectionPreOverlapRemovalElectrons(); + } + if (m_config->useFwdElectrons()) { + applySelectionPreOverlapRemovalFwdElectrons(); + } + + if (m_config->applyElectronInJetSubtraction()) { + top::check(m_electronInJetSubtractor->execute( + m_executeNominal), "Failed to execute top::ElectronInJetSubtractionCollectionMaker"); + } + + + if (m_config->usePhotons() && m_photonSelection != nullptr) { + applySelectionPreOverlapRemovalPhotons(); + } + if (m_config->useMuons() && m_muonSelection != nullptr) { + applySelectionPreOverlapRemovalMuons(); + } + if (m_config->useSoftMuons() && m_softmuonSelection != nullptr) { + applySelectionPreOverlapRemovalSoftMuons(); + } + if (m_config->useTaus() && m_tauSelection != nullptr) { + applySelectionPreOverlapRemovalTaus(); + } + if (m_config->useJets() && m_jetSelection != nullptr) { + applySelectionPreOverlapRemovalJets(); + } + if (m_config->useLargeRJets() && m_largeJetSelection != nullptr) { + applySelectionPreOverlapRemovalLargeRJets(); + } + if (m_config->useTrackJets() && m_trackJetSelection != nullptr) { + applySelectionPreOverlapRemovalTrackJets(); + } + if (m_config->useJetGhostTrack() && m_jetGhostTrackSelection != nullptr) { + applySelectionPreOverlapRemovalJetGhostTracks(); + } + if (m_config->useTracks() && m_trackSelection != nullptr) { + applySelectionPreOverlapRemovalTracks(); + } - // If we are doing Electron in Jet subtraction, - // We need to: - // (1) Apply object selection to the electrons - // (2) Subtract the electron from the jet, which: - // - Changes the jet 4-momentum - // - Reject additional electrons - // (3) Apply object selection to the modified jets - - if( m_config->useElectrons() ){applySelectionPreOverlapRemovalElectrons() ;} - - if (m_config->applyElectronInJetSubtraction()) { - top::check( m_electronInJetSubtractor->execute() , "Failed to execute top::ElectronInJetSubtractionCollectionMaker" ); } + void TopObjectSelection::applySelectionPreOverlapRemovalPhotons() { + for (auto currentSystematic : *m_config->systSgKeyMapPhotons()) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; - if( m_config->usePhotons() && m_photonSelection != nullptr ){applySelectionPreOverlapRemovalPhotons() ;} - if( m_config->useMuons() && m_muonSelection != nullptr ){applySelectionPreOverlapRemovalMuons() ;} - if( m_config->useTaus() && m_tauSelection != nullptr ){applySelectionPreOverlapRemovalTaus() ;} - if( m_config->useJets() && m_jetSelection != nullptr ){applySelectionPreOverlapRemovalJets() ;} - if( m_config->useLargeRJets() && m_largeJetSelection != nullptr){applySelectionPreOverlapRemovalLargeRJets() ;} - if( m_config->useTrackJets() && m_trackJetSelection != nullptr){applySelectionPreOverlapRemovalTrackJets() ;} -} + const xAOD::PhotonContainer* photons(nullptr); + top::check(evtStore()->retrieve(photons, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalPhotons() failed to retrieve photons"); + ATH_MSG_DEBUG(" Cut on Photons with key = " << currentSystematic.second); -void TopObjectSelection::applySelectionPreOverlapRemovalPhotons() { - for (auto currentSystematic : *m_config->systSgKeyMapPhotons()) { - const xAOD::PhotonContainer* photons(nullptr); - top::check(evtStore()->retrieve(photons, currentSystematic.second), "TopObjectSelection::applySelectionPreOverlapRemovalPhotons() failed to retrieve photons"); - ATH_MSG_DEBUG(" Cut on Photons with key = "<<currentSystematic.second); - - for (auto photonPtr : *photons) { - photonPtr->auxdecor<char>( m_passPreORSelection ) = m_photonSelection->passSelection(*photonPtr); - photonPtr->auxdecor<char>( m_ORToolDecoration ) = photonPtr->auxdataConst<char>( m_passPreORSelection ) * 2; - if (m_doLooseCuts) { - photonPtr->auxdecor<char>( m_passPreORSelectionLoose ) = m_photonSelection->passSelectionLoose(*photonPtr); - photonPtr->auxdecor<char>( m_ORToolDecorationLoose ) = photonPtr->auxdataConst<char>( m_passPreORSelectionLoose ) * 2; + for (auto photonPtr : *photons) { + photonPtr->auxdecor<char>(m_passPreORSelection) = m_photonSelection->passSelection(*photonPtr); + photonPtr->auxdecor<char>(m_ORToolDecoration) = photonPtr->auxdataConst<char>(m_passPreORSelection) * 2; + if (m_doLooseCuts) { + photonPtr->auxdecor<char>(m_passPreORSelectionLoose) = m_photonSelection->passSelectionLoose(*photonPtr); + photonPtr->auxdecor<char>(m_ORToolDecorationLoose) = + photonPtr->auxdataConst<char>(m_passPreORSelectionLoose) * 2; + } } } } -} /** * @brief For each systematic load each of the electrons and test if they pass * the object selection. */ -void TopObjectSelection::applySelectionPreOverlapRemovalElectrons() -{ + void TopObjectSelection::applySelectionPreOverlapRemovalElectrons() { for (auto currentSystematic : *m_config->systSgKeyMapElectrons()) { - const xAOD::ElectronContainer* electrons(nullptr); - top::check(evtStore()->retrieve(electrons, currentSystematic.second), "TopObjectSelection::applySelectionPreOverlapRemovalElectrons() failed to retrieve electrons"); - ATH_MSG_DEBUG(" Cut on Electrons with key = "<<currentSystematic.second); - - for (auto electronPtr : *electrons) { - electronPtr->auxdecor<char>( m_passPreORSelection ) = m_electronSelection->passSelection(*electronPtr); - electronPtr->auxdecor<char>( m_ORToolDecoration ) = electronPtr->auxdataConst<char>( m_passPreORSelection ) * 2; - if (m_doLooseCuts) { - electronPtr->auxdecor<char>( m_passPreORSelectionLoose ) = m_electronSelection->passSelectionLoose(*electronPtr); - electronPtr->auxdecor<char>( m_ORToolDecorationLoose ) = electronPtr->auxdataConst<char>( m_passPreORSelectionLoose ) * 2; - } + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + + const xAOD::ElectronContainer* electrons(nullptr); + top::check(evtStore()->retrieve(electrons, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalElectrons() failed to retrieve electrons"); + ATH_MSG_DEBUG(" Cut on Electrons with key = " << currentSystematic.second); + + for (auto electronPtr : *electrons) { + electronPtr->auxdecor<char>(m_passPreORSelection) = m_electronSelection->passSelection(*electronPtr); + electronPtr->auxdecor<char>(m_ORToolDecoration) = electronPtr->auxdataConst<char>(m_passPreORSelection) * 2; + if (m_doLooseCuts) { + electronPtr->auxdecor<char>(m_passPreORSelectionLoose) = + m_electronSelection->passSelectionLoose(*electronPtr); + electronPtr->auxdecor<char>(m_ORToolDecorationLoose) = electronPtr->auxdataConst<char>( + m_passPreORSelectionLoose) * 2; } + } } -} + } -void TopObjectSelection::applySelectionPreOverlapRemovalMuons() -{ +/** + * @brief For each systematic load each of the fwd electrons and test if they pass + * the object selection. + */ + void TopObjectSelection::applySelectionPreOverlapRemovalFwdElectrons() { + for (const auto& currentSystematic : *m_config->systSgKeyMapFwdElectrons()) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + + const xAOD::ElectronContainer* fwdelectrons(nullptr); + top::check(evtStore()->retrieve(fwdelectrons, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalFwdElectrons() failed to retrieve fwd electrons"); + ATH_MSG_DEBUG(" Cut on Electrons with key = " << currentSystematic.second); + + int bcid = 0; + int runNumber = 0; + if (!m_config->isMC()) { + const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, + m_config->sgKeyEventInfo()), + "Failed to retrieve EventInfo in TopObjectSelection::applySelectionPreOverlapRemovalFwdElectrons()"); + bcid = eventInfo->bcid(); + runNumber = eventInfo->runNumber(); + } + + for (auto electronPtr : *fwdelectrons) { + electronPtr->auxdecor<char>(m_passPreORSelection) = m_fwdElectronSelection->passSelection(*electronPtr, bcid, + runNumber); + electronPtr->auxdecor<char>(m_ORToolDecoration) = electronPtr->auxdataConst<char>(m_passPreORSelection) * 2; + if (m_doLooseCuts) { + electronPtr->auxdecor<char>(m_passPreORSelectionLoose) = m_fwdElectronSelection->passSelectionLoose( + *electronPtr, bcid, runNumber); + electronPtr->auxdecor<char>(m_ORToolDecorationLoose) = electronPtr->auxdataConst<char>( + m_passPreORSelectionLoose) * 2; + } + }//end of loop on electrons + }//end of loop on systematics + } + + void TopObjectSelection::applySelectionPreOverlapRemovalMuons() { for (auto currentSystematic : *m_config->systSgKeyMapMuons()) { - const xAOD::MuonContainer* muons(nullptr); - top::check(evtStore()->retrieve(muons, currentSystematic.second) , "TopObjectSelection::applySelectionPreOverlapRemovalMuons() failed to retrieve muons" ); - - for (auto muonPtr : *muons) { - muonPtr->auxdecor<char>( m_passPreORSelection ) = m_muonSelection->passSelection(*muonPtr); - muonPtr->auxdecor<char>( m_ORToolDecoration ) = muonPtr->auxdataConst<char>( m_passPreORSelection ) * 2; - if (m_doLooseCuts) { - muonPtr->auxdecor<char>( m_passPreORSelectionLoose ) = m_muonSelection->passSelectionLoose(*muonPtr); - muonPtr->auxdecor<char>( m_ORToolDecorationLoose ) = muonPtr->auxdataConst<char>( m_passPreORSelectionLoose ) * 2; - } + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + const xAOD::MuonContainer* muons(nullptr); + top::check(evtStore()->retrieve(muons, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalMuons() failed to retrieve muons"); + + for (auto muonPtr : *muons) { + muonPtr->auxdecor<char>(m_passPreORSelection) = m_muonSelection->passSelection(*muonPtr); + muonPtr->auxdecor<char>(m_ORToolDecoration) = muonPtr->auxdataConst<char>(m_passPreORSelection) * 2; + if (m_doLooseCuts) { + muonPtr->auxdecor<char>(m_passPreORSelectionLoose) = m_muonSelection->passSelectionLoose(*muonPtr); + muonPtr->auxdecor<char>(m_ORToolDecorationLoose) = muonPtr->auxdataConst<char>(m_passPreORSelectionLoose) * 2; } + } } -} + } -void TopObjectSelection::applySelectionPreOverlapRemovalTaus() -{ - for (auto currentSystematic : *m_config->systSgKeyMapTaus()) { - const xAOD::TauJetContainer* taus(nullptr); - top::check(evtStore()->retrieve(taus, currentSystematic.second) , "TopObjectSelection::applySelectionPreOverlapRemovalTaus() failed to retrieve taus" ); - - for (auto tauPtr : *taus) { - tauPtr->auxdecor<char>( m_passPreORSelection ) = m_tauSelection->passSelection(*tauPtr); - tauPtr->auxdecor<char>( m_ORToolDecoration ) = tauPtr->auxdataConst<char>( m_passPreORSelection ) * 2; - if (m_doLooseCuts) { - tauPtr->auxdecor<char>( m_passPreORSelectionLoose ) = m_tauSelection->passSelectionLoose(*tauPtr); - tauPtr->auxdecor<char>( m_ORToolDecorationLoose ) = tauPtr->auxdataConst<char>( m_passPreORSelectionLoose ) * 2; - } - } - } -} + void TopObjectSelection::applySelectionPreOverlapRemovalSoftMuons() { + for (const std::pair<std::size_t, std::string>& currentSystematic : *m_config->systSgKeyMapSoftMuons()) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + const xAOD::MuonContainer* softmuons(nullptr); + top::check(evtStore()->retrieve(softmuons, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalSoftMuons() failed to retrieve soft muons"); -void TopObjectSelection::applySelectionPreOverlapRemovalJets() -{ - - // Boosted analysis subtract electrons from jets - // If we use Loose electrons we end up with loose jet collections - - bool isLooseJets(false); - - for (auto currentSystematic : *m_config->systSgKeyMapJets(isLooseJets)) { - const xAOD::JetContainer* jets(nullptr); - top::check(evtStore()->retrieve(jets, currentSystematic.second) , "TopObjectSelection::applySelectionPreOverlapRemovalJets() failed to retrieve jets" ); - ATH_MSG_DEBUG(" Cut on Jets with key = "<<currentSystematic.second); - - for (auto jetPtr : *jets) { - ATH_MSG_DEBUG(" Jet pt = "<<(jetPtr)->pt()); - char decoration = m_jetSelection->passSelection(*jetPtr); - jetPtr->auxdecor<char>( m_passPreORSelection ) = decoration; - // if JVT cut enabled: jets that pass JVT get a 2, otherwise the same as passPreORSelection - // if not, passPreORSelection * 2 - if (jetPtr->isAvailable<char>("passJVT")) { - jetPtr->auxdecor<char>( m_ORToolDecoration ) = decoration + jetPtr->auxdataConst<char>( "passJVT" ); - } else { - jetPtr->auxdecor<char>( m_ORToolDecoration ) = decoration * 2; - } - if (m_doLooseCuts) { - jetPtr->auxdecor<char>( m_passPreORSelectionLoose ) = decoration; - if (jetPtr->isAvailable<char>("passJVT")) { - jetPtr->auxdecor<char>( m_ORToolDecorationLoose ) = decoration + jetPtr->auxdataConst<char>( "passJVT" ); - } else { - jetPtr->auxdecor<char>( m_ORToolDecorationLoose ) = decoration * 2; - } + for (const xAOD::Muon* softmuonPtr : *softmuons) { + softmuonPtr->auxdecor<char>(m_passPreORSelection) = m_softmuonSelection->passSelection(*softmuonPtr); + softmuonPtr->auxdecor<char>(m_ORToolDecoration) = softmuonPtr->auxdataConst<char>(m_passPreORSelection) * 2; } - //decorate with b-tagging flags - std::vector<std::string> availableWPs = m_config->bTagWP_available(); - for (auto& WP : availableWPs) { - if (WP!= "Continuous") { - bool isTagged = false; - if (std::fabs(jetPtr->eta()) < 2.5 ) { - ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; - isTagged = btagsel->accept(*jetPtr); - } - jetPtr->auxdecor<char>("isbtagged_"+WP) = isTagged; - } - else { - int tagWeightBin = -2; // AT default - if (std::fabs(jetPtr->eta()) < 2.5 ) { - ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; - tagWeightBin = btagsel->getQuantile(*jetPtr); - } - jetPtr->auxdecor<int>("tagWeightBin") = tagWeightBin; + } + } + + void TopObjectSelection::applySelectionPreOverlapRemovalTaus() { + for (auto currentSystematic : *m_config->systSgKeyMapTaus()) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + const xAOD::TauJetContainer* taus(nullptr); + top::check(evtStore()->retrieve(taus, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalTaus() failed to retrieve taus"); + + for (auto tauPtr : *taus) { + tauPtr->auxdecor<char>(m_passPreORSelection) = m_tauSelection->passSelection(*tauPtr); + tauPtr->auxdecor<char>(m_ORToolDecoration) = tauPtr->auxdataConst<char>(m_passPreORSelection) * 2; + if (m_doLooseCuts) { + tauPtr->auxdecor<char>(m_passPreORSelectionLoose) = m_tauSelection->passSelectionLoose(*tauPtr); + tauPtr->auxdecor<char>(m_ORToolDecorationLoose) = tauPtr->auxdataConst<char>(m_passPreORSelectionLoose) * 2; } } } } - - // Are we using the ElectronInJetSubtraction and running with loose lepton definitons - if (m_doLooseCuts && m_config->applyElectronInJetSubtraction()) { - for (auto currentSystematic : *m_config->systSgKeyMapJets(m_doLooseCuts)) { + + void TopObjectSelection::applySelectionPreOverlapRemovalJets() { + // Boosted analysis subtract electrons from jets + // If we use Loose electrons we end up with loose jet collections + + bool isLooseJets(false); + + for (auto currentSystematic : *m_config->systSgKeyMapJets(isLooseJets)) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + const xAOD::JetContainer* jets(nullptr); - top::check(evtStore()->retrieve(jets, currentSystematic.second) , "TopObjectSelection::applySelectionPreOverlapRemovalJets() failed to retrieve jets" ); - ATH_MSG_DEBUG(" Cut on Jets with key = "<<currentSystematic.second); + top::check(evtStore()->retrieve(jets, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalJets() failed to retrieve jets"); + ATH_MSG_DEBUG(" Cut on Jets with key = " << currentSystematic.second); for (auto jetPtr : *jets) { - char decoration = m_jetSelection->passSelection(*jetPtr); - jetPtr->auxdecor<char>( m_passPreORSelection ) = decoration; - // if JVT cut enabled: jets that pass JVT get a 2, otherwise the same as passPreORSelection - // if not, passPreORSelection * 2 - if (jetPtr->isAvailable<char>("passJVT")) { - jetPtr->auxdecor<char>( m_ORToolDecoration ) = decoration + jetPtr->auxdataConst<char>( "passJVT" ); - } else { - jetPtr->auxdecor<char>( m_ORToolDecoration ) = decoration * 2; + ATH_MSG_DEBUG(" Jet pt = " << (jetPtr)->pt()); + bool passed = m_jetSelection->passSelection(*jetPtr); + + //Forward jets always get JVT=1, Central jets always get fJVT=1 + bool passedJVT_and_fJVT = true; + if (jetPtr->isAvailable<char>("passJVT")) { + if (jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")) { + passedJVT_and_fJVT = jetPtr->auxdataConst<char>("passJVT") && jetPtr->auxdataConst<char>("AnalysisTop_fJVTdecision"); + } + else { + passedJVT_and_fJVT = jetPtr->auxdataConst<char>("passJVT"); + } + } + else if (jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")) { //Possibly redundant, fJVT shouldn't really be able to run if passJVT isn't avaliable + passedJVT_and_fJVT = jetPtr->auxdataConst<char>("AnalysisTop_fJVTdecision"); + } + + if (m_config->applyElectronInJetSubtraction()) { + if (jetPtr->isAvailable<char>("passesFancyOR")) { + if (!jetPtr->auxdecor<char>("passesFancyOR")) passed = false; + } } + // if JVT or fJVT cut enabled and valid: jets that pass (f)JVT get passPreORSelection * 2, jets that fail get the same as passPreORSelection + // if no JVT cut and central jet, or no fJVT and forward jet, jet gets: passPreORSelection * 2 + jetPtr->auxdecor<char>(m_passPreORSelection) = passed; + jetPtr->auxdecor<char>(m_ORToolDecoration) = (passed ? (passedJVT_and_fJVT ? 2 : 1) : 0); if (m_doLooseCuts) { - jetPtr->auxdecor<char>( m_passPreORSelectionLoose ) = decoration; - if (jetPtr->isAvailable<char>("passJVT")) { - jetPtr->auxdecor<char>( m_ORToolDecorationLoose ) = decoration + jetPtr->auxdataConst<char>( "passJVT" ); - } else { - jetPtr->auxdecor<char>( m_ORToolDecorationLoose ) = decoration * 2; - } + jetPtr->auxdecor<char>(m_passPreORSelectionLoose) = passed; + jetPtr->auxdecor<char>(m_ORToolDecorationLoose) = (passed ? (passedJVT_and_fJVT ? 2 : 1) : 0); } //decorate with b-tagging flags std::vector<std::string> availableWPs = m_config->bTagWP_available(); for (auto& WP : availableWPs) { - if (WP!= "Continuous") { - bool isTagged = false; - if (std::fabs(jetPtr->eta()) < 2.5 ) { + if (WP.find("Continuous") == std::string::npos) { + bool isTagged = false; + if (std::fabs(jetPtr->eta()) <= 2.5) { ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; - isTagged = btagsel->accept(*jetPtr); + isTagged = static_cast<bool>(btagsel->accept(*jetPtr)); } - jetPtr->auxdecor<char>("isbtagged_"+WP) = isTagged; - } - else { + jetPtr->auxdecor<char>("isbtagged_" + WP) = isTagged; + } else { int tagWeightBin = -2; // AT default - if (std::fabs(jetPtr->eta()) < 2.5 ) { + if (std::fabs(jetPtr->eta()) <= 2.5) { ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; tagWeightBin = btagsel->getQuantile(*jetPtr); } - jetPtr->auxdecor<int>("tagWeightBin") = tagWeightBin; + jetPtr->auxdecor<int>("tagWeightBin_" + WP) = tagWeightBin; } } } - } - } - -} + } + + // Are we using the ElectronInJetSubtraction and running with loose lepton definitons + if (m_doLooseCuts && m_config->applyElectronInJetSubtraction()) { + for (auto currentSystematic : *m_config->systSgKeyMapJets(m_doLooseCuts)) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; -void TopObjectSelection::applySelectionPreOverlapRemovalLargeRJets() -{ - for (auto currentSystematic : *m_config->systSgKeyMapLargeRJets()) { const xAOD::JetContainer* jets(nullptr); - top::check(evtStore()->retrieve(jets, currentSystematic.second) , "TopObjectSelection::applySelectionPreOverlapRemovalLargeRJets() failed to retrieve large R jets" ); + top::check(evtStore()->retrieve(jets, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalJets() failed to retrieve jets"); + ATH_MSG_DEBUG(" Cut on Jets with key = " << currentSystematic.second); for (auto jetPtr : *jets) { - char decoration = m_largeJetSelection->passSelection(*jetPtr); - jetPtr->auxdecor<char>( m_passPreORSelection ) = decoration; - jetPtr->auxdecor<char>( m_ORToolDecoration ) = decoration * 2; - if (m_doLooseCuts) { - jetPtr->auxdecor<char>( m_passPreORSelectionLoose ) = decoration; - jetPtr->auxdecor<char>( m_ORToolDecorationLoose ) = decoration * 2; + bool decoration = m_jetSelection->passSelection(*jetPtr); + + //Forward jets always get JVT=1, Central jets always get fJVT=1 + bool passedJVT_and_fJVT = true; + if (jetPtr->isAvailable<char>("passJVT")) { + if (jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")) { + passedJVT_and_fJVT = jetPtr->auxdataConst<char>("passJVT") && jetPtr->auxdataConst<char>("AnalysisTop_fJVTdecision"); + } + else { + passedJVT_and_fJVT = jetPtr->auxdataConst<char>("passJVT"); + } + } + else if (jetPtr->isAvailable<char>("AnalysisTop_fJVTdecision")) { //Possibly redundant, fJVT shouldn't really be able to run if passJVT isn't avaliable + passedJVT_and_fJVT = jetPtr->auxdataConst<char>("AnalysisTop_fJVTdecision"); + } + + // if JVT or fJVT cut enabled: jets that pass (f)JVT get passPreORSelection*2, jets which fail get the same as passPreORSelection + // if no JVT cut and central jet, or no fJVT cut and forward jet, jet gets: passPreORSelection * 2 + jetPtr->auxdecor<char>(m_passPreORSelection) = decoration; + jetPtr->auxdecor<char>(m_passPreORSelectionLoose) = decoration; + + jetPtr->auxdecor<char>(m_ORToolDecoration) = (decoration ? (passedJVT_and_fJVT ? 2 : 1) : 0); + jetPtr->auxdecor<char>(m_ORToolDecorationLoose) = (decoration ? (passedJVT_and_fJVT ? 2 : 1) : 0);; + + //decorate with b-tagging flags + std::vector<std::string> availableWPs = m_config->bTagWP_available(); + for (auto& WP : availableWPs) { + if (WP.find("Continuous") == std::string::npos) { + bool isTagged = false; + if (std::fabs(jetPtr->eta()) < 2.5) { + ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; + isTagged = static_cast<bool>(btagsel->accept(*jetPtr)); + } + jetPtr->auxdecor<char>("isbtagged_" + WP) = isTagged; + } else { + int tagWeightBin = -2; // AT default + if (std::fabs(jetPtr->eta()) < 2.5) { + ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; + tagWeightBin = btagsel->getQuantile(*jetPtr); + } + jetPtr->auxdecor<int>("tagWeightBin_" + WP) = tagWeightBin; + } } } + } } -} + } -void TopObjectSelection::applySelectionPreOverlapRemovalTrackJets() -{ - const xAOD::JetContainer* jets(nullptr); - top::check(evtStore()->retrieve(jets, m_config->sgKeyTrackJets()) , "TopObjectSelection::applySelectionPreOverlapRemovalTrackJets() failed to retrieve track jets" ); - for (auto jetPtr : *jets) { - char decoration = m_trackJetSelection->passSelection(*jetPtr); - jetPtr->auxdecor<char>( m_passPreORSelection ) = decoration; - if (m_doLooseCuts) { - jetPtr->auxdecor<char>( m_passPreORSelectionLoose ) = decoration; - } - std::vector<std::string> availableWPs = m_config->bTagWP_available_trkJet(); - for (auto& WP : availableWPs) { - if (WP!= "Continuous") { - bool isTagged = false; - if (std::fabs(jetPtr->eta()) < 2.5 ) { - ToolHandle<IBTaggingSelectionTool>& btagsel = m_trkjet_btagSelTools[WP]; - isTagged = btagsel->accept(*jetPtr); + void TopObjectSelection::applySelectionPreOverlapRemovalLargeRJets() { + for (auto currentSystematic : *m_config->systSgKeyMapLargeRJets()) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + + const xAOD::JetContainer* jets(nullptr); + top::check(evtStore()->retrieve(jets, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalLargeRJets() failed to retrieve large R jets"); + + for (auto jetPtr : *jets) { + //char decoration = m_largeJetSelection->passSelection(*jetPtr); + char decoration = '0'; + jetPtr->auxdecor<char>(m_passPreORSelection) = decoration; + jetPtr->auxdecor<char>(m_ORToolDecoration) = decoration * 2; + if (m_doLooseCuts) { + jetPtr->auxdecor<char>(m_passPreORSelectionLoose) = decoration; + jetPtr->auxdecor<char>(m_ORToolDecorationLoose) = decoration * 2; + } + } + } + } + + void TopObjectSelection::applySelectionPreOverlapRemovalTrackJets() { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (!m_executeNominal) return; + + const xAOD::JetContainer* jets(nullptr); + top::check(evtStore()->retrieve(jets, + m_config->sgKeyTrackJets()), + "TopObjectSelection::applySelectionPreOverlapRemovalTrackJets() failed to retrieve track jets"); + + + + for (const xAOD::Jet* jetPtr : *jets) { + //char decoration = m_trackJetSelection->passSelection(*jetPtr); + char decoration = '0'; + jetPtr->auxdecor<char>(m_passPreORSelection) = decoration; + if (m_doLooseCuts) { + jetPtr->auxdecor<char>(m_passPreORSelectionLoose) = decoration; + } + + if (m_config->sgKeyTrackJetsType() == "AntiKtVR30Rmax4Rmin02TrackJets") { // Event cleaning for variable-R track jets + float pt_baseline = 5e3; + float radius1 = std::max(0.02, std::min(0.4, 30000. / jetPtr->pt())); + + float dr_jets; + bool passDRcut = true; + for (const xAOD::Jet* jet2 : *jets) { + if (jet2->pt() < pt_baseline) continue; + if (jetPtr == jet2) continue; + + float radius2 = std::max(0.02, std::min(0.4, 30000. / jet2->pt())); + + dr_jets = xAOD::P4Helpers::deltaR(jetPtr, jet2, false); + if (dr_jets < std::min(radius1, radius2)) passDRcut = false; } - jetPtr->auxdecor<char>("isbtagged_"+WP) = isTagged; + jetPtr->auxdecor<char>("passDRcut") = passDRcut; } - else { - int tagWeightBin = -2; // AT default - if (std::fabs(jetPtr->eta()) < 2.5 ) { - ToolHandle<IBTaggingSelectionTool>& btagsel = m_btagSelTools[WP]; - tagWeightBin = btagsel->getQuantile(*jetPtr); + + std::vector<std::string> availableWPs = m_config->bTagWP_available_trkJet(); + for (auto& WP : availableWPs) { + if (WP.find("Continuous") == std::string::npos) { + bool isTagged = false; + if (std::fabs(jetPtr->eta()) < 2.5) { + ToolHandle<IBTaggingSelectionTool>& btagsel = m_trkjet_btagSelTools[WP]; + isTagged = static_cast<bool>(btagsel->accept(*jetPtr)); + } + jetPtr->auxdecor<char>("isbtagged_" + WP) = isTagged; + } else { + int tagWeightBin = -2; // AT default + if (std::fabs(jetPtr->eta()) < 2.5) { + ToolHandle<IBTaggingSelectionTool>& btagsel = m_trkjet_btagSelTools[WP]; + tagWeightBin = btagsel->getQuantile(*jetPtr); + } + jetPtr->auxdecor<int>("tagWeightBin_" + WP) = tagWeightBin; } - jetPtr->auxdecor<int>("tagWeightBin") = tagWeightBin; } } } -} -StatusCode TopObjectSelection::applyOverlapRemoval() -{ - bool aLooseEvent(true),aTightEvent(false); - if (!m_config->doLooseTreeOnly()) { - top::check( applyOverlapRemoval(aTightEvent,m_config->sgKeyTopSystematicEvents()) , "Failed to apply overlap removal" ); - } - if (m_config->doLooseEvents()) { - top::check( applyOverlapRemoval(aLooseEvent,m_config->sgKeyTopSystematicEventsLoose()) , "Failed to apply overlap removal" ); - } - return StatusCode::SUCCESS; -} +void TopObjectSelection::applySelectionPreOverlapRemovalJetGhostTracks() { + + auto jetsystematic = *m_config->systSgKeyMapJets(false); + CP::SystematicSet nominal; + std::size_t m_nominalHashValue = nominal.hash(); + + for (auto currentSystematic : *m_config->systMapJetGhostTrack()) { + + // At this point some specific jet collection doesn't exist for tracking systematic so use the nominal jet collection to retrieve the ghost tracks + std::unordered_map<std::size_t, std::string>::const_iterator jetsyst_name = jetsystematic.find(currentSystematic.first); + if (jetsyst_name == jetsystematic.end()) { + jetsyst_name = jetsystematic.find(m_nominalHashValue); + } + + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; -StatusCode TopObjectSelection::applyOverlapRemoval(const bool isLoose,const std::string& sgKey) -{ - // create the xAOD::SystematicEventContainer - xAOD::SystematicEventAuxContainer* systEventAuxCont = new xAOD::SystematicEventAuxContainer{}; - xAOD::SystematicEventContainer* systEventCont = new xAOD::SystematicEventContainer{}; - systEventCont->setStore( systEventAuxCont ); - - for (auto systematicNumber : *m_config->systHashAll()) { - xAOD::SystematicEvent* systEvent = new xAOD::SystematicEvent{}; - systEventCont->push_back( systEvent ); - systEvent->setHashValue( systematicNumber ); - systEvent->setIsLooseEvent( isLoose ); - if (!isLoose) {systEvent->setTtreeIndex( m_config->ttreeIndex( systematicNumber ) );} - if (isLoose) {systEvent->setTtreeIndex( m_config->ttreeIndexLoose( systematicNumber ) );} - systEvent->auxdecor<char> (m_config->passEventSelectionDecoration()) = 0; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; - top::check( applyOverlapRemoval( systEvent ) , "Failed to apply overlap removal" ); - } - - // Save to StoreGate / TStore - std::string outputSGKeyAux = sgKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( systEventCont ,sgKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( systEventAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; + + const xAOD::JetContainer* jets(nullptr); + top::check(evtStore()->retrieve(jets, + (*jetsyst_name).second), + "TopObjectSelection::applySelectionPreOverlapRemovalJetGhostTracks() failed to retrieve jets"); + ATH_MSG_DEBUG(" Cut on JetsGhostTracks with key = " << (*jetsyst_name).second); + + + + for (auto jetPtr : *jets) + { + if(!m_jetGhostTrackSelection->JetConsideredForGhostTrackSelection(jetPtr->pt(),jetPtr->eta())) continue; + + + std::vector<const xAOD::TrackParticle*> jetTracks; + + jetTracks = jetPtr->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(currentSystematic.first)); + + if (jetTracks.size() == 0){ + ATH_MSG_WARNING("TopObjectSelection::applySelectionPreOverlapRemovalJetGhostTracks() failed to retrieve tracks, jet pT and eta:" << jetPtr->pt() << " " << std::fabs(jetPtr->eta()) ); + continue; + } + + const xAOD::VertexContainer* vertices = nullptr; + top::check(evtStore() -> retrieve( vertices, "PrimaryVertices" ), "Failed to get primary vertices"); + const auto it_pv = std::find_if(vertices->cbegin(), vertices->cend(), + [](const xAOD::Vertex* vtx) + {return vtx->vertexType() == xAOD::VxType::PriVtx;}); + const xAOD::Vertex* primaryVertex = (it_pv == vertices->cend()) ? nullptr : *it_pv; + if (primaryVertex == nullptr) ATH_MSG_WARNING("TopObjectSelection No primary vertex found." ); + + + + for (auto jetTrIt : jetTracks){ + + //Decorate the tracks with a flag "passPreORSelection" to indicate if they passed the selection + //jetTrIt->auxdecor<char>(m_passPreORSelection) = m_jetGhostTrackSelection->passSelection(*jetTrIt, *primaryVertex); + jetTrIt->auxdecor<char>(m_passPreORSelection) = '0'; + jetTrIt->auxdecor<char>(m_ORToolDecoration) = jetTrIt->auxdataConst<char>(m_passPreORSelection) * 2; + + } + + } + } } - return StatusCode::SUCCESS; -} -StatusCode TopObjectSelection::applyOverlapRemoval(xAOD::SystematicEvent* currentSystematic) { + void TopObjectSelection::applySelectionPreOverlapRemovalTracks() { - // Which lepton definition are we using for the overlap removal? - // Default for top analysis is "Tight" - // - // Use "Loose" for Fakes estimates - // - // Other physics groups choose to do overlap removal on "Loose" lepton definitions - // As such, this mode is fully supported, simply set: - // OverlapRemovalLeptonDef Loose - // In your configuration file + for (auto currentSystematic : *m_config->systSgKeyMapTracks()) { + + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic.first))) continue; + + const xAOD::TrackParticleContainer* tracks(nullptr); + top::check(evtStore()->retrieve(tracks, + currentSystematic.second), + "TopObjectSelection::applySelectionPreOverlapRemovalTracks() failed to retrieve tracks"); + + ATH_MSG_DEBUG(" Cut on Tracks with key = " << currentSystematic.second); + + const xAOD::VertexContainer* vertices = nullptr; + + top::check(evtStore() -> retrieve( vertices, "PrimaryVertices" ), "Failed to get primary vertices"); + const auto it_pv = std::find_if(vertices->cbegin(), vertices->cend(), + [](const xAOD::Vertex* vtx) + {return vtx->vertexType() == xAOD::VxType::PriVtx;}); + const xAOD::Vertex* primaryVertex = (it_pv == vertices->cend()) ? nullptr : *it_pv; + if (primaryVertex == nullptr) ATH_MSG_WARNING("TopObjectSelection. No primary vertex found." ); + + + int counter = 0; + + for (auto trackPtr : *tracks) { + + //trackPtr -> auxdecor<char>(m_passPreORSelection) = m_trackSelection->passSelection(*trackPtr, *primaryVertex); + trackPtr->auxdecor<char>(m_passPreORSelection) = '0'; + trackPtr -> auxdecor<char>(m_ORToolDecoration) = trackPtr->auxdataConst<char>(m_passPreORSelection) * 2; + + counter++; + + + } + } + + } + - bool looseLeptonOR(false); // default behaviour for top analysis - use the "Tight" definitions - if (currentSystematic->isLooseEvent()) { - looseLeptonOR = true; + StatusCode TopObjectSelection::applyOverlapRemoval() { + bool aLooseEvent(true), aTightEvent(false); + + if (m_config->doTightEvents()) { + top::check(applyOverlapRemoval(aTightEvent, + m_config->sgKeyTopSystematicEvents()), "Failed to apply overlap removal"); + } + if (m_config->doLooseEvents()) { + top::check(applyOverlapRemoval(aLooseEvent, + m_config->sgKeyTopSystematicEventsLoose()), "Failed to apply overlap removal"); + } + return StatusCode::SUCCESS; } - if (m_config->doOverlapRemovalOnLooseLeptonDef()) { - looseLeptonOR = true; + + StatusCode TopObjectSelection::applyOverlapRemoval(const bool isLoose, const std::string& sgKey) { + // create the xAOD::SystematicEventContainer + xAOD::SystematicEventAuxContainer* systEventAuxCont = new xAOD::SystematicEventAuxContainer {}; + xAOD::SystematicEventContainer* systEventCont = new xAOD::SystematicEventContainer {}; + systEventCont->setStore(systEventAuxCont); + + // We need to be able to have the nominal systematic processed first + // but we cannot alter this inside TopConfig as we use unordered_set + // Using an ordered set will only order on hash and not on insertion + // so we still cannot control it there + // Best place to handle it is when the systematic object container is being filled (before it is const) + // We read all hashes into a vector, and then custom sort to be nominal, then alphabetical + std::vector<size_t> sortedSystHashAll(m_config->systHashAll()->begin(), m_config->systHashAll()->end()); + std::sort(sortedSystHashAll.begin(), sortedSystHashAll.end(), + [this](const size_t& lhs, const size_t& rhs) { + // if lhs is nominal, true - move + if (this->m_config->isSystNominal(this->m_config->systematicName(lhs))) return true; + // if rhs is nominal, false - fix + else if (this->m_config->isSystNominal(this->m_config->systematicName(rhs))) return false; + // otherwise alphabetical - sort + else return(this->m_config->systematicName(lhs) < this->m_config->systematicName(rhs)); + }); + + for (auto systematicNumber : sortedSystHashAll) { + ATH_MSG_DEBUG(systematicNumber << " " << m_config->systematicName(systematicNumber)); + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (m_executeNominal && !m_config->isSystNominal(m_config->systematicName(systematicNumber))) continue; + if (!m_executeNominal && m_config->isSystNominal(m_config->systematicName(systematicNumber))) continue; + + if ((!m_config->doTightSysts() && !isLoose) && + !m_config->isSystNominal(m_config->systematicName(systematicNumber))) continue; + if ((!m_config->doLooseSysts() && isLoose) && + !m_config->isSystNominal(m_config->systematicName(systematicNumber))) continue; + + xAOD::SystematicEvent* systEvent = new xAOD::SystematicEvent {}; + systEventCont->push_back(systEvent); + systEvent->setHashValue(systematicNumber); + systEvent->setIsLooseEvent(isLoose); + if (!isLoose) { + systEvent->setTtreeIndex(m_config->ttreeIndex(systematicNumber)); + } + if (isLoose) { + systEvent->setTtreeIndex(m_config->ttreeIndexLoose(systematicNumber)); + } + systEvent->auxdecor<char> (m_config->passEventSelectionDecoration()) = 0; + top::check(applyOverlapRemoval(systEvent), "Failed to apply overlap removal"); + } + + if (m_executeNominal) { + // Create a new StoreGate key + std::string sgKeyNominal = sgKey + "Nominal"; + + // Save to StoreGate / TStore + std::string outputSGKeyNominalAux = sgKeyNominal + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(systEventCont, sgKeyNominal); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(systEventAuxCont, outputSGKeyNominalAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + return StatusCode::SUCCESS; + } else { + // Retrieve nominal container, get nominal event, copy into full systematic container + xAOD::SystematicEventContainer* systEventContNominal = new xAOD::SystematicEventContainer {}; + top::check(evtStore()->retrieve(systEventContNominal, sgKey + "Nominal"), "Failed to retrieve nominal container"); + for (auto x: *systEventContNominal) { + xAOD::SystematicEvent* systEventNominal = new xAOD::SystematicEvent {}; + systEventCont->push_back(systEventNominal); + *systEventNominal = *x; + } + + // Save to StoreGate / TStore + std::string outputSGKeyAux = sgKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(systEventCont, sgKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(systEventAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + return StatusCode::SUCCESS; + } } - - std::size_t hash = currentSystematic->hashValue(); - // Retrieve the relevant shallow copies - const xAOD::PhotonContainer* xaod_photon(nullptr); - if (m_config->usePhotons()) - top::check(evtStore()->retrieve(xaod_photon, m_config->sgKeyPhotons(hash)) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve photons"); + StatusCode TopObjectSelection::applyOverlapRemoval(xAOD::SystematicEvent* currentSystematic) { + // Which lepton definition are we using for the overlap removal? + // Default for top analysis is "Tight" + // + // Use "Loose" for Fakes estimates + // + // Other physics groups choose to do overlap removal on "Loose" lepton definitions + // As such, this mode is fully supported, simply set: + // OverlapRemovalLeptonDef Loose + // In your configuration file + + bool looseLeptonOR(false); // default behaviour for top analysis - use the "Tight" definitions + + if (currentSystematic->isLooseEvent()) { + looseLeptonOR = true; + } + if (m_config->doOverlapRemovalOnLooseLeptonDef()) { + looseLeptonOR = true; + } + + std::size_t hash = currentSystematic->hashValue(); - const xAOD::ElectronContainer* xaod_el(nullptr); - if (m_config->useElectrons()) - top::check(evtStore()->retrieve(xaod_el, m_config->sgKeyElectrons(hash)) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve electrons" ); - const xAOD::MuonContainer* xaod_mu(nullptr); - if (m_config->useMuons()) - top::check(evtStore()->retrieve(xaod_mu, m_config->sgKeyMuons(hash)) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve muons" ); - - const xAOD::TauJetContainer* xaod_tau(nullptr); - if (m_config->useTaus()) - top::check(evtStore()->retrieve(xaod_tau, m_config->sgKeyTaus(hash)) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve taus"); - - const xAOD::JetContainer* xaod_jet(nullptr); - if (m_config->useJets()) - top::check(evtStore()->retrieve(xaod_jet, m_config->sgKeyJets(hash,looseLeptonOR)) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve jets" ); + // Retrieve the relevant shallow copies + const xAOD::PhotonContainer* xaod_photon(nullptr); + if (m_config->usePhotons()) top::check(evtStore()->retrieve(xaod_photon, m_config->sgKeyPhotons( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve photons"); - const xAOD::JetContainer* xaod_ljet(nullptr); - if (m_config->useLargeRJets()) - top::check(evtStore()->retrieve(xaod_ljet, m_config->sgKeyLargeRJets(hash)) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve large-R jets"); - const xAOD::JetContainer* xaod_tjet(nullptr); - if (m_config->useTrackJets()) - top::check(evtStore()->retrieve(xaod_tjet, m_config->sgKeyTrackJets()) , "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve track jets"); - - // vectors to store the indices of objects passing selection and overlap removal - std::vector<unsigned int> goodPhotons,goodElectrons,goodMuons,goodTaus,goodJets,goodLargeRJets,goodTrackJets; - - // Apply overlap removal - m_overlapRemovalToolPostSelection->overlapremoval(xaod_photon,xaod_el,xaod_mu,xaod_tau, - xaod_jet,xaod_ljet, - goodPhotons,goodElectrons,goodMuons,goodTaus, - goodJets,goodLargeRJets,looseLeptonOR); - - // Additonal lepton information - std::vector<unsigned int> overlapsEl,overlapsMu; - if (m_overlapRemovalToolPostSelection->overlapsEl(overlapsEl) ) { - currentSystematic->auxdecor< std::vector<unsigned int> >("overlapsEl") = overlapsEl; - } - if (m_overlapRemovalToolPostSelection->overlapsMu(overlapsMu) ) { - currentSystematic->auxdecor< std::vector<unsigned int> >("overlapsMu") = overlapsMu; - } - + const xAOD::ElectronContainer* xaod_el(nullptr); + if (m_config->useElectrons()) top::check(evtStore()->retrieve(xaod_el, m_config->sgKeyElectrons( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve electrons"); - - // If we did use overlap removal on "Loose" lepton definitions - // We take the remaining leptons and only keep those passing the "Tight" cuts - if (!currentSystematic->isLooseEvent() && m_config->doOverlapRemovalOnLooseLeptonDef()) { - applyTightSelectionPostOverlapRemoval( xaod_photon , goodPhotons ); - applyTightSelectionPostOverlapRemoval( xaod_el , goodElectrons ); - applyTightSelectionPostOverlapRemoval( xaod_mu , goodMuons ); - applyTightSelectionPostOverlapRemoval( xaod_tau , goodTaus ); - applyTightSelectionPostOverlapRemoval( xaod_jet , goodJets ); - applyTightSelectionPostOverlapRemoval( xaod_ljet , goodLargeRJets ); + + const xAOD::ElectronContainer* xaod_fwdel(nullptr); + if (m_config->useFwdElectrons()) top::check(evtStore()->retrieve(xaod_fwdel, m_config->sgKeyFwdElectrons( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve fwd electrons"); + + + const xAOD::MuonContainer* xaod_mu(nullptr); + if (m_config->useMuons()) top::check(evtStore()->retrieve(xaod_mu, m_config->sgKeyMuons( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve muons"); + + + const xAOD::MuonContainer* xaod_softmu(nullptr); + if (m_config->useSoftMuons()) top::check(evtStore()->retrieve(xaod_softmu, m_config->sgKeySoftMuons( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve soft muons"); + + + const xAOD::TauJetContainer* xaod_tau(nullptr); + if (m_config->useTaus()) top::check(evtStore()->retrieve(xaod_tau, m_config->sgKeyTaus( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve taus"); + + + const xAOD::JetContainer* xaod_jet(nullptr); + if (m_config->useJets()) top::check(evtStore()->retrieve(xaod_jet, m_config->sgKeyJets(hash, + looseLeptonOR)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve jets"); + + + const xAOD::JetContainer* xaod_ljet(nullptr); + if (m_config->useLargeRJets()) top::check(evtStore()->retrieve(xaod_ljet, m_config->sgKeyLargeRJets( + hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve large-R jets"); + + + const xAOD::JetContainer* xaod_tjet(nullptr); + if (m_config->useTrackJets()) top::check(evtStore()->retrieve(xaod_tjet, + m_config->sgKeyTrackJets()), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve track jets"); + + const xAOD::TrackParticleContainer* xaod_tracks(nullptr); + if (m_config->useTracks()) top::check(evtStore()->retrieve(xaod_tracks, + m_config->sgKeyTracks(hash)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve tracks"); + + + // vectors to store the indices of objects passing selection and overlap removal + std::vector<unsigned int> goodPhotons, goodElectrons, goodFwdElectrons, goodMuons, goodSoftMuons, goodTaus, + goodJets, goodLargeRJets, goodTrackJets, goodTracks; + + // Apply overlap removal + m_overlapRemovalToolPostSelection->overlapremoval(xaod_photon, xaod_el, xaod_mu, xaod_tau, + xaod_jet, xaod_ljet, + goodPhotons, goodElectrons, goodMuons, goodTaus, + goodJets, goodLargeRJets, looseLeptonOR); + + // Additonal lepton information + std::vector<unsigned int> overlapsEl, overlapsMu; + if (m_overlapRemovalToolPostSelection->overlapsEl(overlapsEl)) { + currentSystematic->auxdecor< std::vector<unsigned int> >("overlapsEl") = overlapsEl; + } + if (m_overlapRemovalToolPostSelection->overlapsMu(overlapsMu)) { + currentSystematic->auxdecor< std::vector<unsigned int> >("overlapsMu") = overlapsMu; + } + + // If we did use overlap removal on "Loose" lepton definitions + // We take the remaining leptons and only keep those passing the "Tight" cuts + if (!currentSystematic->isLooseEvent() && m_config->doOverlapRemovalOnLooseLeptonDef()) { + applyTightSelectionPostOverlapRemoval(xaod_photon, goodPhotons); + applyTightSelectionPostOverlapRemoval(xaod_el, goodElectrons); + applyTightSelectionPostOverlapRemoval(xaod_mu, goodMuons); + applyTightSelectionPostOverlapRemoval(xaod_tau, goodTaus); + applyTightSelectionPostOverlapRemoval(xaod_jet, goodJets); + applyTightSelectionPostOverlapRemoval(xaod_ljet, goodLargeRJets); + } + + if (m_config->useTrackJets()) { + for (unsigned int i = 0; i < xaod_tjet->size(); ++i) goodTrackJets.push_back(i); + trackJetOverlapRemoval(xaod_el, xaod_mu, xaod_tjet, goodElectrons, goodMuons, goodTrackJets); + applyTightSelectionPostOverlapRemoval(xaod_tjet, goodTrackJets); + } + + // for the time being no OR applied on FwdElectrons + if (xaod_fwdel) { + int i(0); + std::string passTopCuts(""); + if (!looseLeptonOR) { + passTopCuts = "passPreORSelection"; + } + if (looseLeptonOR) { + passTopCuts = "passPreORSelectionLoose"; + } + for (const xAOD::Electron* x: *xaod_fwdel) { + if (x->auxdataConst< char >(passTopCuts) == 1) goodFwdElectrons.push_back(i); + + i++; + } + } + + // no OR applied on tracks + if (xaod_tracks) { + int i(0); + std::string passTopCuts = "passPreORSelection"; + + for (const xAOD::TrackParticle* x: *xaod_tracks) { + + if (x->auxdataConst< char >(m_passPreORSelection) == 1) goodTracks.push_back(i); + + i++; + } + } + + + // for the time being the only OR performed on soft muons is wrt prompt muons + if (xaod_softmu) { + + if(m_config->useJets()) + { + top::check(m_overlapRemovalTool_softMuons_Alljets->removeOverlaps(nullptr, xaod_softmu, xaod_jet, nullptr, nullptr), "Failed to identify overlap for soft muons - all jets"); + if(m_config->useParticleFlowJets())top::check(m_overlapRemovalTool_softMuons_PFjets->removeOverlaps(nullptr, xaod_softmu, xaod_jet, nullptr, nullptr), "Failed to identify overlap for soft muons - PFlow jets"); + } + + int i(0); + std::string passTopCuts = "passPreORSelection"; + + for (const xAOD::Muon* x: *xaod_softmu) { + //OR with prompt muons + bool promptMuOR = false; + if (xaod_mu) { + for (unsigned int iMu : goodMuons) { + // Get muon iMu + const xAOD::Muon* muPtr = xaod_mu->at(iMu); + if (muPtr->p4().DeltaR(x->p4()) < 0.01) { + promptMuOR = true; + break; + } + } + } + + float dRmin = 100; //nearest jet dR + if(m_config->useJets()) dRmin=this->calculateMinDRMuonJet(*x, xaod_jet, goodJets, m_config->softmuonDRJetcutUseRapidity()); + + if (x->auxdataConst< char >(passTopCuts) == 1 && !promptMuOR && (!m_config->useJets() || dRmin < m_config->softmuonDRJetcut())) + { + goodSoftMuons.push_back(i);//the dR selection must be done here, because we need the post-OR jets... + } + i++; + } + }//end of OR procedure for soft muons + + if(m_config->isMC() && m_config->useSoftMuons() && m_config->softmuonAdditionalTruthInfo()) decorateSoftMuonsPostOverlapRemoval(xaod_softmu,goodSoftMuons); + + + //Change the collection of ghost tracks associated to jets + //Store the selected ghost associated tracks + //It doesn't work for the nominal systematic + if (m_config->useJetGhostTrack() && m_config->useJets()) { + + std::vector<const xAOD::TrackParticle*> jetTracks; + + xAOD::JetContainer* xaod_jet_ga(nullptr); + top::check(evtStore()->retrieve(xaod_jet_ga, m_config->sgKeyJets(hash,looseLeptonOR)), + "TopObjectSelection::applyOverlapRemovalPostSelection() failed to retrieve jets for ghost matching"); + + unsigned int index= -1; + + for (const auto jetPtr : *xaod_jet_ga){ + + index=index+1; + + if(!m_jetGhostTrackSelection->JetConsideredForGhostTrackSelection(jetPtr->pt(),jetPtr->eta())) + continue; + + if (std::find(goodJets.begin(), goodJets.end(), index) == goodJets.end()){ + continue; + } + + jetTracks.clear(); + + std::vector<const xAOD::TrackParticle*> goodJetGhostTracks; + jetTracks = jetPtr->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(hash)); + + if (jetTracks.size() != 0) { + + std::string passTopCuts = "passPreORSelection"; + + for (auto& track: jetTracks) { + + if (track->auxdataConst< char >(passTopCuts) == 1) { + goodJetGhostTracks.push_back(track); + } + + } + + jetPtr->setAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack(hash), goodJetGhostTracks); + + } + } + + } + + // set the indices in the xAOD::SystematicEvent + currentSystematic->setGoodPhotons(goodPhotons); + currentSystematic->setGoodElectrons(goodElectrons); + currentSystematic->setGoodFwdElectrons(goodFwdElectrons); + currentSystematic->setGoodMuons(goodMuons); + currentSystematic->setGoodSoftMuons(goodSoftMuons); + currentSystematic->setGoodTaus(goodTaus); + currentSystematic->setGoodJets(goodJets); + currentSystematic->setGoodLargeRJets(goodLargeRJets); + currentSystematic->setGoodTrackJets(goodTrackJets); + currentSystematic->setGoodTracks(goodTracks); + + decorateEventInfoPostOverlapRemoval(goodJets.size(), currentSystematic->isLooseEvent()); + + + + return StatusCode::SUCCESS; } - if (m_config->useTrackJets()){ - for (unsigned int i=0; i<xaod_tjet->size(); ++i) goodTrackJets.push_back(i); - trackJetOverlapRemoval(xaod_el, xaod_mu, xaod_tjet, goodElectrons, goodMuons, goodTrackJets); - applyTightSelectionPostOverlapRemoval( xaod_tjet , goodTrackJets ); - } - - // set the indices in the xAOD::SystematicEvent - currentSystematic->setGoodPhotons( goodPhotons ); - currentSystematic->setGoodElectrons( goodElectrons ); - currentSystematic->setGoodMuons( goodMuons ); - currentSystematic->setGoodTaus( goodTaus ); - currentSystematic->setGoodJets( goodJets ); - currentSystematic->setGoodLargeRJets( goodLargeRJets ); - currentSystematic->setGoodTrackJets( goodTrackJets ); - - return StatusCode::SUCCESS; -} + void TopObjectSelection::decorateSoftMuonsPostOverlapRemoval(const xAOD::MuonContainer* xaod_softmu,std::vector<unsigned int>& goodSoftMuons) + { -void TopObjectSelection::applyTightSelectionPostOverlapRemoval( const xAOD::IParticleContainer* xaod , std::vector<unsigned int>& indices ) -{ - // Copy the original indices of the xAOD objects in - // the collection that pass the overlap removal - std::vector<unsigned int> tmpCopy; - for (auto i : indices) { - tmpCopy.push_back( i ); + for (auto iMu : goodSoftMuons) { + // Get muon iMu + const xAOD::Muon* muon = xaod_softmu->at(iMu); + + top::truth::initRecoMuonHistoryInfo(muon,m_config->softmuonAdditionalTruthInfoCheckPartonOrigin()); //it's safer if we initialize everything to default for each muon before filling the muon history + top::truth::getRecoMuonHistory(muon,m_config->softmuonAdditionalTruthInfoCheckPartonOrigin(),m_config->getShoweringAlgorithm(),m_config->softmuonAdditionalTruthInfoDoVerbose()); + }//end of loop on soft muons } - - // Clear the original indices - indices.clear(); - - // Only save indices that are in tmpCopy && passPreORSelection - // This will keep the objects that pass the "Loose" overlap selection - // and pass the "Tight" cuts - for (auto i : tmpCopy) { - if (xaod->at(i)->isAvailable< char> ( m_passPreORSelection )) { - if (xaod->at(i)->auxdataConst< char >( m_passPreORSelection ) == 1) { - indices.push_back( i ); + void TopObjectSelection::applyTightSelectionPostOverlapRemoval(const xAOD::IParticleContainer* xaod, + std::vector<unsigned int>& indices) { + // Copy the original indices of the xAOD objects in + // the collection that pass the overlap removal + std::vector<unsigned int> tmpCopy; + for (auto i : indices) { + tmpCopy.push_back(i); + } + + // Clear the original indices + indices.clear(); + + // Only save indices that are in tmpCopy && passPreORSelection + // This will keep the objects that pass the "Loose" overlap selection + // and pass the "Tight" cuts + for (auto i : tmpCopy) { + if (xaod->at(i)->isAvailable< char> (m_passPreORSelection)) { + if (xaod->at(i)->auxdataConst< char >(m_passPreORSelection) == 1) { + indices.push_back(i); + } } } } -} -void TopObjectSelection::trackJetOverlapRemoval(const xAOD::IParticleContainer* xaod_el, - const xAOD::IParticleContainer* xaod_mu, - const xAOD::IParticleContainer* xaod_tjet, - std::vector<unsigned int>& goodElectrons, - std::vector<unsigned int>& goodMuons, - std::vector<unsigned int>& goodTrackJets) -{ - - // Copy the original indices of the xAOD objects in - // the collection that pass the overlap removal - std::vector<unsigned int> tmpGoodTrackJets; - for (auto i : goodTrackJets) { - tmpGoodTrackJets.push_back( i ); - } - - // Clear the original indices - goodTrackJets.clear(); - - int counterTrk = 0; - for (auto jet : *xaod_tjet){ - bool matchEl(false); - int counterEl = 0; - for (auto el : *xaod_el){ - if ((std::find(goodElectrons.begin(), goodElectrons.end(), counterEl) != goodElectrons.end())){ - if ( el->p4().DeltaR(jet->p4())<0.2){ - matchEl = true; - break; + void TopObjectSelection::trackJetOverlapRemoval(const xAOD::IParticleContainer* xaod_el, + const xAOD::IParticleContainer* xaod_mu, + const xAOD::IParticleContainer* xaod_tjet, + std::vector<unsigned int>& goodElectrons, + std::vector<unsigned int>& goodMuons, + std::vector<unsigned int>& goodTrackJets) { + // Copy the original indices of the xAOD objects in + // the collection that pass the overlap removal + std::vector<unsigned int> tmpGoodTrackJets; + for (auto i : goodTrackJets) { + tmpGoodTrackJets.push_back(i); + } + + // Clear the original indices + goodTrackJets.clear(); + + int counterTrk = 0; + for (auto jet : *xaod_tjet) { + bool matchEl(false); + int counterEl = 0; + for (auto el : *xaod_el) { + if ((std::find(goodElectrons.begin(), goodElectrons.end(), counterEl) != goodElectrons.end())) { + if (el->p4().DeltaR(jet->p4()) < 0.2) { + matchEl = true; + break; + } } + counterEl++; } - counterEl++; - } - bool matchMu(false); - int counterMu = 0; - for (auto mu : *xaod_mu){ - if ((std::find(goodMuons.begin(), goodMuons.end(), counterMu) != goodMuons.end())){ - if ( mu->p4().DeltaR(jet->p4())<0.2){ - matchMu = true; - break; + bool matchMu(false); + int counterMu = 0; + for (auto mu : *xaod_mu) { + if ((std::find(goodMuons.begin(), goodMuons.end(), counterMu) != goodMuons.end())) { + if (mu->p4().DeltaR(jet->p4()) < 0.2) { + matchMu = true; + break; + } } + counterMu++; } - counterMu++; + + if (!(matchEl || matchMu)) goodTrackJets.push_back(counterTrk); + counterTrk++; } + } - if (!(matchEl || matchMu)) goodTrackJets.push_back(counterTrk); - counterTrk++; + float TopObjectSelection::calculateMinDRMuonJet(const xAOD::Muon& mu, const xAOD::JetContainer* xaod_jet, std::vector<unsigned int>& goodJets, bool useRapidity) { + + float dRMin = 100.0; + + // Loop over jets, calculate dR and record smallest value + for (auto iJet : goodJets) { + const xAOD::Jet* jetPtr = xaod_jet->at(iJet); + if(jetPtr->isAvailable<char>("passJVT") && !(jetPtr->auxdataConst<char>("passJVT") )) continue; //at this level we still have jets not passing the JVT cut in the ntuple + float dR = xAOD::P4Helpers::deltaR(mu,*jetPtr,useRapidity); + if (dR < dRMin) + { + dRMin = dR; + } + } + + return dRMin; } -} -void TopObjectSelection::print() const -{ - asg::AsgTool::print(); -} + void TopObjectSelection::decorateEventInfoPostOverlapRemoval(int nGoodJets, bool isLoose) { + ///-- Decorate event info with number of nominal jets for flavour composition + // Only continue if this is nominal processing + if (!m_executeNominal) return; -void TopObjectSelection::print(std::ostream& os) const { + bool UseLooseNJets = false; + // If we only run on loose nominal, we need to use loose event, otherwise use tight + if (m_config->doLooseEvents() && !m_config->doTightEvents()) UseLooseNJets = true; + // If we use loose, but this is tight, skip + if (UseLooseNJets && !isLoose) return; + + // Get the EventInfo object + const xAOD::EventInfo* eventInfo(nullptr); + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + // Decorate with number of good jets + eventInfo->auxdecor< int >("Njet") = nGoodJets; + + return; + } + + void TopObjectSelection::print() const { + asg::AsgTool::print(); + } + + void TopObjectSelection::print(std::ostream& os) const { os << "TopObjectSelection configuration\n"; os << "\n"; os << "Electrons\n"; os << " ContainerName: " << m_config->sgKeyElectrons() << "\n"; if (m_config->useElectrons()) { - os << " Selection: "; - if (!m_electronSelection) - os << "All"; - else - os << *m_electronSelection; + os << " Selection: "; + if (!m_electronSelection) os << "All"; + else os << *m_electronSelection; + } + + os << "\n"; + os << "FwdElectrons\n"; + os << " ContainerName: " << m_config->sgKeyFwdElectrons() << "\n"; + if (m_config->useFwdElectrons()) { + os << " Selection: "; + if (!m_fwdElectronSelection) os << "All"; + else os << *m_fwdElectronSelection; } os << "\n"; os << "Photons\n"; os << " ContainerName: " << m_config->sgKeyPhotons() << "\n"; if (m_config->usePhotons()) { - os << " Selection: "; - if (!m_photonSelection) - os << "All"; - else - os << *m_photonSelection; + os << " Selection: "; + if (!m_photonSelection) os << "All"; + else os << *m_photonSelection; } os << "\n"; os << "Muons\n"; os << " ContainerName: " << m_config->sgKeyMuons() << "\n"; if (m_config->useMuons()) { - os << " Selection: "; - if (!m_muonSelection) - os << "All"; - else - os << *m_muonSelection; + os << " Selection: "; + if (!m_muonSelection) os << "All"; + else os << *m_muonSelection; + } + + os << "\n"; + os << "SoftMuons\n"; + os << " ContainerName: " << m_config->sgKeySoftMuons() << "\n"; + if (m_config->useSoftMuons()) { + os << " Selection: "; + if (!m_softmuonSelection) os << "All"; + else os << *m_softmuonSelection; } // // os << "\n"; @@ -665,23 +1242,30 @@ void TopObjectSelection::print(std::ostream& os) const { os << "Jets\n"; os << " ContainerName: " << m_config->sgKeyJets() << "\n"; if (m_config->useJets()) { - os << " Selection: "; - if (!m_jetSelection) - os << "All"; - else - os << *m_jetSelection; + os << " Selection: "; + if (!m_jetSelection) os << "All"; + else os << *m_jetSelection; } os << "\n"; os << "LargeJets\n"; os << " ContainerName: " << m_config->sgKeyLargeRJets() << "\n"; if (m_config->useLargeRJets()) { - os << " Selection: "; - if (!m_largeJetSelection) - os << "All"; - else - os << *m_largeJetSelection; + os << " Selection: "; + if (!m_largeJetSelection) os << "All"; + else os << *m_largeJetSelection; } + + os << "\n"; + os << "GhostTracks\n"; + os << " ContainerName: " << m_config->decoKeyJetGhostTrack() << "\n"; + if (m_config->useJetGhostTrack()) { + os << " Selection: "; + if (!m_jetGhostTrackSelection) os << "All"; +// else m_jetGhostTrackSelection->print(os); + else os << *m_jetGhostTrackSelection; + } + os << "\n"; os << "MET\n"; @@ -689,12 +1273,9 @@ void TopObjectSelection::print(std::ostream& os) const { os << "\n\n"; os << "OverlapRemoval after object selection: "; - if (!m_overlapRemovalToolPostSelection) - os << "None"; - else - os << *m_overlapRemovalToolPostSelection; + if (!m_overlapRemovalToolPostSelection) os << "None"; + else os << *m_overlapRemovalToolPostSelection; os << "\n\n"; -} - + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackJetMC15.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackJetMC15.cxx index daad4eeaee7eb2333904ea66af2da73fea86f869..dc483cb11860a145504ceb631615d9fdc5c75b7e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackJetMC15.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackJetMC15.cxx @@ -1,38 +1,33 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/TrackJetMC15.h" -namespace top{ - - TrackJetMC15::TrackJetMC15(const double ptcut,const double etamax) : +namespace top { + TrackJetMC15::TrackJetMC15(const double ptcut, const double etamax) : m_ptcut(ptcut), m_etamax(etamax) { - } + } TrackJetMC15::~TrackJetMC15() { } bool TrackJetMC15::passSelection(const xAOD::Jet& jet) { - - if (jet.pt() < m_ptcut) - return false; + if (jet.pt() < m_ptcut) return false; - if (std::fabs(jet.eta()) > m_etamax) - return false; + if (std::fabs(jet.eta()) > m_etamax) return false; // See https://twiki.cern.ch/twiki/bin/view/AtlasProtected/TrackJetSelectionRecAndGuide - if (jet.numConstituents() < 2) - return false; + if (jet.numConstituents() < 2) return false; return true; } void TrackJetMC15::print(std::ostream& os) const { os << "Track jet\n" - << " * pT > " << m_ptcut << "\n" - << " * |eta| < " << m_etamax << "\n" - << " * >= 2 tracks \n"; + << " * pT > " << m_ptcut << "\n" + << " * |eta| < " << m_etamax << "\n" + << " * >= 2 tracks \n"; } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackSelection.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackSelection.cxx new file mode 100644 index 0000000000000000000000000000000000000000..118f01a48f063b1079038c59d88ac70c981e4636 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackSelection.cxx @@ -0,0 +1,54 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopObjectSelectionTools/TrackSelection.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" + +#include "xAODTracking/TrackParticle.h" +#include "xAODTracking/Vertex.h" + +#include "TopEvent/EventTools.h" + +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +#include "TopObjectSelectionTools/MsgCategory.h" +using namespace TopObjectSelectionTools; + +namespace top { + + TrackSelection::TrackSelection(const double ptcut, const double etamax) : + m_ptcut(ptcut), + m_etamax(etamax), + m_trkseltool("TrkSelTool") + { + + top::check(m_trkseltool.retrieve(), "Failed to retrieve InDetTrackSelectionTool"); + + } + + TrackSelection::~TrackSelection() { + } + +// bool TrackSelection::passSelection(const xAOD::TrackParticle& track, const xAOD::Vertex& primaryVertex) { +// if (track.pt() < m_ptcut) return false; +// +// if (std::fabs(track.eta()) > m_etamax) return false; +// +// +// if (track.isAvailable<char>("passTruthFilter")) { +// if (!track.auxdecor<char>("passTruthFilter")) return false; +// } +// +// if ( !m_trkseltool->accept(track, &primaryVertex ) ) return false; +// +// return true; +// } + + void TrackSelection::print(std::ostream& os) const { + os << "Track \n" + << " * pT > " << m_ptcut << "\n" + << " * |eta| < " << m_etamax; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackSelectionBase.cxx new file mode 100644 index 0000000000000000000000000000000000000000..8cc82e9a543d81c9a9ad178a39dee124802884db --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TrackSelectionBase.cxx @@ -0,0 +1,18 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration +*/ + +#include "TopObjectSelectionTools/TrackSelectionBase.h" + +namespace top { + TrackSelectionBase::TrackSelectionBase() { + } + + TrackSelectionBase::~TrackSelectionBase() { + } + + std::ostream& operator << (std::ostream& os, const top::TrackSelectionBase& selection) { + selection.print(os); + return os; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionBase.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionBase.cxx index a1e93857ccb9a7ea0607c46573bc212884b2e110..c6f87441355cb382a2b0b3068f009edc5bdeff51 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionBase.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionBase.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/TruthSelectionBase.h" @@ -10,13 +10,13 @@ #include <iostream> namespace top { - TruthSelectionBase::TruthSelectionBase() { } bool TruthSelectionBase::isBhadron(int pid) const { pid = (int) std::fabs(pid); - if ( (pid >= 511 && pid <= 545) || (pid >= 10511 && pid <= 10545) || (pid >= 20511 && pid <= 20545) || (pid >= 5112 && pid <= 5554)) { // check if it's a B-hadron + if ((pid >= 511 && pid <= 545) || (pid >= 10511 && pid <= 10545) || (pid >= 20511 && pid <= 20545) || + (pid >= 5112 && pid <= 5554)) { // check if it's a B-hadron return true; } return false; @@ -24,15 +24,15 @@ namespace top { bool TruthSelectionBase::isChadron(int pid) const { pid = (int) std::fabs(pid); - if ( (pid >= 400 && pid < 500 && pid != 443) || (pid >= 4000 && pid < 5000) || (pid >= 10411 && pid <= 10455) || (pid >= 20411 && pid <= 20445)) { // check if it's a C-hadron + if ((pid >= 400 && pid < 500 && pid != 443) || (pid >= 4000 && pid < 5000) || (pid >= 10411 && pid <= 10455) || + (pid >= 20411 && pid <= 20445)) { // check if it's a C-hadron return true; } return false; } - } -std::ostream& operator<<(std::ostream& os, const top::TruthSelectionBase& selection) { - selection.print(os); - return os; +std::ostream& operator << (std::ostream& os, const top::TruthSelectionBase& selection) { + selection.print(os); + return os; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionTtres.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionTtres.cxx index 94c94d7357ca217a5ed946b55903900d4579963f..5caaba706a663059da4487b8c145398f7f2378bc 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionTtres.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/Root/TruthSelectionTtres.cxx @@ -1,44 +1,46 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopObjectSelectionTools/TruthSelectionTtres.h" #include "TopEvent/EventTools.h" namespace top { - - TruthSelectionTtres::TruthSelectionTtres() - { + TruthSelectionTtres::TruthSelectionTtres() { } - bool TruthSelectionTtres::passSelection(const xAOD::TruthParticle& mc) const - { + bool TruthSelectionTtres::passSelection(const xAOD::TruthParticle& mc) const { int p = (int) std::fabs(mc.pdgId()); int s = mc.status(); int b = mc.barcode(); if (b > 100000) return false; + if (p == 11 || p == 13) { if (s != 1) // only final electrons and muons for e-in-jet and isolation performance eval. return false; + return true; } if (p == 6) { if (s != 3) // tops after radiation for mtt reconstruction return false; + return true; } if (isBhadron(p) || isChadron(p)) { if (s != 3) // b and c hadrons with status 3 to match with jets return false; + return true; } if (p == 12 || p == 14 || p == 16) { if (s != 1) // only final neutrinos for m_tt reconstruction return false; + return true; } @@ -47,12 +49,11 @@ namespace top { } void TruthSelectionTtres::print(std::ostream& os) const { - os << "TruthSelectionTtres\n" - << " * keep final electrons and muons\n" - << " * keep top quarks after radiation\n" - << " * keep b and c hadrons\n" - << " * keep final neutrinos\n" - ; + os << "TruthSelectionTtres\n" + << " * keep final electrons and muons\n" + << " * keep top quarks after radiation\n" + << " * keep b and c hadrons\n" + << " * keep final neutrinos\n" + ; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/AntiMuonMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/AntiMuonMC15.h index 359c0bcd48df3c32326c7e1fdb4becbc48943bf4..66c7dbec39e0ebd000e5e7fd653038ab6dfa9bbc 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/AntiMuonMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/AntiMuonMC15.h @@ -1,67 +1,63 @@ -/* - Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration -*/ - -#ifndef ANTIMUONMC15_H_ -#define ANTIMUONMC15_H_ - -#include "TopObjectSelectionTools/MuonSelectionBase.h" -#include "TopObjectSelectionTools/IsolationTools.h" - -#include "AsgTools/ToolHandle.h" -#include "MuonAnalysisInterfaces/IMuonSelectionTool.h" - -namespace top { - -/** - * @brief Select muons based on some early MC15 suggestions. - */ -class AntiMuonMC15 : public MuonSelectionBase { -public: - /** - * @brief Construct the tool to select good muons. - * - * @param ptcut The minimum pT cut for good muons. - * @param isolation The isolation the user wants to apply. Don't want any - * isolation to be applied? Then leave this as a nullptr. - */ - AntiMuonMC15(const double ptcut, IsolationBase* isolation); - - ///Does nothing. - virtual ~AntiMuonMC15(){} - - /** - * @brief Implements the logic to select good muons. - * - * @param mu The muon that we want to check. - * @return True if the muon is good, false otherwise. - */ - virtual bool passSelection(const xAOD::Muon& mu) const override; - - /** - * @brief The loose selection needed by some background estimates. - * - * @param mu - * @return - */ - virtual bool passSelectionLoose(const xAOD::Muon& mu) const override; - - ///Print the cuts to the ostream. - virtual void print(std::ostream& os) const override; - - -protected: - ///Lower pT threshold to apply to object selection. - double m_ptcut; - - ///Proper tool to select muons. - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; -// ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolLoose; - - ///Isolation tool, can be nullptr meaning "no isolation requirement" -// std::unique_ptr<top::IsolationBase> m_isolation; -}; - -} - -#endif +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANTIMUONMC15_H_ +#define ANTIMUONMC15_H_ + +#include "TopObjectSelectionTools/MuonSelectionBase.h" +#include "TopObjectSelectionTools/IsolationTools.h" + +#include "AsgTools/ToolHandle.h" +#include "MuonAnalysisInterfaces/IMuonSelectionTool.h" + +namespace top { +/** + * @brief Select muons based on some early MC15 suggestions. + */ + class AntiMuonMC15: public MuonSelectionBase { + public: + /** + * @brief Construct the tool to select good muons. + * + * @param ptcut The minimum pT cut for good muons. + * @param isolation The isolation the user wants to apply. Don't want any + * isolation to be applied? Then leave this as a nullptr. + */ + AntiMuonMC15(const double ptcut, IsolationBase* isolation); + + ///Does nothing. + virtual ~AntiMuonMC15() {} + + /** + * @brief Implements the logic to select good muons. + * + * @param mu The muon that we want to check. + * @return True if the muon is good, false otherwise. + */ + virtual bool passSelection(const xAOD::Muon& mu) const override; + + /** + * @brief The loose selection needed by some background estimates. + * + * @param mu + * @return + */ + virtual bool passSelectionLoose(const xAOD::Muon& mu) const override; + + ///Print the cuts to the ostream. + virtual void print(std::ostream& os) const override; + protected: + ///Lower pT threshold to apply to object selection. + double m_ptcut; + + ///Proper tool to select muons. + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; +// ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolLoose; + + ///Isolation tool, can be nullptr meaning "no isolation requirement" +// std::unique_ptr<top::IsolationBase> m_isolation; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronCutBasedMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronCutBasedMC15.h index eb38ce5c10a3690f32f38eaed1416fcf65bd2bf0..41f8d0a5653564142c3a859480534d4cb8a74e45 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronCutBasedMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronCutBasedMC15.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ELECTRONCUTBASEDMC15_H_ #define ELECTRONCUTBASEDMC15_H_ @@ -11,12 +11,11 @@ #include <memory> namespace top { - /** * @brief Electron selection based on the cut-based thingy. */ -class ElectronCutBasedMC15 : public top::ElectronSelectionBase { -public: + class ElectronCutBasedMC15: public top::ElectronSelectionBase { + public: /** * @brief Class to help select cut-based good electrons. * @@ -28,8 +27,9 @@ public: * @param isolation nullptr for un-isolated, or a new "isolation object" to * apply isolation cuts */ - ElectronCutBasedMC15(double ptcut, bool vetoCrack, const std::string& quality, const std::string& qualityLoose, IsolationBase* isolation); - virtual ~ElectronCutBasedMC15(){} + ElectronCutBasedMC15(double ptcut, bool vetoCrack, const std::string& quality, const std::string& qualityLoose, + IsolationBase* isolation); + virtual ~ElectronCutBasedMC15() {} /** * @brief The cuts to select good electrons for your analysis should be * implemented in here. @@ -53,11 +53,10 @@ public: * * Usually this goes to the log file, so you know what you ran with. * - * @param Where the print-out should go, e.g. cout. + * @param Where the print-out should go, e.g. msg stream */ virtual void print(std::ostream&) const override; - -protected: + protected: /** * @brief Since both selections are fairly similar, we can perform * the un-isolated part in one function. @@ -85,8 +84,7 @@ protected: ///The isolation tool, or nullptr if we don't want isolation std::unique_ptr<top::IsolationBase> m_isolation; -}; - + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronLikelihoodMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronLikelihoodMC15.h index 81833bcf8864dd6db9519bb40645c02f8cca1e1c..67b5fc430f9d416775355828c35a16e9ef36665c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronLikelihoodMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronLikelihoodMC15.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ELECTRONLIKELIHOODMC15_H_ #define ELECTRONLIKELIHOODMC15_H_ @@ -11,112 +11,112 @@ #include <memory> namespace top { - /** - * @brief To select electrons based on the "likelihood" definition. - */ - class ElectronLikelihoodMC15 : public top::ElectronSelectionBase { - public: - /** - * @brief Cut on likelihood electrons - * - * @param ptcut The minimum pT electrons should have - * @param vetoCrack Do you want to veto 1.37 < |cluster_eta| < 1.52? - * @param operatingPoint Likelihood operating point for the main object - * definition - * @param operatingPointLoose Likelihood operating point for the loose - * objects (fakes estimates?) - * @param isolation The isolation tool the user wants to use. If you don't - * want any isolation cuts to be applied then leave this as a nullptr. - */ - ElectronLikelihoodMC15(const double ptcut, const bool vetoCrack, const std::string& operatingPoint, - const std::string& operatingPointLoose, StandardIsolation* isolation, const bool applyTTVACut=true); - // this constructor is kept for backward compatibility - isPrimaryxAOD is not needed anymore - ElectronLikelihoodMC15(const bool, - const double ptcut, const bool vetoCrack, const std::string& operatingPoint, - const std::string& operatingPointLoose, StandardIsolation* isolation, const bool applyTTVACut=true); - virtual ~ElectronLikelihoodMC15(){} - /** - * @brief Selection for the main analysis (i.e. tight object definitions). - * - * @param el The electron in question - * @return True if it passes the selection, false otherwise. - */ - virtual bool passSelection(const xAOD::Electron& el) const override; - - /** - * @brief Selection for the loose object definitions (e.g. in fakes - * estimates). - * - * @param el The electron in question - * @return True if it passes the selection, false otherwise. - */ - virtual bool passSelectionLoose(const xAOD::Electron& el) const override; - - /** - * @brief The BLayer cuts for the loose lepton LH WP. - * - * @param el - * @return True if passes, false otherwise - */ - virtual bool passBLayerCuts(const xAOD::Electron& el) const; - - - /** - * @brief The track-to-vertex association (TTVA) cuts. - * - * @param el - * @return True if passes, false otherwise - */ - virtual bool passTTVACuts(const xAOD::Electron& el) const; - - /** - * @brief The charge flip selector cut - * - * @param el - * @return True if passes, false otherwise - */ - virtual bool passChargeIDCut(const xAOD::Electron& el) const; - - /** - * @brief Why would you not want to know what you're running? - * - * @param os Print details of the cuts to the output stream. - */ - virtual void print(std::ostream& os) const override; - - protected: - /** - * @brief The loose and tight selections are the same, except they have different - * use isolation and a different likelihood tool. - * - * @param el The electron in question. - * @param likelihoodTool The tool to use (m_likelihood, or m_likelihoodLoose) - * @return True if it's good, False if it's not - */ - bool passSelectionNoIsolation(const xAOD::Electron& el, const std::string& operatingPoint_DF, const std::string& operatingPoint) const; - - ///Minimum pT that electrons should have - double m_ptcut; - - ///Veto the crack region? - bool m_vetoCrack; - - std::string m_operatingPoint; - std::string m_operatingPointLoose; - std::string m_operatingPoint_DF; - std::string m_operatingPointLoose_DF; - - ///The isolation tool, or nullptr if we don't want isolation - std::unique_ptr<top::StandardIsolation> m_isolation; - - /// decide if TTVA cut should be applied at all - bool m_applyTTVACut; - - /// decide to apply the charge ID selector tool - bool m_applyChargeIDCut; + * @brief To select electrons based on the "likelihood" definition. + */ + class ElectronLikelihoodMC15: public top::ElectronSelectionBase { + public: + /** + * @brief Cut on likelihood electrons + * + * @param ptcut The minimum pT electrons should have + * @param vetoCrack Do you want to veto 1.37 < |cluster_eta| < 1.52? + * @param operatingPoint Likelihood operating point for the main object + * definition + * @param operatingPointLoose Likelihood operating point for the loose + * objects (fakes estimates?) + * @param isolation The isolation tool the user wants to use. If you don't + * want any isolation cuts to be applied then leave this as a nullptr. + */ + ElectronLikelihoodMC15(const double ptcut, const bool vetoCrack, const std::string& operatingPoint, + const std::string& operatingPointLoose, StandardIsolation* isolation, + const bool applyTTVACut = true, const bool applyChargeIDCut = false); + // this constructor is kept for backward compatibility - isPrimaryxAOD is not needed anymore + ElectronLikelihoodMC15(const bool, + const double ptcut, const bool vetoCrack, const std::string& operatingPoint, + const std::string& operatingPointLoose, StandardIsolation* isolation, + const bool applyTTVACut = true, const bool applyChargeIDCut = false); + virtual ~ElectronLikelihoodMC15() {} + /** + * @brief Selection for the main analysis (i.e. tight object definitions). + * + * @param el The electron in question + * @return True if it passes the selection, false otherwise. + */ + virtual bool passSelection(const xAOD::Electron& el) const override; + + /** + * @brief Selection for the loose object definitions (e.g. in fakes + * estimates). + * + * @param el The electron in question + * @return True if it passes the selection, false otherwise. + */ + virtual bool passSelectionLoose(const xAOD::Electron& el) const override; + + /** + * @brief The BLayer cuts for the loose lepton LH WP. + * + * @param el + * @return True if passes, false otherwise + */ + virtual bool passBLayerCuts(const xAOD::Electron& el) const; + + + /** + * @brief The track-to-vertex association (TTVA) cuts. + * + * @param el + * @return True if passes, false otherwise + */ + virtual bool passTTVACuts(const xAOD::Electron& el) const; + + /** + * @brief The charge flip selector cut + * + * @param el + * @return True if passes, false otherwise + */ + virtual bool passChargeIDCut(const xAOD::Electron& el) const; + + /** + * @brief Why would you not want to know what you're running? + * + * @param os Print details of the cuts to the output stream. + */ + virtual void print(std::ostream& os) const override; + protected: + /** + * @brief The loose and tight selections are the same, except they have different + * use isolation and a different likelihood tool. + * + * @param el The electron in question. + * @param likelihoodTool The tool to use (m_likelihood, or m_likelihoodLoose) + * @return True if it's good, False if it's not + */ + bool passSelectionNoIsolation(const xAOD::Electron& el, const std::string& operatingPoint_DF, + const std::string& operatingPoint) const; + + ///Minimum pT that electrons should have + double m_ptcut; + + ///Veto the crack region? + bool m_vetoCrack; + + std::string m_operatingPoint; + std::string m_operatingPointLoose; + std::string m_operatingPoint_DF; + std::string m_operatingPointLoose_DF; + + ///The isolation tool, or nullptr if we don't want isolation + std::unique_ptr<top::StandardIsolation> m_isolation; + + /// decide if TTVA cut should be applied at all + bool m_applyTTVACut; + + /// decide to apply the charge ID selector tool + bool m_applyChargeIDCut; }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronSelectionBase.h index 970a06b104a2f53666ce538b7700496cf861fe59..0bf44b51d59c97e9145a80471f28e174184afe33 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronSelectionBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/ElectronSelectionBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ELECTRONSELECTIONBASE_H_ #define ELECTRONSELECTIONBASE_H_ @@ -10,7 +10,6 @@ #include <memory> namespace top { - /** * @brief Base class for implementing an electron selection. * @@ -20,8 +19,8 @@ namespace top { * passSelection for an Electron. I think it would be a less-clean solution if * we were to use the 'proper' CP tool style. */ -class ElectronSelectionBase { -public: + class ElectronSelectionBase { + public: ElectronSelectionBase(); virtual ~ElectronSelectionBase(); @@ -32,7 +31,7 @@ public: ElectronSelectionBase(ElectronSelectionBase&& rhs) = delete; ///No assignment - ElectronSelectionBase& operator=(const ElectronSelectionBase& rhs) = delete; + ElectronSelectionBase& operator = (const ElectronSelectionBase& rhs) = delete; ///For the main analysis object selection virtual bool passSelection(const xAOD::Electron&) const = 0; @@ -42,10 +41,9 @@ public: ///Because everybody likes to know what object definitions they ran with virtual void print(std::ostream&) const = 0; -}; + }; + std::ostream& operator << (std::ostream& os, const ElectronSelectionBase& selection); } -std::ostream& operator<<(std::ostream& os, const top::ElectronSelectionBase& selection); - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/EventCleaningSelection.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/EventCleaningSelection.h index 9787fc024922ef04125124a4aeb57d37f54c551d..743aca7bdd2bb14075878bf83c192ed4fb131e71 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/EventCleaningSelection.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/EventCleaningSelection.h @@ -1,11 +1,14 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ -// $Id: EventCleaningSelection.h 797163 2017-02-14 16:31:05Z grancagn $ #ifndef ANALYSISTOP_TOPOBJECTSELECTIONTOOLS_EVENTCLEANINGSELECTION_H #define ANALYSISTOP_TOPOBJECTSELECTIONTOOLS_EVENTCLEANINGSELECTION_H +#include <string> +#include <unordered_set> +#include <vector> + // Framework include(s): #include "AsgTools/AsgTool.h" #include "AsgTools/ToolHandle.h" @@ -18,90 +21,101 @@ #include "TrigDecisionTool/TrigDecisionTool.h" #include "TriggerMatchingTool/IMatchingTool.h" #include "TrigTauMatching/ITrigTauMatching.h" +#include "TriggerAnalysisInterfaces/ITrigGlobalEfficiencyCorrectionTool.h" // Top include(s): #include "TopConfiguration/SelectionConfigurationData.h" -namespace top{ +namespace top { class TopConfig; - - class EventCleaningSelection final : public asg::AsgTool { - public: - explicit EventCleaningSelection( const std::string& name ); - virtual ~EventCleaningSelection(){} - - StatusCode initilize(); - - void setEventSelections( const std::vector<top::SelectionConfigurationData>& selections ); - bool applyGRL() const; - bool applyTrigger(); - bool applyGoodCalo() const; - bool applyPrimaryVertex() const; - - // Print trigger configuration - very verbose, but tells you which triggers are included for an event - void printTriggers() const; - - // helper to allow us to added trigger decisions to our output files - void addExtraBranches( std::vector<std::string>& extraBranchList ); - - // Delete Standard constructors - EventCleaningSelection(const EventCleaningSelection& rhs) = delete; - EventCleaningSelection(EventCleaningSelection&& rhs) = delete; - EventCleaningSelection& operator=(const EventCleaningSelection& rhs) = delete; - - private: - - ///Match offline electrons to the trigger - void matchElectrons(); - - ///Match offline muons to the trigger - void matchMuons(); - - ///Match offline taus to the trigger - void matchTaus(); - - /// Top config - std::shared_ptr<top::TopConfig> m_config; - - /// GoodRunsLists - ToolHandle<IGoodRunsListSelectionTool> m_grlTool; - - /// Trigger configuration tool - ToolHandle<TrigConf::ITrigConfigTool> m_trigConfTool; - - ///Trigger decision tool - ToolHandle<Trig::TrigDecisionTool> m_trigDecisionTool; - - // Trigger matching tool - ToolHandle<Trig::IMatchingTool> m_trigMatchTool; - - //Tau trigger matching - ToolHandle<Trig::ITrigTauMatchingTool> m_trigMatchTauTool; - - ///List of triggers to 'or' together for each event. If any one passes, the event passes - std::vector<std::string> m_allTriggers; - std::vector<std::string> m_electronTriggers; - std::vector<std::string> m_muonTriggers; - std::vector<std::string> m_tauTriggers; - - /// Apply a logical OR cut to all supplied triggers - /// If ANY selection does not request the trigger, this will not be set - /// In this case, the apply method will always return true - /// - /// If ALL selections request a trigger, then we can veto events - /// and not run the systematics, pre-OR cuts and the overlap removal - bool m_vetoEventsTrigger; - - /// If ALL selections request GRL, then we can veto events - /// and not run the systematics, pre-OR cuts and the overlap removal - bool m_vetoEventsGRL; - - /// If ALL selections request GOODCALO, then we can veto events - /// Data only - bool m_vetoEventsGoodCalo; - - /// If ALL selections request PRIVTX, then we can veto events - bool m_vetoEventsPriVtx; + + class EventCleaningSelection final: public asg::AsgTool { + public: + explicit EventCleaningSelection(const std::string& name); + virtual ~EventCleaningSelection() {} + + StatusCode initialize(); + + void setEventSelections(const std::vector<top::SelectionConfigurationData>& selections); + bool applyGRL() const; + bool applyTrigger(); + bool applyGoodCalo() const; + bool applyPrimaryVertex() const; + + // Print trigger configuration - very verbose, but tells you which triggers are included for an event + void printTriggers() const; + + // helper to allow us to added trigger decisions to our output files + void addExtraBranches(std::vector<std::string>& extraBranchList); + + // Delete Standard constructors + EventCleaningSelection(const EventCleaningSelection& rhs) = delete; + EventCleaningSelection(EventCleaningSelection&& rhs) = delete; + EventCleaningSelection& operator = (const EventCleaningSelection& rhs) = delete; + + bool isElectronTrigger(std::string const& trigger) const; + bool isMuonTrigger(std::string const& trigger) const; + static std::vector<std::string> getIndividualFromGlobalTriggers(std::vector<std::string> const& triggers); + private: + ///Match offline electrons to the trigger + void matchElectrons(); + + ///Match offline muons to the trigger + void matchMuons(); + + ///Match offline taus to the trigger + void matchTaus(); + + /// Top config + std::shared_ptr<top::TopConfig> m_config; + + /// GoodRunsLists + ToolHandle<IGoodRunsListSelectionTool> m_grlTool; + + /// Trigger configuration tool + ToolHandle<TrigConf::ITrigConfigTool> m_trigConfTool; + + ///Trigger decision tool + ToolHandle<Trig::TrigDecisionTool> m_trigDecisionTool; + + // Trigger matching tool + ToolHandle<Trig::IMatchingTool> m_trigMatchTool; + + //Tau trigger matching + ToolHandle<Trig::ITrigTauMatchingTool> m_trigMatchTauTool; + + //Global trigger efficiency tool + ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSF; + ToolHandle<ITrigGlobalEfficiencyCorrectionTool> m_globalTriggerSFLoose; + + ///List of triggers to 'or' together for each event. If any one passes, the event passes + std::vector<std::string> m_allTriggers_Tight; + std::vector<std::string> m_electronTriggers_Tight; + std::vector<std::string> m_muonTriggers_Tight; + std::vector<std::string> m_tauTriggers_Tight; + std::vector<std::string> m_allTriggers_Loose; + std::vector<std::string> m_electronTriggers_Loose; + std::vector<std::string> m_muonTriggers_Loose; + std::vector<std::string> m_tauTriggers_Loose; + + /// Apply a logical OR cut to all supplied triggers + /// If ANY selection does not request the trigger, this will not be set + /// In this case, the apply method will always return true + /// + /// If ALL selections request a trigger, then we can veto events + /// and not run the systematics, pre-OR cuts and the overlap removal + bool m_vetoEventsTrigger; + + /// If ALL selections request GRL, then we can veto events + /// and not run the systematics, pre-OR cuts and the overlap removal + bool m_vetoEventsGRL; + + /// If ALL selections request GOODCALO, then we can veto events + /// Data only + bool m_vetoEventsGoodCalo; + + /// If ALL selections request PRIVTX, then we can veto events + bool m_vetoEventsPriVtx; }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/FwdElectronSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/FwdElectronSelectionBase.h new file mode 100644 index 0000000000000000000000000000000000000000..3ca141c526603950fc91122ac53ab2784b61b041 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/FwdElectronSelectionBase.h @@ -0,0 +1,49 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef FWDELECTRONSELECTIONBASE_H_ +#define FWDELECTRONSELECTIONBASE_H_ + +#include "xAODEgamma/Electron.h" + +#include <memory> + +namespace top { +/** + * @brief Base class for implementing an electron selection. + * + * If you want to build a new electron selection, you should inherit from this. + * Why didn't I use ASG tools as a base? I suspect it's a bit over-complicated + * for this simple task, and this way we can force people to implement + * passSelection for an Electron. I think it would be a less-clean solution if + * we were to use the 'proper' CP tool style. + */ + class FwdElectronSelectionBase { + public: + FwdElectronSelectionBase(); + virtual ~FwdElectronSelectionBase(); + + ///No copy construction + FwdElectronSelectionBase(const FwdElectronSelectionBase& rhs) = delete; + + ///No moving - really? Seems a bit strict. We'll see + FwdElectronSelectionBase(FwdElectronSelectionBase&& rhs) = delete; + + ///No assignment + FwdElectronSelectionBase& operator = (const FwdElectronSelectionBase& rhs) = delete; + + ///For the main analysis object selection + virtual bool passSelection(const xAOD::Electron&, int bcid, int runNumber) const = 0; + + ///For the loose (e.g. fakes) object selection + virtual bool passSelectionLoose(const xAOD::Electron&, int bcid, int runNumber) const = 0; + + ///Because everybody likes to know what object definitions they ran with + virtual void print(std::ostream&) const = 0; + }; + + std::ostream& operator << (std::ostream& os, const top::FwdElectronSelectionBase& selection); +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/IsolationTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/IsolationTools.h index 63dc09989ae1da1fe644f4bac3c3a8bec7cfbdd1..f503b60d8f4b5fc965a8e2f88bcd3508eeb27067 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/IsolationTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/IsolationTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ISOLATIONTOOLS_H_ #define ISOLATIONTOOLS_H_ @@ -9,13 +9,12 @@ #include "xAODPrimitives/IsolationType.h" namespace top { - /** * @brief A common base for implementing isolation cuts. Probably these * isolation tools should be in individual files? Time will tell. */ -class IsolationBase { -public: + class IsolationBase { + public: ///Create IsolationBase(); @@ -45,10 +44,10 @@ public: /** * @brief Because people like to know what isolation cuts they're applying. * - * @param os Where to print things to, e.g. cout. + * @param os Where to print things to, e.g. msg stream. */ virtual void print(std::ostream& os) const = 0; -}; + }; /** * @brief These should give you access to xAOD::Iso::topoetcone20, 30, 40 @@ -61,8 +60,8 @@ public: * fancy things, we should implement them. Don't you want to look at using * RelativePTVarCone instead though? */ -class AbsoluteIsolationDC14 : public IsolationBase { -public: + class AbsoluteIsolationDC14: public IsolationBase { + public: /** * @brief Absolute cut on topoetcone or ptcone. * @@ -83,21 +82,20 @@ public: virtual bool passSelection(const xAOD::IParticle& p) const override; virtual bool passSelectionLoose(const xAOD::IParticle& p) const override; virtual void print(std::ostream& os) const override; - -protected: + protected: ///What to cut on (topoetcone20, 30, 40 or ptcone20, 30, 40). xAOD::Iso::IsolationType m_type; ///The value, in MeV, to cut. double m_cutvalue; -}; + }; /** * @brief Yay DC14 now has isolation! This should allow you to cut on the * isolation (ptvarcone) as a fraction of the pt of the lepton. */ -class RelativePTVarCone : public IsolationBase { -public: + class RelativePTVarCone: public IsolationBase { + public: /** * @brief Cut on the mini-isolation (aka ptvarcone) as a fraction of the * pt of the lepton. @@ -129,8 +127,7 @@ public: ///Come on, you really need me to tell you what this does? virtual void print(std::ostream& os) const override; - -protected: + protected: ///The name of the variable to access, e.g. ptvarcone20 formed in the constructor. std::string m_size; @@ -142,7 +139,7 @@ protected: ///For the objects used in the looser object selection (e.g. matrix method fakes) double m_fractionLoose; -}; + }; /** * @brief Danilo's approximation of mini-isolation which has been calculated @@ -153,8 +150,8 @@ protected: * options will be better, and almost certainly faster if we don't need to load * all the tracks! */ -class ApproxPTVarCone : public IsolationBase { -public: + class ApproxPTVarCone: public IsolationBase { + public: /** * @brief An approximation of mini-isolation. * @@ -186,27 +183,26 @@ public: ///Come on, you really need me to tell you what this does? virtual void print(std::ostream& os) const override; - -protected: + protected: ///For the main analysis object selection double m_fraction; ///For the objects used in the looser object selection (e.g. matrix method fakes) double m_fractionLoose; -}; + }; /** * @brief Apply the cuts to etcone and ptcone like we used to in Run-I */ -class StandardIsolation : public IsolationBase { -public: + class StandardIsolation: public IsolationBase { + public: /** * @brief Applies the cuts to etcone and ptcone like we used to in Run-I * * This sets up the isolation tool and configures it with the cuts. */ - StandardIsolation(const std::string& tightLeptonIsolation = "Gradient" , - const std::string& looseLeptonIsolation = "None" ); + StandardIsolation(const std::string& tightLeptonIsolation = "Gradient", + const std::string& looseLeptonIsolation = "None"); /** * @brief Does this particle pass the isolation cuts for the main analysis @@ -231,16 +227,17 @@ public: ///Come on, you really need me to tell you what this does? virtual void print(std::ostream& os) const override; - -protected: + protected: std::string m_tightLeptonDecoration; std::string m_looseLeptonDecoration; std::string m_tightLeptonIsolation; std::string m_looseLeptonIsolation; bool m_doTightIsolation; bool m_doLooseIsolation; -}; - + bool m_doTightPromptLeptonIso; + bool m_doLoosePromptLeptonIso; + bool m_skipUnavailable; // skip unavailable working points (instead of aborting) + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetGhostTrackSelection.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetGhostTrackSelection.h new file mode 100644 index 0000000000000000000000000000000000000000..ec800ccde2767022f767fb384c38ad5c5eeb4034 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetGhostTrackSelection.h @@ -0,0 +1,42 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef JETGHOSTTRACKSELECTION_H_ +#define JETGHOSTTRACKSELECTION_H_ + +#include "TopObjectSelectionTools/JetGhostTrackSelectionBase.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" + +#include "xAODTracking/VertexContainer.h" +#include "xAODTracking/Vertex.h" + + +namespace top { + class JetGhostTrackSelection: public JetGhostTrackSelectionBase { + public: + JetGhostTrackSelection(const double ptcut, const double etamax, const std::string vertexassociation, const double m_ptcut_jet, const double m_etamax_jet ); + ~JetGhostTrackSelection(); + virtual bool JetConsideredForGhostTrackSelection(double pt, double eta) const override; +// virtual bool passSelection(const xAOD::TrackParticle&, const xAOD::Vertex&) const override; + virtual void print(std::ostream& os) const override; + private: + //Include selection on pt and eta of the tracks + double m_ptcut; + double m_etamax; + + //Include selection on pt and eta of the jets + double m_ptcut_jet; + double m_etamax_jet; + + //Requirement on the vertex association + std::string m_vertexassociation; + double m_d0; + double m_z0sintheta; + + + ToolHandle<InDet::InDetTrackSelectionTool> m_trkseltool; + + }; +} +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetGhostTrackSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetGhostTrackSelectionBase.h new file mode 100644 index 0000000000000000000000000000000000000000..e2584a8071f6c128420e57d5c0bdffbc4c928ca4 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetGhostTrackSelectionBase.h @@ -0,0 +1,28 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef JETGHOSTTRACKSELECTIONBASE_H_ +#define JETGHOSTTRACKSELECTIONBASE_H_ + +#include "xAODTracking/TrackParticle.h" + +namespace top { + class JetGhostTrackSelectionBase { + public: + JetGhostTrackSelectionBase(); + virtual ~JetGhostTrackSelectionBase(); + + ///For the main analysis object selection +// virtual bool passSelection(const xAOD::TrackParticle&, const xAOD::Vertex&) const = 0; + ///To see if a jet hase the requirements to retrieve the corresponding tracks + virtual bool JetConsideredForGhostTrackSelection(double pt, double eta) const = 0; + ///Because everybody likes to know what object definitions they ran with + virtual void print(std::ostream&) const = 0; + + }; + +std::ostream& operator << (std::ostream& os, const top::JetGhostTrackSelectionBase& selection); + +} +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetMC15.h index 67c37327f20d97f076d0dc21413ef91713c661cc..65ed5756eb2eac067fef848e3857b4107fbb260b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetMC15.h @@ -1,87 +1,92 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef JETMC15_H_ #define JETMC15_H_ #include "TopObjectSelectionTools/JetSelectionBase.h" -#include "JetJvtEfficiency/IJetJvtEfficiency.h" +#include "JetAnalysisInterfaces/IJetJvtEfficiency.h" #include "AsgTools/ToolHandle.h" # include <string> namespace top { - /** * @brief A class that performs object cuts on Jets (of any size!). At the * moment it includes a cut on pT, eta and JVT. */ -class JetMC15 : public JetSelectionBase { - public: - /** - * @brief A tool to select some jets for MC15 based on the pT and eta cuts. - * - * @param ptcut The minimum pT to accept good jets. - * @param etamax The maximum eta cut. - * @param doJVTCut To perform JVT cut - should be false for small-R jets - * @param fwdJetSel Scenario for treating forward jets. - */ - JetMC15(const double ptcut, const double etamax, const bool doJVTCut, const std::string fwdJetSel="default"); - - /** - * @brief A tool to select some jets for MC15 based on the pT and eta cuts. - * - * This version of the constructor always perform JVT cut - * - * @param ptcut The minimum pT to accept good jets. - * @param etamax The maximum eta cut. - * @param fwdJetSel Scenario for treating forward jets. - */ - JetMC15(const double ptcut, const double etamax, const std::string fwdJetSel="default"); - - /** - * @brief A tool to select some jets for MC15 based on the pT and eta cuts. - * - * DEPRECATED - only kept for backward compatibility - no need to specify any jvt cut, please use the above function instead. - * - * @param ptcut The minimum pT to accept good jets. - * @param etamax The maximum eta cut. - * @param jvtmin The minimum cut on the jet vertex fraction (no longer used) - */ - JetMC15(const double ptcut, const double etamax, const double); - - // Does nothing. - virtual ~JetMC15() {} - - /** - * @brief Implements the logic to select jets based on pT and eta. - * - * It cuts on pt, eta, jvt. - * - * @param jet The jet to check. - * @return True if the jet passes the cuts, false otherwise. - */ - virtual bool passSelection(const xAOD::Jet& jet) override; - - // Print the cuts to the ostream. - virtual void print(std::ostream& os) const override; - - protected: - // The lower pT cut threshold to apply to the object. - double m_ptcut; - - // The upper eta cut. - double m_etamax; - - // Scenario for treating forward jets - std::string m_fwdJetSel; - - // To do JVT cut - should be false for large-R jets - bool m_applyJVTCut; - - ToolHandle<CP::IJetJvtEfficiency> m_jvt_tool; -}; + class JetMC15: public JetSelectionBase { + public: + /** + * @brief A tool to select some jets for MC15 based on the pT and eta cuts. + * + * @param ptcut The minimum pT to accept good jets. + * @param etamax The maximum eta cut. + * @param doJVTCut To perform JVT cut - should be false for small-R jets + */ + JetMC15(const double ptcut, const double etamax, const bool doJVTCut); + + /** + * @brief A tool to select some jets for MC15 based on the pT and eta cuts. + * + * This version of the constructor always perform JVT cut + * + * @param ptcut The minimum pT to accept good jets. + * @param etamax The maximum eta cut. + */ + JetMC15(const double ptcut, const double etamax); + + /** + * @brief A tool to select some jets for MC15 based on the pT and eta cuts. + * + * DEPRECIATED - Only kept for backwards compatibility, to stop external extensions from crashing, please use above forms + * + * @param ptcut The minimum pT to accept good jets. + * @param etamax The maximum eta cut. + * @param fwdJetSel Scenario for treating forward jets. + */ + JetMC15(const double ptcut, const double etamax, const std::string); + + /** + * @brief A tool to select some jets for MC15 based on the pT and eta cuts. + * + * DEPRECATED - only kept for backward compatibility - no need to specify any jvt cut, please use the above function + *instead. + * + * @param ptcut The minimum pT to accept good jets. + * @param etamax The maximum eta cut. + * @param jvtmin The minimum cut on the jet vertex fraction (no longer used) + */ + JetMC15(const double ptcut, const double etamax, const double); + + // Does nothing. + virtual ~JetMC15() {} + + /** + * @brief Implements the logic to select jets based on pT and eta. + * + * It cuts on pt, eta, jvt. + * + * @param jet The jet to check. + * @return True if the jet passes the cuts, false otherwise. + */ + virtual bool passSelection(const xAOD::Jet& jet) override; + + // Print the cuts to the ostream. + virtual void print(std::ostream& os) const override; + protected: + // The lower pT cut threshold to apply to the object. + double m_ptcut; + + // The upper eta cut. + double m_etamax; + + // To do JVT cut - should be false for large-R jets + bool m_applyJVTCut; + + ToolHandle<CP::IJetJvtEfficiency> m_jvt_tool; + }; } // namespace top #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetSelectionBase.h index eeb33f65c694645f98116e918d66959f79c505f5..9faf48646fab454822b1963dc703ea873820a0fd 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetSelectionBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/JetSelectionBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef JETSELECTIONBASE_H_ #define JETSELECTIONBASE_H_ @@ -8,9 +8,8 @@ #include "xAODJet/Jet.h" namespace top { - -class JetSelectionBase { -public: + class JetSelectionBase { + public: JetSelectionBase(); virtual ~JetSelectionBase(); @@ -18,10 +17,9 @@ public: virtual bool passSelection(const xAOD::Jet&) = 0; virtual void print(std::ostream&) const = 0; -}; + }; + std::ostream& operator << (std::ostream& os, const top::JetSelectionBase& selection); } -std::ostream& operator<<(std::ostream& os, const top::JetSelectionBase& selection); - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MsgCategory.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MsgCategory.h new file mode 100644 index 0000000000000000000000000000000000000000..9bc3f50ed6328d454918749011b2b468dc151b46 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MsgCategory.h @@ -0,0 +1,11 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#ifndef TOPOBJSELTOOLS_MSG_CATEGORY_H_ +#define TOPOBJSELTOOLS_MSG_CATEGORY_H_ + +#include <AsgMessaging/MessageCheck.h> + +ANA_MSG_HEADER(TopObjectSelectionTools) + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonMC15.h index f0801c397a74b139ae39576185ccb498bf8ab399..beaf3c9d60a2860cb69e29c44952837aeb2f5f2d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonMC15.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MUONMC15_H_ #define MUONMC15_H_ @@ -12,68 +12,65 @@ #include "MuonAnalysisInterfaces/IMuonSelectionTool.h" namespace top { - /** * @brief Select muons based on some early MC15 suggestions. */ -class MuonMC15 : public MuonSelectionBase { - public: - /** - * @brief Construct the tool to select good muons. - * - * @param ptcut The minimum pT cut for good muons. - * @param isolation The isolation the user wants to apply. Don't want any - * isolation to be applied? Then leave this as a nullptr. - */ - MuonMC15(const double ptcut, - IsolationBase* isolation, - const bool applyTTVACut = true); - - // Does nothing. - virtual ~MuonMC15() {} - - /** - * @brief Implements the logic to select good muons. - * - * @param mu The muon that we want to check. - * @return True if the muon is good, false otherwise. - */ - virtual bool passSelection(const xAOD::Muon& mu) const override; - - /** - * @brief The loose selection needed by some background estimates. - * - * @param mu - * @return - */ - virtual bool passSelectionLoose(const xAOD::Muon& mu) const override; - - /** - * @brief The track-to-vertex association (TTVA) cuts. - * - * @param mu - * @return True if passes, false otherwise - */ - virtual bool passTTVACuts(const xAOD::Muon& mu) const; - - // Print the cuts to the ostream. - virtual void print(std::ostream& os) const override; - - - protected: - // Lower pT threshold to apply to object selection. - double m_ptcut; - - // Proper tool to select muons. - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolLoose; - - // Isolation tool, can be nullptr meaning "no isolation requirement" - std::unique_ptr<top::IsolationBase> m_isolation; - - // decide if TTVA cut should be applied at all - bool m_applyTTVACut; -}; + class MuonMC15: public MuonSelectionBase { + public: + /** + * @brief Construct the tool to select good muons. + * + * @param ptcut The minimum pT cut for good muons. + * @param isolation The isolation the user wants to apply. Don't want any + * isolation to be applied? Then leave this as a nullptr. + */ + MuonMC15(const double ptcut, + IsolationBase* isolation, + const bool applyTTVACut = true); + + // Does nothing. + virtual ~MuonMC15() {} + + /** + * @brief Implements the logic to select good muons. + * + * @param mu The muon that we want to check. + * @return True if the muon is good, false otherwise. + */ + virtual bool passSelection(const xAOD::Muon& mu) const override; + + /** + * @brief The loose selection needed by some background estimates. + * + * @param mu + * @return + */ + virtual bool passSelectionLoose(const xAOD::Muon& mu) const override; + + /** + * @brief The track-to-vertex association (TTVA) cuts. + * + * @param mu + * @return True if passes, false otherwise + */ + virtual bool passTTVACuts(const xAOD::Muon& mu) const; + + // Print the cuts to the ostream. + virtual void print(std::ostream& os) const override; + protected: + // Lower pT threshold to apply to object selection. + double m_ptcut; + + // Proper tool to select muons. + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionTool; + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolLoose; + + // Isolation tool, can be nullptr meaning "no isolation requirement" + std::unique_ptr<top::IsolationBase> m_isolation; + + // decide if TTVA cut should be applied at all + bool m_applyTTVACut; + }; } // namespace top #endif // MUONMC15_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonSelectionBase.h index d0fe26fb0697fdc0edda55f91cc5e63e45cb1531..e8af99396ea4266de53f3abebc0a3918bb8e2a52 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonSelectionBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/MuonSelectionBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef MUONSELECTIONBASE_H_ #define MUONSELECTIONBASE_H_ @@ -8,12 +8,11 @@ #include "xAODMuon/Muon.h" namespace top { - -class MuonSelectionBase { -public: + class MuonSelectionBase { + public: MuonSelectionBase(); virtual ~MuonSelectionBase(); - + ///No copy construction MuonSelectionBase(const MuonSelectionBase& rhs) = delete; @@ -21,7 +20,7 @@ public: MuonSelectionBase(MuonSelectionBase&& rhs) = delete; ///No assignment - MuonSelectionBase& operator=(const MuonSelectionBase& rhs) = delete; + MuonSelectionBase& operator = (const MuonSelectionBase& rhs) = delete; ///For the main analysis object selection virtual bool passSelection(const xAOD::Muon&) const = 0; @@ -30,12 +29,10 @@ public: virtual bool passSelectionLoose(const xAOD::Muon&) const = 0; ///Because everybody likes to know what object definitions they ran with - virtual void print(std::ostream&) const = 0; - -}; + virtual void print(std::ostream&) const = 0; + }; + std::ostream& operator << (std::ostream& os, const top::MuonSelectionBase& selection); } -std::ostream& operator<<(std::ostream& os, const top::MuonSelectionBase& selection); - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalASG.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalASG.h index 4806f7b19778ab4e64de1109ec5464de4d515136..241919ac687b8f8d5ca4ac5470c9255da0b5a8b8 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalASG.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalASG.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: OverlapRemovalIndices.h 643484 2015-02-02 11:23:34Z simon $ #ifndef ANALYSISTOP_TOPOBJECTSELECTONTOOLS_OVERLAPREMOVALASG_H @@ -16,89 +16,84 @@ #include "AssociationUtils/IOverlapRemovalTool.h" namespace top { - /** * @brief The Harmonization Group recommended object overlap removal */ - class OverlapRemovalASG : public top::OverlapRemovalBase { - public: - /** - * @brief Sets up ASG Overlap Removal Tool - * - * @param dolargeJet Enables OR also with large-R jets - * This is false by default becaause large-R jets are a bit special. - * - */ - OverlapRemovalASG(bool dolargeJet = false); + class OverlapRemovalASG: public top::OverlapRemovalBase { + public: + /** + * @brief Sets up ASG Overlap Removal Tool + * + * @param dolargeJet Enables OR also with large-R jets + * This is false by default becaause large-R jets are a bit special. + * + */ + OverlapRemovalASG(bool dolargeJet = false); ///does nothing - virtual ~OverlapRemovalASG(); - - /** - * @brief Perform the "ASG standard" overlap removal. - * - * This runs for every event. - * - * @param photon All the photons in the event - * @param el All the electrons (even bad ones). Good ones are decorated - * with passPreORSelection = 1. - * @param mu All the muons in the event - * @param tau All the taus in the event - * @param jet All the jets in the event - * @param ljet All the large-R jets in the event - * - * @param goodPhotons The indices of the photons to keep - * @param goodElectrons The indices of the electrons to keep (e.g. the 0th, 2nd) - * @param goodMuons The indices of the muons to keep - * @param goodTaus The indices of the taus to keep - * @param goodJets The indices of the jets to keep - * @param goodLargeRJets The indices of the large-R jets to keep - * - */ - virtual void overlapremoval(const xAOD::PhotonContainer* photon , - const xAOD::ElectronContainer* el , - const xAOD::MuonContainer* mu , - const xAOD::TauJetContainer* tau , - const xAOD::JetContainer* jet , - const xAOD::JetContainer* ljet, - std::vector<unsigned int>& goodPhotons, - std::vector<unsigned int>& goodElectrons, - std::vector<unsigned int>& goodMuons, - std::vector<unsigned int>& goodTaus, - std::vector<unsigned int>& goodJets, - std::vector<unsigned int>& goodLargeRJets, - const bool isLooseEvent ); - - ///Print something useful to the screen - virtual void print(std::ostream&) const; - + virtual ~OverlapRemovalASG(); + + /** + * @brief Perform the "ASG standard" overlap removal. + * + * This runs for every event. + * + * @param photon All the photons in the event + * @param el All the electrons (even bad ones). Good ones are decorated + * with passPreORSelection = 1. + * @param mu All the muons in the event + * @param tau All the taus in the event + * @param jet All the jets in the event + * @param ljet All the large-R jets in the event + * + * @param goodPhotons The indices of the photons to keep + * @param goodElectrons The indices of the electrons to keep (e.g. the 0th, 2nd) + * @param goodMuons The indices of the muons to keep + * @param goodTaus The indices of the taus to keep + * @param goodJets The indices of the jets to keep + * @param goodLargeRJets The indices of the large-R jets to keep + * + */ + virtual void overlapremoval(const xAOD::PhotonContainer* photon, + const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::TauJetContainer* tau, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, + std::vector<unsigned int>& goodPhotons, + std::vector<unsigned int>& goodElectrons, + std::vector<unsigned int>& goodMuons, + std::vector<unsigned int>& goodTaus, + std::vector<unsigned int>& goodJets, + std::vector<unsigned int>& goodLargeRJets, + const bool isLooseEvent); + + ///Print something useful to the screen + virtual void print(std::ostream&) const; protected: - - /// For a generic container of type DataVector, fill a vector of - /// ints for objects we want to keep - virtual void removeObjectOverlap( const xAOD::IParticleContainer* xaod , - std::vector<unsigned int>& OUT_vec, - const std::string passTopCuts); + /// For a generic container of type DataVector, fill a vector of + /// ints for objects we want to keep + virtual void removeObjectOverlap(const xAOD::IParticleContainer* xaod, + std::vector<unsigned int>& OUT_vec, + const std::string passTopCuts); - /// For a generic container of type DataVector, fill a vector of - /// ints for objects we want to keep - /// This doesn't check for overlap removal (Large R jets) - virtual void removeObject( const xAOD::IParticleContainer* xaod , - std::vector<unsigned int>& OUT_vec, - const std::string passTopCuts); + /// For a generic container of type DataVector, fill a vector of + /// ints for objects we want to keep + /// This doesn't check for overlap removal (Large R jets) + virtual void removeObject(const xAOD::IParticleContainer* xaod, + std::vector<unsigned int>& OUT_vec, + const std::string passTopCuts); - // ASG overlap removal tool - asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool; - asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalToolLoose; + // ASG overlap removal tool + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool; + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalToolLoose; - const std::string m_passPreORSelection; - const std::string m_passPreORSelectionLoose; - const std::string m_overlaps; // true if object overlaps with another - - bool m_doLargeJet; + const std::string m_passPreORSelection; + const std::string m_passPreORSelectionLoose; + const std::string m_overlaps; // true if object overlaps with another + bool m_doLargeJet; }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalBase.h index a88009b7d1dd2890f5427e4cbea5d313c8696234..305b1600dc0086f5b6f2f7896034e39f1da1a42c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef OVERLAPREMOVALBASE_H_ #define OVERLAPREMOVALBASE_H_ @@ -12,38 +12,36 @@ #include "xAODTau/TauJetContainer.h" namespace top { - -class OverlapRemovalBase { -public: + class OverlapRemovalBase { + public: OverlapRemovalBase(); virtual ~OverlapRemovalBase(); OverlapRemovalBase(const OverlapRemovalBase& rhs) = delete; OverlapRemovalBase(OverlapRemovalBase&& rhs) = delete; - OverlapRemovalBase& operator=(const OverlapRemovalBase& rhs) = delete; - - virtual void overlapremoval(const xAOD::PhotonContainer* photon , - const xAOD::ElectronContainer* el , - const xAOD::MuonContainer* mu , - const xAOD::TauJetContainer* tau , - const xAOD::JetContainer* jet , - const xAOD::JetContainer* ljet, - std::vector<unsigned int>& goodPhotons, + OverlapRemovalBase& operator = (const OverlapRemovalBase& rhs) = delete; + + virtual void overlapremoval(const xAOD::PhotonContainer* photon, + const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::TauJetContainer* tau, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, + std::vector<unsigned int>& goodPhotons, std::vector<unsigned int>& goodElectrons, std::vector<unsigned int>& goodMuons, std::vector<unsigned int>& goodTaus, std::vector<unsigned int>& goodJets, std::vector<unsigned int>& goodLargeRJets, - const bool isLooseEvent ) = 0; - + const bool isLooseEvent) = 0; + virtual bool overlapsEl(std::vector<unsigned int>&) {return false;} virtual bool overlapsMu(std::vector<unsigned int>&) {return false;} virtual void print(std::ostream&) const = 0; -}; + }; + std::ostream& operator << (std::ostream& os, const top::OverlapRemovalBase& overlapremoval); } -std::ostream& operator<<(std::ostream& os, const top::OverlapRemovalBase& overlapremoval); - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalIndices.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalIndices.h index ea92eab8ebc4c9514475b1008ebcfab29697ae1d..f35aa2048aba7f8ed38b58912007778a2c005639 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalIndices.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/OverlapRemovalIndices.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: OverlapRemovalIndices.h 661110 2015-04-17 00:03:39Z morrisj $ #ifndef ANALYSISTOP_TOPOBJECTSELECTONTOOLS_OVERLAPREMOVALINDICES_H #define ANALYSISTOP_TOPOBJECTSELECTONTOOLS_OVERLAPREMOVALINDICES_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief OverlapRemovalIndices - * Do overlap removal based on selected indices - * - * $Revision: 661110 $ - * $Date: 2015-04-17 02:03:39 +0200 (Fri, 17 Apr 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief OverlapRemovalIndices + * Do overlap removal based on selected indices + * + * $Revision: 661110 $ + * $Date: 2015-04-17 01:03:39 +0100 (Fri, 17 Apr 2015) $ + * + **/ // system include(s): #include <memory> @@ -24,65 +24,63 @@ #include "TopObjectSelectionTools/OverlapRemovalBase.h" namespace top { - /** * @brief The "standard" overlap removal for the top group */ - class OverlapRemovalIndices : public top::OverlapRemovalBase { - public: - ///Doesn't do anything - OverlapRemovalIndices(); + class OverlapRemovalIndices: public top::OverlapRemovalBase { + public: + ///Doesn't do anything + OverlapRemovalIndices(); - ///Doesn't do anything - virtual ~OverlapRemovalIndices(); + ///Doesn't do anything + virtual ~OverlapRemovalIndices(); - /** - * @brief Perform our "standard" overlap removal. - * - * This runs for every event. - * - * The overlap removal consists of: - * - (1) remove muon within dR < 0.4 of any jet - * - (2) remove single jet closest to an electron (within dR < 0.2) - * - (3) remove electron with dR < 0.4 of jet - * - * @param el All the electrons (even bad ones). Good ones are decorated - * with passPreORSelection = 1. - * @param mu All the muons in the event - * @param jet All the jets in the event - * @param ljet All the large-R jets in the event - * @param OUT_el The indices of the electrons to keep (e.g. the 0th, 2nd) - * @param OUT_mu The indices of the muons to keep - * @param OUT_jet The indices of the jets to keep - * @param OUT_ljet The indices of the large-R jets to keep - */ - virtual void overlapremoval(const xAOD::ElectronContainer* el , - const xAOD::MuonContainer* mu , - const xAOD::JetContainer* jet , - const xAOD::JetContainer* ljet , - std::vector<unsigned int>& OUT_el , - std::vector<unsigned int>& OUT_mu , - std::vector<unsigned int>& OUT_jet , - std::vector<unsigned int>& OUT_ljet , - const bool isLooseEvent ); + /** + * @brief Perform our "standard" overlap removal. + * + * This runs for every event. + * + * The overlap removal consists of: + * - (1) remove muon within dR < 0.4 of any jet + * - (2) remove single jet closest to an electron (within dR < 0.2) + * - (3) remove electron with dR < 0.4 of jet + * + * @param el All the electrons (even bad ones). Good ones are decorated + * with passPreORSelection = 1. + * @param mu All the muons in the event + * @param jet All the jets in the event + * @param ljet All the large-R jets in the event + * @param OUT_el The indices of the electrons to keep (e.g. the 0th, 2nd) + * @param OUT_mu The indices of the muons to keep + * @param OUT_jet The indices of the jets to keep + * @param OUT_ljet The indices of the large-R jets to keep + */ + virtual void overlapremoval(const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, + std::vector<unsigned int>& OUT_el, + std::vector<unsigned int>& OUT_mu, + std::vector<unsigned int>& OUT_jet, + std::vector<unsigned int>& OUT_ljet, + const bool isLooseEvent); - virtual void overlapremoval(const xAOD::PhotonContainer* photon , - const xAOD::ElectronContainer* el , - const xAOD::MuonContainer* mu , - const xAOD::TauJetContainer* tau , - const xAOD::JetContainer* jet , - const xAOD::JetContainer* ljet, - std::vector<unsigned int>& goodPhotons, - std::vector<unsigned int>& goodElectrons, - std::vector<unsigned int>& goodMuons, - std::vector<unsigned int>& goodTaus, - std::vector<unsigned int>& goodJets, - std::vector<unsigned int>& goodLargeRJets, - const bool isLooseEvent ); + virtual void overlapremoval(const xAOD::PhotonContainer* photon, + const xAOD::ElectronContainer* el, + const xAOD::MuonContainer* mu, + const xAOD::TauJetContainer* tau, + const xAOD::JetContainer* jet, + const xAOD::JetContainer* ljet, + std::vector<unsigned int>& goodPhotons, + std::vector<unsigned int>& goodElectrons, + std::vector<unsigned int>& goodMuons, + std::vector<unsigned int>& goodTaus, + std::vector<unsigned int>& goodJets, + std::vector<unsigned int>& goodLargeRJets, + const bool isLooseEvent); - ///Print something useful to the screen - virtual void print(std::ostream&) const; + ///Print something useful to the screen + virtual void print(std::ostream&) const; }; - } -#endif +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonMC16.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonMC16.h new file mode 100644 index 0000000000000000000000000000000000000000..9990990988a855f2e9a21dc1ab5a8ef74d53c29e --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonMC16.h @@ -0,0 +1,110 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TOPOBJECTSELECTIONTOOLS_PHOTONMC16_H_ +#define TOPOBJECTSELECTIONTOOLS_PHOTONMC16_H_ + +#include <memory> +#include <string> + +#include "TopObjectSelectionTools/PhotonSelectionBase.h" +#include "TopObjectSelectionTools/IsolationTools.h" + +#include "ElectronPhotonSelectorTools/AsgPhotonIsEMSelector.h" + +namespace top { +/** + * @brief Photon selection for top analyses. + * For Release 21 specific cleaning + */ + + class PhotonMC16: public top::PhotonSelectionBase { + public: + /** + * @brief Class to help select good photons. + * + * @param ptcut The minimum pT cut to apply to the photons. + * @param etamax The maximum eta cut + * @param isolation nullptr for un-isolated, or a new "isolation object" to + * @param usePhotonShowerShapeVariables to turn on/off the reading of shower shape variables + * apply isolation cuts + */ + PhotonMC16(double ptcut, double etamax, IsolationBase* isolation, bool usePhotonShowerShapeVariables); + + /** + * @brief Class to help select good photons. + * + * @param ptcut The minimum pT cut to apply to the photons. + * @param etamax The maximum eta cut + * @param tightID The ID level used to select tight photons. + * @param looseID The ID level used to select loose photons. + * @param isolation nullptr for un-isolated, or a new "isolation object" to + * @param usePhotonShowerShapeVariables to turn on/off the reading of shower shape variables + * apply isolation cuts + */ + PhotonMC16(double ptcut, double etamax, + const std::string& tightID, + const std::string& looseID, + IsolationBase* isolation, + bool usePhotonShowerShapeVariables); + + /** + * @brief The cuts to select good photons for your analysis should be + * implemented in here. + * + * @param ph The photon to cut on (all photons in the event are passed + * to the tool) + * @return True if this is a good photon, false otherwise. + */ + bool passSelection(const xAOD::Photon& ph) const override; + + /** + * @brief The loose selection. + * + * @param ph + * @return + */ + bool passSelectionLoose(const xAOD::Photon& ph) const override; + + /** + * @brief Print some useful information about the photon selection. + * + * Usually this goes to the log file, so you know what you ran with. + * + * @param Where the print-out should go, e.g. msg stream. + */ + void print(std::ostream&) const override; + private: + /** + * @brief Do all the cuts except for the isolation. + * + * @param ph The photon in question + * @return True if the photon passes + */ + bool passSelectionNoIsolation(const xAOD::Photon& ph, + const std::string& photon_selection) const; + + std::string getConfigFile(int operatingPoint); + + // minimum pT cut to apply + double m_ptcut; + + // max eta cut + double m_etamax; + + std::string m_photon_selection; + std::string m_loose_photon_selection; + + // Proper tool to select photons. + // ToolHandle<AsgPhotonIsEMSelector> m_photonTightIsEMSelector; + // ToolHandle<AsgPhotonIsEMSelector> m_photonMediumIsEMSelector; + // ToolHandle<AsgPhotonIsEMSelector> m_photonLooseIsEMSelector; + + // The isolation tool, or nullptr if we don't want isolation + std::unique_ptr<top::IsolationBase> m_isolation; + + mutable bool m_usePhotonShowerShapeVariables; + }; +} // namespace top +#endif // TOPOBJECTSELECTIONTOOLS_PHOTONMC16_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonSelectionBase.h index bb1015d25c4455f667cd2dd03d9f8870c4fc8f95..11c602044d46381fb162a2b0d7575ff71cab699e 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonSelectionBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/PhotonSelectionBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef PHOTONSELECTIONBASE_H_ #define PHOTONSELECTIONBASE_H_ @@ -10,7 +10,6 @@ #include <memory> namespace top { - /** * @brief Base class for implementing an Photon selection. * @@ -18,19 +17,19 @@ namespace top { * */ -class PhotonSelectionBase { -public: + class PhotonSelectionBase { + public: PhotonSelectionBase(); virtual ~PhotonSelectionBase(); ///No copy construction PhotonSelectionBase(const PhotonSelectionBase& rhs) = delete; - ///No moving + ///No moving PhotonSelectionBase(PhotonSelectionBase&& rhs) = delete; ///No assignment - PhotonSelectionBase& operator=(const PhotonSelectionBase& rhs) = delete; + PhotonSelectionBase& operator = (const PhotonSelectionBase& rhs) = delete; ///For the main analysis object selection virtual bool passSelection(const xAOD::Photon&) const = 0; @@ -40,10 +39,9 @@ public: ///Because everybody likes to know what object definitions they ran with virtual void print(std::ostream&) const = 0; -}; + }; + std::ostream& operator << (std::ostream& os, const top::PhotonSelectionBase& selection); } -std::ostream& operator<<(std::ostream& os, const top::PhotonSelectionBase& selection); - #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/SoftMuonMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/SoftMuonMC15.h new file mode 100644 index 0000000000000000000000000000000000000000..7aca4ee0de2775030e4833fa4d1b88e6c58368c3 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/SoftMuonMC15.h @@ -0,0 +1,51 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef SOFTMUONMC15_H_ +#define SOFTMUONMC15_H_ + +#include "TopObjectSelectionTools/SoftMuonSelectionBase.h" +#include "TopObjectSelectionTools/IsolationTools.h" + +#include "AsgTools/ToolHandle.h" +#include "MuonAnalysisInterfaces/IMuonSelectionTool.h" + +namespace top { +/** + * @brief Select muons based on some early MC15 suggestions. + */ + class SoftMuonMC15: public SoftMuonSelectionBase { + public: + /** + * @brief Construct the tool to select good muons. + * + * @param ptcut The minimum pT cut for good muons. + * @param isolation The isolation the user wants to apply. Don't want any + * isolation to be applied? Then leave this as a nullptr. + */ + SoftMuonMC15(const double ptcut); + + // Does nothing. + virtual ~SoftMuonMC15() {} + + /** + * @brief Implements the logic to select good muons. + * + * @param mu The muon that we want to check. + * @return True if the muon is good, false otherwise. + */ + virtual bool passSelection(const xAOD::Muon& mu) const override; + + // Print the cuts to the ostream. + virtual void print(std::ostream& os) const override; + protected: + // Lower pT threshold to apply to object selection. + double m_ptcut; + + // Proper tool to select muons. + ToolHandle<CP::IMuonSelectionTool> m_softmuonSelectionTool; + }; +} // namespace top + +#endif // SOFTMUONMC15_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/SoftMuonSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/SoftMuonSelectionBase.h new file mode 100644 index 0000000000000000000000000000000000000000..c4e91235706ef5043cf9ff06e75b6dafd9743493 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/SoftMuonSelectionBase.h @@ -0,0 +1,35 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef SOFTMUONSELECTIONBASE_H_ +#define SOFTMUONSELECTIONBASE_H_ + +#include "xAODMuon/Muon.h" + +namespace top { + class SoftMuonSelectionBase { + public: + SoftMuonSelectionBase(); + virtual ~SoftMuonSelectionBase(); + + ///No copy construction + SoftMuonSelectionBase(const SoftMuonSelectionBase& rhs) = delete; + + ///No moving - really? Seems a bit strict. We'll see + SoftMuonSelectionBase(SoftMuonSelectionBase&& rhs) = delete; + + ///No assignment + SoftMuonSelectionBase& operator = (const SoftMuonSelectionBase& rhs) = delete; + + ///For the main analysis object selection + virtual bool passSelection(const xAOD::Muon&) const = 0; + + ///Because everybody likes to know what object definitions they ran with + virtual void print(std::ostream&) const = 0; + }; + + std::ostream& operator << (std::ostream& os, const top::SoftMuonSelectionBase& selection); +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauMC15.h index aa343e8e5d1d7c450748511cd78bd422b1c395f4..455614d428896329439a8d43f3e29ec183110212 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauMC15.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TOPOBJECTSELECTIONTOOLS_TAUMC15_H_ #define TOPOBJECTSELECTIONTOOLS_TAUMC15_H_ @@ -13,48 +13,44 @@ #include "TopEvent/EventTools.h" namespace top { - /** * @brief To select taus based on BoostedDecisionTree definition. */ -class TauMC15 : public top::TauSelectionBase { - public: - TauMC15(); - - virtual ~TauMC15() {} - /** - * @brief Selection for the main analysis (i.e. tight object definitions). - * - * @param tauJet The tau in question - * @return True if it passes the selection, false otherwise. - */ - bool passSelection(const xAOD::TauJet& tau) const override; - - /** - * @brief Selection for the "loose" object definitions (e.g. in fakes - * estimates). - * - * @param tauJet The tau in question - * @return True if it passes the selection, false otherwise. - */ - bool passSelectionLoose(const xAOD::TauJet& tau) const override; - - /** - * @brief Why would you not want to know what you're running? - * - * @param os Print details of the cuts to the output stream. - */ - void print(std::ostream& os) const override; - - - protected: - // The selection tool to use for the tight (main) analysis. - ToolHandle<TauAnalysisTools::TauSelectionTool> m_tauSelection; - - // The selection tool to use for the loose (e.g. fakes) object selection. - ToolHandle<TauAnalysisTools::TauSelectionTool> m_tauSelectionLoose; -}; - + class TauMC15: public top::TauSelectionBase { + public: + TauMC15(); + + virtual ~TauMC15() {} + /** + * @brief Selection for the main analysis (i.e. tight object definitions). + * + * @param tauJet The tau in question + * @return True if it passes the selection, false otherwise. + */ + bool passSelection(const xAOD::TauJet& tau) const override; + + /** + * @brief Selection for the "loose" object definitions (e.g. in fakes + * estimates). + * + * @param tauJet The tau in question + * @return True if it passes the selection, false otherwise. + */ + bool passSelectionLoose(const xAOD::TauJet& tau) const override; + + /** + * @brief Why would you not want to know what you're running? + * + * @param os Print details of the cuts to the output stream. + */ + void print(std::ostream& os) const override; + protected: + // The selection tool to use for the tight (main) analysis. + ToolHandle<TauAnalysisTools::TauSelectionTool> m_tauSelection; + + // The selection tool to use for the loose (e.g. fakes) object selection. + ToolHandle<TauAnalysisTools::TauSelectionTool> m_tauSelectionLoose; + }; } // namespace top #endif // TOPOBJECTSELECTIONTOOLS_TAUMC15_H_ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauSelectionBase.h index 4a106f8b8280024798f71fad9d5f646235becf67..702fb5749c7e20500af66cc06e7130c348816a6d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauSelectionBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TauSelectionBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TAUSELECTIONBASE_H_ #define TAUSELECTIONBASE_H_ @@ -8,12 +8,11 @@ #include "xAODTau/TauJet.h" namespace top { - -class TauSelectionBase { -public: + class TauSelectionBase { + public: TauSelectionBase(); virtual ~TauSelectionBase(); - + ///No copy construction TauSelectionBase(const TauSelectionBase& rhs) = delete; @@ -21,7 +20,7 @@ public: TauSelectionBase(TauSelectionBase&& rhs) = delete; ///No assignment - TauSelectionBase& operator=(const TauSelectionBase& rhs) = delete; + TauSelectionBase& operator = (const TauSelectionBase& rhs) = delete; ///For the main analysis object selection virtual bool passSelection(const xAOD::TauJet&) const = 0; @@ -30,11 +29,10 @@ public: virtual bool passSelectionLoose(const xAOD::TauJet&) const = 0; ///Because everybody likes to know what object definitions they ran with - virtual void print(std::ostream&) const = 0; -}; - + virtual void print(std::ostream&) const = 0; + }; } -std::ostream& operator<<(std::ostream& os, const top::TauSelectionBase& selection); +std::ostream& operator << (std::ostream& os, const top::TauSelectionBase& selection); #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TopObjectSelection.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TopObjectSelection.h index 31b0b8d8af0ef46dfcae606ee75f5732c5b833a5..02ab3e54891f8deea90129585e741eb0a371bcd0 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TopObjectSelection.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TopObjectSelection.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ -// $Id: TopObjectSelection.h 802995 2017-04-17 01:23:28Z tpelzer $ +// $Id: TopObjectSelection.h 810745 2017-09-29 14:03:01Z iconnell $ #ifndef ANALYSISTOP_TOPOBJECTSELECTONTOOLS_TOPOBJECTSELECTION_H #define ANALYSISTOP_TOPOBJECTSELECTONTOOLS_TOPOBJECTSELECTION_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief TopObjectSelection - * Selects top objects according to the ObjectLoaderBase type - * - * $Revision: 802995 $ - * $Date: 2017-04-17 03:23:28 +0200 (Mon, 17 Apr 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief TopObjectSelection + * Selects top objects according to the ObjectLoaderBase type + * + * $Revision: 810745 $ + * $Date: 2017-09-29 15:03:01 +0100 (Fri, 29 Sep 2017) $ + * + **/ // system include(s): #include <memory> @@ -23,35 +23,51 @@ // Framework include(s): #include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" +#include "AsgTools/ToolHandleArray.h" +#include "AsgTools/AnaToolHandle.h" +#include "AssociationUtils/IOverlapRemovalTool.h" // Top include(s): #include "TopObjectSelectionTools/ElectronSelectionBase.h" +#include "TopObjectSelectionTools/FwdElectronSelectionBase.h" #include "TopObjectSelectionTools/MuonSelectionBase.h" +#include "TopObjectSelectionTools/SoftMuonSelectionBase.h" #include "TopObjectSelectionTools/JetSelectionBase.h" +#include "TopObjectSelectionTools/JetGhostTrackSelectionBase.h" #include "TopObjectSelectionTools/TauSelectionBase.h" #include "TopObjectSelectionTools/PhotonSelectionBase.h" +#include "TopObjectSelectionTools/TrackSelectionBase.h" #include "TopObjectSelectionTools/OverlapRemovalBase.h" - #include "TopSystematicObjectMaker/ElectronInJetSubtractionCollectionMaker.h" -#include "xAODBTaggingEfficiency/BTaggingSelectionTool.h" +// boosted-tagging includes +//#include "BoostedJetTaggers/SmoothedTopTagger.h" +//#include "BoostedJetTaggers/SmoothedWZTagger.h" +//#include "BoostedJetTaggers/JSSWTopTaggerDNN.h" + +// b-tagging +#include "FTagAnalysisInterfaces/IBTaggingSelectionTool.h" #include "TopEvent/Event.h" +#include "xAODMuon/MuonContainer.h" +#include "xAODJet/JetContainer.h" + // forward declare -namespace xAOD{ +namespace xAOD { class SystematicEvent; } namespace top { -class TopConfig; + class TopConfig; /** * @brief Configure the object selection used in the analysis. The user should * be able to configure this, or if they really really want to, then overload it * with a class based on TopObjectSelection and load that at run time. Crazy. */ -class TopObjectSelection : public asg::AsgTool { -public: + class TopObjectSelection: public asg::AsgTool { + public: /** * @brief Setup the object selection at the start of the run. * @@ -59,16 +75,16 @@ public: * of information about what the user wants (which containers to load for * example). Note that it's not a smart pointer (yet) because of root5 * restrictions on dynamic class loading. - * + * */ - explicit TopObjectSelection( const std::string& name ); - virtual ~TopObjectSelection(){} + explicit TopObjectSelection(const std::string& name); + virtual ~TopObjectSelection() {} // Delete Standard constructors TopObjectSelection(const TopObjectSelection& rhs) = delete; TopObjectSelection(TopObjectSelection&& rhs) = delete; - TopObjectSelection& operator=(const TopObjectSelection& rhs) = delete; - + TopObjectSelection& operator = (const TopObjectSelection& rhs) = delete; + StatusCode initialize(); /** @@ -77,7 +93,7 @@ public: * * @param topEvt The top event containing all the systematic variations. */ - StatusCode execute(); + StatusCode execute(bool); /** * @brief Set the code used to select electrons. @@ -90,6 +106,18 @@ public: */ void electronSelection(ElectronSelectionBase* ptr); + + /** + * @brief Set the code used to select forward electrons. + * + * Note that nullptr means that no selection will be applied (so all + * electrons will be accepted). + * + * @param ptr The code used to perform the forward electron selection (see + * TopObjectSelectionTools). + */ + void fwdElectronSelection(FwdElectronSelectionBase* ptr); + /** * @brief Set the code used to select muons. * @@ -100,17 +128,28 @@ public: * TopObjectSelectionTools). */ void muonSelection(MuonSelectionBase* ptr); - - /** - * @brief Set the code used to select taus. + + /** + * @brief Set the code used to select soft muons. * * Note that nullptr means that no selection will be applied (so all * muons will be accepted). * - * @param ptr The code used to perform the muon selection (see + * @param ptr The code used to perform the soft muon selection (see + * TopObjectSelectionTools). + */ + void softmuonSelection(SoftMuonSelectionBase* ptr); + + /** + * @brief Set the code used to select taus. + * + * Note that nullptr means that no selection will be applied (so all + * taus will be accepted). + * + * @param ptr The code used to perform the taus selection (see * TopObjectSelectionTools). */ - void tauSelection(TauSelectionBase* ptr); + void tauSelection(TauSelectionBase* ptr); /** * @brief Set the code used to select jets. @@ -133,7 +172,7 @@ public: * TopObjectSelectionTools). */ void photonSelection(PhotonSelectionBase* ptr); - + /** * @brief Set the code used to select large jets. @@ -145,7 +184,7 @@ public: * TopObjectSelectionTools). */ void largeJetSelection(JetSelectionBase* ptr); - + /** * @brief Set the code used to select track jets. * @@ -155,7 +194,30 @@ public: * @param ptr The code used to perform the track jets selection (see * TopObjectSelectionTools). */ - void trackJetSelection(JetSelectionBase* ptr); + void trackJetSelection(JetSelectionBase* ptr); + + /** + * @brief Set the code used to select tracks ghost associated to small-R jets. + * + * Note that nullptr means that no selection will be applied (so all + * tracks associated to jets will be accepted) a part from the one during the thinning. + * + * @param ptr The code used to perform the ghost track selection (see + * TopObjectSelectionTools). + */ + void jetGhostTrackSelection(JetGhostTrackSelectionBase* ptr); + + /** + * @brief Set the code used to select tracks. + * + * Note that nullptr means that no selection will be applied (so all + * tracks will be accepted). + * + * @param ptr The code used to perform the track selection (see + * TopObjectSelectionTools). + **/ + void trackSelection(TrackSelectionBase* ptr); + /** * @brief Set the code used to perform the overlap removal. At the moment @@ -171,37 +233,44 @@ public: * @brief Print details of this object selection to wherever the user asks * for. Useful for checking cuts in the log files I hope! * - * @param os Where you would like the output printing to, presumably std::cout? + * @param os Where you would like the output printing to, e.g. msg stream. */ virtual void print(std::ostream& os) const; - + /** * @brief or prehaps you'd like the AsgTool print function */ virtual void print() const; - -private: + private: void applySelectionPreOverlapRemoval(); void applySelectionPreOverlapRemovalPhotons(); void applySelectionPreOverlapRemovalElectrons(); + void applySelectionPreOverlapRemovalFwdElectrons(); void applySelectionPreOverlapRemovalMuons(); + void applySelectionPreOverlapRemovalSoftMuons(); void applySelectionPreOverlapRemovalTaus(); void applySelectionPreOverlapRemovalJets(); void applySelectionPreOverlapRemovalLargeRJets(); void applySelectionPreOverlapRemovalTrackJets(); - - virtual StatusCode applyOverlapRemoval(); - virtual StatusCode applyOverlapRemoval(const bool isLoose,const std::string& sgKey); + void applySelectionPreOverlapRemovalJetGhostTracks(); + void applySelectionPreOverlapRemovalTracks(); + + virtual StatusCode applyOverlapRemoval(); + virtual StatusCode applyOverlapRemoval(const bool isLoose, const std::string& sgKey); virtual StatusCode applyOverlapRemoval(xAOD::SystematicEvent* currentSystematic); - - void applyTightSelectionPostOverlapRemoval( const xAOD::IParticleContainer* xaod , std::vector<unsigned int>& indices ); - void trackJetOverlapRemoval(const xAOD::IParticleContainer* xaod_el, - const xAOD::IParticleContainer* xaod_mu, - const xAOD::IParticleContainer* xaod_tjet, + + void applyTightSelectionPostOverlapRemoval(const xAOD::IParticleContainer* xaod, + std::vector<unsigned int>& indices); + void trackJetOverlapRemoval(const xAOD::IParticleContainer* xaod_el, + const xAOD::IParticleContainer* xaod_mu, + const xAOD::IParticleContainer* xaod_tjet, std::vector<unsigned int>& goodElectrons, std::vector<unsigned int>& goodMuons, - std::vector<unsigned int>& goodTrackJets); - + std::vector<unsigned int>& goodTrackJets); + + void decorateSoftMuonsPostOverlapRemoval(const xAOD::MuonContainer* xaod_softmu, + std::vector<unsigned int>& goodMuons); + /** * @brief Pointer to the configuration object so we can check which objects * were requested in the config file. @@ -211,44 +280,67 @@ private: ///Electron selection code - can load user defined classes std::unique_ptr<top::ElectronSelectionBase> m_electronSelection; + ///Fwd Electron selection code - can load user defined classes + std::unique_ptr<top::FwdElectronSelectionBase> m_fwdElectronSelection; + ///Muon selection code - can load user defined classes std::unique_ptr<top::MuonSelectionBase> m_muonSelection; + ///Soft Muon selection code - can load user defined classes + std::unique_ptr<top::SoftMuonSelectionBase> m_softmuonSelection; + ///Tau selection code - can load user defined classes std::unique_ptr<top::TauSelectionBase> m_tauSelection; ///Jet selection code - can load user defined classes std::unique_ptr<top::JetSelectionBase> m_jetSelection; - ///Photon selection code - can load user defined classes + ///Photon selection code - can load user defined classes std::unique_ptr<top::PhotonSelectionBase> m_photonSelection; ///Large-R jet selection code - can load user defined classes std::unique_ptr<top::JetSelectionBase> m_largeJetSelection; - + ///Track jet selection code - can load user defined classes - std::unique_ptr<top::JetSelectionBase> m_trackJetSelection; + std::unique_ptr<top::JetSelectionBase> m_trackJetSelection; + + ///Ghost Track associated to small-R jets selection code - can load user defined classes + std::unique_ptr<top::JetGhostTrackSelectionBase> m_jetGhostTrackSelection; + + ///Track selection code - can load user defined classes + std::unique_ptr<top::TrackSelectionBase> m_trackSelection; ///Overlap removal that runs after all object selection std::unique_ptr<top::OverlapRemovalBase> m_overlapRemovalToolPostSelection; - + //Electron In Jet Subtraction std::unique_ptr<top::ElectronInJetSubtractionCollectionMaker> m_electronInJetSubtractor; - + // Pass selection strings const std::string m_passPreORSelection; const std::string m_passPreORSelectionLoose; - // the following two are used to give failing JVT jets a lower priority in the OR + // the following two are used to give failing JVT and failing fJVT jets a lower priority in the OR const std::string m_ORToolDecoration; const std::string m_ORToolDecorationLoose; - + // Do we need to request loose lepton selection bool m_doLooseCuts; - + // do decorate the jets with the b-tagging flags - std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool>> m_btagSelTools; - std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool>> m_trkjet_btagSelTools; -}; + std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool> > m_btagSelTools; + std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool> > m_trkjet_btagSelTools; + + // Boolean to handle only running selection on nominal/systematics + bool m_executeNominal; + + //helper OR tool for soft muons + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool_softMuons_PFjets; + asg::AnaToolHandle<ORUtils::IOverlapRemovalTool> m_overlapRemovalTool_softMuons_Alljets; + + // Function to decorate event info + void decorateEventInfoPostOverlapRemoval(int, bool); + float calculateMinDRMuonJet(const xAOD::Muon& mu, const xAOD::JetContainer* xaod_jet, std::vector<unsigned int>& goodJets, bool useRapidity=false); + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackJetMC15.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackJetMC15.h index b36b72ba12c2bbd4a7b6bea23bc6dcab452f65a3..08c3e78514b90c9310a2e1f34647ce24d68e50eb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackJetMC15.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackJetMC15.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TRACKJETMC15_H_ #define TRACKJETMC15_H_ @@ -8,17 +8,15 @@ #include "TopObjectSelectionTools/JetSelectionBase.h" namespace top { - class TrackJetMC15 : public top::JetSelectionBase { - public: - TrackJetMC15(const double ptcut,const double etamax); - ~TrackJetMC15(); - virtual bool passSelection(const xAOD::Jet& jet) override; - virtual void print(std::ostream& os) const override; - private: - double m_ptcut; - double m_etamax; - - + class TrackJetMC15: public top::JetSelectionBase { + public: + TrackJetMC15(const double ptcut, const double etamax); + ~TrackJetMC15(); + virtual bool passSelection(const xAOD::Jet& jet) override; + virtual void print(std::ostream& os) const override; + private: + double m_ptcut; + double m_etamax; }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackSelection.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackSelection.h new file mode 100644 index 0000000000000000000000000000000000000000..044cc995b74194c76f6f48ba0613cf61498e3ea0 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackSelection.h @@ -0,0 +1,30 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TRACKSELECTION_H_ +#define TRACKSELECTION_H_ + +#include "TopObjectSelectionTools/TrackSelectionBase.h" +#include "InDetTrackSelectionTool/InDetTrackSelectionTool.h" + +#include "xAODTracking/VertexContainer.h" +#include "xAODTracking/Vertex.h" + + +namespace top { + class TrackSelection: public TrackSelectionBase { + public: + TrackSelection(const double ptcut, const double etamax); + virtual ~TrackSelection(); +// virtual bool passSelection(const xAOD::TrackParticle&, const xAOD::Vertex&) override; + virtual void print(std::ostream& os) const override; + private: + double m_ptcut; + double m_etamax; + + ToolHandle<InDet::IInDetTrackSelectionTool> m_trkseltool; + + }; +} +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackSelectionBase.h new file mode 100644 index 0000000000000000000000000000000000000000..ca63c80c8d3f6b915a4205f4f43b07e8312aa21d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TrackSelectionBase.h @@ -0,0 +1,25 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef TRACKSELECTIONBASE_H_ +#define TRACKSELECTIONBASE_H_ + +#include "xAODTracking/TrackParticle.h" + +namespace top { + class TrackSelectionBase { + public: + TrackSelectionBase(); + virtual ~TrackSelectionBase(); + + ///For the main analysis object selection +// virtual bool passSelection(const xAOD::TrackParticle&, const xAOD::Vertex&) = 0; + ///Because everybody likes to know what object definitions they ran with + virtual void print(std::ostream&) const = 0; + }; +} + +std::ostream& operator << (std::ostream& os, const top::TrackSelectionBase& selection); + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionBase.h index b875e44d189bd54ecd0bdafd03a6eb44c4acca53..2a6fade11224bbf756f1d4c2914f54dc930dc192 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TRUTHSELECTIONBASE_H_ #define TRUTHSELECTIONBASE_H_ @@ -9,34 +9,32 @@ #include <memory> - /** - * @brief Base class for implementing a truth selection. - * - * If you want to build a new truth selection, you should inherit from this. - */ - -namespace top { +/** + * @brief Base class for implementing a truth selection. + * + * If you want to build a new truth selection, you should inherit from this. + */ +namespace top { class TruthSelectionBase { - public: - TruthSelectionBase(); + public: + TruthSelectionBase(); - virtual ~TruthSelectionBase(){} + virtual ~TruthSelectionBase() {} - virtual bool passSelection(const xAOD::TruthParticle&) const = 0; + virtual bool passSelection(const xAOD::TruthParticle&) const = 0; - virtual void print(std::ostream&) const = 0; - - protected: - bool isBhadron(int pid) const; - bool isChadron(int pid) const; + virtual void print(std::ostream&) const = 0; + protected: + bool isBhadron(int pid) const; + bool isChadron(int pid) const; - TruthSelectionBase(const TruthSelectionBase& rhs); - TruthSelectionBase(const TruthSelectionBase&& rhs); - void operator=(const TruthSelectionBase& rhs); + TruthSelectionBase(const TruthSelectionBase& rhs); + TruthSelectionBase(const TruthSelectionBase&& rhs); + void operator = (const TruthSelectionBase& rhs); }; } -std::ostream& operator<<(std::ostream& os, const top::TruthSelectionBase& selection); +std::ostream& operator << (std::ostream& os, const top::TruthSelectionBase& selection); #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionTtres.h b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionTtres.h index 462c0462bf6fb193a6ad824ea4256638abf9d41f..63c22cb745b5e75503eb98c1a2562742096b08e9 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionTtres.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools/TopObjectSelectionTools/TruthSelectionTtres.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef TRUTHSELECTIONTTRES_H_ #define TRUTHSELECTIONTTRES_H_ @@ -8,42 +8,38 @@ #include "TopObjectSelectionTools/TruthSelectionBase.h" - /** - * @brief An example class implementing a truth selection for tt resonances. - * - */ +/** + * @brief An example class implementing a truth selection for tt resonances. + * + */ namespace top { - - class TruthSelectionTtres : public top::TruthSelectionBase { - public: - - TruthSelectionTtres(); - /** - * @brief Doesn't do anything itself. - */ - virtual ~TruthSelectionTtres(){} - - /** - * @brief The cuts (per object) are implemented in here. - * - * Not that I've marked this as final, to stop people going crazy with - * inheritance. Why not just inherit from TruthSelectionBase instead? - * - * @param mc The particle to cut on. - * @return True if you want to keep this particle, false otherwise. - */ - bool passSelection(const xAOD::TruthParticle& mc) const override final; - - ///Print the cuts to the ostream. - void print(std::ostream& os) const override final; - - private: - TruthSelectionTtres(const TruthSelectionTtres& rhs); - TruthSelectionTtres(const TruthSelectionTtres&& rhs); - void operator=(const TruthSelectionTtres& rhs); + class TruthSelectionTtres: public top::TruthSelectionBase { + public: + TruthSelectionTtres(); + /** + * @brief Doesn't do anything itself. + */ + virtual ~TruthSelectionTtres() {} + + /** + * @brief The cuts (per object) are implemented in here. + * + * Not that I've marked this as final, to stop people going crazy with + * inheritance. Why not just inherit from TruthSelectionBase instead? + * + * @param mc The particle to cut on. + * @return True if you want to keep this particle, false otherwise. + */ + bool passSelection(const xAOD::TruthParticle& mc) const override final; + + ///Print the cuts to the ostream. + void print(std::ostream& os) const override final; + private: + TruthSelectionTtres(const TruthSelectionTtres& rhs); + TruthSelectionTtres(const TruthSelectionTtres&& rhs); + void operator = (const TruthSelectionTtres& rhs); }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/CMakeLists.txt index 9cc50fae456db65c0064e534c32feba1b9e99f4f..4ca1c02bfcaacb1f8c85a17ed25befb1834bf5eb 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/CMakeLists.txt @@ -1,40 +1,56 @@ -# Auto-generated on: 2017-03-08 14:47:38.688787 - # Declare the name of this package: -atlas_subdir( TopParticleLevel None ) +atlas_subdir( TopParticleLevel ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC + xAODBase xAODTruth xAODJet xAODMissingET xAODCore xAODRootAccess + FourMomUtils TopEvent TopConfiguration - TruthUtils - MCTruthClassifier ) + TopDataPreparation + TruthUtils + MCTruthClassifier + JetReclustering + JetSubStructureUtils + AsgTools + + ) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) -# Custom definitions needed for this package: -add_definitions( -g ) +# Need fast jet for the RC jet substructure code +find_package( FastJet COMPONENTS fastjetplugins fastjettools ) +find_package( FastJetContrib COMPONENTS EnergyCorrelator Nsubjettiness ) # Build a library that other components can link against: atlas_add_library( TopParticleLevel Root/*.cxx Root/*.h Root/*.icc TopParticleLevel/*.h TopParticleLevel/*.icc TopParticleLevel/*/*.h TopParticleLevel/*/*.icc PUBLIC_HEADERS TopParticleLevel - LINK_LIBRARIES xAODTruth + LINK_LIBRARIES + xAODBase + xAODTruth xAODJet xAODMissingET xAODCore xAODRootAccess + FourMomUtils TopEvent TopConfiguration + TopDataPreparation MCTruthClassifierLib - TruthUtils - ${ROOT_LIBRARIES} + TruthUtils + JetReclusteringLib + JetSubStructureUtils + AsgTools + ${ROOT_LIBRARIES} + ${FASTJET_LIBRARIES} + ${FASTJETCONTRIB_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/MsgCategory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/MsgCategory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..902b85113fc0ea2312a7252c9e41e575b53fdc64 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/MsgCategory.cxx @@ -0,0 +1,6 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#include "TopParticleLevel/MsgCategory.h" + +ANA_MSG_SOURCE(TopParticleLevel, "TopParticleLevel") diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelElectronObjectSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelElectronObjectSelector.cxx index 4c4f713403de88e7ed1c155dd25156827b0021cf..f8efd7900b2a0274c5208645daff29c38a548581 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelElectronObjectSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelElectronObjectSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelElectronObjectSelector.cxx // Description: @@ -13,61 +13,63 @@ #include "TopParticleLevel/TruthTools.h" namespace top { + ParticleLevelElectronObjectSelector::ParticleLevelElectronObjectSelector(Options opt /* = Options() */) + : m_opt(opt) { /* Deliberately Empty */} - ParticleLevelElectronObjectSelector::ParticleLevelElectronObjectSelector( Options opt /* = Options() */ ) - : m_opt( opt ){ /* Deliberately Empty */ } + /* virtual */ bool + ParticleLevelElectronObjectSelector::apply(const xAOD::TruthParticle& truthParticle) { + // Obtain the particle type and particle origin from the decoration + // created by the MCTruthClassifier. For legacy reasons, try both + // decoration names. + unsigned int type; - /* virtual */ bool - ParticleLevelElectronObjectSelector::apply( const xAOD::TruthParticle & truthParticle ) { - - // Obtain the particle type and particle origin from the decoration - // created by the MCTruthClassifier. For legacy reasons, try both - // decoration names. - unsigned int type; - if ( truthParticle.isAvailable<unsigned int>( "particleType" ) ){ - type = truthParticle.auxdata<unsigned int>( "particleType" ); - } else if ( truthParticle.isAvailable<unsigned int>( "classifierParticleType" ) ){ - type = truthParticle.auxdata<unsigned int>( "classifierParticleType" ); - } else { - std::cerr << "Could not obtain MCTruthClassifier result decoration." << std::endl; - std::exit( 1 ); - } - - // -------------------------------------------------- - // Accept electrons iff they do not come from a hadron - using namespace MCTruthPartClassifier; - if ( m_opt.not_from_hadron && - type != ParticleType::IsoElectron ){ - return false; - } - - // If it is requested that tauons are hadrons, perform a check of the - // ancestry: It shall not contain a single tauon. - if ( m_opt.tau_is_hadron ){ - auto truthProxy = truthParticle.auxdata<ElementLink<xAOD::TruthParticleContainer> >( "originalTruthParticle" ); - if ( not truthProxy.isValid() ){ - std::cerr << "Could not obtain 'originalTruthParticle' reference." << std::endl; - std::exit( 1 ); - } - if ( truth::isLeptonFromTau( * truthProxy ) ){ - return false; - } - } + if (truthParticle.isAvailable<unsigned int>("particleType")) { + type = truthParticle.auxdata<unsigned int>("particleType"); + } else if (truthParticle.isAvailable<unsigned int>("classifierParticleType")) { + type = truthParticle.auxdata<unsigned int>("classifierParticleType"); + } else { + throw std::runtime_error("ParticleLevelElectronObjectSelector::apply: " + "Could not obtain MCTruthClassifier result decoration."); + } - // -------------------------------------------------- - // Apply kinematic cut on the dressed pT: - // must exceed 25 GeV - if ( truthParticle.auxdata<float>( "pt_dressed" ) < m_opt.pt_min ){ return false; } + // -------------------------------------------------- + // Accept electrons iff they do not come from a hadron + using namespace MCTruthPartClassifier; + if (m_opt.not_from_hadron && + type != ParticleType::IsoElectron) { + return false; + } - // -------------------------------------------------- - // Apply kinematic cut on the dressed eta: - // must be less than or equal to 2.5 - if ( std::abs( truthParticle.auxdata<float>( "eta_dressed" ) ) > m_opt.eta_max ){ return false; } + // If it is requested that tauons are hadrons, perform a check of the + // ancestry: It shall not contain a single tauon. + if (m_opt.tau_is_hadron) { + auto truthProxy = truthParticle.auxdata<ElementLink<xAOD::TruthParticleContainer> >("originalTruthParticle"); + if (not truthProxy.isValid()) { + throw std::runtime_error("ParticleLevelElectronObjectSelector::apply: " + "Could not obtain 'originalTruthParticle' reference."); + } + if (truth::isLeptonFromTau(*truthProxy)) { + return false; + } + } + // -------------------------------------------------- + // Apply kinematic cut on the dressed pT: + // must exceed 25 GeV + if (truthParticle.auxdata<float>("pt_dressed") < m_opt.pt_min) { + return false; + } - // -------------------------------------------------- - // Everything that reaches this point has passed the selection - return true; + // -------------------------------------------------- + // Apply kinematic cut on the dressed eta: + // must be less than or equal to 2.5 + if (std::abs(truthParticle.auxdata<float>("eta_dressed")) > m_opt.eta_max) { + return false; } + + // -------------------------------------------------- + // Everything that reaches this point has passed the selection + return true; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelEvent.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelEvent.cxx new file mode 100644 index 0000000000000000000000000000000000000000..62f9d7a2bb0eea1cdf1f75b54267ec0b5df4dd9d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelEvent.cxx @@ -0,0 +1,94 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopParticleLevel/ParticleLevelEvent.h" + +std::ostream & operator << (std::ostream& os, const top::ParticleLevelEvent& plEvent) { + if (plEvent.m_electrons) { + os << "Number of electrons: " << plEvent.m_electrons->size() << "\n"; + for (const auto& elPtr : *plEvent.m_electrons) { + if (elPtr) { + os << " " << *elPtr << "\n"; + } + } + } else { + os << "ParticleLevelEvent: Cannot find electron truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_muons) { + os << "Number of muons: " << plEvent.m_muons->size() << "\n"; + for (const auto& muPtr : *plEvent.m_muons) { + if (muPtr) { + os << " " << *muPtr << "\n"; + } + } + } else { + os << "ParticleLevelEvent: Cannot find muon truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_softmuons) { + os << "Number of soft muons: " << plEvent.m_softmuons->size() << "\n"; + for (const auto& muPtr : *plEvent.m_softmuons) { + if (muPtr) { + os << " " << *muPtr << "\n"; + } + } + } else { + os << "ParticleLevelEvent: Cannot find muon truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_jets) { + os << "Number of jets: " << plEvent.m_jets->size() << "\n"; + for (const auto& jetPtr : *plEvent.m_jets) { + if (jetPtr) { + os << " " << *jetPtr << "\n"; + } + } + } else { + os << "ParticleLevelEvent: Cannot find jet truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_largeRJets) { + os << "Number of large R jets: " << plEvent.m_largeRJets->size() << "\n"; + for (const auto& largeRjetPtr : *plEvent.m_largeRJets) { + if (largeRjetPtr) { + os << " " << *largeRjetPtr << "\n"; + } + } + } else { + os << + "ParticleLevelEvent: Cannot find large R jets truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_taus) { + os << "Number of taus: " << plEvent.m_taus->size() << "\n"; + for (const auto& tauPtr : *plEvent.m_taus) { + if (tauPtr) { + os << " " << *tauPtr << "\n"; + } + } + } else { + os << "ParticleLevelEvent: Cannot find tau truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_photons) { + os << "Number of photons: " << plEvent.m_photons->size() << "\n"; + for (const auto& phPtr : *plEvent.m_photons) { + if (phPtr) { + os << " " << *phPtr << "\n"; + } + } + } else { + os << "ParticleLevelEvent: Cannot find photon truth collection. Did you set the truth collection correctly?\n"; + } + + if (plEvent.m_met) { + os << *plEvent.m_met; + } else { + os << + "ParticleLevelEvent: Cannot find MET (neutrino) truth collection. Did you set the truth collection correctly?\n"; + } + + return os; +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelJetObjectSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelJetObjectSelector.cxx index a01bbfd9dfb8f03020e57742d683ca38d269e172..5c55332030b0ac1e6dc574b0632404b18da9df80 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelJetObjectSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelJetObjectSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelJetObjectSelector.cxx // Description: @@ -10,25 +10,27 @@ #include "TopParticleLevel/ParticleLevelJetObjectSelector.h" namespace top { + ParticleLevelJetObjectSelector::ParticleLevelJetObjectSelector(Options opt /* = Options() */) + : m_opt(opt) { /* Deliberately Empty */} + + /* virtual */ bool + ParticleLevelJetObjectSelector::apply(const xAOD::Jet& jet) { + // -------------------------------------------------- + // Apply kinematic cut on the pT: + // must exceed 25 GeV + if (jet.pt() < m_opt.pt_min) { + return false; + } - ParticleLevelJetObjectSelector::ParticleLevelJetObjectSelector( Options opt /* = Options() */) - : m_opt( opt ){ /* Deliberately Empty */ } - - /* virtual */ bool - ParticleLevelJetObjectSelector::apply( const xAOD::Jet & jet ) { - // -------------------------------------------------- - // Apply kinematic cut on the pT: - // must exceed 25 GeV - if ( jet.pt() < m_opt.pt_min ){ return false; } - - // -------------------------------------------------- - // Apply kinematic cut on the eta: - // must be less than or equal to 2.5 - if ( std::abs( jet.eta() ) > m_opt.eta_max ){ return false; } - - // -------------------------------------------------- - // Everything that reaches this point has passed the selection - return true; + // -------------------------------------------------- + // Apply kinematic cut on the eta: + // must be less than or equal to 2.5 + if (std::abs(jet.eta()) > m_opt.eta_max) { + return false; } + // -------------------------------------------------- + // Everything that reaches this point has passed the selection + return true; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelLoader.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelLoader.cxx index 7b39d65f5dbf8d37a6c7c7ca11525fcea098d7a3..066c08ec73544b591387346e1486b41777bf5665 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelLoader.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelLoader.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelLoader.cxx // Description: @@ -8,6 +8,7 @@ // Created: Sun Feb 22 13:24:02 2015 #include "TopParticleLevel/ParticleLevelLoader.h" +#include "TopParticleLevel/TruthTools.h" #include <list> #include <cassert> @@ -21,543 +22,834 @@ #include "TopParticleLevel/ParticleLevelMuonObjectSelector.h" #include "TopParticleLevel/ParticleLevelPhotonObjectSelector.h" #include "TopParticleLevel/ParticleLevelJetObjectSelector.h" +#include "TopParticleLevel/ParticleLevelTauObjectSelector.h" #include "TopConfiguration/TopConfig.h" +#include "FourMomUtils/xAODP4Helpers.h" + +#include <boost/algorithm/string.hpp> // #define TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL 1 namespace top { + ParticleLevelLoader::ParticleLevelLoader(const std::shared_ptr<top::TopConfig>& cfg) + : asg::AsgTool("ParticleLevelLoader"), + m_config(cfg), + // Don't create them here because construction is a bit long-ish + m_objectSelector_Electron(nullptr), + m_objectSelector_Muon(nullptr), + m_objectSelector_Photon(nullptr), + m_objectSelector_Jet(nullptr), + m_objectSelector_LargeRJet(nullptr), + m_objectSelector_Tau(nullptr), + // Tool is inactive on non-MC data and whenever particle level is not requested + m_active(m_config->doTopParticleLevel() && + m_config->isMC() && + (m_config->useTruthElectrons() || + m_config->useTruthMuons() || + m_config->useTruthPhotons() || + m_config->useTruthJets() || + m_config->useTruthLargeRJets() || + m_config->useTruthTaus() || + m_config->useTruthMET())) { + // Configure and create electron object selector + auto optEl = ParticleLevelElectronObjectSelector::Options { + m_config->truth_electron_PtCut(), + m_config->truth_electron_EtaCut(), + m_config->truth_electron_NotFromHadron(), + m_config->truth_electron_TauIsHadron() + }; + + m_objectSelector_Electron.reset(new ParticleLevelElectronObjectSelector(optEl)); + + // Configure and create muon object selector + auto optMu = ParticleLevelMuonObjectSelector::Options { + m_config->truth_muon_PtCut(), + m_config->truth_muon_EtaCut(), + m_config->truth_muon_NotFromHadron(), + m_config->truth_muon_TauIsHadron() + }; + + m_objectSelector_Muon.reset(new ParticleLevelMuonObjectSelector(optMu)); + + // Configure and create photon object selector + auto optPhoton = ParticleLevelPhotonObjectSelector::Options { + m_config->truth_photon_PtCut(), + m_config->truth_photon_EtaCut(), + m_config->truth_photon_Origin(), + m_config->truth_photon_Isolation() + }; + + m_objectSelector_Photon.reset(new ParticleLevelPhotonObjectSelector(optPhoton)); + + + // Configure and create jet object selector + auto optJet = ParticleLevelJetObjectSelector::Options { + m_config->truth_jet_PtCut(), + m_config->truth_jet_EtaCut() + }; + + m_objectSelector_Jet.reset(new ParticleLevelJetObjectSelector(optJet)); + + // Configure and create jet object selector + auto optLargeRJet = ParticleLevelJetObjectSelector::Options { + m_config->truth_jet_largeR_PtCut(), + m_config->truth_jet_largeR_EtaCut() + }; + + m_objectSelector_LargeRJet.reset(new ParticleLevelJetObjectSelector(optLargeRJet)); + + // Configure and create muon object selector + auto optTau = ParticleLevelTauObjectSelector::Options { + m_config->truth_tau_PtCut(), + m_config->truth_tau_EtaCut() + }; + + m_objectSelector_Tau.reset(new ParticleLevelTauObjectSelector(optTau)); + + + std::ostream &msgInfo = msg(MSG::Level::INFO); + if (m_active) { + msgInfo << "Particle level reconstruction is enabled; telling you how I am configured:" << '\n'; + msgInfo << " " << std::setw(20) << "UseElectrons? " << std::setw(5) << std::boolalpha << + m_config->useTruthElectrons(); + if (m_config->useTruthElectrons()) { + msgInfo << " [" << m_config->sgKeyTruthElectrons() << "]" << '\n' + << " --- Pt > " << m_config->truth_electron_PtCut() << '\n' + << " --- |eta| < " << m_config->truth_electron_EtaCut() << '\n' + << " --- notFromHadron? " << std::boolalpha << m_config->truth_electron_NotFromHadron() << '\n' + << " --- tauIsHadron? " << std::boolalpha << m_config->truth_electron_TauIsHadron() << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "UseMuons? " << std::setw(5) << std::boolalpha << + m_config->useTruthMuons(); + if (m_config->useTruthMuons()) { + msgInfo << " [" << m_config->sgKeyTruthMuons() << "]" << '\n' + << " --- Pt > " << m_config->truth_muon_PtCut() << '\n' + << " --- |eta| < " << m_config->truth_muon_EtaCut() << '\n' + << " --- notFromHadron? " << std::boolalpha << m_config->truth_muon_NotFromHadron() << '\n' + << " --- tauIsHadron? " << std::boolalpha << m_config->truth_muon_TauIsHadron() << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "UsePhotons? " << std::setw(5) << std::boolalpha << + m_config->useTruthPhotons(); + if (m_config->useTruthPhotons()) { + msgInfo << " [" << m_config->sgKeyTruthPhotons() << "]" << '\n' + << " --- Pt > " << m_config->truth_photon_PtCut() << '\n' + << " --- |eta| < " << m_config->truth_photon_EtaCut() << '\n' + << " --- Origin = " << m_config->truth_photon_Origin() << '\n' + << " --- Isolation = " << m_config->truth_photon_Isolation() << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "UseJets? " << std::setw(5) << std::boolalpha << m_config->useTruthJets(); + if (m_config->useTruthJets()) { + msgInfo << " [" << m_config->sgKeyTruthJets() << "]" << '\n' + << " --- Pt > " << m_config->truth_jet_PtCut() << '\n' + << " --- |eta| < " << m_config->truth_jet_EtaCut() << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "UseLargeRJets? " << std::setw(5) << std::boolalpha << + m_config->useTruthLargeRJets(); + if (m_config->useTruthJets()) { + msgInfo << " [" << m_config->sgKeyTruthLargeRJets() << "]" << '\n' + << " --- Pt > " << m_config->truth_jet_largeR_PtCut() << '\n' + << " --- |eta| < " << m_config->truth_jet_largeR_EtaCut() << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "UseTaus? " << std::setw(5) << std::boolalpha << m_config->useTruthTaus(); + if (m_config->useTruthTaus()) { + msgInfo << " [" << m_config->sgKeyTruthTaus() << "]" << '\n' + << " --- Pt > " << m_config->truth_tau_PtCut() << '\n' + << " --- |eta| < " << m_config->truth_tau_EtaCut() << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "UseMET? " << std::setw(5) << std::boolalpha << m_config->useTruthMET(); + if (m_config->useTruthMET()) { + msgInfo << " [" << m_config->sgKeyTruthMET() << "]" << '\n'; + } else { + msgInfo << '\n'; + } + msgInfo << " " << std::setw(20) << "DoOverlapRemoval Mu-Jet? " << std::setw(5) << std::boolalpha << + m_config->doParticleLevelOverlapRemovalMuJet() << '\n'; + msgInfo << " " << std::setw(20) << "DoOverlapRemoval El-Jet? " << std::setw(5) << std::boolalpha << + m_config->doParticleLevelOverlapRemovalElJet() << '\n'; + msgInfo << " " << std::setw(20) << "DoOverlapRemoval Jet-Photon? " << std::setw(5) << std::boolalpha << + m_config->doParticleLevelOverlapRemovalJetPhoton() << '\n'; + + + if (m_config->useRCJets()) { + m_particleLevelRCJetObjectLoader = std::unique_ptr<ParticleLevelRCJetObjectLoader> (new ParticleLevelRCJetObjectLoader( + m_config)); + top::check(m_particleLevelRCJetObjectLoader->initialize(), + "Failed to initialize ParticleLevelRCJetObjectLoader"); + } + + if (m_config->useVarRCJets() == true) { + boost::split(m_VarRCJetRho, m_config->VarRCJetRho(), boost::is_any_of(",")); + boost::split(m_VarRCJetMassScale, m_config->VarRCJetMassScale(), boost::is_any_of(",")); + + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + m_particleLevelVarRCJetObjectLoader[name] = std::unique_ptr<ParticleLevelRCJetObjectLoader> (new ParticleLevelRCJetObjectLoader( + m_config)); + top::check(m_particleLevelVarRCJetObjectLoader[name]->setProperty("VarRCjets", + true), + "Failed to set VarRCjets property of VarRCJetMC15"); + top::check(m_particleLevelVarRCJetObjectLoader[name]->setProperty("VarRCjets_rho", + rho), + "Failed to set VarRCjets rho property of VarRCJetMC15"); + top::check(m_particleLevelVarRCJetObjectLoader[name]->setProperty("VarRCjets_mass_scale", + mass_scale), + "Failed to set VarRCjets mass scale property of VarRCJetMC15"); + top::check(m_particleLevelVarRCJetObjectLoader[name]->initialize(), "Failed to initialize VarRCJetMC15"); + } // end loop over mass scale parameters (e.g., top mass, w mass, etc.) + } // end loop over mass scale multiplies (e.g., 1.,2.,etc.) + } + } else { + msgInfo << "Particle level reconstruction is disabled." << '\n'; + } + } - ParticleLevelLoader::ParticleLevelLoader( const std::shared_ptr<top::TopConfig> & cfg ) - : asg::AsgTool( "ParticleLevelLoader" ), - m_config( cfg ), - // Don't create them here because construction is a bit long-ish - m_objectSelector_Electron( nullptr ), - m_objectSelector_Muon( nullptr ), - m_objectSelector_Photon( nullptr ), - m_objectSelector_Jet( nullptr ), - m_objectSelector_LargeRJet( nullptr ), - // Tool is inactive on non-MC data and whenever particle level is not requested - m_active( m_config->doTopParticleLevel() && - m_config->isMC() && - ( m_config->useTruthElectrons() || - m_config->useTruthMuons() || - m_config->useTruthPhotons() || - m_config->useTruthJets() || - m_config->useTruthLargeRJets() || - m_config->useTruthMET() ) ) { - - // Configure and create electron object selector - auto optEl = ParticleLevelElectronObjectSelector::Options{ - m_config->truth_electron_PtCut(), - m_config->truth_electron_EtaCut(), - m_config->truth_electron_NotFromHadron(), - m_config->truth_electron_TauIsHadron() - }; - - m_objectSelector_Electron.reset( new ParticleLevelElectronObjectSelector( optEl ) ); - - // Configure and create muon object selector - auto optMu = ParticleLevelMuonObjectSelector::Options{ - m_config->truth_muon_PtCut(), - m_config->truth_muon_EtaCut(), - m_config->truth_muon_NotFromHadron(), - m_config->truth_muon_TauIsHadron() - }; - - m_objectSelector_Muon.reset( new ParticleLevelMuonObjectSelector( optMu ) ); - - // Configure and create photon object selector - auto optPhoton = ParticleLevelPhotonObjectSelector::Options{ - m_config->truth_photon_PtCut(), - m_config->truth_photon_EtaCut(), - m_config->truth_photon_Origin(), - m_config->truth_photon_Isolation() - }; - - m_objectSelector_Photon.reset( new ParticleLevelPhotonObjectSelector( optPhoton ) ); - - - // Configure and create jet object selector - auto optJet = ParticleLevelJetObjectSelector::Options{ - m_config->truth_jet_PtCut(), - m_config->truth_jet_EtaCut() - }; - - m_objectSelector_Jet.reset( new ParticleLevelJetObjectSelector( optJet ) ); - - // Configure and create jet object selector - auto optLargeRJet = ParticleLevelJetObjectSelector::Options{ - m_config->truth_jet_largeR_PtCut(), - m_config->truth_jet_largeR_EtaCut() - }; - - m_objectSelector_LargeRJet.reset( new ParticleLevelJetObjectSelector( optLargeRJet ) ); - - - if ( m_active ){ - std::cout << "Particle level reconstruction is enabled; telling you how I am configured:" << '\n'; - std::cout << " " << std::setw( 20 ) << "UseElectrons? " << std::setw( 5 ) << std::boolalpha << m_config->useTruthElectrons(); - if ( m_config->useTruthElectrons() ){ - std::cout << " [" << m_config->sgKeyTruthElectrons() << "]" << '\n' - << " --- Pt > " << m_config->truth_electron_PtCut() << '\n' - << " --- |eta| < " << m_config->truth_electron_EtaCut() << '\n' - << " --- notFromHadron? " << std::boolalpha << m_config->truth_electron_NotFromHadron() << '\n' - << " --- tauIsHadron? " << std::boolalpha << m_config->truth_electron_TauIsHadron() << '\n'; - } else { - std::cout << '\n'; - } - std::cout << " " << std::setw( 20 ) << "UseMuons? " << std::setw( 5 ) << std::boolalpha << m_config->useTruthMuons(); - if ( m_config->useTruthMuons() ){ - std::cout << " [" << m_config->sgKeyTruthMuons() << "]" << '\n' - << " --- Pt > " << m_config->truth_muon_PtCut() << '\n' - << " --- |eta| < " << m_config->truth_muon_EtaCut() << '\n' - << " --- notFromHadron? " << std::boolalpha << m_config->truth_muon_NotFromHadron() << '\n' - << " --- tauIsHadron? " << std::boolalpha << m_config->truth_muon_TauIsHadron() << '\n'; - } else { - std::cout << '\n'; - } - std::cout << " " << std::setw( 20 ) << "UsePhotons? " << std::setw( 5 ) << std::boolalpha << m_config->useTruthPhotons(); - if ( m_config->useTruthPhotons() ){ - std::cout << " [" << m_config->sgKeyTruthPhotons() << "]" << '\n' - << " --- Pt > " << m_config->truth_photon_PtCut() << '\n' - << " --- |eta| < " << m_config->truth_photon_EtaCut() << '\n' - << " --- Origin = " << m_config->truth_photon_Origin() << '\n' - << " --- Isolation = " << m_config->truth_photon_Isolation() << '\n'; - } else { - std::cout << '\n'; - } - std::cout << " " << std::setw( 20 ) << "UseJets? " << std::setw( 5 ) << std::boolalpha << m_config->useTruthJets(); - if ( m_config->useTruthJets() ){ - std::cout << " [" << m_config->sgKeyTruthJets() << "]" << '\n' - << " --- Pt > " << m_config->truth_jet_PtCut() << '\n' - << " --- |eta| < " << m_config->truth_jet_EtaCut() << '\n'; - } else { - std::cout << '\n'; - } - std::cout << " " << std::setw( 20 ) << "UseLargeRJets? " << std::setw( 5 ) << std::boolalpha << m_config->useTruthLargeRJets(); - if ( m_config->useTruthJets() ){ - std::cout << " [" << m_config->sgKeyTruthLargeRJets() << "]" << '\n' - << " --- Pt > " << m_config->truth_jet_largeR_PtCut() << '\n' - << " --- |eta| < " << m_config->truth_jet_largeR_EtaCut() << '\n'; - } else { - std::cout << '\n'; - } - std::cout << " " << std::setw( 20 ) << "UseMET? " << std::setw( 5 ) << std::boolalpha << m_config->useTruthMET(); - if ( m_config->useTruthMET() ){ - std::cout << " [" << m_config->sgKeyTruthMET() << "]" << '\n'; - } else { - std::cout << '\n'; - } - std::cout << " " << std::setw( 20 ) << "DoOverlapRemoval Mu-Jet? " << std::setw( 5 ) << std::boolalpha << m_config->doParticleLevelOverlapRemovalMuJet() << '\n'; - std::cout << " " << std::setw( 20 ) << "DoOverlapRemoval El-Jet? " << std::setw( 5 ) << std::boolalpha << m_config->doParticleLevelOverlapRemovalElJet() << '\n'; - std::cout << " " << std::setw( 20 ) << "DoOverlapRemoval Jet-Photon? " << std::setw( 5 ) << std::boolalpha << m_config->doParticleLevelOverlapRemovalJetPhoton() << '\n'; + ParticleLevelLoader::~ParticleLevelLoader() { /* Deliberately Empty */} - } else { - std::cout << "Particle level reconstruction is disabled." << '\n'; - } + ParticleLevelEvent ParticleLevelLoader::load() { + // If the ParticleLevelLoader is not active, return an empty object + if (!m_active) { + return {}; } - ParticleLevelLoader::~ParticleLevelLoader(){ /* Deliberately Empty */ } + // Create the result object. + ParticleLevelEvent plEvent; + + // Load event info object directly into the plEvent + top::check(evtStore()->retrieve(plEvent.m_info, m_config->sgKeyEventInfo()), + "xAOD::TEvent::retrieve failed for EventInfo"); + + // Load the info for electrons, muons, jets, and MET into local objects: + // They need to be selected / modified / etc + const xAOD::TruthParticleContainer* electrons { + nullptr + }; + const xAOD::TruthParticleContainer* muons { + nullptr + }; + const xAOD::TruthParticleContainer* photons { + nullptr + }; + const xAOD::JetContainer* jets { + nullptr + }; + const xAOD::JetContainer* largeRJets { + nullptr + }; + const xAOD::TruthParticleContainer* taus { + nullptr + }; + const xAOD::MissingETContainer* mets { + nullptr + }; + + if (m_config->useTruthElectrons()) { + top::check(evtStore()->retrieve(electrons, m_config->sgKeyTruthElectrons()), + "xAOD::TEvent::retrieve failed for Truth Electrons"); + } - ParticleLevelEvent ParticleLevelLoader::load() { + if (m_config->useTruthMuons()) { + top::check(evtStore()->retrieve(muons, m_config->sgKeyTruthMuons()), + "xAOD::TEvent::retrieve failed for Truth Muons"); + } - // If the ParticleLevelLoader is not active, return an empty object - if ( ! m_active ){ return {}; } + if (m_config->useTruthPhotons()) { + top::check(evtStore()->retrieve(photons, m_config->sgKeyTruthPhotons()), + "xAOD::TEvent::retrieve failed for Truth Photons"); + } - // Create the result object. - ParticleLevelEvent plEvent; + if (m_config->useTruthJets()) { + top::check(evtStore()->retrieve(jets, m_config->sgKeyTruthJets()), + "xAOD::TEvent::retrieve failed for Truth Jets"); + } - // Load event info object directly into the plEvent - top::check( evtStore()->retrieve( plEvent.m_info, m_config->sgKeyEventInfo() ), - "xAOD::TEvent::retrieve failed for EventInfo" ); + if (m_config->useTruthLargeRJets()) { + top::check(evtStore()->retrieve(largeRJets, m_config->sgKeyTruthLargeRJets()), + "xAOD::TEvent::retrieve failed for Truth Jets Large R"); + } - // Load the info for electrons, muons, jets, and MET into local objects: - // They need to be selected / modified / etc - const xAOD::TruthParticleContainer * electrons{ nullptr }; - const xAOD::TruthParticleContainer * muons{ nullptr }; - const xAOD::TruthParticleContainer * photons{ nullptr }; - const xAOD::JetContainer * jets{ nullptr }; - const xAOD::JetContainer * largeRJets{ nullptr }; - const xAOD::MissingETContainer * mets{ nullptr }; + if (m_config->useTruthTaus()) { + top::check(evtStore()->retrieve(taus, m_config->sgKeyTruthTaus()), + "xAOD::TEvent::retrieve failed for Truth Taus"); + } - if ( m_config->useTruthElectrons() ){ - top::check( evtStore()->retrieve( electrons, m_config->sgKeyTruthElectrons() ), - "xAOD::TEvent::retrieve failed for Truth Electrons" ); - } + if (m_config->useTruthMET()) { + top::check(evtStore()->retrieve(mets, m_config->sgKeyTruthMET()), + "xAOD::TEvent::retrieve failed for Truth Missing ET"); + } - if ( m_config->useTruthMuons() ){ - top::check( evtStore()->retrieve( muons, m_config->sgKeyTruthMuons() ), - "xAOD::TEvent::retrieve failed for Truth Muons" ); - } + // ====================================================================== + // DRESSING + // We want to put the dressed leptons into the Event container, however, + // after reading from the TOPQ file, their dressed kinematics are stored + // as decorations. Lets (1) create a shallow copied container now, (2) + // set the kinematics for the shallow copies to the dressed values, (3) + // create decorations for the bare (non-dressed) kinematics, and (4) + // deep-copy the selection electrons from that container later. + + // ELECTRONS + if (m_config->useTruthElectrons()) { + top::check(loadDressedLeptons(*electrons, + m_electronsDressed, + m_electronsDressedAux), + "Failure to load dressed electrons."); + } - if ( m_config->useTruthPhotons() ){ - top::check( evtStore()->retrieve( photons, m_config->sgKeyTruthPhotons() ), - "xAOD::TEvent::retrieve failed for Truth Photons" ); - } + // MUONS + if (m_config->useTruthMuons()) { + top::check(loadDressedLeptons(*muons, + m_muonsDressed, + m_muonsDressedAux), + "Failure to load dressed muons."); + } - if ( m_config->useTruthJets() ){ - top::check( evtStore()->retrieve( jets, m_config->sgKeyTruthJets() ), - "xAOD::TEvent::retrieve failed for Truth Jets" ); + // ====================================================================== + // OBJECT SELECTION + // This yields index collections, one for each + // { electrons, muons, photons, jets, largeRJets }. + std::list<std::size_t> idx_electrons; // -> relative to `electrons` + std::list<std::size_t> idx_muons; // -> relative to `muons` + std::list<std::size_t> idx_photons; // -> relative to `photons` + std::list<std::size_t> idx_jets; // -> relative to `jets` + std::list<std::size_t> idx_largeRJets; // -> relative to `largeRJets` + std::list<std::size_t> idx_taus; // -> relative to `taus` + + // Electrons + if (m_config->useTruthElectrons()) { + for (std::size_t i = 0; i < electrons->size(); ++i) { + const auto* electron = electrons->at(i); + + // Allow use of mixed-particle input container. + if (electron->absPdgId() != 11) { + continue; } - if ( m_config->useTruthLargeRJets() ){ - top::check( evtStore()->retrieve( largeRJets, m_config->sgKeyTruthLargeRJets() ), - "xAOD::TEvent::retrieve failed for Truth Jets Large R" ); + // FIXME: Is this still needed? + if (electron->barcode() >= 2e5) { + continue; } - if ( m_config->useTruthMET() ){ - top::check( evtStore()->retrieve( mets, m_config->sgKeyTruthMET() ), - "xAOD::TEvent::retrieve failed for Truth Missing ET" ); + if (m_objectSelector_Electron->apply(*electron)) { + idx_electrons.push_back(i); } + } + } - // ====================================================================== - // DRESSING - // We want to put the dressed leptons into the Event container, however, - // after reading from the TOPQ file, their dressed kinematics are stored - // as decorations. Lets (1) create a shallow copied container now, (2) - // set the kinematics for the shallow copies to the dressed values, (3) - // create decorations for the bare (non-dressed) kinematics, and (4) - // deep-copy the selection electrons from that container later. - - // ELECTRONS - if ( m_config->useTruthElectrons() ) { - top::check(loadDressedLeptons(* electrons, - m_electronsDressed, - m_electronsDressedAux), - "Failure to load dressed electrons."); + // Muons + if (m_config->useTruthMuons()) { + for (std::size_t i = 0; i < muons->size(); ++i) { + const auto* muon = muons->at(i); + + // Allow use of mixed-particle input container. + if (muon->absPdgId() != 13) { + continue; } - // MUONS - if ( m_config->useTruthMuons() ){ - top::check(loadDressedLeptons(* muons, - m_muonsDressed, - m_muonsDressedAux), - "Failure to load dressed muons."); + // FIXME: Is this still needed? + if (muon->barcode() >= 2e5) { + continue; } - // ====================================================================== - // OBJECT SELECTION - // This yields index collections, one for each - // { electrons, muons, photons, jets, largeRJets }. - std::list<std::size_t> idx_electrons; // -> relative to `electrons` - std::list<std::size_t> idx_muons; // -> relative to `muons` - std::list<std::size_t> idx_photons; // -> relative to `photons` - std::list<std::size_t> idx_jets; // -> relative to `jets` - std::list<std::size_t> idx_largeRJets; // -> relative to `largeRJets` - - // Electrons - if ( m_config->useTruthElectrons() ) { - for ( std::size_t i = 0; i < electrons->size(); ++i ){ - const auto * electron = electrons->at(i); - - // Allow use of mixed-particle input container. - if ( electron->absPdgId() != 11 ){ continue; } - - // FIXME: Is this still needed? - if ( electron->barcode() >= 2e5 ){ continue; } - - if ( m_objectSelector_Electron->apply(* electron) ){ - idx_electrons.push_back( i ); - } - } + if (m_objectSelector_Muon->apply(*muon)) { + idx_muons.push_back(i); } + } + } - // Muons - if ( m_config->useTruthMuons() ){ - for ( std::size_t i = 0; i < muons->size(); ++i ){ - const auto * muon = muons->at(i); + // Photons + if (m_config->useTruthPhotons()) { + for (std::size_t i = 0; i < photons->size(); ++i) { + const auto* photon = photons->at(i); - // Allow use of mixed-particle input container. - if ( muon->absPdgId() != 13 ){ continue; } + // Allow use of mixed-particle input container. + if (photon->absPdgId() != 22) { + continue; + } - // FIXME: Is this still needed? - if ( muon->barcode() >= 2e5 ){ continue; } + // FIXME: Is this still needed? + if (photon->barcode() >= 2e5) { + continue; + } - if ( m_objectSelector_Muon->apply(* muon) ){ - idx_muons.push_back( i ); - } - } + if (not m_objectSelector_Photon->apply(*photon)) { + continue; } - // Photons - if ( m_config->useTruthPhotons() ){ - for ( std::size_t i = 0; i < photons->size(); ++i ){ - const auto * photon = photons->at(i); - - // Allow use of mixed-particle input container. - if ( photon->absPdgId() != 22 ){ continue; } - - // FIXME: Is this still needed? - if ( photon->barcode() >= 2e5 ){ continue; } - - if ( not m_objectSelector_Photon->apply(* photon) ){ - continue; - } - - // Reject photons used for electron dressing. - if (m_config->useTruthElectrons()){ - if (isDressingPhoton(* photon, * electrons)){ - continue; - } - } - - // Reject photons used for muon dressing. - if (m_config->useTruthMuons()){ - if (isDressingPhoton(* photon, * muons)){ - continue; - } - } - idx_photons.push_back( i ); - } + // Reject photons used for electron dressing. + if (m_config->useTruthElectrons()) { + if (isDressingPhoton(*photon, *electrons)) { + continue; + } } - // Jets - if ( m_config->useTruthJets() ){ - for ( std::size_t i = 0; i < jets->size(); ++i ){ - if ( m_objectSelector_Jet->apply( * jets->at( i ) ) ){ - idx_jets.push_back( i ); - } - } + // Reject photons used for muon dressing. + if (m_config->useTruthMuons()) { + if (isDressingPhoton(*photon, *muons)) { + continue; + } } + idx_photons.push_back(i); + } + } - // Large-R-Jets - if ( m_config->useTruthLargeRJets() ){ - for ( std::size_t i = 0; i < largeRJets->size(); ++i ){ - if ( m_objectSelector_LargeRJet->apply( * largeRJets->at( i ) ) ){ - idx_largeRJets.push_back( i ); - } - } + // Jets + if (m_config->useTruthJets()) { + for (std::size_t i = 0; i < jets->size(); ++i) { + if (m_objectSelector_Jet->apply(*jets->at(i))) { + idx_jets.push_back(i); } + } + } - // ====================================================================== - // OVERLAP REMOVAL - // Removal Steps: - // 1. Jets & Muons: - // Remove Muons with dR < 0.4 - // 2. Jets & Electrons: - // Remove Electrons with dR < 0.4 - // 3. Photons & Jets: - // Remove Jets with dR < 0.4 + // Large-R-Jets + if (m_config->useTruthLargeRJets()) { + for (std::size_t i = 0; i < largeRJets->size(); ++i) { + if (m_objectSelector_LargeRJet->apply(*largeRJets->at(i))) { + idx_largeRJets.push_back(i); + } + } + } - // Jets and Muons: Remove Muon with dR < 0.4 - if ( m_config->useTruthMuons() && m_config->useTruthJets() && m_config->doParticleLevelOverlapRemovalMuJet() ) { + // Taus + if (m_config->useTruthTaus()) { + for (std::size_t i = 0; i < taus->size(); ++i) { + if (m_objectSelector_Tau->apply(*taus->at(i))) { + idx_taus.push_back(i); + } + } + } + // ====================================================================== + // OVERLAP REMOVAL + // Removal Steps: + // 1. Jets & Muons: + // Remove Muons with dR < 0.4 + // 2. Jets & Electrons: + // Remove Electrons with dR < 0.4 + // 3. Photons & Jets: + // Remove Jets with dR < 0.4 + + // Jets and Muons: Remove Muon with dR < 0.4 + if (m_config->useTruthMuons() && m_config->useTruthJets() && m_config->doParticleLevelOverlapRemovalMuJet()) { #ifdef TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL - const std::size_t nMuonsPreOR{idx_muons.size()}; + const std::size_t nMuonsPreOR { + idx_muons.size() + }; #endif - idx_muons.remove_if([& idx_jets, & jets, this](std::size_t m){ - for( auto j : idx_jets ){ - if ( jets->at( j )->p4().DeltaR( m_muonsDressed->at( m )->p4() ) < 0.4 ){ - return true; - } - } - return false; - }); + idx_muons.remove_if([&idx_jets, &jets, this](std::size_t m) { + for (auto j : idx_jets) { + if (jets->at(j)->p4().DeltaR(m_muonsDressed->at(m)->p4()) < 0.4) { + return true; + } + } + return false; + }); #ifdef TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL - std::cout << "[top::ParticleLevelLoader] Muon-In-Jet OR: " - << nMuonsPreOR << " -> " << idx_muons.size() << std::endl; + ATH_MSG_INFO("[top::ParticleLevelLoader] Muon-In-Jet OR: " + << nMuonsPreOR << " -> " << idx_muons.size()); #endif - } - - // Jets and Electrons: Remove Electron with dR < 0.4 - if ( m_config->useTruthElectrons() && m_config->useTruthJets() && m_config->doParticleLevelOverlapRemovalElJet() ) { + } + // Jets and Electrons: Remove Electron with dR < 0.4 + if (m_config->useTruthElectrons() && m_config->useTruthJets() && m_config->doParticleLevelOverlapRemovalElJet()) { #ifdef TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL - const std::size_t nElectronsPreOR{idx_electrons.size()}; + const std::size_t nElectronsPreOR { + idx_electrons.size() + }; #endif - idx_electrons.remove_if([& idx_jets, & jets, this](std::size_t e){ - for( auto j : idx_jets ){ - if ( jets->at( j )->p4().DeltaR( m_electronsDressed->at( e )->p4() ) < 0.4 ){ - return true; - } - } - return false; - }); + idx_electrons.remove_if([&idx_jets, &jets, this](std::size_t e) { + for (auto j : idx_jets) { + if (jets->at(j)->p4().DeltaR(m_electronsDressed->at(e)->p4()) < 0.4) { + return true; + } + } + return false; + }); #ifdef TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL - std::cout << "[top::ParticleLevelLoader] Electron-In-Jet OR: " - << nElectronsPreOR << " -> " << idx_electrons.size() << std::endl; + ATH_MSG_INFO("[top::ParticleLevelLoader] Electron-In-Jet OR: " + << nElectronsPreOR << " -> " << idx_electrons.size()); #endif - } - - // Photons and Jets: Remove Jet with dR < 0.4 - if ( m_config->useTruthPhotons() && m_config->useTruthJets() && m_config->doParticleLevelOverlapRemovalJetPhoton() ) { + } + // Photons and Jets: Remove Jet with dR < 0.4 + if (m_config->useTruthPhotons() && m_config->useTruthJets() && m_config->doParticleLevelOverlapRemovalJetPhoton()) { #ifdef TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL - const std::size_t nJetPreOR{idx_jets.size()}; + const std::size_t nJetPreOR { + idx_jets.size() + }; #endif - idx_jets.remove_if([& idx_photons, & photons, & jets](std::size_t j){ - for( auto ph : idx_photons ){ - if ( photons->at( ph )->p4().DeltaR( jets->at( j )->p4() ) < 0.4 ){ - return true; - } - } - return false; - }); + idx_jets.remove_if([&idx_photons, &photons, &jets](std::size_t j) { + for (auto ph : idx_photons) { + if (photons->at(ph)->p4().DeltaR(jets->at(j)->p4()) < 0.4) { + return true; + } + } + return false; + }); #ifdef TOP_PARTICLE_LEVEL_DEBUG_OVERLAP_REMOVAL - std::cout << "[top::ParticleLevelLoader] Jet-In-Photon OR: " - << nJetsPreOR << " -> " << idx_jets.size() << std::endl; + ATH_MSG_INFO("[top::ParticleLevelLoader] Jet-In-Photon OR: " + << nJetsPreOR << " -> " << idx_jets.size()); #endif - } + } - // ====================================================================== - // WRITE TO LOADER - // 1. Loop index lists for electrons / muons / photons / jets - // 2. Create a deep copy of the item and insert it into the - // appropriate container - // 3. Create a shallow copy of the containers and apply corrections - // if needed (dressing, etc.) - - // Create New Containers holding the "Good" Electrons / Muons / Jets - // and the MET - if ( m_config->useTruthElectrons() ) { - xAOD::TruthParticleContainer * goodElectrons = new xAOD::TruthParticleContainer(); - xAOD::TruthParticleAuxContainer * goodElectronsAux = new xAOD::TruthParticleAuxContainer(); - goodElectrons->setStore( goodElectronsAux ); //< Connect the two - - m_goodElectrons.reset( goodElectrons ); - m_goodElectronsAux.reset( goodElectronsAux ); - - for ( auto e : idx_electrons ){ - const auto & elPtr = m_electronsDressed->at( e ); - xAOD::TruthParticle * electron = new xAOD::TruthParticle(); - electron->makePrivateStore( * elPtr ); - m_goodElectrons->push_back( electron ); - } - } + // ====================================================================== + // WRITE TO LOADER + // 1. Loop index lists for electrons / muons / photons / jets + // 2. Create a deep copy of the item and insert it into the + // appropriate container + // 3. Create a shallow copy of the containers and apply corrections + // if needed (dressing, etc.) + + // Create New Containers holding the "Good" Electrons / Muons / Jets + // and the MET + if (m_config->useTruthElectrons()) { + xAOD::TruthParticleContainer* goodElectrons = new xAOD::TruthParticleContainer(); + xAOD::TruthParticleAuxContainer* goodElectronsAux = new xAOD::TruthParticleAuxContainer(); + goodElectrons->setStore(goodElectronsAux); //< Connect the two + + m_goodElectrons.reset(goodElectrons); + m_goodElectronsAux.reset(goodElectronsAux); + + for (auto e : idx_electrons) { + const auto& elPtr = m_electronsDressed->at(e); + xAOD::TruthParticle* electron = new xAOD::TruthParticle(); + electron->makePrivateStore(*elPtr); + m_goodElectrons->push_back(electron); + } + + // sort electrons based on dressed pT -- otherwise they remain sorted according to bare pT + std::sort(m_goodElectrons->begin(), m_goodElectrons->end(), top::descendingPtSorter); + } - if ( m_config->useTruthMuons() ){ - xAOD::TruthParticleContainer * goodMuons = new xAOD::TruthParticleContainer(); - xAOD::TruthParticleAuxContainer * goodMuonsAux = new xAOD::TruthParticleAuxContainer(); - goodMuons->setStore( goodMuonsAux ); //< Connect the two + if (m_config->useTruthMuons()) { + xAOD::TruthParticleContainer* goodMuons = new xAOD::TruthParticleContainer(); + xAOD::TruthParticleAuxContainer* goodMuonsAux = new xAOD::TruthParticleAuxContainer(); + goodMuons->setStore(goodMuonsAux); //< Connect the two - m_goodMuons.reset( goodMuons ); - m_goodMuonsAux.reset( goodMuonsAux ); + m_goodMuons.reset(goodMuons); + m_goodMuonsAux.reset(goodMuonsAux); - for ( auto m : idx_muons ){ - const auto & muPtr = m_muonsDressed->at( m ); - xAOD::TruthParticle * muon = new xAOD::TruthParticle(); - muon->makePrivateStore( * muPtr ); - m_goodMuons->push_back( muon ); - } - } + for (auto m : idx_muons) { + const auto& muPtr = m_muonsDressed->at(m); + xAOD::TruthParticle* muon = new xAOD::TruthParticle(); + muon->makePrivateStore(*muPtr); + m_goodMuons->push_back(muon); + } - if ( m_config->useTruthPhotons() ){ - xAOD::TruthParticleContainer * goodPhotons = new xAOD::TruthParticleContainer(); - xAOD::TruthParticleAuxContainer * goodPhotonsAux = new xAOD::TruthParticleAuxContainer(); - goodPhotons->setStore( goodPhotonsAux ); //< Connect the two + // sort muons based on dressed pT -- otherwise they remain sorted according to bare pT + std::sort(m_goodMuons->begin(), m_goodMuons->end(), top::descendingPtSorter); + } - m_goodPhotons.reset( goodPhotons ); - m_goodPhotonsAux.reset( goodPhotonsAux ); + if (m_config->useTruthPhotons()) { + xAOD::TruthParticleContainer* goodPhotons = new xAOD::TruthParticleContainer(); + xAOD::TruthParticleAuxContainer* goodPhotonsAux = new xAOD::TruthParticleAuxContainer(); + goodPhotons->setStore(goodPhotonsAux); //< Connect the two - for ( auto ph : idx_photons ){ - const auto & phPtr = photons->at( ph ); - xAOD::TruthParticle * photon = new xAOD::TruthParticle(); - photon->makePrivateStore( * phPtr ); - m_goodPhotons->push_back( photon ); - } - } + m_goodPhotons.reset(goodPhotons); + m_goodPhotonsAux.reset(goodPhotonsAux); - if ( m_config->useTruthJets() ){ - xAOD::JetContainer * goodJets = new xAOD::JetContainer(); - xAOD::JetAuxContainer * goodJetsAux = new xAOD::JetAuxContainer(); - goodJets->setStore( goodJetsAux ); //< Connect the two + for (auto ph : idx_photons) { + const auto& phPtr = photons->at(ph); + xAOD::TruthParticle* photon = new xAOD::TruthParticle(); + photon->makePrivateStore(*phPtr); + m_goodPhotons->push_back(photon); + } + } - m_goodJets.reset( goodJets ); - m_goodJetsAux.reset( goodJetsAux ); + if (m_config->useTruthJets()) { + xAOD::JetContainer* goodJets = new xAOD::JetContainer(); + xAOD::JetAuxContainer* goodJetsAux = new xAOD::JetAuxContainer(); + goodJets->setStore(goodJetsAux); //< Connect the two - for ( auto j : idx_jets ){ - const auto & jetPtr = jets->at( j ); - xAOD::Jet * jet = new xAOD::Jet(); - jet->makePrivateStore( * jetPtr ); - m_goodJets->push_back( jet ); - } - } + m_goodJets.reset(goodJets); + m_goodJetsAux.reset(goodJetsAux); - if ( m_config->useTruthLargeRJets() ){ - xAOD::JetContainer * goodLargeRJets = new xAOD::JetContainer(); - xAOD::JetAuxContainer * goodLargeRJetsAux = new xAOD::JetAuxContainer(); - goodLargeRJets->setStore( goodLargeRJetsAux ); //< Connect the two + for (auto j : idx_jets) { + const auto& jetPtr = jets->at(j); + xAOD::Jet* jet = new xAOD::Jet(); + jet->makePrivateStore(*jetPtr); + m_goodJets->push_back(jet); + } + } - m_goodLargeRJets.reset( goodLargeRJets ); - m_goodLargeRJetsAux.reset( goodLargeRJetsAux ); + if (m_config->useTruthLargeRJets()) { + xAOD::JetContainer* goodLargeRJets = new xAOD::JetContainer(); + xAOD::JetAuxContainer* goodLargeRJetsAux = new xAOD::JetAuxContainer(); + goodLargeRJets->setStore(goodLargeRJetsAux); //< Connect the two - for ( auto j : idx_largeRJets ){ - const auto & jetPtr = largeRJets->at( j ); - xAOD::Jet * jet = new xAOD::Jet(); - jet->makePrivateStore( * jetPtr ); - m_goodLargeRJets->push_back( jet ); - } - } + m_goodLargeRJets.reset(goodLargeRJets); + m_goodLargeRJetsAux.reset(goodLargeRJetsAux); - // ====================================================================== - // INSERTION INTO STORAGE - // Put everything into storage, i.e. into the ParticleLevel.event object - plEvent.m_electrons = m_config->useTruthElectrons() ? m_goodElectrons.get() : nullptr; - plEvent.m_muons = m_config->useTruthMuons() ? m_goodMuons.get() : nullptr; - plEvent.m_photons = m_config->useTruthPhotons() ? m_goodPhotons.get() : nullptr; - plEvent.m_jets = m_config->useTruthJets() ? m_goodJets.get() : nullptr; - plEvent.m_largeRJets = m_config->useTruthLargeRJets() ? m_goodLargeRJets.get() : nullptr; - plEvent.m_met = m_config->useTruthMET() ? (* mets)[ "NonInt" ] : nullptr; - - return plEvent; + for (auto j : idx_largeRJets) { + const auto& jetPtr = largeRJets->at(j); + xAOD::Jet* jet = new xAOD::Jet(); + jet->makePrivateStore(*jetPtr); + m_goodLargeRJets->push_back(jet); + } } - bool ParticleLevelLoader::loadDressedLeptons(const xAOD::TruthParticleContainer & input, - std::unique_ptr<xAOD::TruthParticleContainer> & store, - std::unique_ptr<xAOD::ShallowAuxContainer> & storeAux) const { - auto dressed = xAOD::shallowCopyContainer(input); - store.reset(dressed.first); - storeAux.reset(dressed.second); - - for (auto pl : * store.get()){ - TLorentzVector fvDressed; - fvDressed.SetPtEtaPhiE(pl->auxdata<float>("pt_dressed"), - pl->auxdata<float>("eta_dressed"), - pl->auxdata<float>("phi_dressed"), - pl->auxdata<float>("e_dressed")); - - // Store original kinematics as decoration - // m->auxdata<int>( "nPhotons_dressed" ) = m->auxdata<int>( "nPhotons_dressed" ); - - pl->auxdata<float>( "pt_bare" ) = pl->pt(); - pl->auxdata<float>( "eta_bare" ) = pl->eta(); - pl->auxdata<float>( "phi_bare" ) = pl->phi(); - pl->auxdata<float>( "e_bare" ) = pl->e(); - - pl->setPx( fvDressed.Px() ); - pl->setPy( fvDressed.Py() ); - pl->setPz( fvDressed.Pz() ); - pl->setE( fvDressed.E() ); + if (m_config->useTruthTaus()) { + xAOD::TruthParticleContainer* goodTaus = new xAOD::TruthParticleContainer(); + xAOD::TruthParticleAuxContainer* goodTausAux = new xAOD::TruthParticleAuxContainer(); + goodTaus->setStore(goodTausAux); //< Connect the two + + m_goodTaus.reset(goodTaus); + m_goodTausAux.reset(goodTausAux); + + for (auto t : idx_taus) { + const auto& tauPtr = taus->at(t); + xAOD::TruthParticle* tau = new xAOD::TruthParticle(); + tau->makePrivateStore(*tauPtr); + m_goodTaus->push_back(tau); + } + } + + if (m_config->useTruthMuons() && m_config->useSoftMuons() ) { + xAOD::TruthParticleContainer* goodSoftMuons = new xAOD::TruthParticleContainer(); + xAOD::TruthParticleAuxContainer* goodSoftMuonsAux = new xAOD::TruthParticleAuxContainer(); + goodSoftMuons->setStore(goodSoftMuonsAux); //< Connect the two + + m_goodSoftMuons.reset(goodSoftMuons); + m_goodSoftMuonsAux.reset(goodSoftMuonsAux); + + //if we want the soft muon truth history, the parent navigation for the TruthMuons collection is unfortunately working only in DAOD_PHYS, in other derivations + //we need a workaround, i.e. we need to use the muon from the TruthParticles container instead of the one from the TruthMuon container + std::vector<const xAOD::TruthParticle*> truth_particles_vec; //this is an helper vector to speed up looking for the right muon... + const xAOD::TruthParticleContainer* truth_particles = nullptr; + if (m_config->useTruthParticles() && m_config->softmuonAdditionalTruthInfo()) { + top::check(evtStore()->retrieve(truth_particles, m_config->sgKeyMCParticle()), + "xAOD::TEvent::retrieve failed for Truth Particles"); + if(truth_particles) + { + for(const xAOD::TruthParticle* p : *truth_particles) + { + if(p->isMuon() && p->status()==1) truth_particles_vec.push_back(p); + } + } + } + + for (std::size_t i = 0; i < muons->size(); ++i) { //note we don't use dressed muons in this case + if(std::find(idx_muons.begin(), idx_muons.end(), i)!=idx_muons.end()) continue; //we don't want to store muons both as standard muons and as soft muons + const auto& muPtr = muons->at(i); + + //here we apply the selection for soft muons + if(muPtr->absPdgId()!=13) continue; + if(muPtr->pt()<m_config->truth_softmuon_PtCut()) continue; + if(fabs(muPtr->eta())>m_config->truth_softmuon_EtaCut()) continue; + //now the association with the jets + + if(m_config->useTruthJets()) + { + bool isInJet=false; + for(xAOD::Jet* jetPtr : *m_goodJets) + { + float dR = xAOD::P4Helpers::deltaR(*muPtr,*jetPtr,m_config->softmuonDRJetcutUseRapidity()); + if(dR<m_config->softmuonDRJetcut()) + { + isInJet=true; + break; + } + } + if(!isInJet) continue; } + //end of selection + + if(m_config->softmuonAdditionalTruthInfo() && (!muPtr->isAvailable<bool>("hasTruthMuonHistoryInfo") || !muPtr->auxdecor<bool>("hasTruthMuonHistoryInfo"))) //if "hasTruthMuonPartonHistoryInfo" exists and is true, we already filled these info for this muon (since muon history filling can be done in several parts of the code for good reasons) + { + bool doPartonHistory=m_config->softmuonAdditionalTruthInfoCheckPartonOrigin(); + top::truth::initTruthMuonHistoryInfo(muPtr,doPartonHistory); + + //in DAOD_PHYS we can just navigate directly from the muon from TruthMuons + if (m_config->getDerivationStream() == "PHYS") + { + top::truth::getTruthMuonHistory(muPtr,doPartonHistory,m_config->getShoweringAlgorithm(),m_config->softmuonAdditionalTruthInfoDoVerbose()); + } + else //apparently in older derivation formats we have to navigate using the muon from the TruthParticles container, this is annoying + { + //first we find the associated truth muon from truth_particles + const xAOD::TruthParticle* assMuon = 0; + for(const xAOD::TruthParticle* p : truth_particles_vec) + { + if(!p) continue; + if(p->barcode() == muPtr->barcode()) + { + assMuon = p; + break; + } + } + if(assMuon) //then we use it + { + //if we don't have the info correctly filled already, let's initialize it to default values + if(!assMuon->isAvailable<bool>("hasTruthMuonHistoryInfo") || ! assMuon->auxdecor<bool>("hasTruthMuonHistoryInfo")) top::truth::initTruthMuonHistoryInfo(assMuon,doPartonHistory); + //we have to use the associated muon from the TruthParticles container in this case + top::truth::getTruthMuonHistory(assMuon,doPartonHistory,m_config->getShoweringAlgorithm(),m_config->softmuonAdditionalTruthInfoDoVerbose()); + //then we copy the info to our muon + top::truth::copyTruthMuonHistoryInfo(assMuon,muPtr); + + } + } + }//end of additional soft muon filling + + xAOD::TruthParticle* muon = new xAOD::TruthParticle(); + muon->makePrivateStore(*muPtr); + + m_goodSoftMuons->push_back(muon); + + } + + // sort muons based on dressed pT -- otherwise they remain sorted according to bare pT + std::sort(m_goodSoftMuons->begin(), m_goodSoftMuons->end(), top::descendingPtSorter); + } - return true; + + // ====================================================================== + // INSERTION INTO STORAGE + // Put everything into storage, i.e. into the ParticleLevel.event object + plEvent.m_electrons = m_config->useTruthElectrons() ? m_goodElectrons.get() : nullptr; + plEvent.m_muons = m_config->useTruthMuons() ? m_goodMuons.get() : nullptr; + plEvent.m_softmuons = (m_config->useTruthMuons() && m_config->useSoftMuons()) ? m_goodSoftMuons.get() : nullptr; + plEvent.m_photons = m_config->useTruthPhotons() ? m_goodPhotons.get() : nullptr; + plEvent.m_jets = m_config->useTruthJets() ? m_goodJets.get() : nullptr; + plEvent.m_largeRJets = m_config->useTruthLargeRJets() ? m_goodLargeRJets.get() : nullptr; + plEvent.m_taus = m_config->useTruthTaus() ? m_goodTaus.get() : nullptr; + plEvent.m_met = m_config->useTruthMET() ? (*mets)[ "NonInt" ] : nullptr; + + // Reclustered jets + if (m_config->useRCJets()) { + top::check(m_particleLevelRCJetObjectLoader->execute( + plEvent), "Failed to execute ParticleLevelRCJetObjectLoader container"); + // Get the name of the container of re-clustered jets + std::string RCJetContainerNane = m_particleLevelRCJetObjectLoader->rcjetContainerName(); + + // -- Retrieve the re-clustered jets from TStore & save good re-clustered jets -- // + const xAOD::JetContainer* rc_jets(nullptr); + top::check(evtStore()->retrieve(rc_jets, RCJetContainerNane), "Failed to retrieve particle RC JetContainer"); + + for (auto rcjet : *rc_jets) { + top::check(rcjet->isAvailable<bool>( + "PassedSelection"), + " Can't find reclustered jet decoration \"PassedSelection\" - we need it to decide if we should keep the reclustered jet in the top::Event instance or not!"); + if (rcjet->auxdataConst<bool>("PassedSelection")) plEvent.m_RCJets.push_back((xAOD::Jet*) rcjet); + } + } + // Variable-R reclustered jets + if (m_config->useVarRCJets()) { + for (auto& rho : m_VarRCJetRho) { + for (auto& mass_scale : m_VarRCJetMassScale) { + std::replace(rho.begin(), rho.end(), '.', '_'); + std::string name = rho + mass_scale; + top::check(m_particleLevelVarRCJetObjectLoader[name]->execute( + plEvent), "Failed to execute RCJetMC15 container"); + + // Get the name of the container of re-clustered jets in TStore + std::string varRCJetContainerName = m_particleLevelVarRCJetObjectLoader[name]->rcjetContainerName(); + + // -- Retrieve the re-clustered jets from TStore & save good re-clustered jets -- // + const xAOD::JetContainer* vrc_jets(nullptr); + top::check(evtStore()->retrieve(vrc_jets, varRCJetContainerName), "Failed to retrieve RC JetContainer"); + + plEvent.m_VarRCJets[name] = std::make_shared<xAOD::JetContainer>(SG::VIEW_ELEMENTS); + for (auto vrcjet : *vrc_jets) { + top::check(vrcjet->isAvailable<bool>( + "PassedSelection"), + " Can't find jet decoration \"PassedSelection\" - we need it to decide if we should keep the variable-R reclustered jet in the top::Event instance or not!"); + if (vrcjet->auxdataConst<bool>("PassedSelection")) plEvent.m_VarRCJets[name]->push_back((xAOD::Jet*) vrcjet); + + } + } + } } - bool ParticleLevelLoader::isDressingPhoton(const xAOD::TruthParticle & photon, - const xAOD::TruthParticleContainer & dressedParticles, - const float dressingCone /* = 0.1 */) const { - // We do not check whether the original truth particle decoration exists - // and / or is valid because at this point we assume that it was already - // used by the lepton loading function. - static const std::string decoName{"originalTruthParticle"}; - for (const auto & particle : dressedParticles){ - auto truthProxy = particle->auxdata<ElementLink<xAOD::TruthParticleContainer> >("originalTruthParticle"); - if ((* truthProxy)->p4().DeltaR(photon.p4()) <= dressingCone){ - return true; - } + return plEvent; + } - } + bool ParticleLevelLoader::loadDressedLeptons(const xAOD::TruthParticleContainer& input, + std::unique_ptr<xAOD::TruthParticleContainer>& store, + std::unique_ptr<xAOD::ShallowAuxContainer>& storeAux) const { + auto dressed = xAOD::shallowCopyContainer(input); - return false; + store.reset(dressed.first); + storeAux.reset(dressed.second); + + for (auto pl : *store.get()) { + TLorentzVector fvDressed; + fvDressed.SetPtEtaPhiE(pl->auxdata<float>("pt_dressed"), + pl->auxdata<float>("eta_dressed"), + pl->auxdata<float>("phi_dressed"), + pl->auxdata<float>("e_dressed")); + + // Store original kinematics as decoration + // m->auxdata<int>( "nPhotons_dressed" ) = m->auxdata<int>( "nPhotons_dressed" ); + + pl->auxdata<float>("pt_bare") = pl->pt(); + pl->auxdata<float>("eta_bare") = pl->eta(); + pl->auxdata<float>("phi_bare") = pl->phi(); + pl->auxdata<float>("e_bare") = pl->e(); + + pl->setPx(fvDressed.Px()); + pl->setPy(fvDressed.Py()); + pl->setPz(fvDressed.Pz()); + pl->setE(fvDressed.E()); } + + return true; + } + + bool ParticleLevelLoader::isDressingPhoton(const xAOD::TruthParticle& photon, + const xAOD::TruthParticleContainer& dressedParticles, + const float dressingCone /* = 0.1 */) const { + // We do not check whether the original truth particle decoration exists + // and / or is valid because at this point we assume that it was already + // used by the lepton loading function. + static const std::string decoName { + "originalTruthParticle" + }; + + for (const auto& particle : dressedParticles) { + bool tp_isValid = false; + ElementLink<xAOD::TruthParticleContainer> truthProxy; + try { + truthProxy = particle->auxdata<ElementLink<xAOD::TruthParticleContainer> >("originalTruthParticle"); + tp_isValid = truthProxy.isValid(); + } catch (const SG::ExcBadAuxVar&) { + // ExcBadAuxVar can be thrown before checking if proxy is valid + tp_isValid = false; + } + + if (not tp_isValid) { + if (particle->p4().DeltaR(photon.p4()) <= dressingCone) { + return true; + } + } else { + if ((*truthProxy)->p4().DeltaR(photon.p4()) <= dressingCone) { + return true; + } + } + } + + return false; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelMuonObjectSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelMuonObjectSelector.cxx index ce976792e0f7d2c4d1b6c89b50ac75618dd4739b..c650dfef27870f874f2ceb1b8ead6d6624fcc26d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelMuonObjectSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelMuonObjectSelector.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelMuonObjectSelector.cxx // Description: @@ -13,62 +13,64 @@ #include "TopParticleLevel/TruthTools.h" namespace top { + ParticleLevelMuonObjectSelector::ParticleLevelMuonObjectSelector(Options opt /* = Options() */) + : m_opt(opt) { /* Deliberately Empty */} - ParticleLevelMuonObjectSelector::ParticleLevelMuonObjectSelector( Options opt /* = Options() */ ) - : m_opt( opt ){ /* Deliberately Empty */ } + /* virtual */ bool + ParticleLevelMuonObjectSelector::apply(const xAOD::TruthParticle& truthParticle) { + // Obtain the particle type and particle origin from the decoration + // created by the MCTruthClassifier. For legacy reasons, try both + // decoration names. + unsigned int type; - /* virtual */ bool - ParticleLevelMuonObjectSelector::apply( const xAOD::TruthParticle & truthParticle ) { - - // Obtain the particle type and particle origin from the decoration - // created by the MCTruthClassifier. For legacy reasons, try both - // decoration names. - unsigned int type; - if ( truthParticle.isAvailable<unsigned int>( "particleType" ) ){ - type = truthParticle.auxdata<unsigned int>( "particleType" ); - } else if ( truthParticle.isAvailable<unsigned int>( "classifierParticleType" ) ){ - type = truthParticle.auxdata<unsigned int>( "classifierParticleType" ); - } else { - std::cerr << "Could not obtain MCTruthClassifier result decoration." << std::endl; - std::exit( 1 ); - } - - // -------------------------------------------------- - // Accept muons iff they do not come from a hadron - using namespace MCTruthPartClassifier; - if ( m_opt.not_from_hadron && - type != ParticleType::IsoMuon ){ - return false; - } - - // If it is requested that tauons are hadrons, perform a check of the - // ancestry: It shall not contain a single tauon. - if ( m_opt.tau_is_hadron ){ - auto truthProxy = truthParticle.auxdata<ElementLink<xAOD::TruthParticleContainer> >( "originalTruthParticle" ); - if ( not truthProxy.isValid() ){ - std::cerr << "Could not obtain 'originalTruthParticle' reference." << std::endl; - std::exit( 1 ); - } - if ( truth::isLeptonFromTau( * truthProxy ) ){ - return false; - } - } + if (truthParticle.isAvailable<unsigned int>("particleType")) { + type = truthParticle.auxdata<unsigned int>("particleType"); + } else if (truthParticle.isAvailable<unsigned int>("classifierParticleType")) { + type = truthParticle.auxdata<unsigned int>("classifierParticleType"); + } else { + throw std::runtime_error("ParticleLevelMuonObjectSelector::apply: " + "Could not obtain MCTruthClassifier result decoration."); + } + // -------------------------------------------------- + // Accept muons iff they do not come from a hadron + using namespace MCTruthPartClassifier; + if (m_opt.not_from_hadron && + type != ParticleType::IsoMuon) { + return false; + } - // -------------------------------------------------- - // Apply kinematic cut on the dressed pT: - // must exceed 25 GeV - if ( truthParticle.auxdata<float>( "pt_dressed" ) < m_opt.pt_min ){ return false; } + // If it is requested that tauons are hadrons, perform a check of the + // ancestry: It shall not contain a single tauon. + if (m_opt.tau_is_hadron) { + auto truthProxy = truthParticle.auxdata<ElementLink<xAOD::TruthParticleContainer> >("originalTruthParticle"); + if (not truthProxy.isValid()) { + throw std::runtime_error("ParticleLevelMuonObjectSelector::apply: " + "Could not obtain 'originalTruthParticle' reference."); + } + if (truth::isLeptonFromTau(*truthProxy)) { + return false; + } + } - // -------------------------------------------------- - // Apply kinematic cut on the dressed eta: - // must be less than or equal to 2.5 - if ( std::abs( truthParticle.auxdata<float>( "eta_dressed" ) ) > m_opt.eta_max ){ return false; } + // -------------------------------------------------- + // Apply kinematic cut on the dressed pT: + // must exceed 25 GeV + if (truthParticle.auxdata<float>("pt_dressed") < m_opt.pt_min) { + return false; + } - // -------------------------------------------------- - // Everything that reaches this point has passed the selection - return true; + // -------------------------------------------------- + // Apply kinematic cut on the dressed eta: + // must be less than or equal to 2.5 + if (std::abs(truthParticle.auxdata<float>("eta_dressed")) > m_opt.eta_max) { + return false; } + + // -------------------------------------------------- + // Everything that reaches this point has passed the selection + return true; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelPhotonObjectSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelPhotonObjectSelector.cxx index 964255de328e761e1900b8399a7209db72c6ccfc..39e4e51a7c174b5098c6a2f49f0ed5cd0c561163 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelPhotonObjectSelector.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelPhotonObjectSelector.cxx @@ -1,134 +1,122 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: ParticleLevelPhotonObjectSelector.cxx -// Description: -// Author: Fabian Wilk -// Created: Wed Oct 12 11:41:36 2016 -// -// (c) by The ATLAS Collaboration -// by Fabian Wilk <mail@fabianwilk.de> -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopParticleLevel/ParticleLevelPhotonObjectSelector.h" #include "TopConfiguration/Tokenize.h" namespace top { - ParticleLevelPhotonObjectSelector::ParticleLevelPhotonObjectSelector(Options opt /* = Options() */) - : m_opt(opt){ /* Deliberately Empty */ } - - ParticleLevelPhotonObjectSelector::Options::Options(double ptMin /* = 25.e3 */, - double etaMax /* = 2.5 */, - const std::string & Origin /* = "" */, - const std::string & Isolation /* = "" */) : - pt_min(ptMin), - eta_max(etaMax), - origin(), - isolationVar(""), - isolationCut(){ - - // ========================================================= - // Parse the TruthOrigin Configuration Parameter. - if (Origin == "" || Origin == " "|| Origin == "False" || Origin == "None"){ - // Deliberately Empty - } else { - // This allows us to convert from string name to enum value. - MCTruthPartClassifier::ParticleDef def; - - // Tokenize at comma. - std::vector<std::string> tokens; - tokenize(Origin, tokens, ","); - - while (tokens.size()){ - const auto & token = tokens.back(); - - auto it = std::find(def.sParticleOrigin.begin(), - def.sParticleOrigin.end(), - token); - - top::check(it != def.sParticleOrigin.end(), - "[ParticleLevelPhotonObjectSelector] Invalid particle origin '" + token + "'"); - - origin.push_back( - static_cast<MCTruthPartClassifier::ParticleOrigin>( - std::distance(def.sParticleOrigin.begin(), - it))); - - tokens.pop_back(); - } - } - - // ========================================================= - // Parse the TruthIsolation Configuration Parameter - if (Isolation == "" || Isolation == " " || Isolation == "False" || Isolation == "None"){ - isolationVar = ""; - } else { - // Split at space, should be exactly 2 tokens. - std::vector<std::string> tokens; - tokenize(Isolation, tokens, " "); - top::check(tokens.size() == 2, - "[ParticleLevelPhotonObjectSelector] Invalid input for isolation parameter (expected 2 tokens)."); - - isolationVar = tokens.at(0); - isolationCut = std::stof(tokens.at(1)); - } - } - - - /* virtual */ bool ParticleLevelPhotonObjectSelector::apply(const xAOD::TruthParticle & truthParticle){ - // -------------------------------------------------- - // Require that the photon is status=1 (stable) - // TODO: Should we include other statuses? - if (truthParticle.status() != 1){ - return false; - } - - // -------------------------------------------------- - // Apply kinematic cut on the pT: - // must exceed 25 GeV - if ( truthParticle.pt() < m_opt.pt_min ){ return false; } - - // -------------------------------------------------- - // Apply kinematic cut on the eta: - // must be less than or equal to 2.5 - if ( std::abs( truthParticle.eta() ) > m_opt.eta_max ){ return false; } - - // -------------------------------------------------- - // Apply particle origin cut. - if (m_opt.origin.size()){ - unsigned int origin; - if ( truthParticle.isAvailable<unsigned int>( "particleOrigin" ) ){ - origin = truthParticle.auxdata<unsigned int>( "particleOrigin" ); - } else if ( truthParticle.isAvailable<unsigned int>( "classifierParticleOrigin" ) ){ - origin = truthParticle.auxdata<unsigned int>( "classifierParticleOrigin" ); - } else { - top::check(false, "Could not obtain MCTruthClassifier result decoration."); - } - - if (std::find(m_opt.origin.begin(), m_opt.origin.end(), origin) == m_opt.origin.end()){ - return false; - } - } - - // -------------------------------------------------- - // Apply isolation cut - if (m_opt.isolationVar.size()){ - top::check(truthParticle.isAvailable<float>(m_opt.isolationVar), - "[ParticleLevelPhotonObjectSelector] Selected isolation variable not available!"); - if (m_opt.isolationCut <= truthParticle.auxdata<float>(m_opt.isolationVar) / truthParticle.pt()){ - return false; - } - } - - // -------------------------------------------------- - // Everything that reaches this point has passed the selection - return true; + ParticleLevelPhotonObjectSelector::ParticleLevelPhotonObjectSelector(Options opt /* = Options() */) + : m_opt(opt) { /* Deliberately Empty */} + + ParticleLevelPhotonObjectSelector::Options::Options(double ptMin /* = 25.e3 */, + double etaMax /* = 2.5 */, + const std::string& Origin /* = "" */, + const std::string& Isolation /* = "" */) : + pt_min(ptMin), + eta_max(etaMax), + origin(), + isolationVar(""), + isolationCut() { + // ========================================================= + // Parse the TruthOrigin Configuration Parameter. + if (Origin == "" || Origin == " " || Origin == "False" || Origin == "None") { + // Deliberately Empty + } else { + // This allows us to convert from string name to enum value. + MCTruthPartClassifier::ParticleDef def; + + // Tokenize at comma. + std::vector<std::string> tokens; + tokenize(Origin, tokens, ","); + + while (tokens.size()) { + const auto& token = tokens.back(); + + auto it = std::find(def.sParticleOrigin.begin(), + def.sParticleOrigin.end(), + token); + + top::check(it != def.sParticleOrigin.end(), + "[ParticleLevelPhotonObjectSelector] Invalid particle origin '" + token + "'"); + + origin.push_back( + static_cast<MCTruthPartClassifier::ParticleOrigin>( + std::distance(def.sParticleOrigin.begin(), + it))); + + tokens.pop_back(); + } } + + // ========================================================= + // Parse the TruthIsolation Configuration Parameter + if (Isolation == "" || Isolation == " " || Isolation == "False" || Isolation == "None") { + isolationVar = ""; + } else { + // Split at space, should be exactly 2 tokens. + std::vector<std::string> tokens; + tokenize(Isolation, tokens, " "); + top::check(tokens.size() == 2, + "[ParticleLevelPhotonObjectSelector] Invalid input for isolation parameter (expected 2 tokens)."); + + isolationVar = tokens.at(0); + isolationCut = std::stof(tokens.at(1)); + } + } + + /* virtual */ bool ParticleLevelPhotonObjectSelector::apply(const xAOD::TruthParticle& truthParticle) { + // -------------------------------------------------- + // Require that the photon is status=1 (stable) + // TODO: Should we include other statuses? + if (truthParticle.status() != 1) { + return false; + } + + // -------------------------------------------------- + // Apply kinematic cut on the pT: + // must exceed 25 GeV + if (truthParticle.pt() < m_opt.pt_min) { + return false; + } + + // -------------------------------------------------- + // Apply kinematic cut on the eta: + // must be less than or equal to 2.5 + if (std::abs(truthParticle.eta()) > m_opt.eta_max) { + return false; + } + + // -------------------------------------------------- + // Apply particle origin cut. + if (m_opt.origin.size()) { + unsigned int origin; + if (truthParticle.isAvailable<unsigned int>("particleOrigin")) { + origin = truthParticle.auxdata<unsigned int>("particleOrigin"); + } else if (truthParticle.isAvailable<unsigned int>("classifierParticleOrigin")) { + origin = truthParticle.auxdata<unsigned int>("classifierParticleOrigin"); + } else { + top::check(false, "Could not obtain MCTruthClassifier result decoration."); + } + + if (std::find(m_opt.origin.begin(), m_opt.origin.end(), origin) == m_opt.origin.end()) { + return false; + } + } + + // -------------------------------------------------- + // Apply isolation cut + if (m_opt.isolationVar.size()) { + top::check(truthParticle.isAvailable<float>(m_opt.isolationVar), + "[ParticleLevelPhotonObjectSelector] Selected isolation variable not available!"); + if (m_opt.isolationCut <= truthParticle.auxdata<float>(m_opt.isolationVar) / truthParticle.pt()) { + return false; + } + } + + // -------------------------------------------------- + // Everything that reaches this point has passed the selection + return true; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelRCJetObjectLoader.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelRCJetObjectLoader.cxx new file mode 100644 index 0000000000000000000000000000000000000000..ac513b2d29a5a9b515f020a6f9c6a16a5a6a5118 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelRCJetObjectLoader.cxx @@ -0,0 +1,406 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "xAODJet/JetContainer.h" +#include "xAODJet/JetAuxContainer.h" +#include "xAODEventInfo/EventInfo.h" +#include "xAODCore/ShallowCopy.h" +#include "xAODBase/IParticleHelpers.h" +#include "AthContainers/ConstDataVector.h" + + +#include "TopParticleLevel/ParticleLevelRCJetObjectLoader.h" +#include "TopEvent/EventTools.h" +#include "TopParticleLevel/ParticleLevelEvent.h" +#include "TopConfiguration/TopConfig.h" + +#include "fastjet/ClusterSequence.hh" +#include <fastjet/contrib/Nsubjettiness.hh> +#include <fastjet/contrib/EnergyCorrelator.hh> +#include "JetSubStructureUtils/Qw.h" +#include "JetSubStructureUtils/KtSplittingScale.h" +#include "JetSubStructureUtils/EnergyCorrelatorGeneralized.h" +#include "JetSubStructureUtils/EnergyCorrelator.h" + +ParticleLevelRCJetObjectLoader::ParticleLevelRCJetObjectLoader(const std::shared_ptr<top::TopConfig>& cfg) : asg:: + AsgTool("ParticleLevelRCJetObjectLoader"), m_config(cfg) { + m_ptcut = 0.; + m_etamax = 0.; + m_inputJetPtMin = 0.; + m_inputJetEtaMax = 999.; + m_trim = 0.; + m_radius = 0.; + m_treeName = "particleLevel"; + m_InJetContainerBase = "AntiKt4TruthWZJets_RC"; + m_OutJetContainerBase = "AntiKt10RCTrim"; + m_InputJetContainer = "AntiKt4TruthWZJets_RC"; + m_OutputJetContainer = "AntiKt10RCTrim"; + m_name = ""; + m_useJSS = false; + m_useAdditionalJSS = false; + m_jet_def_rebuild = nullptr; + m_nSub1_beta1 = nullptr; + m_nSub2_beta1 = nullptr; + m_nSub3_beta1 = nullptr; + m_ECF1 = nullptr; + m_ECF2 = nullptr; + m_ECF3 = nullptr; + m_split12 = nullptr; + m_split23 = nullptr; + m_qw = nullptr; + m_gECF332 = nullptr; + m_gECF461 = nullptr; + m_gECF322 = nullptr; + m_gECF331 = nullptr; + m_gECF422 = nullptr; + m_gECF441 = nullptr; + m_gECF212 = nullptr; + m_gECF321 = nullptr; + m_gECF311 = nullptr; + + + declareProperty("VarRCjets", m_VarRCjets = false); + declareProperty("VarRCjets_rho", m_VarRCjets_rho = ""); + declareProperty("VarRCjets_mass_scale", m_VarRCjets_mass_scale = ""); +} + +ParticleLevelRCJetObjectLoader::~ParticleLevelRCJetObjectLoader() {} + + +StatusCode ParticleLevelRCJetObjectLoader::initialize() { + /* Initialize the re-clustered jets */ + ATH_MSG_INFO(" Initializing particle level Re-clustered jets "); + + m_name = m_VarRCjets_rho + m_VarRCjets_mass_scale; + + + if (m_VarRCjets) { + m_ptcut = m_config->VarRCJetPtcut(); // 100 GeV + m_etamax = m_config->VarRCJetEtacut(); // 2.5 + m_trim = m_config->VarRCJetTrimcut(); // 0.05 (5% jet pT) + m_radius = m_config->VarRCJetMaxRadius(); // 1.2 (min=0.4) + m_minradius = 0.4; // 0.4 default (until we have smaller jets!) + std::string original_rho(m_VarRCjets_rho); + std::replace(original_rho.begin(), original_rho.end(), '_', '.'); + float rho = std::stof(original_rho); + float m_scale = mass_scales.at(m_VarRCjets_mass_scale); + m_massscale = rho * m_scale * 1e-3; + + m_useJSS = m_config->useVarRCJetSubstructure(); + m_useAdditionalJSS = m_config->useVarRCJetAdditionalSubstructure(); + } else { + m_ptcut = m_config->RCJetPtcut(); // for initialize [GeV] & passSelection + m_etamax = m_config->RCJetEtacut(); // for passSelection + m_trim = m_config->RCJetTrimcut(); // for initialize + m_radius = m_config->RCJetRadius(); // for initialize + m_minradius = -1.0; + m_massscale = -1.0; + + m_useJSS = m_config->useRCJetSubstructure(); + m_useAdditionalJSS = m_config->useRCJetAdditionalSubstructure(); + } + + m_inputJetPtMin = m_config->RCInputJetPtMin(); + m_inputJetEtaMax = m_config->RCInputJetEtaMax(); + + + + m_InputJetContainer = m_InJetContainerBase; + m_OutputJetContainer = m_OutJetContainerBase + m_name; + + // build a jet re-clustering tool for each case + m_jetReclusteringTool = std::make_shared<JetReclusteringTool>(m_treeName + m_name); + top::check(m_jetReclusteringTool->setProperty("InputJetContainer", + m_InputJetContainer), + "Failed inputjetcontainer initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("OutputJetContainer", + m_OutputJetContainer), + "Failed outputjetcontainer initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("ReclusterRadius", + m_radius), "Failed re-clustering radius initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("RCJetPtMin", + m_ptcut * 1e-3), "Failed ptmin [GeV] initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("InputJetPtMin", m_inputJetPtMin * 1e-3), "Failed InputJetPtMin [GeV] initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("TrimPtFrac", + m_trim), "Failed pT fraction initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("VariableRMinRadius", + m_minradius), "Failed VarRC min radius initialize reclustering tool"); + top::check(m_jetReclusteringTool->setProperty("VariableRMassScale", + m_massscale), "Failed VarRC mass scale initialize reclustering tool"); + top::check(m_jetReclusteringTool->initialize(), "Failed to initialize reclustering tool"); + + if (m_useJSS || m_useAdditionalJSS) { + ATH_MSG_INFO("Calculating RCJet Substructure"); + + // Setup a bunch of FastJet stuff + //define the type of jets you will build (http://fastjet.fr/repo/doxygen-3.0.3/classfastjet_1_1JetDefinition.html) + m_jet_def_rebuild = std::make_shared<fastjet::JetDefinition>(fastjet::antikt_algorithm, 1.0, fastjet::E_scheme, + fastjet::Best); + } + if (m_useJSS) { + //Substructure tool definitions + m_nSub1_beta1 = std::make_shared<fastjet::contrib::Nsubjettiness>(1, + fastjet::contrib::OnePass_WTA_KT_Axes(), + fastjet::contrib::UnnormalizedMeasure(1.0)); + m_nSub2_beta1 = std::make_shared<fastjet::contrib::Nsubjettiness>(2, + fastjet::contrib::OnePass_WTA_KT_Axes(), + fastjet::contrib::UnnormalizedMeasure(1.0)); + m_nSub3_beta1 = std::make_shared<fastjet::contrib::Nsubjettiness>(3, + fastjet::contrib::OnePass_WTA_KT_Axes(), + fastjet::contrib::UnnormalizedMeasure(1.0)); + + + m_split12 = std::make_shared<JetSubStructureUtils::KtSplittingScale>(1); + m_split23 = std::make_shared<JetSubStructureUtils::KtSplittingScale>(2); + + m_qw = std::make_shared<JetSubStructureUtils::Qw>(); + + m_ECF1 = std::make_shared<fastjet::contrib::EnergyCorrelator>(1, 1.0, fastjet::contrib::EnergyCorrelator::pt_R); + m_ECF2 = std::make_shared<fastjet::contrib::EnergyCorrelator>(2, 1.0, fastjet::contrib::EnergyCorrelator::pt_R); + m_ECF3 = std::make_shared<fastjet::contrib::EnergyCorrelator>(3, 1.0, fastjet::contrib::EnergyCorrelator::pt_R); + } + if (m_useAdditionalJSS) { + + m_gECF332 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(3, 3, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF461 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(6, 4, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF322 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(2, 3, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF331 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(3, 3, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF422 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(2, 4, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF441 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(4, 4, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF212 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(1, 2, 2, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF321 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(2, 3, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + m_gECF311 = std::make_shared<JetSubStructureUtils::EnergyCorrelatorGeneralized>(1, 3, 1, + JetSubStructureUtils::EnergyCorrelator::pt_R); + } + ATH_MSG_INFO(" Re-clustered jets initialized "); + + return StatusCode::SUCCESS; +} // end initialize() + +StatusCode ParticleLevelRCJetObjectLoader::execute(const top::ParticleLevelEvent& plEvent) { + /* + Make the jet container (if necessary) and execute the re-clustering tool + https://svnweb.cern.ch/trac/atlasoff/browser/PhysicsAnalysis/TopPhys/xAOD/TopEvent/trunk/Root/TopEventMaker.cxx#L31 + */ + + // -- Save the jet container to the TStore (only if it doesn't already exist!) + // -- Then, we can access it with the re-clustering tool further down + if (!evtStore()->contains<xAOD::JetContainer>(m_InputJetContainer)) { + auto rcJetInputs = std::make_unique< ConstDataVector< xAOD::JetContainer > >(SG::VIEW_ELEMENTS); + for(const xAOD::Jet* jet : *plEvent.m_jets) { + if(jet->pt() < m_inputJetPtMin || std::abs(jet->eta()) > m_inputJetEtaMax) continue; + rcJetInputs->push_back(jet); + } + top::check(evtStore()->tds()->record(std::move(rcJetInputs), m_InputJetContainer), + "Failed to put jets in TStore for re-clustering"); + } // end if jet container exists + + + + + + // --- EXECUTE --- // + // only execute if the jet container doesn't exist + // (do not re-make the 'nominal' jet container over & over again!) + if (!evtStore()->contains<xAOD::JetContainer>(m_OutputJetContainer)) { + m_jetReclusteringTool->execute(); + + const xAOD::JetContainer* myJets(nullptr); + top::check(evtStore()->retrieve(myJets, m_OutputJetContainer), "Failed to retrieve particle RC JetContainer"); + + for (auto rcjet : *myJets) { + rcjet->auxdecor<bool>("PassedSelection") = passSelection(*rcjet); + } + + if (m_useJSS || m_useAdditionalJSS) { + static const SG::AuxElement::ConstAccessor<bool> passedSelection("PassedSelection"); + + for (auto rcjet : *myJets) { + if (!passedSelection(*rcjet)) continue; // Calculate JSS only if passed object selection + + + std::vector<fastjet::PseudoJet> clusters; + clusters.clear(); + + for (auto subjet : rcjet->getConstituents()) { + const xAOD::Jet* subjet_raw = static_cast<const xAOD::Jet*>(subjet->rawConstituent()); + + + for (auto clus_itr : subjet_raw->getConstituents()) { + + TLorentzVector temp_p4; + temp_p4.SetPtEtaPhiM(clus_itr->pt(), clus_itr->eta(), clus_itr->phi(), clus_itr->m()); + + + // Only in case AntiKt4EMPFlowJets are used include in the substructure only the charged component of the + // substructure + if (m_config->sgKeyJetsTDS(m_config->nominalHashValue(), + false).find("AntiKt4EMPFlowJets") != std::string::npos) { + + const xAOD::TruthParticle* tp = dynamic_cast<const xAOD::TruthParticle*>(clus_itr->rawConstituent()); + + if( tp == nullptr) + continue; + + // Do not use charged particles + if (tp->charge() == 0) continue; + + //Apply same track selection used at reco-level + if ((clus_itr->pt() < m_config->ghostTrackspT()) || ( std::abs(clus_itr->eta()) > 2.5 ) ) continue; + } + + clusters.push_back(fastjet::PseudoJet(temp_p4.Px(), temp_p4.Py(), temp_p4.Pz(), temp_p4.E())); + } + } + + if (clusters.size() != 0) { + fastjet::ClusterSequence clust_seq_rebuild = fastjet::ClusterSequence(clusters, *m_jet_def_rebuild); + std::vector<fastjet::PseudoJet> my_pjets = fastjet::sorted_by_pt(clust_seq_rebuild.inclusive_jets(0.0)); + + fastjet::PseudoJet correctedJet; + correctedJet = my_pjets[0]; + //Sometimes fastjet splits the jet into two, so need to correct for that!! + if (my_pjets.size() > 1) correctedJet += my_pjets[1]; + + if (m_useJSS) { + // Now finally we can calculate some substructure! + double tau32 = -1, tau21 = -1; + + double tau1 = m_nSub1_beta1->result(correctedJet); + double tau2 = m_nSub2_beta1->result(correctedJet); + double tau3 = m_nSub3_beta1->result(correctedJet); + + if (std::abs(tau1) > 1e-8) tau21 = tau2 / tau1; + else tau21 = -999.0; + if (std::abs(tau2) > 1e-8) tau32 = tau3 / tau2; + else tau32 = -999.0; + + + + double split12 = m_split12->result(correctedJet); + double split23 = m_split23->result(correctedJet); + double qw = m_qw->result(correctedJet); + + double D2 = -1; + + double vECF1 = m_ECF1->result(correctedJet); + double vECF2 = m_ECF2->result(correctedJet); + double vECF3 = m_ECF3->result(correctedJet); + if (std::abs(vECF2) > 1e-8) D2 = vECF3 * vECF1* vECF1* vECF1 / (vECF2 * vECF2 * vECF2); + else D2 = -999.0; + + // now attach the results to the original jet + rcjet->auxdecor<float>("Tau32_clstr") = tau32; + rcjet->auxdecor<float>("Tau21_clstr") = tau21; + + // lets also write out the components so we can play with them later + rcjet->auxdecor<float>("Tau3_clstr") = tau3; + rcjet->auxdecor<float>("Tau2_clstr") = tau2; + rcjet->auxdecor<float>("Tau1_clstr") = tau1; + + rcjet->auxdecor<float>("d12_clstr") = split12; + rcjet->auxdecor<float>("d23_clstr") = split23; + rcjet->auxdecor<float>("Qw_clstr") = qw; + + + rcjet->auxdecor<float>("nconstituent_clstr") = clusters.size(); + + rcjet->auxdecor<float>("ECF1_clstr") = vECF1; + rcjet->auxdecor<float>("ECF2_clstr") = vECF2; + rcjet->auxdecor<float>("ECF3_clstr") = vECF3; + rcjet->auxdecor<float>("D2_clstr") = D2; + } // end of if useJSS + + if (m_useAdditionalJSS) { + + // MlB's t/H discriminators + // E = (a*n) / (b*m) + // for an ECFG_X_Y_Z, a=Y, n=Z -> dimenionless variable + double gECF332 = m_gECF332->result(correctedJet); + double gECF461 = m_gECF461->result(correctedJet); + double gECF322 = m_gECF322->result(correctedJet); + double gECF331 = m_gECF331->result(correctedJet); + double gECF422 = m_gECF422->result(correctedJet); + double gECF441 = m_gECF441->result(correctedJet); + double gECF212 = m_gECF212->result(correctedJet); + double gECF321 = m_gECF321->result(correctedJet); + double gECF311 = m_gECF311->result(correctedJet); + + double L1 = -999.0, L2 = -999.0, L3 = -999.0, L4 = -999.0, L5 = -999.0; + if (std::abs(gECF212) > 1e-12) { + L1 = gECF321 / gECF212; + L2 = gECF331 / sqrt(gECF212*gECF212*gECF212); + } + if (std::abs(gECF331) > 1e-12) { + L3 = gECF311 / pow(gECF331,1./3.); + L4 = gECF322 / pow(gECF331,4./3.); + } + if (std::abs(gECF441) > 1e-12) { + L5 = gECF422/gECF441; + } + + rcjet->auxdecor<float>("gECF332_clstr") = gECF332; + rcjet->auxdecor<float>("gECF461_clstr") = gECF461; + rcjet->auxdecor<float>("gECF322_clstr") = gECF322; + rcjet->auxdecor<float>("gECF331_clstr") = gECF331; + rcjet->auxdecor<float>("gECF422_clstr") = gECF422; + rcjet->auxdecor<float>("gECF441_clstr") = gECF441; + rcjet->auxdecor<float>("gECF212_clstr") = gECF212; + rcjet->auxdecor<float>("gECF321_clstr") = gECF321; + rcjet->auxdecor<float>("gECF311_clstr") = gECF311; + rcjet->auxdecor<float>("L1_clstr") = L1; + rcjet->auxdecor<float>("L2_clstr") = L2; + rcjet->auxdecor<float>("L3_clstr") = L3; + rcjet->auxdecor<float>("L4_clstr") = L4; + rcjet->auxdecor<float>("L5_clstr") = L5; + } + + // lets also store the rebuilt jet in case we need it later + if (m_useJSS || m_useAdditionalJSS) { + rcjet->auxdecor<float>("RRCJet_pt") = correctedJet.pt(); + rcjet->auxdecor<float>("RRCJet_eta") = correctedJet.eta(); + rcjet->auxdecor<float>("RRCJet_phi") = correctedJet.phi(); + rcjet->auxdecor<float>("RRCJet_e") = correctedJet.e(); + }// end of if useAdditional JSS + }//end of check on cluster size + } // end rcjet loop + } // //m_useJSS || m_useAdditionalJSS + } //if (!evtStore()->contains<xAOD::JetContainer>(m_OutputJetContainer)) + + + // // } + + return StatusCode::SUCCESS; +} // end execute() + +StatusCode ParticleLevelRCJetObjectLoader::finalize() { + return StatusCode::SUCCESS; +} + +bool ParticleLevelRCJetObjectLoader::passSelection(const xAOD::Jet& jet) const { + /* + Check if the re-clustered jet passes selection. + Right now, this only does something for |eta| because + pT is taken care of in the re-clustering tool. When + small-r jet mass is available (calibrated+uncertainties), + we can cut on that. + */ + // [pT] calibrated to >~ 22 GeV (23 Jan 2016) + if (jet.pt() < m_ptcut) return false; + + // [|eta|] calibrated < 2.5 + if (std::abs(jet.eta()) > m_etamax) return false; + + // small-r jet mass not calibrated and no uncertainties + + return true; +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelTauObjectSelector.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelTauObjectSelector.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e312a2e4dc9036247e641ed2d00f7e9f8071db47 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/ParticleLevelTauObjectSelector.cxx @@ -0,0 +1,55 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopParticleLevel/ParticleLevelTauObjectSelector.h" + +#include "MCTruthClassifier/MCTruthClassifierDefs.h" +#include "TopParticleLevel/TruthTools.h" + +namespace top { + ParticleLevelTauObjectSelector::ParticleLevelTauObjectSelector(Options opt /* = Options() */) + : m_opt(opt) { /* Deliberately Empty */} + + bool ParticleLevelTauObjectSelector::apply(const xAOD::TruthParticle& truthParticle) { + // Obtain the particle type and particle origin from the decoration + // created by the MCTruthClassifier. For legacy reasons, try both + // decoration names. + unsigned int type; + + if (truthParticle.isAvailable<unsigned int>("particleType")) { + type = truthParticle.auxdata<unsigned int>("particleType"); + } else if (truthParticle.isAvailable<unsigned int>("classifierParticleType")) { + type = truthParticle.auxdata<unsigned int>("classifierParticleType"); + } else { + throw std::runtime_error { + "Could not obtain MCTruthClassifier result decoration." + }; + } + + // -------------------------------------------------- + // Accept muons iff they do not come from a hadron + using namespace MCTruthPartClassifier; + if (type != ParticleType::IsoTau) { + return false; + } + + // -------------------------------------------------- + // Apply kinematic cut on the dressed pT: + // must exceed 25 GeV + if (truthParticle.pt() < m_opt.pt_min) { + return false; + } + + // -------------------------------------------------- + // Apply kinematic cut on the dressed eta: + // must be less than or equal to 2.5 + if (std::fabs(truthParticle.eta()) > m_opt.eta_max) { + return false; + } + + // -------------------------------------------------- + // Everything that reaches this point has passed the selection + return true; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/TruthTools.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/TruthTools.cxx index b10ea4e16386126383ae8eb4d67d95814a75da2a..823acab9e818ac8c722e0a625978736a899989ea 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/TruthTools.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/Root/TruthTools.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // Filename: TruthTools.cxx // Description: @@ -8,8 +8,12 @@ // Created: Wed Feb 4 11:05:43 2015 #include "TopParticleLevel/TruthTools.h" +#include "TopEvent/EventTools.h" #include "xAODTruth/TruthVertex.h" +#include "AthContainers/AuxElement.h" +#include "xAODTruth/xAODTruthHelpers.h" +#include "xAODTruth/TruthParticleContainer.h" #include "TruthUtils/PIDHelpers.h" @@ -17,311 +21,1119 @@ #include <string> #include <sstream> #include <functional> +#include <iostream> + +#include "TopParticleLevel/MsgCategory.h" + +using namespace TopParticleLevel; + namespace top { - namespace truth { - - void printDecayChain( const xAOD::TruthParticle * truthPart, - std::ostream & os /* = std::cout */, - const std::string & prefix /* = "" */ ){ - // Protect against a faulty production vertex reference. - if ( not truthPart->prodVtx() ){ - os << prefix << "[" << truthPart->pdgId() << " <- NULL]" << '\n'; - return; - } - - const xAOD::TruthParticle * parent{ truthPart->prodVtx()->incomingParticle( 0 ) }; - os << prefix << "[" << truthPart->pdgId(); - while ( parent ){ - os << " <- " << parent->pdgId(); - if ( parent->prodVtx() ){ - parent = parent->prodVtx()->incomingParticle( 0 ); - } - else { - break; - } - } - os << "]" << '\n'; - } - - - bool isFrom( const xAOD::TruthParticle * truthParticle, - const std::vector<int> & parentPDGIds, - bool bOnlyDirect /* = false */ ){ - // If the input does not have aproper production vertex reference or - // there are no incoming particle to the production vertex, directly - // return false - if ( ! truthParticle->hasProdVtx() || - ! truthParticle->prodVtx() || - truthParticle->prodVtx()->nIncomingParticles() == 0 ) { - return false; - } - - // The current production vertex - const xAOD::TruthVertex * prodVtx = truthParticle->prodVtx(); - // The previous production vertex (initialised to the current - // production vertex) - const xAOD::TruthVertex * prevProdVtx = prodVtx; - - auto numIncoming = prodVtx->nIncomingParticles(); - for ( std::size_t motherIndex = 0; - motherIndex < numIncoming; - ++motherIndex ){ - - const xAOD::TruthParticle * mother= nullptr; - int motherPdgId = truthParticle->pdgId(); - - // Ascend through the decay chain until we find the "actual" - // decay, i.e. a change in the PDG ID. This skips all the - // non-decay truth table entries which come from "particle - // evolution" rather than physical decay - while ( truthParticle->pdgId() == motherPdgId ) { - mother = prodVtx->incomingParticle( motherIndex ); - if ( mother ) { - motherPdgId = mother->pdgId(); - } - else { break; } - - if ( truthParticle->pdgId() != motherPdgId ) { break; } - - // Include protection against cyclic or broken reference - // chains which can occur in SHERPA samples - if( ! mother->hasProdVtx() ) { break; } - if ( prevProdVtx == mother->prodVtx() ) { break; } - - // Update the previous / current production vertex references - prevProdVtx = prodVtx; - prodVtx = mother->prodVtx(); - - // safeguard - if ( ! prodVtx || prodVtx->nIncomingParticles() == 0 ) { break; } - } - - // Check that the mother pointer is valid. If it is not valid, then - // the particle could not possibly come from any of the requested - // PDG Ids, hence return false - if ( ! mother ){ return false; } - - // If the mother PDG ID is in the parentPDGIds collection, then return true - if ( std::find( parentPDGIds.begin(), parentPDGIds.end(), motherPdgId ) != parentPDGIds.end() ){ - return true; - } - - // If we allow chained matching (I.e. not only _direct_ decays) and - // the mother particle does come from the request PDG ID(s), return true - if ( ! bOnlyDirect && isFrom( mother, parentPDGIds, bOnlyDirect ) ){ - return true; - } - } - - // If we did't find an ancestor with the requested pdg id, return false - return false; - } - - bool isFromWZDecay( const xAOD::TruthParticle * truthParticle, - bool bOnlyDirect /* = false */ ) { - // If the input does not have aproper production vertex reference or - // there are no incoming particle to the production vertex, directly - // return false - if ( ! truthParticle->hasProdVtx() || - ! truthParticle->prodVtx() || - truthParticle->prodVtx()->nIncomingParticles() == 0 ) { - return false; - } - - // The current production vertex - const xAOD::TruthVertex * prodVtx = truthParticle->prodVtx(); - // The previous production vertex (initialised to the current - // production vertex) - const xAOD::TruthVertex * prevProdVtx = prodVtx; - - - auto numIncoming = prodVtx->nIncomingParticles(); - for ( std::size_t motherIndex = 0; - motherIndex < numIncoming; - ++motherIndex ){ - - const xAOD::TruthParticle * mother = nullptr; - int motherAbsPdgId = truthParticle->absPdgId(); - - // Ascend through the decay chain until we find the "actual" - // decay, i.e. a change in the PDG ID. This skips all the - // non-decay truth table entries which come from "particle - // evolution" rather than physical decay - while ( truthParticle->absPdgId() == motherAbsPdgId ) { - mother = prodVtx->incomingParticle( motherIndex ); - if ( mother ) { - motherAbsPdgId = mother->absPdgId(); - } - else { break; } - - if ( truthParticle->absPdgId() != motherAbsPdgId ) { break; } - - // Include protection against cyclic or broken reference - // chains which can occur in SHERPA samples - if( ! mother->hasProdVtx() ) { break; } - if ( prevProdVtx == mother->prodVtx() ) { break; } - - // Update the previous / current production vertex references - prevProdVtx = prodVtx; - prodVtx = mother->prodVtx(); - - // safeguard - if ( ! prodVtx || prodVtx->nIncomingParticles() == 0 ) { break; } - } - - // Check that the mother pointer is valid. If it is not valid, then - // the particle could not possibly come from any of the requested - // PDG Ids, hence return false - if ( ! mother ){ return false; } - - // If the direct physical decay in the MC record was from a Z or W - // boson to the truth particle then return true - // Otherwise perform a vertex-based identification of W/Z's - if ( motherAbsPdgId == 23 || motherAbsPdgId == 24 ){ - return true; - } - - // The following vertex-based identification of W/Z's is needed - // for SHERPA samples where the W/Z particle is not explicitly - // in the particle record. At this point if we have a valid - // vertex, it should be a true decay vertex. - // - // If it is a W or Z then two of those decay products should be - // lepton / neutrino pair corresponding to the transitions - // W+ -> l+ nu - // W- -> l- nu~ - // Z -> l+ l- - // Z -> nu nu~ - // Hence loop through the outgoing particles of the truth vertex - // and check that the vertex matches the requirement. We - // simplify this check by just counting the number of leptonic - // outgoing particles which should be equal to 2. It is assumed - // that the MC generator does not produce unphysical decays. - // - // Furthermore, prompt W/Z's should come from a vertex with more - // than one incoming particle. Consequently, test this - // requirement prior to checking the outgoing states. - int nDecay = 0; - if ( prodVtx && prodVtx->nIncomingParticles() > 1 ) { - for ( const auto & child : prodVtx->outgoingParticleLinks() ){ - if ( ( * child )->absPdgId() > 10 && - ( * child )->absPdgId() < 17 ) { - nDecay++; - } - } - } - - // There must be exactly two leptonic outgoing particles in that vertex - if ( nDecay == 2 ){ - return true; - } - - // If we allow chained matching (I.e. not only _direct_ decays) and - // the mother particle does come from a W / Z, return true - if ( ! bOnlyDirect && isFromWZDecay( mother, bOnlyDirect ) ){ - return true; - } - } - - // We did not find any W / Z in the ancestry of the input particle -> - // return false - return false; - } - - bool isLeptonFromTau( const xAOD::TruthParticle * truthParticle ){ - // If the input particle is not a lepton directly terminate the - // algorithm retunring false - if ( truthParticle->absPdgId() != 11 && - truthParticle->absPdgId() != 12 && - truthParticle->absPdgId() != 13 && - truthParticle->absPdgId() != 14 && - truthParticle->absPdgId() != 15 && - truthParticle->absPdgId() != 16 ) { - return false; - } - return isFrom( truthParticle, { 15, -15 }, true ); - } - - bool isNotFromHadron( const xAOD::TruthParticle * truthParticle, - bool bOnlyDirect /* = false */, - bool bTauIsHadron /* = false */ ){ - // If there is no production vertex, either something is wrong, or - // we are at the beginning of the record. However, either way, the - // particle does not come from a hadron, hence return true. - if ( ! truthParticle->hasProdVtx() || - ! truthParticle->prodVtx() || - truthParticle->prodVtx()->nIncomingParticles() == 0 ) { - return true; - } - - // The current production vertex - const xAOD::TruthVertex * prodVtx = truthParticle->prodVtx(); - // The previous production vertex (initialised to the current - // production vertex) - const xAOD::TruthVertex * prevProdVtx = prodVtx; - - // Loop all the particles going into the production vertex of the - // current truth particle. - // * If the mother of any of the is a physical hadron return false - // * If the mother of any of them descends from a physical return false - // * Otherwise return true - auto numIncoming = prodVtx->nIncomingParticles(); - for ( std::size_t motherIndex = 0; - motherIndex < numIncoming; - ++motherIndex ){ - - int motherPdgId = truthParticle->pdgId(); - const xAOD::TruthParticle * mother = nullptr; - - // Ascend through the decay chain until we find the "actual" - // decay, i.e. a change in the PDG ID. This skips all the - // non-decay truth table entries which come from "particle - // evolution" rather than physical decay - while ( truthParticle->pdgId() == motherPdgId ) { - mother = prodVtx->incomingParticle( motherIndex ); - if ( mother ) { - motherPdgId = mother->pdgId(); - } - else { break; } - - // Include protection against cyclic or broken reference - // chains which can occur in SHERPA samples - if( ! mother->hasProdVtx() ) { break; } - if ( prevProdVtx == mother->prodVtx() ) { break; } - - // Update the previous / current production vertex references - prevProdVtx = prodVtx; - prodVtx = mother->prodVtx(); - - // safeguard - if ( ! prodVtx || prodVtx->nIncomingParticles() == 0 ) { break; } - } - - // Check that the mother pointer is valid. If it is not valid, then - // the particle could not possibly come from a hadron, hence return - // true - if ( ! mother ){ return true; } - - // If the mother particle is a "physical decayed" particle (HepMC - // status code) and a hadron, then return false. - if ( mother->status() == 2 && - ( MC::PID::isHadron( motherPdgId ) || - ( bTauIsHadron && MC::PID::isTau( motherPdgId ) ) ) ){ - return false; - } - // } else { - // std::cout << "Mother is: " << motherPdgId << ", " << mother->status() << std::endl; - // } - - // If we allow chained matching (I.e. not only _direct_ decays) and - // the mother particle does come from a hadron, return false - if ( ! bOnlyDirect && ! isNotFromHadron( mother, bOnlyDirect, bTauIsHadron ) ){ - return false; - } - } - // No hadronic && physical parents - return true; - } + namespace truth { + + + void initCommonMuonHistoryInfo(const xAOD::IParticle* muon, bool doPartonHistory) + { + muon->auxdecor<top::LepParticleOriginFlag>("LepParticleOriginFlag") = top::LepParticleOriginFlag::MissingTruthInfo; + muon->auxdecor<const xAOD::TruthParticle*>("truthMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthFirstNonLeptonMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthBMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthCMotherLink") = 0; + + if(doPartonHistory) + { + muon->auxdecor<top::LepPartonOriginFlag>("LepPartonOriginFlag") = top::LepPartonOriginFlag::MissingTruthInfo; + muon->auxdecor<const xAOD::TruthParticle*>("truthPartonMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthWMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthZMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthPhotonMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink") = 0; + muon->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink") = 0; + } + } + + void initRecoMuonHistoryInfo(const xAOD::Muon* muon, bool doPartonHistory) + { + muon->auxdecor<bool>("hasRecoMuonHistoryInfo")=false; + muon->auxdecor<const xAOD::TruthParticle*>("truthMuonLink") = 0; + initCommonMuonHistoryInfo(muon,doPartonHistory); + } + void initTruthMuonHistoryInfo(const xAOD::TruthParticle* truthmu, bool doPartonHistory) + { + truthmu->auxdecor<bool>("hasTruthMuonHistoryInfo")=false; + if(doPartonHistory) truthmu->auxdecor<bool>("hasTruthMuonPartonHistoryInfo")=false; + initCommonMuonHistoryInfo(truthmu,doPartonHistory); + + } + + void copyRecoMuonHistoryInfo(const xAOD::Muon* m_origin, const xAOD::Muon* m_target) + { + copyCommonMuonHistoryInfo(m_origin,m_target); + m_target->auxdecor<bool>("hasRecoMuonHistoryInfo") = m_origin->auxdecor<bool>("hasRecoMuonHistoryInfo"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthMuonLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthMuonLink"); + } + + void copyTruthMuonHistoryInfo(const xAOD::TruthParticle* tm_origin, const xAOD::TruthParticle* tm_target) + { + copyCommonMuonHistoryInfo(tm_origin,tm_target); + tm_target->auxdecor<bool>("hasTruthMuonHistoryInfo")= tm_origin->auxdecor<bool>("hasTruthMuonHistoryInfo"); + tm_target->auxdecor<bool>("hasTruthMuonPartonHistoryInfo")= tm_origin->auxdecor<bool>("hasTruthMuonPartonHistoryInfo"); + } + + void copyCommonMuonHistoryInfo(const xAOD::IParticle* m_origin, const xAOD::IParticle* m_target) + { + if(!m_origin->isAvailable<top::LepParticleOriginFlag>("LepParticleOriginFlag")) + { + ATH_MSG_ERROR(" top::truth::copyCommonMuonHistoryInfo called with an origin muon which has no truth info!"); + throw; + } + m_target->auxdecor<top::LepParticleOriginFlag>("LepParticleOriginFlag") = m_origin->auxdecor<top::LepParticleOriginFlag>("LepParticleOriginFlag"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthFirstNonLeptonMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthFirstNonLeptonMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthBMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthBMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthCMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthCMotherLink"); + + if(m_origin->isAvailable<top::LepPartonOriginFlag>("LepPartonOriginFlag")) + { + m_target->auxdecor<top::LepPartonOriginFlag>("LepPartonOriginFlag") = m_origin->auxdecor<top::LepPartonOriginFlag>("LepPartonOriginFlag"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthPartonMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthPartonMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthWMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthWMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthZMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthZMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthPhotonMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthPhotonMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink"); + m_target->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink") = m_origin->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink"); + } + } + + const xAOD::TruthParticle* getTruthMuonAssociatedToRecoMuon(const xAOD::Muon* muon) + { + if(!muon) return 0; + const xAOD::TrackParticle* track = muon->primaryTrackParticle(); + if(!track) return 0; + + const xAOD::TruthParticle* truthmu= xAOD::TruthHelpers::getTruthParticle(*track); + if(!truthmu) return 0; + if(!truthmu->isMuon()) return 0; //note that the truth particle associated with a muon can be e.g. a pion/kaon in some cases (since pion/kaon decays are not done at generator level, but at simulation level), we ignore these cases + + return truthmu; + } + + void getRecoMuonHistory(const xAOD::Muon* muon, bool doPartonHistory, SampleXsection::showering shAlgo, bool verbose) + { + + if(verbose) ATH_MSG_INFO("getRecoMuonHistory:: ---------------entering in function-----------------"); + if(!muon) return; + + if(verbose) + { + //we retrieve the origin from the MCClassifier, it's useful for crosschecks; see https://gitlab.cern.ch/atlas/athena/blob/21.2/PhysicsAnalysis/MCTruthClassifier/MCTruthClassifier/MCTruthClassifierDefs.h + int origin=0; + const static SG::AuxElement::Accessor<int> origmu("truthOrigin"); + if (origmu.isAvailable(*muon)) origin = origmu(*muon); + + ATH_MSG_INFO("getRecoMuonHistory::called on muon with pt="<<muon->pt()<<" origin="<<origin); + } + + if(doPartonHistory && shAlgo!=SampleXsection::pythia8 && shAlgo!=SampleXsection::herwigpp) + { + static int nWarnings=0; + if(nWarnings<10 || verbose) + { + ATH_MSG_WARNING("top::truth::getRecoMuonHistory : partonHistory can be checked only for pythia8 and herwigpp showering algorithms, SoftMuonAdditionalTruthInfoCheckPartonOrigin will be ignored for this sample"); + nWarnings++; + } + doPartonHistory=false; + } + + if(!muon->isAvailable<bool>("hasRecoMuonHistoryInfo")) //add default values + { + initRecoMuonHistoryInfo(muon,doPartonHistory); + } + else if(muon->auxdecor<bool>("hasRecoMuonHistoryInfo")) + { + if(verbose) ATH_MSG_INFO("getRecoMuonHistory::we already ran on this muon, exiting"); + return; //this means we already ran on this muon in some way + } + muon->auxdecor<bool>("hasRecoMuonHistoryInfo")=true; + + //first we retrieve the truth muon associated with the reco one + const xAOD::TruthParticle* truthmu = muon->auxdecor<const xAOD::TruthParticle*>("truthMuonLink"); //pointer to the truth muon associated with the reco muon + + if(!truthmu) truthmu=top::truth::getTruthMuonAssociatedToRecoMuon(muon); + + if(verbose) ATH_MSG_INFO("getRecoMuonHistory:: retrieved truth muon pointer="<<truthmu); + if(!truthmu) return; + + muon->auxdecor<top::LepParticleOriginFlag>("LepParticleOriginFlag") = top::LepParticleOriginFlag::Unknown; + if(doPartonHistory) muon->auxdecor<top::LepPartonOriginFlag>("LepPartonOriginFlag") = top::LepPartonOriginFlag::Unknown; + + if(verbose) + { + ATH_MSG_INFO("getRecoMuonHistory::---truth decay chain---"); + printDecayChain(truthmu, msg(MSG::Level::INFO)); + } + + getTruthMuonHistory(truthmu, doPartonHistory, shAlgo, verbose); + //we attach the truth muon to the reco muon + copyCommonMuonHistoryInfo(truthmu,muon); + + muon->auxdecor<const xAOD::TruthParticle*>("truthMuonLink") = truthmu; + + if(verbose) + { + ATH_MSG_INFO("getRecoMuonHistory:: written LepParticleOriginFlag decoration = "<<static_cast<int>(muon->auxdecor<top::LepParticleOriginFlag>("LepParticleOriginFlag"))); + if(doPartonHistory) ATH_MSG_INFO("getRecoMuonHistory:: written LepPartonOriginFlag decoration = "<<static_cast<int>(muon->auxdecor<top::LepPartonOriginFlag>("LepPartonOriginFlag"))); + ATH_MSG_INFO("getRecoMuonHistory:: exiting function"); + } + return; + + } + + ////getTruthMuonHistory///// + void getTruthMuonHistory(const xAOD::TruthParticle* truthmu, bool doPartonHistory, SampleXsection::showering shAlgo, bool verbose) + { + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: entering in function"); + + if(!truthmu) + { + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: -> called on empty truth muon"); + return; + } + if(!(truthmu->isMuon())) + { + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: -> called on non-muon particle"); + return; + } + + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: -> called on truth particle with pdgId="<<truthmu->pdgId()<<" barcode="<<truthmu->barcode()<<" status="<<truthmu->status()<<" pt="<<truthmu->pt()); + + if(!truthmu->isAvailable<bool>("hasTruthMuonHistoryInfo")) //add default values + { + initTruthMuonHistoryInfo(truthmu,doPartonHistory); + } + else if(truthmu->auxdecor<bool>("hasTruthMuonHistoryInfo")) + { + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: -> we already ran on this truth muon, exiting"); + return; + } + truthmu->auxdecor<bool>("hasTruthMuonHistoryInfo")=true; + + top::LepParticleOriginFlag lepParticleOriginFlag=top::LepParticleOriginFlag::Unknown; //flag defined in TopEvent/EventTools.h + const xAOD::TruthParticle* truthmu_mother=0; //direct mother of the muon + const xAOD::TruthParticle* truthmu_firstNonLeptonMother=0; //in case of X->muon or X->tau->muon, this will always contain X + const xAOD::TruthParticle* truthmu_Bmother=0; //first bottom hadron encountered when going through ancestors + const xAOD::TruthParticle* truthmu_Cmother=0; //first charmed hadron encountered when going through ancestors + + const xAOD::TruthParticle* initial_mu = getInitialStateParticle(truthmu); + if(initial_mu) truthmu_mother= initial_mu->parent(0); + + if(truthmu_mother && abs(truthmu_mother->pdgId())!=13) //let's then look at the history of this muon + { + + if(!truthmu_mother->isLepton()) truthmu_firstNonLeptonMother=truthmu_mother; //basically all cases apart from tau->muon + + if(verbose) ATH_MSG_INFO("getTruthMuonHistory::mother pdgId="<<truthmu_mother->pdgId()<<" isB="<<truthmu_mother->isBottomHadron()<<" isC="<<truthmu_mother->isCharmHadron()<<" isLight="<<truthmu_mother->isLightHadron()); + + if(truthmu_mother->isLightHadron()) lepParticleOriginFlag=top::LepParticleOriginFlag::FromLightHadron; //in this case we set the muon as coming from a light hadron and we don't investigate further + else if(truthmu_mother->isW()) //W->munu + { + lepParticleOriginFlag=top::LepParticleOriginFlag::FromLeptonicW; + } + else if(truthmu_mother->isZ()) //Z->mumu + { + lepParticleOriginFlag=top::LepParticleOriginFlag::FromLeptonicZ; + } + else if(truthmu_mother->isPhoton()) //gamma*->mumu decay + { + lepParticleOriginFlag=top::LepParticleOriginFlag::FromPhoton; + } + else if(truthmu_mother->isHiggs()) + { + lepParticleOriginFlag=top::LepParticleOriginFlag::FromHiggs; + } + else if(truthmu_mother->isBSM()) + { + lepParticleOriginFlag=top::LepParticleOriginFlag::FromBSM; + } + else if(truthmu_mother->isTau()) //muon from tau + { + lepParticleOriginFlag=top::truth::getTruthMuonFromTauHistory(truthmu_mother,truthmu_Bmother,truthmu_Cmother,truthmu_firstNonLeptonMother,verbose); + } + else if(truthmu_mother->isBottomHadron()) //muon from B->mu+X decay + { + lepParticleOriginFlag=top::LepParticleOriginFlag::FromB; + truthmu_Bmother=truthmu_mother; + } + else if(truthmu_mother->isCharmHadron()) //muon from D->mu+X decay, now we have to understand where the D is coming from + { + truthmu_Cmother=truthmu_mother; + lepParticleOriginFlag=top::truth::getTruthMuonFromCharmHistory(truthmu_Bmother,truthmu_Cmother,verbose); + }//end of if + }//end of if(truthmu_mother) + + if(verbose) + { + ATH_MSG_INFO("getTruthMuonHistory::LepParticleOriginFlag="<<static_cast<int>(lepParticleOriginFlag)); + if(truthmu) ATH_MSG_INFO("getTruthMuonHistory::-->truth muon pdgId="<<truthmu->pdgId()<<" barcode="<<truthmu->barcode()<<" pt="<<truthmu->pt()); + else ATH_MSG_INFO("getTruthMuonHistory::-->truth muon not found"); + if(truthmu_mother) ATH_MSG_INFO("getTruthMuonHistory::-->truth muon mother pdgId="<<truthmu_mother->pdgId()<<" barcode="<<truthmu_mother->barcode()<<" pt="<<truthmu_mother->pt()); + else ATH_MSG_INFO("getTruthMuonHistory::-->truth muon mother not found"); + if(truthmu_firstNonLeptonMother) ATH_MSG_INFO("getTruthMuonHistory::-->truthmu_firstNonLeptonMother pdgId="<<truthmu_firstNonLeptonMother->pdgId()<<" barcode="<<truthmu_firstNonLeptonMother->barcode()<<" pt="<<truthmu_firstNonLeptonMother->pt()); + else ATH_MSG_INFO("getTruthMuonHistory::-->truthmu_firstNonLeptonMother not found"); + if(truthmu_Bmother) ATH_MSG_INFO("getTruthMuonHistory::-->truth muon Bmother pdgId="<<truthmu_Bmother->pdgId()<<" barcode="<<truthmu_Bmother->barcode()<<" pt="<<truthmu_Bmother->pt()); + else ATH_MSG_INFO("getTruthMuonHistory::-->truth muon Bmother not found"); + if(truthmu_Cmother) ATH_MSG_INFO("getTruthMuonHistory::-->truth muon Cmother pdgId="<<truthmu_Cmother->pdgId()<<" barcode="<<truthmu_Cmother->barcode()<<" pt="<<truthmu_Cmother->pt()); + else ATH_MSG_INFO("getTruthMuonHistory::-->truth muon Cmother not found"); + } + + //we decorate also on the truth muon associated with the reco one, because in this way if the truth muon was already decorated in another copy of the muon (for systematics) we avoid losing time. + truthmu->auxdecor<top::LepParticleOriginFlag>("LepParticleOriginFlag") = lepParticleOriginFlag; + truthmu->auxdecor<const xAOD::TruthParticle*>("truthFirstNonLeptonMotherLink") = truthmu_firstNonLeptonMother; + truthmu->auxdecor<const xAOD::TruthParticle*>("truthMotherLink") = truthmu_mother; + truthmu->auxdecor<const xAOD::TruthParticle*>("truthBMotherLink") = truthmu_Bmother; + truthmu->auxdecor<const xAOD::TruthParticle*>("truthCMotherLink") = truthmu_Cmother; + + if(doPartonHistory) top::truth::getTruthMuonPartonHistory(truthmu, lepParticleOriginFlag, truthmu_Bmother, truthmu_Cmother, truthmu_firstNonLeptonMother, shAlgo, verbose); + + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: exiting from function"); + + return; + } + + /////getTruthMuonPartonHistory///// + void getTruthMuonPartonHistory(const xAOD::TruthParticle* truthmu, top::LepParticleOriginFlag lepParticleOriginFlag, const xAOD::TruthParticle* truthmu_Bmother, const xAOD::TruthParticle* truthmu_Cmother, const xAOD::TruthParticle* truthmu_firstNonLeptonMother, SampleXsection::showering shAlgo, bool verbose) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: entering in function"); + + if(!truthmu && verbose) + { + ATH_MSG_INFO("getTruthMuonPartonHistory:: -> called on empty truth muon"); + return; + } + + if(!truthmu->isAvailable<bool>("hasTruthMuonPartonHistoryInfo"))//default values + { + initTruthMuonHistoryInfo(truthmu,true); + } + else if(truthmu->auxdecor<bool>("hasTruthMuonPartonHistoryInfo")) + { + if(verbose) ATH_MSG_INFO("getTruthMuonHistory:: -> we already ran on this truth muon, exiting"); + return; + } + truthmu->auxdecor<bool>("hasTruthMuonPartonHistoryInfo")=true; + + const xAOD::TruthParticle* truthmu_mother=truthmu_firstNonLeptonMother; + + if(!truthmu_mother) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> no muon mother available, returning"); + return; + } + if(lepParticleOriginFlag==top::LepParticleOriginFlag::MissingTruthInfo || lepParticleOriginFlag==top::LepParticleOriginFlag::FromLightHadron) + { + + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from light hadron, will not fill info"); + return; + } + + top::LepPartonOriginFlag lepPartonOriginFlag=top::LepPartonOriginFlag::Unknown; + + //this is the priority we use to look for parents in order: top, higgs, BSM, W/Z, gamma* + auto get_priority = [](const xAOD::TruthParticle* p) -> int { + if(!p) return 999; + if(p->isTop()) return 0; + if(p->isHiggs()) return 10; + if(p->isBSM()) return 15; + if(p->isW() || p->isZ()) return 20; + if(p->isPhoton()) return 25; + return 100; + }; + + if(truthmu_mother->isTop()) // shouldn't happen, but maybe some generators don't store intermediate bosons + { + truthmu->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink") = truthmu_mother; + truthmu->auxdecor<const xAOD::TruthParticle*>("truthPartonMotherLink") = truthmu_mother; + if(truthmu_mother->pdgId()>0) lepPartonOriginFlag=top::LepPartonOriginFlag::FromTopViaLeptonicBoson; + else lepPartonOriginFlag=top::LepPartonOriginFlag::FromAntiTopViaLeptonicBoson; + } + else if(truthmu_mother->isHiggs()) + { + truthmu->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink") = truthmu_mother; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromHiggs; + } + else if(truthmu_mother->isBSM()) + { + truthmu->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink") = truthmu_mother; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromBSM; + } + else if(truthmu_mother->isW() || truthmu_mother->isZ() || truthmu_mother->isPhoton() ) //the muon is coming from a leptonically decaying boson (eventually via a boson->tau->mu) + { + lepPartonOriginFlag=top::LepPartonOriginFlag::FromLeptonicBoson; //this is the basic info if we don't find further infromation + + if(truthmu_mother->isW()) truthmu->auxdecor<const xAOD::TruthParticle*>("truthWMotherLink") = truthmu_mother; + else if(truthmu_mother->isZ()) truthmu->auxdecor<const xAOD::TruthParticle*>("truthZMotherLink") = truthmu_mother; + else if(truthmu_mother->isPhoton()) truthmu->auxdecor<const xAOD::TruthParticle*>("truthPhotonMotherLink") = truthmu_mother; + + //then we check in case we can find the mother of the boson + const xAOD::TruthParticle* initialStateBoson=top::truth::getInitialStateParticle(truthmu_mother,verbose); + const xAOD::TruthParticle* bosonOrigin=0; + unsigned int bosonOrigin_priority=999; + + if(initialStateBoson) + { + for(unsigned int ip=0; ip<initialStateBoson->nParents(); ip++) + { + const xAOD::TruthParticle* parent=initialStateBoson->parent(ip); + if(!parent) continue; + + unsigned int parent_priority=get_priority(parent); + if(parent_priority<bosonOrigin_priority) + { + bosonOrigin_priority=parent_priority; + bosonOrigin=parent; + } + } + } + if(bosonOrigin && bosonOrigin->isTop()) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from boson from top"); + + truthmu->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink") = bosonOrigin; + if(bosonOrigin->pdgId()>0) lepPartonOriginFlag=top::LepPartonOriginFlag::FromTopViaLeptonicBoson; + else lepPartonOriginFlag=top::LepPartonOriginFlag::FromAntiTopViaLeptonicBoson; + } + else if(bosonOrigin && bosonOrigin->isHiggs()) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from boson from higgs"); + truthmu->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink") = bosonOrigin; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromHiggsViaLeptonicBosonToHF; + } + else if(bosonOrigin && bosonOrigin->isBSM()) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from boson from BSM"); + truthmu->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink") = bosonOrigin; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromBSMViaLeptonicBosonToHF; + } + else + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from boson not from top or higgs"); + lepPartonOriginFlag=top::LepPartonOriginFlag::FromLeptonicBoson; + } + } + else if(truthmu_Bmother || truthmu_Cmother) //in this case the muon is not coming from a boson direct decay, we treat only cases from HF hadrons + { + lepPartonOriginFlag=top::LepPartonOriginFlag::FromHFHadronOfUnkownOrigin; //default case + + bool isBHadronMother=truthmu_Bmother; + const xAOD::TruthParticle* hadronMother= isBHadronMother ? truthmu_Bmother : truthmu_Cmother; + const xAOD::TruthParticle* firstHadronMother=getFirstHFHadronOfSameFlavour(hadronMother,verbose); + + if(verbose) + { + ATH_MSG_INFO("getTruthMuonPartonHistory:: isBHadronmother="<<isBHadronMother<<" Bmom="<<truthmu_Bmother<<" Cmom="<<truthmu_Cmother<<" hadMom="<<hadronMother<<" firstHadMom="<<firstHadronMother); + ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from hadron pdgId="<<(hadronMother ? hadronMother->pdgId() : 0)<<", first hadron in chain pdgId="<<(firstHadronMother ? firstHadronMother->pdgId() : 0)); + } + if(firstHadronMother) + { + + const xAOD::TruthParticle* hf_parton_parent=0; + + if(shAlgo == SampleXsection::herwigpp) //in herwig we have pdgId==81 for clusters as hadron parents + { + if(firstHadronMother->parent(0) && firstHadronMother->parent(0)->pdgId()==81) + { + firstHadronMother=getInitialStateParticle(firstHadronMother->parent(0)); + } + } + + //first we find the HF parton that originated the HF hadron + for(unsigned int ip=0; ip<firstHadronMother->nParents(); ip++) + { + const xAOD::TruthParticle* parent=firstHadronMother->parent(ip); + if(!parent) continue; + if(isBHadronMother && abs(parent->pdgId())==5) + { + hf_parton_parent=parent; + break; + } + else if(!isBHadronMother && abs(parent->pdgId())==4) + { + hf_parton_parent=parent; + break; + } + + } + + truthmu->auxdecor<const xAOD::TruthParticle*>("truthPartonMotherLink") =hf_parton_parent; + + //the we get the first HF parton of the evolution chain + const xAOD::TruthParticle* initial_hf_parton_parent=0; + if(hf_parton_parent) initial_hf_parton_parent = top::truth::getInitialStateParticle(hf_parton_parent,verbose); + + //parton ancestor will be the particle/resonance originating the first HF quark + const xAOD::TruthParticle* parton_ancestor=0; + unsigned int parton_ancestor_priority=999; + + if(initial_hf_parton_parent) + { + for(unsigned int ip=0; ip<initial_hf_parton_parent->nParents(); ip++) + { + const xAOD::TruthParticle* parent=initial_hf_parton_parent->parent(ip); + if(!parent) continue; + if(!parton_ancestor) parton_ancestor=parent; + else + { + unsigned int priority =get_priority(parent); + if(priority < parton_ancestor_priority) + { + parton_ancestor_priority=priority; + parton_ancestor=parent; + } + } + } + } + + //finally we (hopefully) know where the HF hadron is originally coming from + if(parton_ancestor && parton_ancestor->isTop()) + { + truthmu->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink") = parton_ancestor; + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from HF from top"); + + if(parton_ancestor->pdgId()>0) lepPartonOriginFlag=top::LepPartonOriginFlag::FromTopViaQuarkToHF; + else lepPartonOriginFlag=top::LepPartonOriginFlag::FromAntiTopViaQuarkToHF; + } + else if(parton_ancestor && parton_ancestor->isHiggs()) + { + truthmu->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink") = parton_ancestor; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromHiggsToHF; + } + else if(parton_ancestor && parton_ancestor->isBSM()) + { + truthmu->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink") = parton_ancestor; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromBSMToHF; + } + else if(parton_ancestor && (parton_ancestor->isW() || parton_ancestor->isZ() || parton_ancestor->isPhoton())) + { + const xAOD::TruthParticle* first_bosonMotherOfHfQuark=top::truth::getInitialStateParticle(parton_ancestor); + + if(parton_ancestor->isW()) truthmu->auxdecor<const xAOD::TruthParticle*>("truthWMotherLink") = parton_ancestor; + else if(parton_ancestor->isZ()) truthmu->auxdecor<const xAOD::TruthParticle*>("truthZMotherLink") = parton_ancestor; + else if(parton_ancestor->isPhoton()) truthmu->auxdecor<const xAOD::TruthParticle*>("truthPhotonMotherLink") = parton_ancestor; + + const xAOD::TruthParticle* bosonOrigin=0; + unsigned int bosonOrigin_priority=999; + + if(first_bosonMotherOfHfQuark) + { + for(unsigned int ip=0; ip<first_bosonMotherOfHfQuark->nParents(); ip++) + { + const xAOD::TruthParticle* parent=first_bosonMotherOfHfQuark->parent(ip); + if(!parent) continue; + + unsigned int priority =get_priority(parent); + if(priority<bosonOrigin_priority) + { + bosonOrigin=parent; + bosonOrigin_priority=priority; + } + } + if(bosonOrigin && bosonOrigin->isTop()) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from HF from boson from top"); + truthmu->auxdecor<const xAOD::TruthParticle*>("truthTopMotherLink") = bosonOrigin; + + if(bosonOrigin->pdgId()>0) lepPartonOriginFlag=top::LepPartonOriginFlag::FromTopViaHadronicBosonToHF; + else lepPartonOriginFlag=top::LepPartonOriginFlag::FromAntiTopViaHadronicBosonToHF; + } + else if(bosonOrigin && bosonOrigin->isHiggs()) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from HF from boson from higgs"); + truthmu->auxdecor<const xAOD::TruthParticle*>("truthHiggsMotherLink") = bosonOrigin; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromHiggsViaHadronicBosonToHF; + } + else if(bosonOrigin && bosonOrigin->isBSM()) + { + if(verbose) ATH_MSG_INFO("getTruthMuonPartonHistory:: -> muon from HF from boson from BSM"); + truthmu->auxdecor<const xAOD::TruthParticle*>("truthBSMMotherLink") = bosonOrigin; + lepPartonOriginFlag=top::LepPartonOriginFlag::FromBSMViaHadronicBosonToHF; + } + else + { + lepPartonOriginFlag=top::LepPartonOriginFlag::FromHadronicBosonToHF; //not sure where this is coming from + } + } + }//end of V->HF->muon case + + }//end of HF->muon case + + }//end of non-bosonic case + + truthmu->auxdecor<top::LepPartonOriginFlag>("LepPartonOriginFlag") = lepPartonOriginFlag; + + if(verbose) ATH_MSG_INFO("getTruthMuonHistory::------> LepPartonOriginFlag="<<static_cast<int>(lepPartonOriginFlag)); + + return; + + }//end of getTruthMuonPartonHistory + + /////getTruthMuonFromCharmHistory///// + top::LepParticleOriginFlag getTruthMuonFromCharmHistory(const xAOD::TruthParticle* &truthmu_Bmother, const xAOD::TruthParticle* truthmu_Cmother, bool verbose) + { + if(verbose) ATH_MSG_INFO("called getTruthMuonFromCharmHistory"); + const xAOD::TruthParticle* initial_C_hadron=getFirstHFHadronOfSameFlavour(truthmu_Cmother); //we find the first non-Chadron ancestor of the C-hadron + + if(initial_C_hadron) + { + bool hasBHadronParent=false; + for(unsigned int ip=0; ip<initial_C_hadron->nParents(); ip++) + { + const xAOD::TruthParticle* parent=initial_C_hadron->parent(ip); + if(!parent) continue; + if(parent->isBottomHadron()) + { + hasBHadronParent=true; + truthmu_Bmother=parent; + break; + } + } + if(hasBHadronParent) return top::LepParticleOriginFlag::FromBtoC; + } + + return top::LepParticleOriginFlag::FromC; //we don't know where the C-hadron is coming from + } //end of getTruthMuonFromCharmHistory method + + /////getTruthMuonFromTauHistory///// + top::LepParticleOriginFlag getTruthMuonFromTauHistory(const xAOD::TruthParticle* tau, const xAOD::TruthParticle* &truthmu_Bmother, const xAOD::TruthParticle* &truthmu_Cmother, const xAOD::TruthParticle* &truthmu_firstNonLeptonMother, bool verbose) + { + if(!tau && verbose) + { + ATH_MSG_WARNING("getTruthMuonFromTauHistory called on empty tau"); + return top::LepParticleOriginFlag::FromTau; + } + if(!tau->isTau()) + { + ATH_MSG_ERROR("getTruthMuonFromTauHistory called on non-tau, pdgId"<<(tau->pdgId())); + throw; + } + const xAOD::TruthParticle* initialTau = top::truth::getInitialStateParticle(tau); + if(!initialTau) + { + if(verbose)ATH_MSG_INFO("getTruthMuonFromTauHistory:: could not find initial state tau"); + return top::LepParticleOriginFlag::FromTau; + } + + const xAOD::TruthParticle* tauMother=initialTau->parent(0); + + if(!tauMother) return top::LepParticleOriginFlag::FromTau; //muon from tau, we don't know where the tau is coming from + + if(!tauMother->isLepton()) truthmu_firstNonLeptonMother=tauMother; + + if(tauMother->isW()) //W->taunu with tau->mununu decay + { + return top::LepParticleOriginFlag::FromLeptonicWToTau; + } + if(tauMother->isZ()) //Z->tautau with tau->mununu + { + return top::LepParticleOriginFlag::FromLeptonicZToTau; + } + if(tauMother->isPhoton()) + { + return top::LepParticleOriginFlag::FromPhotonToTau; + } + if(tauMother->isHiggs()) + { + return top::LepParticleOriginFlag::FromHiggsToTau; + } + if(tauMother->isBSM()) + { + return top::LepParticleOriginFlag::FromBSMToTau; + } + if(tauMother->isBottomHadron()) //the muon is from a B->tau+X with tau->mununu decay + { + truthmu_Bmother=tauMother; + return top::LepParticleOriginFlag::FromBtoTau; + } + if(tauMother->isCharmHadron()) //now this is getting complicated, the muon is from e.g. D->tau+X with tau->mununu decay, now we have to understand where the D is coming from... + { + truthmu_Cmother=tauMother; + const xAOD::TruthParticle* initial_C_hadron=getFirstHFHadronOfSameFlavour(truthmu_Cmother); //we find the first non-Chadron ancestor of the C-hadron + + bool hasBHadronParent=false; + + for(unsigned int ip=0; ip<initial_C_hadron->nParents(); ip++) + { + const xAOD::TruthParticle* parent=initial_C_hadron->parent(ip); + if(!parent) continue; + if(parent->isBottomHadron()) + { + hasBHadronParent=true; + truthmu_Bmother=parent; + break; + } + } + if(hasBHadronParent) return top::LepParticleOriginFlag::FromBtoCtoTau; + else //in this case this is coming from D->tau->mu+X or something with no B-hadron ancestor + { + return top::LepParticleOriginFlag::FromCtoTau; + } + }//end of if(tauMother->isCharmHadron()) + + return top::LepParticleOriginFlag::FromTau; //in all other cases we don't know anything apart from the fact that the muon is coming from a tau + }//end of getTruthMuonFromTauHistory method + + //getFirstHadronOfSameFlavour// + const xAOD::TruthParticle* getFirstHFHadronOfSameFlavour(const xAOD::TruthParticle* truthParticle, bool verbose) + { + if(!truthParticle) return 0; + bool isBottomHadron=truthParticle->isBottomHadron(); + bool isCharmHadron=truthParticle->isCharmHadron(); + + if(!(isBottomHadron) && !(isCharmHadron)) + { + if(verbose) ATH_MSG_INFO("getFirstHFHadronOfSameFlavour:: this can be called only on HF hadrons..."); + return 0; + } + const xAOD::TruthParticle* parent=truthParticle; + int niterations=0; + while(parent) + { + if((niterations++)>100) + { + if(verbose) ATH_MSG_INFO("getFirstHFHadronOfSameFlavour:: too many iterations on particle "<<(truthParticle->pdgId())); + return 0; + } + + parent=getInitialStateParticle(parent,verbose); + if(!parent) + { + if(verbose) ATH_MSG_INFO("getFirstHFHadronOfSameFlavour:: initial state particle not found"); + break; + } + + if(verbose) ATH_MSG_INFO("getFirstHFHadronOfSameFlavour:: initial state particle found="<<(parent->pdgId())); + + bool hasSameFlavourParent=false; + for(unsigned int ip=0; ip<parent->nParents(); ip++) + { + if(parent->parent(ip)) + { + if((isBottomHadron && parent->parent(ip)->isBottomHadron())||(isCharmHadron && parent->parent(ip)->isCharmHadron())) + { + parent=parent->parent(ip); + hasSameFlavourParent=true; + break; + } + } + } + + if(!hasSameFlavourParent) + { + if(verbose) ATH_MSG_INFO("getFirstHFHadronOfSameFlavour:: parent="<<(parent->pdgId())<<" has no same flavour ancestor"); + break; + } + else + { + if(verbose) ATH_MSG_INFO("getFirstHFHadronOfSameFlavour:: found same flavour parent="<<(parent->pdgId())); + } + + } + return parent; + } + //end of getFirstHadronOfSameFlavour method// + + //getInitialStateParticle// + const xAOD::TruthParticle* getInitialStateParticle(const xAOD::TruthParticle* truthParticle, bool verbose) + { + if(!truthParticle) return 0; + int pdgId=truthParticle->pdgId(); + int niterations=0; + const xAOD::TruthParticle* parent=truthParticle; + + while(parent) + { + if((niterations++)>100) + { + if(verbose) ATH_MSG_INFO("getInitialStateParticle:: too many iterations for particle "<<(truthParticle->pdgId())); + return 0; + } + + bool hasParentWithSamePdgId=false; + for(unsigned int ip=0; ip<parent->nParents(); ip++) + { + if(parent->parent(ip) && (parent->parent(ip)->pdgId()==pdgId)) + { + parent=parent->parent(ip); + hasParentWithSamePdgId=true; + break; + } + } + if(!hasParentWithSamePdgId) break; + } + return parent; + } + //end of getInitialStateParticle method// + + void printDecayChain(const xAOD::TruthParticle* truthPart, + std::ostream& os /* = std::cout */, + const std::string& prefix /* = "" */) { + // Protect against a faulty production vertex reference. + if (!truthPart || !truthPart->prodVtx()) { + os << prefix << "[" << (truthPart ? truthPart->pdgId() :0x0) << " <- NULL]" << '\n'; + return; + } + + os << prefix << "[" << truthPart->pdgId(); + int niterations=0; + + while (truthPart) { + if((niterations++)>30) + { + os<<" STOP! too many iterations "; + break; + } + if(truthPart->nParents()<1) break; + + os << " <- "; + const xAOD::TruthParticle* firstWithSamePdgId=0; + const xAOD::TruthParticle* firstNonParton=0; + const xAOD::TruthParticle* firstCorrectFlavorQuark=0; + + for(unsigned int ip=0; ip<truthPart->nParents(); ip++) + { + if(ip>0) os<<", "; + os<<" "<<(truthPart->parent(ip) ? truthPart->parent(ip)->pdgId() : 0); + if(!truthPart->parent(ip)) continue; + + if(!firstWithSamePdgId && truthPart->parent(ip)->pdgId()==truthPart->pdgId()) + { + firstWithSamePdgId = truthPart->parent(ip); + } + if(!firstNonParton && !truthPart->parent(ip)->isParton()) + { + firstNonParton = truthPart->parent(ip); + } + if(truthPart->isBottomHadron() && abs(truthPart->parent(ip)->pdgId())==5) + { + firstCorrectFlavorQuark = truthPart->parent(ip); + } + if(truthPart->isCharmHadron() && abs(truthPart->parent(ip)->pdgId())==4) + { + firstCorrectFlavorQuark = truthPart->parent(ip); + } + + } + if(firstWithSamePdgId) truthPart=firstWithSamePdgId; + else if(firstNonParton) truthPart=firstNonParton; + else if(firstCorrectFlavorQuark) truthPart=firstCorrectFlavorQuark; + else truthPart=truthPart->parent(0); + + } + os << "]" << '\n'; + } + + bool isFrom(const xAOD::TruthParticle* truthParticle, + const std::vector<int>& parentPDGIds, + bool bOnlyDirect /* = false */) { + // If the input does not have aproper production vertex reference or + // there are no incoming particle to the production vertex, directly + // return false + if (!truthParticle->hasProdVtx() || + !truthParticle->prodVtx() || + truthParticle->prodVtx()->nIncomingParticles() == 0) { + return false; + } + + // The current production vertex + const xAOD::TruthVertex* prodVtx = truthParticle->prodVtx(); + // The previous production vertex (initialised to the current + // production vertex) + const xAOD::TruthVertex* prevProdVtx = prodVtx; + + auto numIncoming = prodVtx->nIncomingParticles(); + for (std::size_t motherIndex = 0; + motherIndex < numIncoming; + ++motherIndex) { + const xAOD::TruthParticle* mother = nullptr; + int motherPdgId = truthParticle->pdgId(); + + // Ascend through the decay chain until we find the "actual" + // decay, i.e. a change in the PDG ID. This skips all the + // non-decay truth table entries which come from "particle + // evolution" rather than physical decay + while (truthParticle->pdgId() == motherPdgId) { + mother = prodVtx->incomingParticle(motherIndex); + if (mother) { + motherPdgId = mother->pdgId(); + } else { + break; + } + + if (truthParticle->pdgId() != motherPdgId) { + break; + } + + // Include protection against cyclic or broken reference + // chains which can occur in SHERPA samples + if (!mother->hasProdVtx()) { + break; + } + if (prevProdVtx == mother->prodVtx()) { + break; + } + + // Update the previous / current production vertex references + prevProdVtx = prodVtx; + prodVtx = mother->prodVtx(); + + // safeguard + if (!prodVtx || prodVtx->nIncomingParticles() == 0) { + break; + } + } + + // Check that the mother pointer is valid. If it is not valid, then + // the particle could not possibly come from any of the requested + // PDG Ids, hence return false + if (!mother) { + return false; + } + + // If the mother PDG ID is in the parentPDGIds collection, then return true + if (std::find(parentPDGIds.begin(), parentPDGIds.end(), motherPdgId) != parentPDGIds.end()) { + return true; + } + + // If we allow chained matching (I.e. not only _direct_ decays) and + // the mother particle does come from the request PDG ID(s), return true + if (!bOnlyDirect && isFrom(mother, parentPDGIds, bOnlyDirect)) { + return true; + } + } + + // If we did't find an ancestor with the requested pdg id, return false + return false; + } + + bool isFromWZDecay(const xAOD::TruthParticle* truthParticle, + bool bOnlyDirect /* = false */) { + // If the input does not have aproper production vertex reference or + // there are no incoming particle to the production vertex, directly + // return false + if (!truthParticle->hasProdVtx() || + !truthParticle->prodVtx() || + truthParticle->prodVtx()->nIncomingParticles() == 0) { + return false; + } + + // The current production vertex + const xAOD::TruthVertex* prodVtx = truthParticle->prodVtx(); + // The previous production vertex (initialised to the current + // production vertex) + const xAOD::TruthVertex* prevProdVtx = prodVtx; + + + auto numIncoming = prodVtx->nIncomingParticles(); + for (std::size_t motherIndex = 0; + motherIndex < numIncoming; + ++motherIndex) { + const xAOD::TruthParticle* mother = nullptr; + int motherAbsPdgId = truthParticle->absPdgId(); + + // Ascend through the decay chain until we find the "actual" + // decay, i.e. a change in the PDG ID. This skips all the + // non-decay truth table entries which come from "particle + // evolution" rather than physical decay + while (truthParticle->absPdgId() == motherAbsPdgId) { + mother = prodVtx->incomingParticle(motherIndex); + if (mother) { + motherAbsPdgId = mother->absPdgId(); + } else { + break; + } + + if (truthParticle->absPdgId() != motherAbsPdgId) { + break; + } + + // Include protection against cyclic or broken reference + // chains which can occur in SHERPA samples + if (!mother->hasProdVtx()) { + break; + } + if (prevProdVtx == mother->prodVtx()) { + break; + } + + // Update the previous / current production vertex references + prevProdVtx = prodVtx; + prodVtx = mother->prodVtx(); + + // safeguard + if (!prodVtx || prodVtx->nIncomingParticles() == 0) { + break; + } + } + + // Check that the mother pointer is valid. If it is not valid, then + // the particle could not possibly come from any of the requested + // PDG Ids, hence return false + if (!mother) { + return false; + } + + // If the direct physical decay in the MC record was from a Z or W + // boson to the truth particle then return true + // Otherwise perform a vertex-based identification of W/Z's + if (motherAbsPdgId == 23 || motherAbsPdgId == 24) { + return true; + } + + // The following vertex-based identification of W/Z's is needed + // for SHERPA samples where the W/Z particle is not explicitly + // in the particle record. At this point if we have a valid + // vertex, it should be a true decay vertex. + // + // If it is a W or Z then two of those decay products should be + // lepton / neutrino pair corresponding to the transitions + // W+ -> l+ nu + // W- -> l- nu~ + // Z -> l+ l- + // Z -> nu nu~ + // Hence loop through the outgoing particles of the truth vertex + // and check that the vertex matches the requirement. We + // simplify this check by just counting the number of leptonic + // outgoing particles which should be equal to 2. It is assumed + // that the MC generator does not produce unphysical decays. + // + // Furthermore, prompt W/Z's should come from a vertex with more + // than one incoming particle. Consequently, test this + // requirement prior to checking the outgoing states. + int nDecay = 0; + if (prodVtx && prodVtx->nIncomingParticles() > 1) { + for (const auto& child : prodVtx->outgoingParticleLinks()) { + if ((*child)->absPdgId() > 10 && + (*child)->absPdgId() < 17) { + nDecay++; + } + } + } + + // There must be exactly two leptonic outgoing particles in that vertex + if (nDecay == 2) { + return true; + } + + // If we allow chained matching (I.e. not only _direct_ decays) and + // the mother particle does come from a W / Z, return true + if (!bOnlyDirect && isFromWZDecay(mother, bOnlyDirect)) { + return true; + } + } + + // We did not find any W / Z in the ancestry of the input particle -> + // return false + return false; + } + + bool isLeptonFromTau(const xAOD::TruthParticle* truthParticle) { + // If the input particle is not a lepton directly terminate the + // algorithm retunring false + if (truthParticle->absPdgId() != 11 && + truthParticle->absPdgId() != 12 && + truthParticle->absPdgId() != 13 && + truthParticle->absPdgId() != 14 && + truthParticle->absPdgId() != 15 && + truthParticle->absPdgId() != 16) { + return false; + } + return isFrom(truthParticle, {15, -15}, true); + } + + bool isNotFromHadron(const xAOD::TruthParticle* truthParticle, + bool bOnlyDirect /* = false */, + bool bTauIsHadron /* = false */) { + // If there is no production vertex, either something is wrong, or + // we are at the beginning of the record. However, either way, the + // particle does not come from a hadron, hence return true. + if (!truthParticle->hasProdVtx() || + !truthParticle->prodVtx() || + truthParticle->prodVtx()->nIncomingParticles() == 0) { + return true; + } + + // The current production vertex + const xAOD::TruthVertex* prodVtx = truthParticle->prodVtx(); + // The previous production vertex (initialised to the current + // production vertex) + const xAOD::TruthVertex* prevProdVtx = prodVtx; + + // Loop all the particles going into the production vertex of the + // current truth particle. + // * If the mother of any of the is a physical hadron return false + // * If the mother of any of them descends from a physical return false + // * Otherwise return true + auto numIncoming = prodVtx->nIncomingParticles(); + for (std::size_t motherIndex = 0; + motherIndex < numIncoming; + ++motherIndex) { + int motherPdgId = truthParticle->pdgId(); + const xAOD::TruthParticle* mother = nullptr; + + // Ascend through the decay chain until we find the "actual" + // decay, i.e. a change in the PDG ID. This skips all the + // non-decay truth table entries which come from "particle + // evolution" rather than physical decay + while (truthParticle->pdgId() == motherPdgId) { + mother = prodVtx->incomingParticle(motherIndex); + if (mother) { + motherPdgId = mother->pdgId(); + } else { + break; + } + + // Include protection against cyclic or broken reference + // chains which can occur in SHERPA samples + if (!mother->hasProdVtx()) { + break; + } + if (prevProdVtx == mother->prodVtx()) { + break; + } + + // Update the previous / current production vertex references + prevProdVtx = prodVtx; + prodVtx = mother->prodVtx(); + + // safeguard + if (!prodVtx || prodVtx->nIncomingParticles() == 0) { + break; + } + } + + // Check that the mother pointer is valid. If it is not valid, then + // the particle could not possibly come from a hadron, hence return + // true + if (!mother) { + return true; + } + + // If the mother particle is a "physical decayed" particle (HepMC + // status code) and a hadron, then return false. + if (mother->status() == 2 && + (MC::PID::isHadron(motherPdgId) || + (bTauIsHadron && MC::PID::isTau(motherPdgId)))) { + return false; + } + // If we allow chained matching (I.e. not only _direct_ decays) and + // the mother particle does come from a hadron, return false + if (!bOnlyDirect && !isNotFromHadron(mother, bOnlyDirect, bTauIsHadron)) { + return false; + } + } + // No hadronic && physical parents + return true; } + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/MsgCategory.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/MsgCategory.h new file mode 100644 index 0000000000000000000000000000000000000000..531d49247e10746cd09444b516647aa5ffe36045 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/MsgCategory.h @@ -0,0 +1,11 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ +#ifndef TOPPARTICLELEVEL_MSG_CATEGORY_H_ +#define TOPPARTICLELEVEL_MSG_CATEGORY_H_ +#include <AsgMessaging/MessageCheck.h> + +// message category for stuff in this package that does not inherit from AsgTool +ANA_MSG_HEADER(TopParticleLevel) + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ObjectSelectorBase.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ObjectSelectorBase.h index 209e8cd3355e3e8fcbc444db925ba24f751f801b..d2ad082bb6ec6e51f58794a9e2a628044b584551 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ObjectSelectorBase.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ObjectSelectorBase.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ObjectSelectorBase.h // Description: @@ -11,14 +11,13 @@ #define _TOP_OBJECTSELECTORBASE_H_ namespace top { - - template <typename ObjectT> - class ObjectSelectorBase { - public: - ObjectSelectorBase(){} - virtual ~ObjectSelectorBase(){} - virtual bool apply( const ObjectT & obj ) = 0; - }; + template <typename ObjectT> + class ObjectSelectorBase { + public: + ObjectSelectorBase() {} + virtual ~ObjectSelectorBase() {} + virtual bool apply(const ObjectT& obj) = 0; + }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelElectronObjectSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelElectronObjectSelector.h index e5cf9de589100520cc1d26891adcfd5eca1540da..3857ad0a92d84340a91e9cd7586248d32d6d366d 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelElectronObjectSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelElectronObjectSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelElectronObjectSelector.h // Description: @@ -15,35 +15,33 @@ #include "xAODTruth/TruthParticleContainer.h" namespace top { - - class ParticleLevelElectronObjectSelector - : public ObjectSelectorBase<xAOD::TruthParticle> { - public: - // Struct used to store the cut values used by the object selector. It - // is important that the object has a sensible default config because it - // will be default constructed for the trivial constructor of the object - // selector. - struct Options { - Options( double ptMin = 25.e3, - double etaMax = 2.5, - bool notFromHadron = true, - bool tauIsHadron = false ) : - pt_min( ptMin ), - eta_max( etaMax ), - not_from_hadron( notFromHadron ), - tau_is_hadron( tauIsHadron ){} - double pt_min; - double eta_max; - bool not_from_hadron; - bool tau_is_hadron; - }; - public: - ParticleLevelElectronObjectSelector( Options cuts = Options() ); - virtual bool apply( const xAOD::TruthParticle & truthParticle ); - private: - Options m_opt; + class ParticleLevelElectronObjectSelector + : public ObjectSelectorBase<xAOD::TruthParticle> { + public: + // Struct used to store the cut values used by the object selector. It + // is important that the object has a sensible default config because it + // will be default constructed for the trivial constructor of the object + // selector. + struct Options { + Options(double ptMin = 25.e3, + double etaMax = 2.5, + bool notFromHadron = true, + bool tauIsHadron = false) : + pt_min(ptMin), + eta_max(etaMax), + not_from_hadron(notFromHadron), + tau_is_hadron(tauIsHadron) {} + double pt_min; + double eta_max; + bool not_from_hadron; + bool tau_is_hadron; }; - + public: + ParticleLevelElectronObjectSelector(Options cuts = Options()); + virtual bool apply(const xAOD::TruthParticle& truthParticle); + private: + Options m_opt; + }; } #endif /* _TOP_PARTICLE_LEVEL_ELECTRONOBJECTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelEvent.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelEvent.h index a4decb7a5bfb2ed6eab3701e4c63844bd641edea..a4949c91c471e685d585a21fa509aabe868e158b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelEvent.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelEvent.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelEvent.h // Description: @@ -12,55 +12,72 @@ #include <string> #include <unordered_map> +#include <iostream> #include "xAODEventInfo/EventInfo.h" #include "xAODJet/JetContainer.h" #include "xAODTruth/TruthParticleContainer.h" #include "xAODMissingET/MissingET.h" +#include "TopEvent/Event.h" namespace top { + class ParticleLevelEvent { + public: + ParticleLevelEvent() + : m_info(nullptr), + m_electrons(nullptr), + m_muons(nullptr), + m_photons(nullptr), + m_jets(nullptr), + m_RCJets(SG::VIEW_ELEMENTS), + m_largeRJets(nullptr), + m_met(nullptr), + m_selectionDecisions() {} - class ParticleLevelEvent { - public: - ParticleLevelEvent() - : m_info( nullptr ), - m_electrons( nullptr ), - m_muons( nullptr ), - m_photons( nullptr ), - m_jets( nullptr ), - m_largeRJets( nullptr ), - m_met( nullptr ), - m_selectionDecisions(){} - - /// Pointer to the event info object - const xAOD::EventInfo * m_info; - - /// Pointer to truth level electrons - const xAOD::TruthParticleContainer * m_electrons; - - /// Pointer to truth level muons - const xAOD::TruthParticleContainer * m_muons; - - /// Pointer to truth level photons - const xAOD::TruthParticleContainer * m_photons; - - /// Pointer to truth level jets - const xAOD::JetContainer * m_jets; - - /// Pointer to the truth level large R jets. - const xAOD::JetContainer * m_largeRJets; - - // Pointer to truth level MET - const xAOD::MissingET * m_met; - - // Maps from the name of an event selection line to the result of - // applying that event selection onto this ParticleLevelEvent. At the - // moment, the mapped value (albeit being of type 'int') is inteded just - // as a true / false statement. Must be mutable because the - // EventSelectionManager will modify it. - mutable std::unordered_map<std::string, int> m_selectionDecisions; - }; + /// Pointer to the event info object + const xAOD::EventInfo* m_info; + + /// Pointer to truth level electrons + const xAOD::TruthParticleContainer* m_electrons; + + /// Pointer to truth level muons + const xAOD::TruthParticleContainer* m_muons; + + /// Pointer to truth level soft-muons + const xAOD::TruthParticleContainer* m_softmuons; + + /// Pointer to truth level photons + const xAOD::TruthParticleContainer* m_photons; + + /// Pointer to truth level jets + const xAOD::JetContainer* m_jets; + + ///Container of recluster jets (can be sorted) + xAOD::JetContainer m_RCJets; + + /// Containers of variable-R reclustered jets (can be sorted) + mutable std::unordered_map< std::string, std::shared_ptr<xAOD::JetContainer> > m_VarRCJets; + + /// Pointer to the truth level large R jets. + const xAOD::JetContainer* m_largeRJets; + + /// Pointer to truth level photons + const xAOD::TruthParticleContainer* m_taus; + + // Pointer to truth level MET + const xAOD::MissingET* m_met; + + // Maps from the name of an event selection line to the result of + // applying that event selection onto this ParticleLevelEvent. At the + // moment, the mapped value (albeit being of type 'int') is inteded just + // as a true / false statement. Must be mutable because the + // EventSelectionManager will modify it. + mutable std::unordered_map<std::string, int> m_selectionDecisions; + }; } +/// Ostream overload operator +std::ostream& operator << (std::ostream& os, const top::ParticleLevelEvent& plEvent); + #endif /* _TOP_PARTICLELEVELEVENT_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelJetObjectSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelJetObjectSelector.h index 4eac883a0d83b671956eec664da2db24e6b7488b..38517e27acd497d1d4aa10f59405ef1d4bdef866 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelJetObjectSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelJetObjectSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelJetObjectSelector.h // Description: @@ -15,27 +15,25 @@ #include "xAODJet/JetContainer.h" namespace top { - - class ParticleLevelJetObjectSelector - : public ObjectSelectorBase<xAOD::Jet> { - public: - // Struct used to store the cut values used by the object selector. It - // is important that the object has a sensible default config because it - // will be default constructed for the trivial constructor of the object - // selector. - struct Options { - Options( double ptMin = 25.e3, double etaMax = 2.5 ) : - pt_min( ptMin ), eta_max( etaMax ){} - double pt_min; - double eta_max; - }; - public: - ParticleLevelJetObjectSelector( Options opt = Options() ); - virtual bool apply( const xAOD::Jet & jet ); - private: - Options m_opt; + class ParticleLevelJetObjectSelector + : public ObjectSelectorBase<xAOD::Jet> { + public: + // Struct used to store the cut values used by the object selector. It + // is important that the object has a sensible default config because it + // will be default constructed for the trivial constructor of the object + // selector. + struct Options { + Options(double ptMin = 25.e3, double etaMax = 2.5) : + pt_min(ptMin), eta_max(etaMax) {} + double pt_min; + double eta_max; }; - + public: + ParticleLevelJetObjectSelector(Options opt = Options()); + virtual bool apply(const xAOD::Jet& jet); + private: + Options m_opt; + }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelLoader.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelLoader.h index bc4ad6980be6fbb122e2bd6711c852c2bc79fff4..d0ed42e648e5ddca07ca99b1f76d41555c2ab06f 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelLoader.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelLoader.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelLoader.h // Description: @@ -13,6 +13,7 @@ #include <memory> #include "TopParticleLevel/ObjectSelectorBase.h" +#include "TopParticleLevel/ParticleLevelRCJetObjectLoader.h" #include "AsgTools/AsgTool.h" @@ -31,104 +32,110 @@ // Forward Declarations namespace top { - class ParticleLevelEvent; - class TopConfig; + class ParticleLevelEvent; + class TopConfig; } namespace top { + /*! + * @brief Loading tool which creates a particle level event object. + * + * After creation of the loader tool, it will be in of of two states: either + * it is "active" or not (can be tested using the active() member function). + * If the tool is not active, then the load function is a no-op, it will + * return an "empty" ParticleLevelEvent object. The active() member function + * allows for the enclosing (i.e. calling) program to conditionally branch + * into computing intensive parts depending on whether particle level data + * is available or not. The loader tool is configured to be non-"active" if + * the input data is not monte carlo or any of the required collection names + * are empty respectively None + */ + class ParticleLevelLoader final: public asg::AsgTool { + public: + /*! + * @brief Constructor of the loader tool. + */ + ParticleLevelLoader(const std::shared_ptr<top::TopConfig>& cfg); + + /*! + * @brief Destructor of the loader tool. + */ + virtual ~ParticleLevelLoader(); + + /*! + * @brief Loading function. Does the actual work. This function will + * load the truth information from the #xaodEvent and return this data + * transformed into a truth level event. The data stored in the + * ParticleLevel is owned by the truth event loader. + * @param xaodEvent The input data event object. + * @return ParticleLevelEvent object. + */ + ParticleLevelEvent load(); /*! - * @brief Loading tool which creates a particle level event object. - * - * After creation of the loader tool, it will be in of of two states: either - * it is "active" or not (can be tested using the active() member function). - * If the tool is not active, then the load function is a no-op, it will - * return an "empty" ParticleLevelEvent object. The active() member function - * allows for the enclosing (i.e. calling) program to conditionally branch - * into computing intensive parts depending on whether particle level data - * is available or not. The loader tool is configured to be non-"active" if - * the input data is not monte carlo or any of the required collection names - * are empty respectively None + * @brief Function that can be used to test whether the ParticleLevelLoader + * is active. The loader is set to inactive if the names of the truth + * collections are unavailable. This is determined at construction. */ - class ParticleLevelLoader final : public asg::AsgTool { - public: - /*! - * @brief Constructor of the loader tool. - */ - ParticleLevelLoader( const std::shared_ptr<top::TopConfig> & cfg ); - - /*! - * @brief Destructor of the loader tool. - */ - virtual ~ParticleLevelLoader(); - - /*! - * @brief Loading function. Does the actual work. This function will - * load the truth information from the #xaodEvent and return this data - * transformed into a truth level event. The data stored in the - * ParticleLevel is owned by the truth event loader. - * @param xaodEvent The input data event object. - * @return ParticleLevelEvent object. - */ - ParticleLevelEvent load(); - - /*! - * @brief Function that can be used to test whether the ParticleLevelLoader - * is active. The loader is set to inactive if the names of the truth - * collections are unavailable. This is determined at construction. - */ - bool active() const { return m_active; } - - protected: - bool loadDressedLeptons(const xAOD::TruthParticleContainer & input, - std::unique_ptr<xAOD::TruthParticleContainer> & store, - std::unique_ptr<xAOD::ShallowAuxContainer> & storeAux) const; - - bool isDressingPhoton(const xAOD::TruthParticle & photon, - const xAOD::TruthParticleContainer & dressedParticles, - const float dressingCone = 0.1) const; - - private: - // The global config object - const std::shared_ptr<top::TopConfig> & m_config; - - // The tools used for electron, muon, and jet object selection. The - // basic idea is to allow exchanging these tools for custom ones, - // however, this is not implemented (yet). - std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Electron; - std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Muon; - std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Photon; - std::unique_ptr<ObjectSelectorBase<xAOD::Jet> > m_objectSelector_Jet; - std::unique_ptr<ObjectSelectorBase<xAOD::Jet> > m_objectSelector_LargeRJet; - private: - // The dressed leptons (shallow copies of the input containers) - std::unique_ptr<xAOD::TruthParticleContainer> m_electronsDressed; - std::unique_ptr<xAOD::ShallowAuxContainer> m_electronsDressedAux; - - std::unique_ptr<xAOD::TruthParticleContainer> m_muonsDressed; - std::unique_ptr<xAOD::ShallowAuxContainer> m_muonsDressedAux; - - std::unique_ptr<xAOD::TruthParticleContainer> m_goodElectrons; - std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodElectronsAux; - - std::unique_ptr<xAOD::TruthParticleContainer> m_goodMuons; - std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodMuonsAux; - - std::unique_ptr<xAOD::TruthParticleContainer> m_goodPhotons; - std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodPhotonsAux; - - - std::unique_ptr<xAOD::JetContainer> m_goodJets; - std::unique_ptr<xAOD::JetAuxContainer> m_goodJetsAux; + bool active() const {return m_active;} + protected: + bool loadDressedLeptons(const xAOD::TruthParticleContainer& input, + std::unique_ptr<xAOD::TruthParticleContainer>& store, + std::unique_ptr<xAOD::ShallowAuxContainer>& storeAux) const; + + bool isDressingPhoton(const xAOD::TruthParticle& photon, + const xAOD::TruthParticleContainer& dressedParticles, + const float dressingCone = 0.1) const; + private: + // The global config object + const std::shared_ptr<top::TopConfig>& m_config; + + // The tools used for electron, muon, and jet object selection. The + // basic idea is to allow exchanging these tools for custom ones, + // however, this is not implemented (yet). + std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Electron; + std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Muon; + std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Photon; + std::unique_ptr<ObjectSelectorBase<xAOD::Jet> > m_objectSelector_Jet; + std::unique_ptr<ObjectSelectorBase<xAOD::Jet> > m_objectSelector_LargeRJet; + std::unique_ptr<ObjectSelectorBase<xAOD::TruthParticle> > m_objectSelector_Tau; + std::unique_ptr<ParticleLevelRCJetObjectLoader> m_particleLevelRCJetObjectLoader; + std::map<std::string, std::unique_ptr<ParticleLevelRCJetObjectLoader> > m_particleLevelVarRCJetObjectLoader; + std::vector<std::string> m_VarRCJetRho; + std::vector<std::string> m_VarRCJetMassScale; + private: + // The dressed leptons (shallow copies of the input containers) + std::unique_ptr<xAOD::TruthParticleContainer> m_electronsDressed; + std::unique_ptr<xAOD::ShallowAuxContainer> m_electronsDressedAux; + + std::unique_ptr<xAOD::TruthParticleContainer> m_muonsDressed; + std::unique_ptr<xAOD::ShallowAuxContainer> m_muonsDressedAux; + + std::unique_ptr<xAOD::TruthParticleContainer> m_goodElectrons; + std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodElectronsAux; + + std::unique_ptr<xAOD::TruthParticleContainer> m_goodMuons; + std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodMuonsAux; + + std::unique_ptr<xAOD::TruthParticleContainer> m_goodSoftMuons; + std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodSoftMuonsAux; + + std::unique_ptr<xAOD::TruthParticleContainer> m_goodPhotons; + std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodPhotonsAux; + + std::unique_ptr<xAOD::JetContainer> m_goodJets; + std::unique_ptr<xAOD::JetAuxContainer> m_goodJetsAux; std::unique_ptr<xAOD::JetContainer> m_goodLargeRJets; - std::unique_ptr<xAOD::JetAuxContainer> m_goodLargeRJetsAux; + std::unique_ptr<xAOD::JetAuxContainer> m_goodLargeRJetsAux; - // Flag denoting whether the loader tool is active. Will be set by the - // constructor and remains unchanged afterwards. - const bool m_active; - }; + std::unique_ptr<xAOD::TruthParticleContainer> m_goodTaus; + std::unique_ptr<xAOD::TruthParticleAuxContainer> m_goodTausAux; + // Flag denoting whether the loader tool is active. Will be set by the + // constructor and remains unchanged afterwards. + const bool m_active; + }; } #endif /* _TOP_PARTICLELEVEL_EVENTLOADER_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelMuonObjectSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelMuonObjectSelector.h index 4e579bec83940a9a6c9fdcfaf568f74a685b3b07..5abbad3ea4beef3d95ebad599a3e8fd3e630fe34 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelMuonObjectSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelMuonObjectSelector.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelMuonObjectSelector.h // Description: @@ -15,35 +15,33 @@ #include "xAODTruth/TruthParticleContainer.h" namespace top { - - class ParticleLevelMuonObjectSelector - : public ObjectSelectorBase<xAOD::TruthParticle> { - public: - // Struct used to store the cut values used by the object selector. It - // is important that the object has a sensible default config because it - // will be default constructed for the trivial constructor of the object - // selector. - struct Options { - Options( double ptMin = 25.e3, - double etaMax = 2.5, - bool notFromHadron = true, - bool tauIsHadron = false ) : - pt_min( ptMin ), - eta_max( etaMax ), - not_from_hadron( notFromHadron ), - tau_is_hadron( tauIsHadron ){} - double pt_min; - double eta_max; - bool not_from_hadron; - bool tau_is_hadron; - }; - public: - ParticleLevelMuonObjectSelector( Options opt = Options() ); - virtual bool apply( const xAOD::TruthParticle & truthParticle ); - private: - Options m_opt; + class ParticleLevelMuonObjectSelector + : public ObjectSelectorBase<xAOD::TruthParticle> { + public: + // Struct used to store the cut values used by the object selector. It + // is important that the object has a sensible default config because it + // will be default constructed for the trivial constructor of the object + // selector. + struct Options { + Options(double ptMin = 25.e3, + double etaMax = 2.5, + bool notFromHadron = true, + bool tauIsHadron = false) : + pt_min(ptMin), + eta_max(etaMax), + not_from_hadron(notFromHadron), + tau_is_hadron(tauIsHadron) {} + double pt_min; + double eta_max; + bool not_from_hadron; + bool tau_is_hadron; }; - + public: + ParticleLevelMuonObjectSelector(Options opt = Options()); + virtual bool apply(const xAOD::TruthParticle& truthParticle); + private: + Options m_opt; + }; } #endif /* _TOP_PARTICLE_LEVEL_MUONOBJECTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelPhotonObjectSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelPhotonObjectSelector.h index 53b976ebf5a01a7570bb84c8a3d7e12cf4c384d6..f8e4b190d4cf7508b841d4bde0efd15323ff6d14 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelPhotonObjectSelector.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelPhotonObjectSelector.h @@ -1,20 +1,11 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // Filename: ParticleLevelPhotonObjectSelector.h // Description: // Author: Fabian Wilk // Created: Wed Oct 12 11:37:51 2016 -// -// (c) by The ATLAS Collaboration -// by Fabian Wilk <mail@fabianwilk.de> -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. #ifndef _TOP_PARTICLE_LEVEL_PHOTONOBJECTSELECTOR_H_ #define _TOP_PARTICLE_LEVEL_PHOTONOBJECTSELECTOR_H_ @@ -32,34 +23,31 @@ #include "TopEvent/EventTools.h" namespace top { - - class ParticleLevelPhotonObjectSelector - : public ObjectSelectorBase<xAOD::TruthParticle> { - public: - // Struct used to store the cut values used by the object selector. It - // is important that the object has a sensible default config because it - // will be default constructed for the trivial constructor of the object - // selector. - struct Options { - Options(double ptMin = 25.e3, - double etaMax = 2.5, - const std::string & Origin = "", - const std::string & Isolation = ""); - - double pt_min; - double eta_max; - std::vector<MCTruthPartClassifier::ParticleOrigin> origin; - std::string isolationVar; - float isolationCut; - }; - - public: - ParticleLevelPhotonObjectSelector(Options cuts = Options()); - virtual bool apply(const xAOD::TruthParticle & truthParticle); - - private: - Options m_opt; + class ParticleLevelPhotonObjectSelector + : public ObjectSelectorBase<xAOD::TruthParticle> { + public: + // Struct used to store the cut values used by the object selector. It + // is important that the object has a sensible default config because it + // will be default constructed for the trivial constructor of the object + // selector. + struct Options { + Options(double ptMin = 25.e3, + double etaMax = 2.5, + const std::string& Origin = "", + const std::string& Isolation = ""); + + double pt_min; + double eta_max; + std::vector<MCTruthPartClassifier::ParticleOrigin> origin; + std::string isolationVar; + float isolationCut; }; + public: + ParticleLevelPhotonObjectSelector(Options cuts = Options()); + virtual bool apply(const xAOD::TruthParticle& truthParticle); + private: + Options m_opt; + }; } #endif /* _TOP_PARTICLE_LEVEL_PHOTONOBJECTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelRCJetObjectLoader.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelRCJetObjectLoader.h new file mode 100644 index 0000000000000000000000000000000000000000..970a9348f41ebef246f98653959c97def041a04b --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelRCJetObjectLoader.h @@ -0,0 +1,139 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +//Load the reclustering tool for the collection of truth jets already selected. +//Create the collection of reclustered jets and save them in the evtStore(). +//There is also the pass selection to apply the cut on eta and pt on the reclustered jets. + +#ifndef ParticleLevelRCJetObjectLoader_H_ +#define ParticleLevelRCJetObjectLoader_H_ + +#include "TopParticleLevel/ObjectSelectorBase.h" +#include "AsgTools/AsgTool.h" +#include "xAODCore/ShallowCopy.h" + +#include "xAODRootAccess/TEvent.h" +#include "xAODRootAccess/TStore.h" +#include "xAODRootAccess/TActiveStore.h" + +#include "xAODJet/JetContainer.h" +#include "xAODJet/JetAuxContainer.h" +#include "JetReclustering/JetReclusteringTool.h" + +#include <unordered_map> +#include <unordered_set> +#include <memory> +#include <set> +#include <list> +#include <vector> + + +namespace top { + class ParticleLevelEvent; + class TopConfig; +} + +namespace fastjet { + class JetDefinition; + namespace contrib { + class Nsubjettiness; + class EnergyCorrelator; + } +} +namespace JetSubStructureUtils { + class KtSplittingScale; + class Qw; + class EnergyCorrelatorGeneralized; +} + + +class ParticleLevelRCJetObjectLoader: public asg::AsgTool { +public: + //Default - so root can load based on a name + ParticleLevelRCJetObjectLoader(const std::shared_ptr<top::TopConfig>& cfg); + + + //Default - so we can clean up + ~ParticleLevelRCJetObjectLoader(); + + //Run once at the start of the job + StatusCode initialize(); + + //Run for every event (in every systematic) that needs saving + StatusCode execute(const top::ParticleLevelEvent& plEvent); + + + //Clean-up remaining things + StatusCode finalize(); + + bool passSelection(const xAOD::Jet& jet) const; + + //Access all of the container names from the Event Saver + std::string inputContainerName() {return m_InputJetContainer;}; + std::string rcjetContainerName() {return m_OutputJetContainer;}; +private: + std::string m_name; + const std::shared_ptr<top::TopConfig>& m_config; + + bool m_VarRCjets; + std::string m_VarRCjets_rho; + std::string m_VarRCjets_mass_scale; + + float m_ptcut; // in GeV + float m_etamax; + float m_inputJetPtMin; + float m_inputJetEtaMax; + float m_trim; + float m_radius; + float m_minradius; + float m_massscale; + + bool m_useJSS; + bool m_useAdditionalJSS; + + std::string m_treeName; + + std::string m_InJetContainerBase; + std::string m_OutJetContainerBase; + std::string m_InputJetContainer; + std::string m_OutputJetContainer; + + + + + //Substructure tool definitions + std::shared_ptr<fastjet::JetDefinition> m_jet_def_rebuild; + std::shared_ptr<fastjet::contrib::Nsubjettiness> m_nSub1_beta1; + std::shared_ptr<fastjet::contrib::Nsubjettiness> m_nSub2_beta1; + std::shared_ptr<fastjet::contrib::Nsubjettiness> m_nSub3_beta1; + std::shared_ptr<fastjet::contrib::EnergyCorrelator> m_ECF1; + std::shared_ptr<fastjet::contrib::EnergyCorrelator> m_ECF2; + std::shared_ptr<fastjet::contrib::EnergyCorrelator> m_ECF3; + std::shared_ptr<JetSubStructureUtils::KtSplittingScale> m_split12; + std::shared_ptr<JetSubStructureUtils::KtSplittingScale> m_split23; + std::shared_ptr<JetSubStructureUtils::Qw> m_qw; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF332; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF461; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF322; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF331; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF422; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF441; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF212; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF321; + std::shared_ptr<JetSubStructureUtils::EnergyCorrelatorGeneralized> m_gECF311; + + std::map<std::string, float> mass_scales = { + {"m_t", 172500.}, + {"m_w", 80385.}, + {"m_z", 91188.}, + {"m_h", 125090.} + }; + + + //re-clustered jets + // -> need unordered map for systematics + std::shared_ptr<JetReclusteringTool> m_jetReclusteringTool; +}; + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelTauObjectSelector.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelTauObjectSelector.h new file mode 100644 index 0000000000000000000000000000000000000000..1cd147e972d4ef855d860ae2f9f7b170d517ad11 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/ParticleLevelTauObjectSelector.h @@ -0,0 +1,36 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef _TOP_PARTICLE_LEVEL_TAUOBJECTSELECTOR_H_ +#define _TOP_PARTICLE_LEVEL_TAUOBJECTSELECTOR_H_ + +#include "TopParticleLevel/ObjectSelectorBase.h" + +#include "xAODTruth/TruthParticleContainer.h" + +namespace top { + class ParticleLevelTauObjectSelector + : public ObjectSelectorBase<xAOD::TruthParticle> { + public: + // Struct used to store the cut values used by the object selector. It + // is important that the object has a sensible default config because it + // will be default constructed for the trivial constructor of the object + // selector. + struct Options { + Options(double ptMin = 25.e3, + double etaMax = 2.5) : + pt_min(ptMin), + eta_max(etaMax) {} + double pt_min; + double eta_max; + }; + public: + ParticleLevelTauObjectSelector(Options opt = Options()); + virtual bool apply(const xAOD::TruthParticle& truthParticle); + private: + Options m_opt; + }; +} + +#endif /* _TOP_PARTICLE_LEVEL_TAUOBJECTSELECTOR_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/TruthTools.h b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/TruthTools.h index 0d04a51886cf4d3638cb12ab48133046e7ecc17c..9377bbb3ebf4ea31ded1e2fb0e99eaefb7aecc29 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/TruthTools.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel/TopParticleLevel/TruthTools.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // Filename: TruthTools.h // Description: @@ -15,165 +15,209 @@ #include <string> #include "xAODTruth/TruthParticleContainer.h" +#include "xAODMuon/MuonContainer.h" +#include "TopEvent/EventTools.h" +#include "TopDataPreparation/SampleXsection.h" +#include "xAODBase/IParticle.h" namespace top { - namespace truth { + namespace truth { + //Functions to decorate a muon with information on its truth-origin. Particle-level origin added on softmuons if config options SoftMuonAdditionalTruthInfo is True. + //Its output should be regarded as experimental and thoroughly tested by analyzers before officially including it in the analysis. + //It is strongly suggested to check its output against the true_origin (calculated by the MCTruthClassifier) to ensure behaviour is as expected. + //Parton-level added if SoftMuonAdditionalTruthInfo is True and SoftMuonAdditionalTruthInfoCheckPartonOrigin is True. + //Parton-level currently only usable on pythia8 and herwig7, will be automatically disabled for other PS generators. + //Some decorations are already written in the default output ntuple, check EventSaverFlatNtuple.cxx + //Some other are available for usage in custom savers: + //<const xAOD::TruthParticle*>("truthMuonLink") -> link to the truth muon associated with reco (can be null if not found) + //<top::LepParticleOriginFlag>("LepParticleOriginFlag") -> flag defined in TopEvent/EventTools.h + //<top::LepPartonOriginFlag>("LepPartonOriginFlag") -> flag defined in TopEvent/EventTools.h + //Then several <const xAOD::TruthParticle*>(...) decorations are also added (pointers are 0 when corresponding particle is not available): + //truthMotherLink -> first direct mother of the truth muon + //truthFirstNonLeptonMotherLink -> self-explanatory, will be different from truthMotherLink if the muon is from a Tau + //truthBMotherLink -> first B-hadron encountered when going back through the chain of ancestors + //truthCMotherLink -> first C-hadron encountered when going back through the chain of ancestors + //The following are added when using the parton-level flag + //truthPartonMotherLink -> link to first b/c quark encountered when going back through the chain of ancestors for muons from Heavy Flavour hadrons decays + //truthTopMotherLink, truthWMotherLink, truthZMotherLink, truthPhotonMotherLink, truthHiggsMotherLink, truthBSMMotherLink -> link to first Top/W/Z/gamma*/Higgs/BSM-particle encountered when going back through the chain of ancestors - /*! - * @brief Prints the decay chain leading up to a certain particle to a - * std::ostream. - * @param part Pointer to xAOD::TruthParticle whose decay origin shall - * be printed. - * @param os The std::ostream into which the decay chain shall be - * printed. Defaults to std::cout. - * @param prefix A string which will be prefixed to the output. - */ - void printDecayChain( const xAOD::TruthParticle * part, - std::ostream & os = std::cout, - const std::string & prefix = "" ); + void getTruthMuonHistory(const xAOD::TruthParticle* truth_muon, bool doPartonHistory, SampleXsection::showering shAlgo, bool verbose=false); + void getTruthMuonPartonHistory(const xAOD::TruthParticle* truthmu, top::LepParticleOriginFlag lepParticleOriginFlag, const xAOD::TruthParticle* truthmu_Bmother, const xAOD::TruthParticle* truthmu_Cmother, const xAOD::TruthParticle* truthmu_firstNonLeptonMother, SampleXsection::showering shAlgo, bool verbose=false); + //helper methods + top::LepParticleOriginFlag getTruthMuonFromTauHistory(const xAOD::TruthParticle* tauMother, const xAOD::TruthParticle* &truthmu_Bmother, const xAOD::TruthParticle* &truthmu_Cmother, const xAOD::TruthParticle* &truthmu_firstNonLeptonMother, bool verbose=false); + top::LepParticleOriginFlag getTruthMuonFromCharmHistory(const xAOD::TruthParticle* &truthmu_Bmother, const xAOD::TruthParticle* truthmu_Cmother, bool verbose=false); + + //function that gets the truth muon associated from a reco muon, runs getTruthMuonHistory on it, and then takes care of propagating the decorations + void getRecoMuonHistory(const xAOD::Muon* muon, bool doPartonHistory, SampleXsection::showering shAlgo, bool verbose=false); + + //helper methods + const xAOD::TruthParticle* getInitialStateParticle(const xAOD::TruthParticle* truthParticle, bool verbose=false); + const xAOD::TruthParticle* getFirstHFHadronOfSameFlavour(const xAOD::TruthParticle* truthParticle, bool verbose=false); + const xAOD::TruthParticle* getTruthMuonAssociatedToRecoMuon(const xAOD::Muon* muon); + //to initialize correctly all decorations to default values + void initTruthMuonHistoryInfo(const xAOD::TruthParticle* truth_muon, bool doPartonHistory); + void initRecoMuonHistoryInfo(const xAOD::Muon* muon, bool doPartonHistory); + //additional method to share common code between the two methods above + void initCommonMuonHistoryInfo(const xAOD::IParticle* muon, bool doPartonHistory); + //helper methods to copy info from one muon to another + void copyTruthMuonHistoryInfo(const xAOD::TruthParticle* tm_origin, const xAOD::TruthParticle* tm_target); + void copyRecoMuonHistoryInfo(const xAOD::Muon* m_origin, const xAOD::Muon* m_target); + //additional method to share common code between the two methods above + void copyCommonMuonHistoryInfo(const xAOD::IParticle* m_origin, const xAOD::IParticle* m_target); + + /*! + * @brief Prints the decay chain leading up to a certain particle to a + * std::ostream. + * @param part Pointer to xAOD::TruthParticle whose decay origin shall + * be printed. + * @param os The std::ostream into which the decay chain shall be + * printed. Defaults to std::cout. + * @param prefix A string which will be prefixed to the output. + */ + void printDecayChain(const xAOD::TruthParticle* part, + std::ostream& os = std::cout, + const std::string& prefix = ""); - /** - * @brief Check if a certain pdg ID corresponds to a B hadron. - * This follows the official PDG Monte-Carlo numbering scheme - * (c.f. http://pdg.lbl.gov/2007/reviews/montecarlorpp.pdf) which defines - * the PDG ID to be a 7 digit number in the form - * +- n_r n_L n_q1 n_q2 n_q3 n_J - * where - * n_q1 = 0, n_q2 >= n_q3 (for mesons) - * n_q1 >= n_q2 >= n_q3 (for baryons) - * n_q1 >= n_q2, n_q3 = 0 (for diquarks) - * the n_qi denote the flavour of the quark composing the hadron, i.e. - * n_q = 1 -> d n_q = 2 -> u - * n_q = 3 -> s n_q = 4 -> 4 - * n_q = 5 -> b - * The digit \f$n_J\f$ encodes the total angular momentum \f$J\f$ of a - * compound system. \f$n_L\f$ is used to distinguish compound objects which - * have the same total angular momentum but different spin (\f$S\f$) and orbital - * (\f$L\f$) angular momentum numbers. Finally, \f$n_r\f$ is used to label - * mesons which are radially exited. - * - * @param pdgId The PDG ID to test. - * - * @return True if pdg ID corresponds to B hadron, false otherwise. - */ - inline bool isBHadron( int pdgId ){ - return ( ( 510 < pdgId && pdgId < 555 ) || // Check for (normal) Mesons / Diquarks - ( 5100 < pdgId && pdgId < 5555 ) || // Check for (normal) Baryons - ( pdgId / 100 ) % 10 == 5 || // Check exited Mesons (and Baryons with double beauty) - ( pdgId / 1000 ) % 10 == 5 ); // Check exited Baryons - } - - - /** - * @brief Function to determine whether the input particle was produced - * in the physical decay of a particle of given PDG ID. - * - * The algorithm uses the MC Truth Record. - * The algorithm works by ascending through the decay chain following - * the production vertex reference (obtained by the prodVtx() member - * function of the xAOD::TruthParticle). From the input particle, the - * algorithm ascends through the chain until the PDG ID of the particle - * found as first incoming particle is not equal to the PDG ID of the - * input particle. The last production vertex found during this ascent - * should then correspond to the physical production vertex of the input - * particle. - * - * @param truthParticle The input particle. - * @param parentPDGIds A list of PDG IDs which are valid parents - * @param bOnlyDirect A flag denoting whether "chained matching" is - * allowed. In chained matching mode, intermittend particles are - * allowed, i.e. for the chain - * A -> B -> C - * isFrom( C, A ) is true (for A != B != C). If only direct decays are - * considered, this is only the case if A == B or B == C. Defaults to false. - * - * @return Return true if the input particle was produced in the decay - * of a particle which has a PDG ID that is listed in - * parentPDGIds. Return false otherwise. Also return false if - * the input particle has an invalid production vertex reference. - */ - bool isFrom( const xAOD::TruthParticle * truthParticle, - const std::vector<int> & parentPDGIds, - bool bOnlyDirect = false ); - - /** - * @brief Function to determine whether a given truth particle is a - * result of a decay chain that started in the decay of a W or Z boson. - * - * The algorithm works by ascending through the decay chain following - * the production vertex reference (obtained by the prodVtx() member - * function of the xAOD::TruthParticle). From the input particle, the - * algorithm ascends through the chain until the PDG ID of the particle - * found as first incoming particle is not equal to the PDG ID of the - * input particle. The last production vertex found during this ascent - * should then correspond to the physical production vertex of the input - * particle. - * - * If the PDG ID of the mother particle (i.e. the incoming particle to - * the truth decay vertex) corresponds to a W / Z boson the algorithm - * terminates directly, returning true. Otherwise a vertex-based check - * is employed (which was designed to operate on SHERPA samples, c.f. - * the JetSimTools-00-02-09 package - * [svn: /Reconstruction/Jet/JetSimTools]). - * - * @param truthParticle The input particle. - * @param bOnlyDirect A flag denoting whether "chained matching" is - * allowed. In chained matching mode, intermittend particles are - * allowed, i.e. for the chain - * A -> B -> C - * isFrom( C, A ) is true (for A != B != C). If only direct decays are - * considered, this is only the case if A == B or B == C. Defaults to false. - * - * @return Return true if the input particle was created in a physical - * decay of a W or Z boson. Otherwise return false. Will also - * return false if the prduction vertex of the input particle is - * invalid or has zero incoming particles. - */ - bool isFromWZDecay( const xAOD::TruthParticle * truthParticle, - bool bOnlyDirect = false ); + /** + * @brief Check if a certain pdg ID corresponds to a B hadron. + * This follows the official PDG Monte-Carlo numbering scheme + * (c.f. http://pdg.lbl.gov/2007/reviews/montecarlorpp.pdf) which defines + * the PDG ID to be a 7 digit number in the form + * +- n_r n_L n_q1 n_q2 n_q3 n_J + * where + * n_q1 = 0, n_q2 >= n_q3 (for mesons) + * n_q1 >= n_q2 >= n_q3 (for baryons) + * n_q1 >= n_q2, n_q3 = 0 (for diquarks) + * the n_qi denote the flavour of the quark composing the hadron, i.e. + * n_q = 1 -> d n_q = 2 -> u + * n_q = 3 -> s n_q = 4 -> 4 + * n_q = 5 -> b + * The digit \f$n_J\f$ encodes the total angular momentum \f$J\f$ of a + * compound system. \f$n_L\f$ is used to distinguish compound objects which + * have the same total angular momentum but different spin (\f$S\f$) and orbital + * (\f$L\f$) angular momentum numbers. Finally, \f$n_r\f$ is used to label + * mesons which are radially exited. + * + * @param pdgId The PDG ID to test. + * + * @return True if pdg ID corresponds to B hadron, false otherwise. + */ + inline bool isBHadron(int pdgId) { + return((510 < pdgId && pdgId < 555) || // Check for (normal) Mesons / Diquarks + (5100 < pdgId && pdgId < 5555) ||// Check for (normal) Baryons + (pdgId / 100) % 10 == 5 || // Check exited Mesons (and Baryons with double beauty) + (pdgId / 1000) % 10 == 5); // Check exited Baryons + } - /** - * @brief Function the check if a particle is a lepton which was - * produced in the decay of a tau lepton. - * - * @param truthParticle The input truth particle which will be checked. - * - * @return True if the input particle is a lepton and it has a parent - * which was a tau. False otherwise. Will also return false if - * the production vertex of the input particle is invalid. - */ - bool isLeptonFromTau( const xAOD::TruthParticle * truthParticle ); + /** + * @brief Function to determine whether the input particle was produced + * in the physical decay of a particle of given PDG ID. + * + * The algorithm uses the MC Truth Record. + * The algorithm works by ascending through the decay chain following + * the production vertex reference (obtained by the prodVtx() member + * function of the xAOD::TruthParticle). From the input particle, the + * algorithm ascends through the chain until the PDG ID of the particle + * found as first incoming particle is not equal to the PDG ID of the + * input particle. The last production vertex found during this ascent + * should then correspond to the physical production vertex of the input + * particle. + * + * @param truthParticle The input particle. + * @param parentPDGIds A list of PDG IDs which are valid parents + * @param bOnlyDirect A flag denoting whether "chained matching" is + * allowed. In chained matching mode, intermittend particles are + * allowed, i.e. for the chain + * A -> B -> C + * isFrom( C, A ) is true (for A != B != C). If only direct decays are + * considered, this is only the case if A == B or B == C. Defaults to false. + * + * @return Return true if the input particle was produced in the decay + * of a particle which has a PDG ID that is listed in + * parentPDGIds. Return false otherwise. Also return false if + * the input particle has an invalid production vertex reference. + */ + bool isFrom(const xAOD::TruthParticle* truthParticle, + const std::vector<int>& parentPDGIds, + bool bOnlyDirect = false); - /** - * @brief Check whether a given truth particle is a lepton. - * @param truthParticle The input truth particle to be tested. - * @return Return true if input is a lepton, false otherwise. - */ - inline bool isLepton( const xAOD::TruthParticle * truthParticle ){ - return ( 10 < truthParticle->absPdgId() && truthParticle->absPdgId() < 17 ); - } + /** + * @brief Function to determine whether a given truth particle is a + * result of a decay chain that started in the decay of a W or Z boson. + * + * The algorithm works by ascending through the decay chain following + * the production vertex reference (obtained by the prodVtx() member + * function of the xAOD::TruthParticle). From the input particle, the + * algorithm ascends through the chain until the PDG ID of the particle + * found as first incoming particle is not equal to the PDG ID of the + * input particle. The last production vertex found during this ascent + * should then correspond to the physical production vertex of the input + * particle. + * + * If the PDG ID of the mother particle (i.e. the incoming particle to + * the truth decay vertex) corresponds to a W / Z boson the algorithm + * terminates directly, returning true. Otherwise a vertex-based check + * is employed (which was designed to operate on SHERPA samples, c.f. + * the JetSimTools-00-02-09 package + * [svn: /Reconstruction/Jet/JetSimTools]). + * + * @param truthParticle The input particle. + * @param bOnlyDirect A flag denoting whether "chained matching" is + * allowed. In chained matching mode, intermittend particles are + * allowed, i.e. for the chain + * A -> B -> C + * isFrom( C, A ) is true (for A != B != C). If only direct decays are + * considered, this is only the case if A == B or B == C. Defaults to false. + * + * @return Return true if the input particle was created in a physical + * decay of a W or Z boson. Otherwise return false. Will also + * return false if the prduction vertex of the input particle is + * invalid or has zero incoming particles. + */ + bool isFromWZDecay(const xAOD::TruthParticle* truthParticle, + bool bOnlyDirect = false); - /*! - * @brief Check whether a given truth particle is not produced in the - * decay of physical hadrons or their descendents. This must be done in - * a recursive manner, i.e. the decay chain must be traversed upwards - * until the initial state is found. - * @param truthParticle The truth particle to be tested. - * @param bOnlyDirect A flag denoting whether "chained matching" is - * allowed. In chained matching mode, intermittend particles are - * allowed, i.e. for the chain - * A -> B -> C - * isFrom( C, A ) is true (for A != B != C). If only direct decays are - * considered, this is only the case if A == B or B == C. Defaults to - * false. - * @param bTauIsHadron If true, any intermediate tauons are treated as hadrons. - * @return True if truthParticle does not descend from a physical - * hadron, false otherwise. - */ - bool isNotFromHadron( const xAOD::TruthParticle * truthParticle, - bool bOnlyDirect = false, bool bTauIsHadron = false ); + /** + * @brief Function the check if a particle is a lepton which was + * produced in the decay of a tau lepton. + * + * @param truthParticle The input truth particle which will be checked. + * + * @return True if the input particle is a lepton and it has a parent + * which was a tau. False otherwise. Will also return false if + * the production vertex of the input particle is invalid. + */ + bool isLeptonFromTau(const xAOD::TruthParticle* truthParticle); + /** + * @brief Check whether a given truth particle is a lepton. + * @param truthParticle The input truth particle to be tested. + * @return Return true if input is a lepton, false otherwise. + */ + inline bool isLepton(const xAOD::TruthParticle* truthParticle) { + return(10 < truthParticle->absPdgId() && truthParticle->absPdgId() < 17); } + + /*! + * @brief Check whether a given truth particle is not produced in the + * decay of physical hadrons or their descendents. This must be done in + * a recursive manner, i.e. the decay chain must be traversed upwards + * until the initial state is found. + * @param truthParticle The truth particle to be tested. + * @param bOnlyDirect A flag denoting whether "chained matching" is + * allowed. In chained matching mode, intermittend particles are + * allowed, i.e. for the chain + * A -> B -> C + * isFrom( C, A ) is true (for A != B != C). If only direct decays are + * considered, this is only the case if A == B or B == C. Defaults to + * false. + * @param bTauIsHadron If true, any intermediate tauons are treated as hadrons. + * @return True if truthParticle does not descend from a physical + * hadron, false otherwise. + */ + bool isNotFromHadron(const xAOD::TruthParticle* truthParticle, + bool bOnlyDirect = false, bool bTauIsHadron = false); + } } #endif /* _TOP_PARTICLE_LEVEL_TRUTHTOOLS_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/CMakeLists.txt index e39ada9b15a41f896215f4c8c6cd9e3d783c23cf..d434650d2ff0a1ce1a113b9238945a4efde170b1 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/CMakeLists.txt @@ -1,4 +1,3 @@ - # Declare the name of this package: atlas_subdir( TopPartons ) @@ -16,8 +15,8 @@ find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore TMVA Gra # Generate a CINT dictionary source file: atlas_add_root_dictionary( TopPartons _cintDictSource - ROOT_HEADERS TopPartons/PartonHistory.h Root/LinkDef.h - EXTERNAL_PACKAGES ROOT ) + ROOT_HEADERS Root/LinkDef.h + EXTERNAL_PACKAGES ROOT ) # Build a library that other components can link against: atlas_add_library( TopPartons Root/*.cxx Root/*.h Root/*.icc diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTTZPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTTZPartonHistory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..744ce9d35cd6ccda41d54d0732017cd177d04be7 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTTZPartonHistory.cxx @@ -0,0 +1,197 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopPartons/CalcTTZPartonHistory.h" +#include "TopConfiguration/TopConfig.h" +#include "TopPartons/PartonHistoryUtils.h" + +namespace top { + CalcTTZPartonHistory::CalcTTZPartonHistory(const std::string& name) : CalcTtbarPartonHistory(name) {} + + void CalcTTZPartonHistory::zHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* ttbarPartonHistory) { + ttbarPartonHistory->IniVarZ(); + + TLorentzVector Z; + TLorentzVector ZDecay1; + TLorentzVector ZDecay2; + int ZDecay1_pdgId; + int ZDecay2_pdgId; + bool is_on_shell; + bool event_has_Z = CalcTTZPartonHistory::getZ(truthParticles, + &Z, + &ZDecay1, + &ZDecay1_pdgId, + &ZDecay2, + &ZDecay2_pdgId, + &is_on_shell); + + if (event_has_Z && !m_ancestry_corrupted) { + ttbarPartonHistory->auxdecor< float >("MC_Z_m") = Z.M(); + ttbarPartonHistory->auxdecor< float >("MC_Z_pt") = Z.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Z_eta") = Z.Eta(); + ttbarPartonHistory->auxdecor< float >("MC_Z_phi") = Z.Phi(); + + ttbarPartonHistory->auxdecor< float >("MC_Zdecay1_m") = ZDecay1.M(); + ttbarPartonHistory->auxdecor< float >("MC_Zdecay1_pt") = ZDecay1.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Zdecay1_eta") = ZDecay1.Eta(); + ttbarPartonHistory->auxdecor< float >("MC_Zdecay1_phi") = ZDecay1.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Zdecay1_pdgId") = ZDecay1_pdgId; + + ttbarPartonHistory->auxdecor< float >("MC_Zdecay2_m") = ZDecay2.M(); + ttbarPartonHistory->auxdecor< float >("MC_Zdecay2_pt") = ZDecay2.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Zdecay2_eta") = ZDecay2.Eta(); + ttbarPartonHistory->auxdecor< float >("MC_Zdecay2_phi") = ZDecay2.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Zdecay2_pdgId") = ZDecay2_pdgId; + + ttbarPartonHistory->auxdecor< int >("MC_Z_IsOnShell") = static_cast<int>(is_on_shell); + } // if + + ttbarPartonHistory->auxdecor< int >("MC_Z_AncestryCorrupted") = static_cast<int>(m_ancestry_corrupted); + } + + bool CalcTTZPartonHistory::getZ(const xAOD::TruthParticleContainer* truthParticles, + TLorentzVector* Z_p4, + TLorentzVector* ZDecay1, + int* ZDecay1_pdgId, + TLorentzVector* ZDecay2, + int* ZDecay2_pdgId, + bool* is_on_shell) { + bool hasZ { + false + }; + bool hasZDecay1 { + false + }; + bool hasZDecay2 { + false + }; + + *is_on_shell = false; + m_ancestry_corrupted = false; + + // First check for real (on-shell) Z bosons in the truth record + // (PDG ID 23). Only consider Z bosons at the end of the chain + // of radiative corrections (i.e. a Z boson decaying into + // something else than a Z). + for (const auto& p : *truthParticles) { + if (!p->isZ()) continue; + if (PartonHistoryUtils::hasParticleIdenticalParent(p)) continue; + + const auto& z = PartonHistoryUtils::findAfterFSR(p); + *is_on_shell = true; + if (z->nChildren() != 2) continue; + + *Z_p4 = z->p4(); + hasZ = true; + + for (size_t i = 0; i < z->nChildren(); ++i) { + const auto& child = z->child(i); + if (!child) continue; + if (child->pdgId() > 0) { + *ZDecay1 = PartonHistoryUtils::findAfterFSR(child)->p4(); + *ZDecay1_pdgId = child->pdgId(); + hasZDecay1 = true; + } else { + *ZDecay2 = PartonHistoryUtils::findAfterFSR(child)->p4(); + *ZDecay2_pdgId = child->pdgId(); + hasZDecay2 = true; + } + } // for + } // for + + // Our job is done if the event has a real Z boson. + if (hasZ && (!hasZDecay1 || !hasZDecay2)) m_ancestry_corrupted = true; + if (hasZ) return hasZ && hasZDecay1 && hasZDecay2; + + // For off-shell Z bosons it's a bit more tricky. We now look + // for two same-flavour particles that are attached to the + // ttbar vertex. + for (const auto& p : *truthParticles) { + if (abs(p->pdgId()) > 19) continue; // Only elementary fermions + if (p->pdgId() < 0) continue; // No anti-particles (to avoid + // double-counting) + const auto& sibling = getFlavourSibling(p); + if (!sibling) continue; + + // Check whether the particle is attached to the ttbar vertex. + bool has_top_sibling { + false + }; + bool has_antitop_sibling { + false + }; + const auto& parent = p->parent(0); + if (!parent) continue; + for (size_t i = 0; i < parent->nChildren(); ++i) { + const auto* child = parent->child(i); + if (!child) continue; + if (child == p) continue; // Make sure we don't look at our candidate. + if (child->pdgId() == 6) has_top_sibling = true; + if (child->pdgId() == -6) has_antitop_sibling = true; + if (has_top_sibling && has_antitop_sibling) break; + } + if (!(has_top_sibling && has_antitop_sibling)) continue; + + *ZDecay1 = p->p4(); + *ZDecay1_pdgId = p->pdgId(); + hasZDecay1 = true; + *ZDecay2 = sibling->p4(); + *ZDecay2_pdgId = sibling->pdgId(); + hasZDecay2 = true; + + *Z_p4 = *ZDecay1 + *ZDecay2; + hasZ = true; + } // for + + if (hasZ && (!hasZDecay1 || !hasZDecay2)) m_ancestry_corrupted = true; + return hasZ && hasZDecay1 && hasZDecay2; + } + + const xAOD::TruthParticle* CalcTTZPartonHistory::getFlavourSibling(const xAOD::TruthParticle* particle) { + const auto& parent = particle->parent(0); + + if (!parent) return nullptr; + + for (size_t i = 0; i < parent->nChildren(); ++i) { + const auto& sibling_candidate = parent->child(i); + if (!sibling_candidate) continue; + if (sibling_candidate->pdgId() == -particle->pdgId()) { + return sibling_candidate; + } + } + return nullptr; + } + + StatusCode CalcTTZPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* ttbarPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(ttbarPartonHistory); + + // Recover the parton history for ttbar events + ttbarHistorySaver(truthParticles, ttbarPartonHistory); + zHistorySaver(truthParticles, ttbarPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTbbarPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTbbarPartonHistory.cxx index 934af91221533251441e072d52c47b1227444f35..ea3121d9b2f797fd35348515e8359e2a66137399 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTbbarPartonHistory.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTbbarPartonHistory.cxx @@ -1,116 +1,114 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopPartons/CalcTbbarPartonHistory.h" #include "TopConfiguration/TopConfig.h" -namespace top{ - - CalcTbbarPartonHistory::CalcTbbarPartonHistory(const std::string& name) : CalcTopPartonHistory( name ){} - - void CalcTbbarPartonHistory::tbbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* tbbarPartonHistory){ - - tbbarPartonHistory->IniVarTbbar(); - - TLorentzVector t_before, t_after; - TLorentzVector Wp; - TLorentzVector b_from_top; - TLorentzVector WpDecay1; - TLorentzVector WpDecay2; - int WpDecay1_pdgId; - int WpDecay2_pdgId; - bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, Wp, b_from_top, WpDecay1, WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); - if(!event_top)event_top = CalcTopPartonHistory::topWb(truthParticles, -6, t_before, t_after, Wp, b_from_top, WpDecay1, WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); - - TLorentzVector b_beforeFSR; - TLorentzVector b_afterFSR; - bool event_b = CalcTopPartonHistory::b(truthParticles, b_beforeFSR, b_afterFSR); - - if (event_top && event_b){ - TLorentzVector temp = t_before+b_beforeFSR; - tbbarPartonHistory->auxdecor< float >( "MC_tbbar_beforeFSR_m" ) = temp.M(); - tbbarPartonHistory->auxdecor< float >( "MC_tbbar_beforeFSR_pt" ) = temp.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_tbbar_beforeFSR_phi" ) = temp.Phi(); - fillEtaBranch(tbbarPartonHistory,"MC_tbbar_beforeFSR_eta", temp); - - temp = WpDecay1+WpDecay2+b_from_top + b_afterFSR; - tbbarPartonHistory->auxdecor< float >( "MC_tbbar_afterFSR_m" ) = temp.M(); - tbbarPartonHistory->auxdecor< float >( "MC_tbbar_afterFSR_pt" ) = temp.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_tbbar_afterFSR_phi" ) = temp .Phi(); - fillEtaBranch(tbbarPartonHistory, "MC_tbbar_afterFSR_eta", temp); - }//if - if (event_top){ - tbbarPartonHistory->auxdecor< float >( "MC_t_beforeFSR_m" ) = t_before.M(); - tbbarPartonHistory->auxdecor< float >( "MC_t_beforeFSR_pt" ) = t_before.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_t_beforeFSR_phi" ) = t_before.Phi(); - fillEtaBranch(tbbarPartonHistory,"MC_t_beforeFSR_eta", t_before); - - tbbarPartonHistory->auxdecor< float >( "MC_W_from_t_m" ) = Wp.M(); - tbbarPartonHistory->auxdecor< float >( "MC_W_from_t_pt" ) = Wp.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_W_from_t_phi" ) = Wp.Phi(); - fillEtaBranch(tbbarPartonHistory, "MC_W_from_t_eta", Wp); - - tbbarPartonHistory->auxdecor< float >( "MC_b_from_t_m" ) = b_from_top.M(); - tbbarPartonHistory->auxdecor< float >( "MC_b_from_t_pt" ) = b_from_top.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_b_from_t_phi" ) = b_from_top.Phi(); - fillEtaBranch(tbbarPartonHistory,"MC_b_from_t_eta", b_from_top); - - tbbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_t_m" ) = WpDecay1.M(); - tbbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_t_pt" ) = WpDecay1.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_t_phi" ) = WpDecay1.Phi(); - tbbarPartonHistory->auxdecor< int >( "MC_Wdecay1_from_t_pdgId" ) = WpDecay1_pdgId; - fillEtaBranch(tbbarPartonHistory,"MC_Wdecay1_from_t_eta", WpDecay1); - - tbbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_t_m" ) = WpDecay2.M(); - tbbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_t_pt" ) = WpDecay2.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_t_phi" ) = WpDecay2.Phi(); - tbbarPartonHistory->auxdecor< int >( "MC_Wdecay2_from_t_pdgId" ) = WpDecay2_pdgId; - fillEtaBranch(tbbarPartonHistory,"MC_Wdecay2_from_t_eta", WpDecay2); - }//if - if (event_b){ - - tbbarPartonHistory->auxdecor< float >( "MC_b_beforeFSR_m" ) = b_beforeFSR.M(); - tbbarPartonHistory->auxdecor< float >( "MC_b_beforeFSR_pt" ) = b_beforeFSR.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_b_beforeFSR_phi" ) = b_beforeFSR.Phi(); - fillEtaBranch(tbbarPartonHistory,"MC_b_beforeFSR_eta", b_beforeFSR); - - tbbarPartonHistory->auxdecor< float >( "MC_b_afterFSR_m" ) = b_afterFSR.M(); - tbbarPartonHistory->auxdecor< float >( "MC_b_afterFSR_pt" ) = b_afterFSR.Pt(); - tbbarPartonHistory->auxdecor< float >( "MC_b_afterFSR_phi" ) = b_afterFSR.Phi(); - fillEtaBranch(tbbarPartonHistory,"MC_b_afterFSR_eta", b_afterFSR); - - }//if - +namespace top { + CalcTbbarPartonHistory::CalcTbbarPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + void CalcTbbarPartonHistory::tbbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* tbbarPartonHistory) { + tbbarPartonHistory->IniVarTbbar(); + + TLorentzVector t_before, t_after; + TLorentzVector Wp; + TLorentzVector b_from_top; + TLorentzVector WpDecay1; + TLorentzVector WpDecay2; + int WpDecay1_pdgId; + int WpDecay2_pdgId; + bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, Wp, b_from_top, WpDecay1, + WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); + if (!event_top) event_top = CalcTopPartonHistory::topWb(truthParticles, -6, t_before, t_after, Wp, b_from_top, + WpDecay1, WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); + + TLorentzVector b_beforeFSR; + TLorentzVector b_afterFSR; + bool event_b = CalcTopPartonHistory::b(truthParticles, b_beforeFSR, b_afterFSR); + + if (event_top && event_b) { + TLorentzVector temp = t_before + b_beforeFSR; + tbbarPartonHistory->auxdecor< float >("MC_tbbar_beforeFSR_m") = temp.M(); + tbbarPartonHistory->auxdecor< float >("MC_tbbar_beforeFSR_pt") = temp.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_tbbar_beforeFSR_phi") = temp.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_tbbar_beforeFSR_eta", temp); + + temp = WpDecay1 + WpDecay2 + b_from_top + b_afterFSR; + tbbarPartonHistory->auxdecor< float >("MC_tbbar_afterFSR_m") = temp.M(); + tbbarPartonHistory->auxdecor< float >("MC_tbbar_afterFSR_pt") = temp.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_tbbar_afterFSR_phi") = temp.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_tbbar_afterFSR_eta", temp); + }//if + if (event_top) { + tbbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_m") = t_before.M(); + tbbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_pt") = t_before.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_phi") = t_before.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_t_beforeFSR_eta", t_before); + + tbbarPartonHistory->auxdecor< float >("MC_W_from_t_m") = Wp.M(); + tbbarPartonHistory->auxdecor< float >("MC_W_from_t_pt") = Wp.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_W_from_t_phi") = Wp.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_W_from_t_eta", Wp); + + tbbarPartonHistory->auxdecor< float >("MC_b_from_t_m") = b_from_top.M(); + tbbarPartonHistory->auxdecor< float >("MC_b_from_t_pt") = b_from_top.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_b_from_t_phi") = b_from_top.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_b_from_t_eta", b_from_top); + + tbbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_m") = WpDecay1.M(); + tbbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_pt") = WpDecay1.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_phi") = WpDecay1.Phi(); + tbbarPartonHistory->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = WpDecay1_pdgId; + fillEtaBranch(tbbarPartonHistory, "MC_Wdecay1_from_t_eta", WpDecay1); + + tbbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_m") = WpDecay2.M(); + tbbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_pt") = WpDecay2.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_phi") = WpDecay2.Phi(); + tbbarPartonHistory->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = WpDecay2_pdgId; + fillEtaBranch(tbbarPartonHistory, "MC_Wdecay2_from_t_eta", WpDecay2); + }//if + if (event_b) { + tbbarPartonHistory->auxdecor< float >("MC_b_beforeFSR_m") = b_beforeFSR.M(); + tbbarPartonHistory->auxdecor< float >("MC_b_beforeFSR_pt") = b_beforeFSR.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_b_beforeFSR_phi") = b_beforeFSR.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_b_beforeFSR_eta", b_beforeFSR); + + tbbarPartonHistory->auxdecor< float >("MC_b_afterFSR_m") = b_afterFSR.M(); + tbbarPartonHistory->auxdecor< float >("MC_b_afterFSR_pt") = b_afterFSR.Pt(); + tbbarPartonHistory->auxdecor< float >("MC_b_afterFSR_phi") = b_afterFSR.Phi(); + fillEtaBranch(tbbarPartonHistory, "MC_b_afterFSR_eta", b_afterFSR); + }//if } - StatusCode CalcTbbarPartonHistory::execute() - { - // Get the Truth Particles - const xAOD::TruthParticleContainer* truthParticles(nullptr); - ATH_CHECK( evtStore()->retrieve( truthParticles , m_config->sgKeyMCParticle() ) ); - - // Create the partonHistory xAOD object - xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer{}; - xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer{}; - partonCont->setStore( partonAuxCont ); - - xAOD::PartonHistory* tbbarPartonHistory = new xAOD::PartonHistory{}; - partonCont->push_back( tbbarPartonHistory ); - - // Recover the parton history for tbbar events - tbbarHistorySaver(truthParticles, tbbarPartonHistory); - - // Save to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyTopPartonHistory(); - std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( partonCont , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( partonAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } - - return StatusCode::SUCCESS; + StatusCode CalcTbbarPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* tbbarPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(tbbarPartonHistory); + + // Recover the parton history for tbbar events + tbbarHistorySaver(truthParticles, tbbarPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcThqPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcThqPartonHistory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..9b1a51ce9b1445464b4970bf537fa0a8de6fdbc0 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcThqPartonHistory.cxx @@ -0,0 +1,196 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopPartons/CalcThqPartonHistory.h" +#include "TopPartons/CalcTopPartonHistory.h" +#include "TopPartons/PartonHistoryUtils.h" +#include "TopConfiguration/TopConfig.h" + +namespace top { + CalcThqPartonHistory::CalcThqPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + bool CalcThqPartonHistory::HiggsAndDecay(const xAOD::TruthParticleContainer* truthParticles) { + + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->pdgId() != 25 || particle->nChildren() != 2) { + continue; + } + tH.Higgs_p4 = particle->p4(); + + const top::PartonHistoryUtils::HiggsDecay& higgs = top::PartonHistoryUtils::AnalyzeHiggsDecay(particle); + + tH.decay1_p4 = higgs.decay1_vector; + tH.decay2_p4 = higgs.decay2_vector; + tH.decay1_pdgId = higgs.decay1_pdgId; + tH.decay2_pdgId = higgs.decay2_pdgId; + tH.tau_decay1_isHadronic = higgs.tau_decay1_isHadronic; + tH.tau_decay2_isHadronic = higgs.tau_decay2_isHadronic; + tH.decay1_from_decay1_p4 = higgs.decay1_from_decay1_vector; + tH.decay2_from_decay1_p4 = higgs.decay2_from_decay1_vector; + tH.decay1_from_decay1_pdgId = higgs.decay1_from_decay1_pdgId; + tH.decay2_from_decay1_pdgId = higgs.decay2_from_decay1_pdgId; + tH.decay1_from_decay2_p4 = higgs.decay1_from_decay2_vector; + tH.decay2_from_decay2_p4 = higgs.decay2_from_decay2_vector; + tH.decay1_from_decay2_pdgId = higgs.decay1_from_decay2_pdgId; + tH.decay2_from_decay2_pdgId = higgs.decay2_from_decay2_pdgId; + tH.tau_decay1_from_decay1_isHadronic = higgs.tau_decay1_from_decay1_isHadronic; + tH.tau_decay2_from_decay1_isHadronic = higgs.tau_decay2_from_decay1_isHadronic; + tH.tau_decay1_from_decay2_isHadronic = higgs.tau_decay1_from_decay2_isHadronic; + tH.tau_decay2_from_decay2_isHadronic = higgs.tau_decay2_from_decay2_isHadronic; + + return true; + } + return false; + } + + void CalcThqPartonHistory::THHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* ThqPartonHistory) { + ThqPartonHistory->IniVarThq(); + TLorentzVector t_before, t_after, t_after_SC; + TLorentzVector Wp; + TLorentzVector b; + TLorentzVector WpDecay1; + TLorentzVector WpDecay2; + int WpDecay1_pdgId; + int WpDecay2_pdgId; + + const bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, + Wp, b, WpDecay1, WpDecay1_pdgId, + WpDecay2, WpDecay2_pdgId); + const bool event_top_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, 6, t_after_SC); + const bool event_topbar = CalcTopPartonHistory::topWb(truthParticles, -6, t_before, t_after, + Wp, b, WpDecay1, + WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); + const bool event_topbar_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, -6, t_after_SC); + const bool event_Higgs = CalcThqPartonHistory::HiggsAndDecay(truthParticles); + + if (event_Higgs) { + if (event_top || event_topbar) { + ThqPartonHistory->auxdecor< float >("MC_t_beforeFSR_m") = t_before.M(); + ThqPartonHistory->auxdecor< float >("MC_t_beforeFSR_pt") = t_before.Pt(); + ThqPartonHistory->auxdecor< float >("MC_t_beforeFSR_phi") = t_before.Phi(); + fillEtaBranch(ThqPartonHistory, "MC_t_beforeFSR_eta", t_before); + + ThqPartonHistory->auxdecor< float >("MC_t_afterFSR_m") = t_after.M(); + ThqPartonHistory->auxdecor< float >("MC_t_afterFSR_pt") = t_after.Pt(); + ThqPartonHistory->auxdecor< float >("MC_t_afterFSR_phi") = t_after.Phi(); + fillEtaBranch(ThqPartonHistory, "MC_t_afterFSR_eta", t_after); + + if (event_top_SC || event_topbar_SC) { + ThqPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_m") = t_after_SC.M(); + ThqPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_pt") = t_after_SC.Pt(); + ThqPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_phi") = t_after_SC.Phi(); + fillEtaBranch(ThqPartonHistory, "MC_t_afterFSR_SC_eta", t_after_SC); + } + + ThqPartonHistory->auxdecor< float >("MC_W_from_t_m") = Wp.M(); + ThqPartonHistory->auxdecor< float >("MC_W_from_t_pt") = Wp.Pt(); + ThqPartonHistory->auxdecor< float >("MC_W_from_t_phi") = Wp.Phi(); + fillEtaBranch(ThqPartonHistory, "MC_W_from_t_eta", Wp); + + ThqPartonHistory->auxdecor< float >("MC_b_from_t_m") = b.M(); + ThqPartonHistory->auxdecor< float >("MC_b_from_t_pt") = b.Pt(); + ThqPartonHistory->auxdecor< float >("MC_b_from_t_phi") = b.Phi(); + fillEtaBranch(ThqPartonHistory, "MC_b_from_t_eta", b); + + ThqPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_m") = WpDecay1.M(); + ThqPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_pt") = WpDecay1.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_phi") = WpDecay1.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = WpDecay1_pdgId; + fillEtaBranch(ThqPartonHistory, "MC_Wdecay1_from_t_eta", WpDecay1); + + ThqPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_m") = WpDecay2.M(); + ThqPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_pt") = WpDecay2.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_phi") = WpDecay2.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = WpDecay2_pdgId; + fillEtaBranch(ThqPartonHistory, "MC_Wdecay2_from_t_eta", WpDecay2); + + //Higgs-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_m") = tH.Higgs_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_pt") = tH.Higgs_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_phi") = tH.Higgs_p4.Phi(); + fillEtaBranch(ThqPartonHistory, "MC_Higgs_eta", tH.Higgs_p4); + + //Higgs-decay1-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_m") = tH.decay1_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_pt") = tH.decay1_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_phi") = tH.decay1_p4.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Higgs_decay1_pdgId") = tH.decay1_pdgId; + ThqPartonHistory->auxdecor< int >("MC_Higgs_tau_decay1_isHadronic") = tH.tau_decay1_isHadronic; + fillEtaBranch(ThqPartonHistory, "MC_Higgs_decay1_eta", tH.decay1_p4); + + //Higgs-decay2-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_m") = tH.decay2_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_pt") = tH.decay2_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_phi") = tH.decay2_p4.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Higgs_decay2_pdgId") = tH.decay2_pdgId; + ThqPartonHistory->auxdecor< int >("MC_Higgs_tau_decay2_isHadronic") = tH.tau_decay1_isHadronic; + fillEtaBranch(ThqPartonHistory, "MC_Higgs_decay2_eta", tH.decay2_p4); + + //Higgs-decay1- from decay1-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_from_decay1_m") = tH.decay1_from_decay1_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_from_decay1_pt") = tH.decay1_from_decay1_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_from_decay1_phi") = tH.decay1_from_decay1_p4.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Higgs_decay1_from_decay1_pdgId") = tH.decay1_from_decay1_pdgId; + ThqPartonHistory->auxdecor< int >("MC_Higgs_tau_decay1_from_decay1_isHadronic") = tH.tau_decay1_from_decay1_isHadronic; + fillEtaBranch(ThqPartonHistory, "MC_Higgs_decay1_from_decay1_eta", tH.decay1_from_decay1_p4); + + //Higgs-decay2- from decay1-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_from_decay1_m") = tH.decay2_from_decay1_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_from_decay1_pt") = tH.decay2_from_decay1_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_from_decay1_phi") = tH.decay2_from_decay1_p4.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Higgs_decay2_from_decay1_pdgId") = tH.decay2_from_decay1_pdgId; + ThqPartonHistory->auxdecor< int >("MC_Higgs_tau_decay2_from_decay1_isHadronic") = tH.tau_decay2_from_decay1_isHadronic; + fillEtaBranch(ThqPartonHistory, "MC_Higgs_decay2_from_decay1_eta", tH.decay2_from_decay1_p4); + + //Higgs-decay1- from decay2-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_from_decay2_m") = tH.decay1_from_decay2_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_from_decay2_pt") = tH.decay1_from_decay2_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay1_from_decay2_phi") = tH.decay1_from_decay2_p4.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Higgs_decay1_from_decay2_pdgId") = tH.decay1_from_decay2_pdgId; + ThqPartonHistory->auxdecor< int >("MC_Higgs_tau_decay1_from_decay2_isHadronic") = tH.tau_decay1_from_decay2_isHadronic; + fillEtaBranch(ThqPartonHistory, "MC_Higgs_decay1_from_decay2_eta", tH.decay1_from_decay2_p4); + + //Higgs-decay2- from decay2-Variables + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_from_decay2_m") = tH.decay2_from_decay2_p4.M(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_from_decay2_pt") = tH.decay2_from_decay2_p4.Pt(); + ThqPartonHistory->auxdecor< float >("MC_Higgs_decay2_from_decay2_phi") = tH.decay2_from_decay2_p4.Phi(); + ThqPartonHistory->auxdecor< int >("MC_Higgs_decay2_from_decay2_pdgId") = tH.decay2_from_decay2_pdgId; + ThqPartonHistory->auxdecor< int >("MC_Higgs_tau_decay2_from_decay2_isHadronic") = tH.tau_decay2_from_decay2_isHadronic; + fillEtaBranch(ThqPartonHistory, "MC_Higgs_decay2_from_decay2_eta", tH.decay2_from_decay2_p4); + + } + } + } + + StatusCode CalcThqPartonHistory::execute() { + //Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* ThqPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(ThqPartonHistory); + + // Recover the parton history for TH events + THHistorySaver(truthParticles, ThqPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTopPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTopPartonHistory.cxx index 9a1646a146a6a0af6ce3deb8c3452eb15126a84a..5b5b738f314a09d3fd4d611e88f657dff1c1c09b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTopPartonHistory.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTopPartonHistory.cxx @@ -1,28 +1,85 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ // $Id: CalcTopPartonHistory.cxx 800464 2017-03-13 18:06:24Z tpelzer $ #include "TopPartons/CalcTopPartonHistory.h" #include "TopPartons/PartonHistory.h" #include "TopConfiguration/TopConfig.h" #include "TopPartons/CalcTtbarPartonHistory.h" +#include "TopPartons/PartonHistoryUtils.h" #include "xAODTruth/TruthVertex.h" -namespace top{ +namespace top { + CalcTopPartonHistory::CalcTopPartonHistory(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr) { + declareProperty("config", m_config); + } + + StatusCode CalcTopPartonHistory::buildContainerFromMultipleCollections(const std::vector<std::string> &collections, const std::string& out_contName) + { + ConstDataVector<DataVector<xAOD::TruthParticle_v1> > *out_cont = new ConstDataVector<DataVector<xAOD::TruthParticle_v1> > (SG::VIEW_ELEMENTS); + + for(const std::string& collection : collections) + { + const xAOD::TruthParticleContainer* cont=nullptr; + ATH_CHECK(evtStore()->retrieve(cont,collection)); + for(const xAOD::TruthParticle* p : *cont) out_cont->push_back(p); + } + + //we give control of the container to the store, because in this way we are able to retrieve it as a const data vector, see https://twiki.cern.ch/twiki/bin/view/AtlasComputing/DataVector#ConstDataVector + xAOD::TReturnCode save = evtStore()->tds()->record(out_cont,out_contName); + if (!save) return StatusCode::FAILURE; + + return StatusCode::SUCCESS; + } - CalcTopPartonHistory::CalcTopPartonHistory( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr) - { - declareProperty( "config" , m_config ); + StatusCode CalcTopPartonHistory::linkBosonCollections() + { + return decorateCollectionWithLinksToAnotherCollection("TruthBoson","TruthBosonsWithDecayParticles","AT_linkToTruthBosonsWithDecayParticles"); + } + StatusCode CalcTopPartonHistory::decorateCollectionWithLinksToAnotherCollection(const std::string &collectionToDecorate, const std::string &collectionToLink, const std::string &nameOfDecoration) + { + const xAOD::TruthParticleContainer* cont1(nullptr); + const xAOD::TruthParticleContainer* cont2(nullptr); + ATH_CHECK(evtStore()->retrieve(cont1,collectionToDecorate)); + ATH_CHECK(evtStore()->retrieve(cont2,collectionToLink)); + + for(const xAOD::TruthParticle *p : *cont1) + { + + const xAOD::TruthParticle* link =0; + for(const xAOD::TruthParticle *p2 : *cont2) + { + if(p->pdgId()==p2->pdgId() && p->barcode()==p2->barcode()) + { + link=p2; + break; + } + } + p->auxdecor<const xAOD::TruthParticle*>(nameOfDecoration)=link; + + } + return StatusCode::SUCCESS; } + const xAOD::TruthParticle* CalcTopPartonHistory::getTruthParticleLinkedFromDecoration(const xAOD::TruthParticle* part, const std::string &decorationName) + { + if(!part->isAvailable<const xAOD::TruthParticle*>(decorationName)) return part; + + const xAOD::TruthParticle* link=part->auxdecor<const xAOD::TruthParticle*>(decorationName); + if(link) return link; + + return part; + } + ///Store the four-momentum of the post-FSR top or anti-top found using statusCodes ///This would only work if there is at most one "true" top of each charge (i.e. won't work for SS tops or 4 tops) - ///This code was adapted from the 7TeV parton-level differential ttbar routine: https://svnweb.cern.ch/trac/atlasphys-top/browser/Physics/Top/Software/MCvalidation/Rivet/Rivet2.X/trunk/routines/ATLAS_2014_I1304289/ATLAS_2014_I1304289.cc - bool CalcTopPartonHistory::topAfterFSR_SC(const xAOD::TruthParticleContainer* truthParticles, int start, TLorentzVector& top_afterFSR_SC_p4){ - + ///This code was adapted from the 7TeV parton-level differential ttbar routine: + // https://svnweb.cern.ch/trac/atlasphys-top/browser/Physics/Top/Software/MCvalidation/Rivet/Rivet2.X/trunk/routines/ATLAS_2014_I1304289/ATLAS_2014_I1304289.cc + bool CalcTopPartonHistory::topAfterFSR_SC(const xAOD::TruthParticleContainer* truthParticles, int start, + TLorentzVector& top_afterFSR_SC_p4) { /// Step1: create vectors of particles of each status codes // Vectors to hold any status=3 (anti-)top quarks (Pythia 6) std::vector<const xAOD::TruthParticle*> v_status3_top; @@ -32,62 +89,59 @@ namespace top{ std::vector<const xAOD::TruthParticle*> v_status11_top; // Vectors to hold any status=22 (anti-)top quarks std::vector<const xAOD::TruthParticle*> v_statusOther_top; - + /// Step2: loop on the container of particles and fill the above created vectors for (const xAOD::TruthParticle* particle : *truthParticles) { if (particle->pdgId() != start) continue; // only keep particles of a given pdgID (e.g. 6 or -6) - - if (particle->status()==3) { + + if (particle->status() == 3) { v_status3_top.push_back(particle); - } - else if (particle->status()==155) { + } else if (particle->status() == 155) { v_status155_top.push_back(particle); - } - else if (particle->status()==11) {// for Herwig++: take only the tops that decay into Wb!!! + } else if (particle->status() == 11) {// for Herwig++: take only the tops that decay into Wb!!! if (!particle->hasDecayVtx()) continue; const xAOD::TruthVertex* vertex = particle->decayVtx(); if (vertex == nullptr) continue; if (vertex->nOutgoingParticles() == 2) v_status11_top.push_back(particle); - } - else { + } else { v_statusOther_top.push_back(particle); } } - + /// Step3: for some of the statuscodes, keep only the last of the vector // If there are more than 1 status 3 tops or anti-tops, only keep the last one put into the vector - if(v_status3_top.size()>1) { + if (v_status3_top.size() > 1) { v_status3_top = std::vector<const xAOD::TruthParticle*>(v_status3_top.end() - 1, v_status3_top.end()); } // If there are more than 1 status 11 tops or anti-tops, only keep the last one put into the vector - if(v_status11_top.size()>1) { + if (v_status11_top.size() > 1) { v_status11_top = std::vector<const xAOD::TruthParticle*>(v_status11_top.end() - 1, v_status11_top.end()); } // Rach: check for Pythia 8 as well // If there are more than 1 status 3 tops or anti-tops, only keep the last one put into the vector - if(v_statusOther_top.size()>1) { + if (v_statusOther_top.size() > 1) { v_statusOther_top = std::vector<const xAOD::TruthParticle*>(v_statusOther_top.end() - 1, v_statusOther_top.end()); } - + /// Step4: chose which statuscode to take according to what is found in the event const xAOD::TruthParticle* top = nullptr; // If there are status 3 tops and no status 155 tops this is probably a Pythia event, so used the status 3s. - if(v_status3_top.size() == 1 && v_status155_top.size() == 0) { + if (v_status3_top.size() == 1 && v_status155_top.size() == 0) { top = v_status3_top[0]; } // If there are status 155 tops this must be a Herwig event, so use the status 155s. - if( v_status155_top.size() == 1 && v_status3_top.size() == 0) { + if (v_status155_top.size() == 1 && v_status3_top.size() == 0) { top = v_status155_top[0]; } - // If there are tops with other status this must be a Pythia8 event, so use them. - if( v_statusOther_top.size() == 1 && v_status155_top.size() == 0 && v_status3_top.size()==0) { + // If there are tops with other status this must be a Pythia8 event, so use them. + if (v_statusOther_top.size() == 1 && v_status155_top.size() == 0 && v_status3_top.size() == 0) { top = v_statusOther_top[0]; } // If there are status 155 tops this must be a Herwig event, so use the status 155s. - if( v_status11_top.size() == 1 && v_status3_top.size() == 0) { + if (v_status11_top.size() == 1 && v_status3_top.size() == 0) { top = v_status11_top[0]; } - + /// Step5: if everything worked, set the 4-vector to its value and return true if (top != nullptr) { top_afterFSR_SC_p4 = top->p4(); @@ -95,210 +149,534 @@ namespace top{ } return false; } - - // for b coming from W'->tb - bool CalcTopPartonHistory::b( const xAOD::TruthParticleContainer* truthParticles, - TLorentzVector& b_beforeFSR, TLorentzVector& b_afterFSR){ + + // for b coming from W'->tb + bool CalcTopPartonHistory::b(const xAOD::TruthParticleContainer* truthParticles, + TLorentzVector& b_beforeFSR, TLorentzVector& b_afterFSR) { for (const xAOD::TruthParticle* particle : *truthParticles) { - - if (fabs(particle->pdgId()) != 5) continue; - - bool skipit(false); - for (size_t i=0; i< particle->nParents(); i++ ) { - const xAOD::TruthParticle* parent = particle->parent(i); - if (parent && (parent->isTop() || fabs(parent->pdgId())==5) ){ - skipit=true; - break; - }//if - }//for - - if( skipit) continue; - - b_beforeFSR = particle->p4(); - b_afterFSR = findAfterFSR(particle)->p4(); - - return true; - } - - - return false; + if (abs(particle->pdgId()) != 5) continue; + + bool skipit(false); + for (size_t i = 0; i < particle->nParents(); i++) { + const xAOD::TruthParticle* parent = particle->parent(i); + if (parent && (parent->isTop() || abs(parent->pdgId()) == 5)) { + skipit = true; + break; + }//if + }//for + + if (skipit) continue; + + b_beforeFSR = particle->p4(); + b_afterFSR = PartonHistoryUtils::findAfterFSR(particle)->p4(); + + return true; + } + + + return false; } - - - bool CalcTopPartonHistory::topWb( const xAOD::TruthParticleContainer* truthParticles, - int start, TLorentzVector& t_beforeFSR_p4, TLorentzVector& t_afterFSR_p4, TLorentzVector& W_p4, - TLorentzVector& b_p4, TLorentzVector& Wdecay1_p4, - int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId){ - - bool hasT = false; - bool hasW = false; - bool hasB = false; - bool hasWdecayProd1 = false; - bool hasWdecayProd2 = false; - + + bool CalcTopPartonHistory::topWb(const xAOD::TruthParticleContainer* truthParticles, + int start, TLorentzVector& t_beforeFSR_p4, TLorentzVector& t_afterFSR_p4, + TLorentzVector& W_p4, + TLorentzVector& b_p4, TLorentzVector& Wdecay1_p4, + int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId) { + bool hasT = false; + bool hasW = false; + bool hasB = false; + bool hasWdecayProd1 = false; + bool hasWdecayProd2 = false; + for (const xAOD::TruthParticle* particle : *truthParticles) { - - if (particle->pdgId() != start) continue; - - if (hasParticleIdenticalParent(particle)) continue; // kepping only top before FSR - - t_beforeFSR_p4 = particle->p4(); // top before FSR - hasT = true; - - // demanding the last tops after FSR - particle = findAfterFSR(particle); - t_afterFSR_p4 = particle->p4(); // top after FSR - - for (size_t k=0; k < particle->nChildren(); k++) { - const xAOD::TruthParticle* topChildren = particle->child(k); - - if (fabs(topChildren->pdgId()) == 24){ - - W_p4 = topChildren->p4(); // W boson after FSR - hasW = true; - - // demanding the last W after FSR - topChildren = findAfterFSR(topChildren); - - for (size_t q = 0; q < topChildren->nChildren(); ++q) { - const xAOD::TruthParticle* WChildren = topChildren->child(q); - if (fabs(WChildren->pdgId())<17){ - if (WChildren->pdgId()>0){ - Wdecay1_p4 = WChildren->p4(); - Wdecay1_pdgId = WChildren->pdgId(); - hasWdecayProd1 = true; - }else{ - Wdecay2_p4 = WChildren->p4(); - Wdecay2_pdgId = WChildren->pdgId(); - hasWdecayProd2 = true; - }//else - }//if - }//for - - } else if (fabs(topChildren->pdgId()) == 5) { - b_p4 = topChildren->p4(); - hasB = true; - } //else if - - } //for (size_t k=0; k < particle->nChildren(); k++) - if (hasT && hasW && hasB && hasWdecayProd1 && hasWdecayProd2) return true; + if (particle->pdgId() != start) continue; + + if (PartonHistoryUtils::hasParticleIdenticalParent(particle)) continue; // kepping only top before FSR + + t_beforeFSR_p4 = particle->p4(); // top before FSR + hasT = true; + + // demanding the last tops after FSR + particle = PartonHistoryUtils::findAfterFSR(particle); + t_afterFSR_p4 = particle->p4(); // top after FSR + + for (size_t k = 0; k < particle->nChildren(); k++) { + const xAOD::TruthParticle* topChildren = particle->child(k); + + if (abs(topChildren->pdgId()) == 24) { + W_p4 = topChildren->p4(); // W boson after FSR + hasW = true; + + // demanding the last W after FSR + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + + //for DAOD_PHYS we have to use a special procedure to associate W bosons linked from the top to those in the TruthBosonsWithDecayParticles collection, which have the correct links for their decay products + //this is better explained in the head; this will work only if the class calling this function has called linkBosonCollections() before + if(m_config->getDerivationStream() == "PHYS") topChildren=getTruthParticleLinkedFromDecoration(topChildren,"AT_linkToTruthBosonsWithDecayParticles"); + + for (size_t q = 0; q < topChildren->nChildren(); ++q) { + const xAOD::TruthParticle* WChildren = topChildren->child(q); + if (abs(WChildren->pdgId()) < 17) { + if (WChildren->pdgId() > 0) { + Wdecay1_p4 = WChildren->p4(); + Wdecay1_pdgId = WChildren->pdgId(); + hasWdecayProd1 = true; + } else { + Wdecay2_p4 = WChildren->p4(); + Wdecay2_pdgId = WChildren->pdgId(); + hasWdecayProd2 = true; + }//else + }//if + }//for + } else if (abs(topChildren->pdgId()) == 5) { + b_p4 = topChildren->p4(); + hasB = true; + } //else if + } //for (size_t k=0; k < particle->nChildren(); k++) + + if (hasT && hasW && hasB && hasWdecayProd1 && hasWdecayProd2) return true; + } //for (const xAOD::TruthParticle* particle : *truthParticles) - return false; - + return false; } - bool CalcTopPartonHistory::Wlv( const xAOD::TruthParticleContainer* truthParticles, - TLorentzVector& W_p4, - TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, - TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId){ + bool CalcTopPartonHistory::topWq(const xAOD::TruthParticleContainer* truthParticles, + int start, TLorentzVector& t_beforeFSR_p4, TLorentzVector& t_afterFSR_p4, + TLorentzVector& W_p4, + TLorentzVector& q_p4, int& q_pdgId, TLorentzVector& Wdecay1_p4, + int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId) { + bool hasT = false; + bool hasW = false; + bool hasQ = false; + bool hasWdecayProd1 = false; + bool hasWdecayProd2 = false; - bool hasW = false; - bool hasWdecayProd1 = false; - bool hasWdecayProd2 = false; - for (const xAOD::TruthParticle* particle : *truthParticles) { - - - if (fabs(particle->pdgId()) != 24) continue; - //std::cout << "PDGID: " << particle->pdgId() << std::endl; - - // demanding the last W after FSR - particle = findAfterFSR(particle); - W_p4 = particle->p4(); // W boson after FSR - hasW = true; - - for (size_t k=0; k < particle->nChildren(); k++) { - const xAOD::TruthParticle* WChildren = particle->child(k); - if (fabs(WChildren->pdgId())<17){ - if (WChildren->pdgId()%2==1){ // charged lepton in the Wlv case - Wdecay1_p4 = WChildren->p4(); - Wdecay1_pdgId = WChildren->pdgId(); - hasWdecayProd1 = true; - }else{// neutral lepton in the Wlv case - Wdecay2_p4 = WChildren->p4(); - Wdecay2_pdgId = WChildren->pdgId(); - hasWdecayProd2 = true; - }//else - }//if - - } //for (size_t k=0; k < particle->nChildren(); k++) - - if (hasW && hasWdecayProd1 && hasWdecayProd2) return true; + if (particle->pdgId() != start) continue; + + if (PartonHistoryUtils::hasParticleIdenticalParent(particle)) continue; // kepping only top before FSR + + t_beforeFSR_p4 = particle->p4(); // top before FSR + hasT = true; + + // demanding the last tops after FSR + particle = PartonHistoryUtils::findAfterFSR(particle); + t_afterFSR_p4 = particle->p4(); // top after FSR + + for (size_t k = 0; k < particle->nChildren(); k++) { + const xAOD::TruthParticle* topChildren = particle->child(k); + + if (abs(topChildren->pdgId()) == 24) { + W_p4 = topChildren->p4(); // W boson after FSR + hasW = true; + + // demanding the last W after FSR + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + + for (size_t q = 0; q < topChildren->nChildren(); ++q) { + const xAOD::TruthParticle* WChildren = topChildren->child(q); + if (abs(WChildren->pdgId()) < 17) { + if (WChildren->pdgId() > 0) { + Wdecay1_p4 = WChildren->p4(); + Wdecay1_pdgId = WChildren->pdgId(); + hasWdecayProd1 = true; + } else { + Wdecay2_p4 = WChildren->p4(); + Wdecay2_pdgId = WChildren->pdgId(); + hasWdecayProd2 = true; + }//else + }//if + }//for + } else if (abs(topChildren->pdgId()) == 5 || abs(topChildren->pdgId()) == 3 || abs(topChildren->pdgId()) == 1) { + q_p4 = topChildren->p4(); + q_pdgId = topChildren->pdgId(); + hasQ = true; + } //else if + } //for (size_t k=0; k < particle->nChildren(); k++) + if (hasT && hasW && hasQ && hasWdecayProd1 && hasWdecayProd2) return true; } //for (const xAOD::TruthParticle* particle : *truthParticles) - - - return false; - + + return false; } - - const xAOD::TruthParticle* CalcTopPartonHistory::findAfterFSR(const xAOD::TruthParticle* particle) { - bool isAfterFSR(false); - const int particle_ID = particle->pdgId(); - int forLoop = 0; - while(!isAfterFSR){ - - forLoop = 0; - for (size_t j=0; j< particle->nChildren(); j++ ) { - const xAOD::TruthParticle* tmp_children = particle->child(j); - if (tmp_children && tmp_children->pdgId()==particle_ID){ - particle = particle->child(j); - forLoop++; - break; - }//if - }//for - - if (forLoop == 0) isAfterFSR = true; - }//while - return particle; + bool CalcTopPartonHistory::Wlv(const xAOD::TruthParticleContainer* truthParticles, + TLorentzVector& W_p4, + TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, + TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId) { + bool hasW = false; + bool hasWdecayProd1 = false; + bool hasWdecayProd2 = false; + + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (abs(particle->pdgId()) != 24) continue; + //std::cout << "PDGID: " << particle->pdgId() << std::endl; + + // demanding the last W after FSR + particle = PartonHistoryUtils::findAfterFSR(particle); + W_p4 = particle->p4(); // W boson after FSR + hasW = true; + + for (size_t k = 0; k < particle->nChildren(); k++) { + const xAOD::TruthParticle* WChildren = particle->child(k); + if (abs(WChildren->pdgId()) < 17) { + if (WChildren->pdgId() % 2 == 1) { // charged lepton in the Wlv case + Wdecay1_p4 = WChildren->p4(); + Wdecay1_pdgId = WChildren->pdgId(); + hasWdecayProd1 = true; + } else {// neutral lepton in the Wlv case + Wdecay2_p4 = WChildren->p4(); + Wdecay2_pdgId = WChildren->pdgId(); + hasWdecayProd2 = true; + }//else + }//if + } //for (size_t k=0; k < particle->nChildren(); k++) + + if (hasW && hasWdecayProd1 && hasWdecayProd2) return true; + } //for (const xAOD::TruthParticle* particle : *truthParticles) + + + return false; } - bool CalcTopPartonHistory::hasParticleIdenticalParent(const xAOD::TruthParticle* particle) { - bool skipit(false); - for (size_t i=0; i< particle->nParents(); i++ ) { - const xAOD::TruthParticle* parent = particle->parent(i); - if (parent && parent->pdgId()==particle->pdgId()){ - skipit=true; - break; - }//if - }//for - return skipit; + // for Wt ST events, find W that is not from top + bool CalcTopPartonHistory::Wt_W(const xAOD::TruthParticleContainer* truthParticles, + TLorentzVector& W_p4, int& W_pdgId, TLorentzVector& Wdecay1_p4, + int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId) { + bool hasW = false; + bool hasWdecayProd1 = false; + bool hasWdecayProd2 = false; + + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle == nullptr) continue; + if (abs(particle->pdgId()) != 24) continue; // W boson + + // need to check if the W is from top + // identify the first in chain and check + // if that particle has top as parent + if (PartonHistoryUtils::hasParticleIdenticalParent(particle)) continue; // kepping only W before FSR + + bool isFromTop = false; + // now we should have only the first W in chain + for (size_t iparent = 0; iparent < particle->nParents(); ++iparent) { + if (particle->parent(iparent) == nullptr) continue; + if (abs(particle->parent(iparent)->pdgId()) == 6) { // has top as parent + isFromTop = true; + break; + } + } + + if (isFromTop) continue; + else { + particle = PartonHistoryUtils::findAfterFSR(particle); + W_p4 = particle->p4(); + W_pdgId = particle->pdgId(); + hasW = true; + } + + // check the decay products of the W + for (size_t q = 0; q < particle->nChildren(); ++q) { + const xAOD::TruthParticle* WChildren = particle->child(q); + if (WChildren == nullptr) continue; + if (abs(WChildren->pdgId()) < 17) { + if (WChildren->pdgId() > 0) { + Wdecay1_p4 = WChildren->p4(); + Wdecay1_pdgId = WChildren->pdgId(); + hasWdecayProd1 = true; + } else { + Wdecay2_p4 = WChildren->p4(); + Wdecay2_pdgId = WChildren->pdgId(); + hasWdecayProd2 = true; + }//else + }//if + }//for + + if (hasW && hasWdecayProd1 && hasWdecayProd2) return true; + } // loop over truth particles + + return false; } - - StatusCode CalcTopPartonHistory::execute() - { - // Get the Truth Particles - const xAOD::TruthParticleContainer* truthParticles(nullptr); - ATH_CHECK( evtStore()->retrieve( truthParticles , m_config->sgKeyMCParticle() ) ); - - // Create the partonHistory xAOD object - xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer{}; - xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer{}; - partonCont->setStore( partonAuxCont ); - - xAOD::PartonHistory* partonHistory = new xAOD::PartonHistory{}; - partonCont->push_back( partonHistory ); - - // Save to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyTopPartonHistory(); - std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( partonCont , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( partonAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } - - return StatusCode::SUCCESS; - } - - void CalcTopPartonHistory::fillEtaBranch( xAOD::PartonHistory* partonHistory, std::string branchName, TLorentzVector &tlv){ - if (tlv.CosTheta()==1.) partonHistory->auxdecor< float >( branchName ) = 1000.; - else if (tlv.CosTheta()==-1.) partonHistory->auxdecor< float >( branchName ) = 1000.; - else partonHistory->auxdecor< float >( branchName ) = tlv.Eta(); - return; - - + + // for Wt ST events, find b that is not from top + bool CalcTopPartonHistory::Wt_b(const xAOD::TruthParticleContainer* truthParticles, + TLorentzVector& b_beforeFSR, TLorentzVector& b_afterFSR, + int& b_pdgId) { + bool hasB = false; + + // identify "other" b quark that is not from radiation but from ME (Wtb) + // logic is simple: search for b quark that doesn't have top, proton, or + // nullptr as parent + + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle == nullptr) continue; + if (abs(particle->pdgId()) != 5) continue; + + for (size_t iparent = 0; iparent < particle->nParents(); ++iparent) { + if (particle->parent(iparent) == nullptr) continue; + + // we dont want b-quarks that have b as parent + if (abs(particle->parent(iparent)->pdgId()) == 5) continue; + + // we dont want b-quarks that come from top + if (abs(particle->parent(iparent)->pdgId()) == 6) continue; + + // we dont want b-quarks that come from W + if (abs(particle->parent(iparent)->pdgId()) == 24) continue; + + // we dont want b-quarks that come from proton + if (abs(particle->parent(iparent)->pdgId()) == 2212) continue; + + hasB = true; + b_beforeFSR = particle->p4(); + b_pdgId = particle->pdgId(); + + // find after FSR + particle = PartonHistoryUtils::findAfterFSR(particle); + b_afterFSR = particle->p4(); + } + } + + + if (hasB) return true; + + return false; + } + + // for ttbar + photon events + bool CalcTopPartonHistory::topPhWb(const xAOD::TruthParticleContainer* truthParticles, int topId, + TLorentzVector& t_beforeFSR_p4, TLorentzVector& t_afterFSR_p4, + TLorentzVector& Ph_p4, TLorentzVector& W_p4, TLorentzVector& b_p4, + TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, + int& Wdecay2_pdgId, bool& has_ph, int& BranchType, int& IniPartonType, + bool& missingTop) { + bool hasT = false; + bool hasW = false; + bool hasAbsentW = false; + bool hasB = false; + + has_ph = false; + bool ph_W = false; + bool ph_Top = false; + bool ph_ISR = false; + bool ph_b = false; + bool hasWdecayProd1 = false; + bool hasWdecayProd2 = false; + missingTop = false; + + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->pdgId() != topId) continue; + + if (PartonHistoryUtils::hasParticleIdenticalParent(particle)) continue; // kepping only top before FSR + BranchType = -1;// 10(50): leptonic(hadronic), 12(52):topRad, 14(54):Wrad, 15(55):ISR, 18(58):b + IniPartonType = -1; + + // finding siblings + for (size_t iparent = 0; iparent < particle->nParents(); iparent++) { + if (abs(particle->parent(iparent)->pdgId()) == 21) { + IniPartonType = 1; + } // gg fusion + else if (abs(particle->parent(iparent)->pdgId()) < 6) { + IniPartonType = 2; + } //qq annihilation + + for (size_t ichild = 0; ichild < particle->parent(iparent)->nChildren(); ichild++) { + if (particle->parent(iparent)->child(ichild)->pdgId() == 22) { + const xAOD::TruthParticle* photon = PartonHistoryUtils::findAfterFSR(particle->parent(iparent)->child(ichild)); + Ph_p4 = photon->p4(); + has_ph = true; + ph_ISR = true; + } + if (!missingTop && + (abs(particle->parent(iparent)->child(ichild)->pdgId()) == 5 || + abs(particle->parent(iparent)->child(ichild)->pdgId()) == 24)) { + missingTop = true; + } + } + } + + t_beforeFSR_p4 = particle->p4(); // top before FSR + hasT = true; + // demanding the last tops after FSR + particle = PartonHistoryUtils::findAfterFSR(particle); + t_afterFSR_p4 = particle->p4(); // top after FSR + + for (size_t k = 0; k < particle->nChildren(); k++) {// top children + const xAOD::TruthParticle* topChildren = particle->child(k); + + if (abs(topChildren->pdgId()) == 24) { + W_p4 = topChildren->p4(); // W boson before FSR + hasW = true; + + // demanding the last W after FSR + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + + for (size_t q = 0; q < topChildren->nChildren(); q++) {// W children + const xAOD::TruthParticle* WChildren = topChildren->child(q); + if (abs(WChildren->pdgId()) > 0 && abs(WChildren->pdgId()) < 17) { + if (abs(WChildren->pdgId()) < 7) { + BranchType = 50; + }// hadronic + else if (abs(WChildren->pdgId()) > 10 && abs(WChildren->pdgId()) < 17) { + BranchType = 10; + }// leptonic + if (WChildren->pdgId() > 0) { + WChildren = PartonHistoryUtils::findAfterFSR(WChildren); + Wdecay1_p4 = WChildren->p4(); + Wdecay1_pdgId = WChildren->pdgId(); + hasWdecayProd1 = true; + } else { + WChildren = PartonHistoryUtils::findAfterFSR(WChildren); + Wdecay2_p4 = WChildren->p4(); + Wdecay2_pdgId = WChildren->pdgId(); + hasWdecayProd2 = true; + }//else + } else if (abs(WChildren->pdgId()) == 22) {// photon + // JUST FOR EXTRA SAFETY (not necessary) + // check if there exists a photon already + // if it does, check the photon's Pt + // if found harder then consider, else do nothing + if (has_ph) { + if (WChildren->p4().Pt() > Ph_p4.Pt()) { + ph_W = true; + ph_ISR = false; + ph_Top = false; + ph_b = false; + WChildren = PartonHistoryUtils::findAfterFSR(WChildren); + Ph_p4 = WChildren->p4(); + } + } else { + has_ph = true; + ph_W = true; + WChildren = PartonHistoryUtils::findAfterFSR(WChildren); + Ph_p4 = WChildren->p4(); + } + } + }// W children + } else if (abs(topChildren->pdgId()) == 5) { // b + hasB = true; + topChildren = PartonHistoryUtils::findAfterFSR(topChildren);// b After FSR + b_p4 = topChildren->p4(); + // In MG5 generation of ttgamma it is not expected to have any b radiation 'recorded' + for (size_t b = 0; b < topChildren->nChildren(); b++) {// b Children + const xAOD::TruthParticle* bChildren = topChildren->child(b); + if (bChildren && bChildren->pdgId() == 22) { + // JUST FOR EXTRA SAFETY (not necessary) + if (has_ph) { + if (bChildren->p4().Pt() > Ph_p4.Pt()) { + ph_b = true; + ph_ISR = false; + ph_Top = false; + ph_W = false; + bChildren = PartonHistoryUtils::findAfterFSR(bChildren); + Ph_p4 = bChildren->p4(); + } + } else { + has_ph = true; + ph_b = true; + bChildren = PartonHistoryUtils::findAfterFSR(bChildren); + Ph_p4 = bChildren->p4(); + } + } + } + } else if (abs(topChildren->pdgId()) == 22) { + // JUST FOR EXTRA SAFETY (not necessary) + if (has_ph) { + if (topChildren->p4().Pt() > Ph_p4.Pt()) { + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + Ph_p4 = topChildren->p4(); + ph_Top = true; + } + } else { + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + Ph_p4 = topChildren->p4(); + has_ph = true; + ph_Top = true; + ph_W = false; + ph_ISR = false; + ph_b = false; + } + } + // sometimes the W is not recorded and the W products are recorded as top products + else if (abs(topChildren->pdgId()) <= 4 || (abs(topChildren->pdgId()) > 10 && abs(topChildren->pdgId()) < 17)) { + hasW = true; + hasAbsentW = true; + if (abs(topChildren->pdgId()) < 7) { + BranchType = 50; + }// hadronic + else if (abs(topChildren->pdgId()) > 10 && abs(topChildren->pdgId()) < 17) { + BranchType = 10; + }// leptonic + if (topChildren->pdgId() > 0) { + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + Wdecay1_p4 = topChildren->p4(); + Wdecay1_pdgId = topChildren->pdgId(); + hasWdecayProd1 = true; + } else { + topChildren = PartonHistoryUtils::findAfterFSR(topChildren); + Wdecay2_p4 = topChildren->p4(); + Wdecay2_pdgId = topChildren->pdgId(); + hasWdecayProd2 = true; + }//else + W_p4 = W_p4 + topChildren->p4(); + }// if top children + } // for top children + + // BranchType Determination if there is a photon + if (hasAbsentW && (ph_Top || ph_W)) { + BranchType = -1; + }// if the W is not recorded and still the photon is from the top, the source of the photon is then ambiguous + // among top and W. BranchType would be +1. Category would be 0. + if (has_ph && ph_Top) { + BranchType = BranchType + 2; + } + if (has_ph && ph_W) { + BranchType = BranchType + 4; + } + if (has_ph && ph_ISR) { + BranchType = BranchType + 5; + } + if (has_ph && ph_b) { + BranchType = BranchType + 8; + } + + if (hasT && hasW && hasB && hasWdecayProd1 && hasWdecayProd2 && BranchType != -1) return true; + }// particle + + return false; + } + + StatusCode CalcTopPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* partonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(partonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } + + void CalcTopPartonHistory::fillEtaBranch(xAOD::PartonHistory* partonHistory, std::string branchName, + TLorentzVector& tlv) { + if (tlv.CosTheta() == 1.) partonHistory->auxdecor< float >(branchName) = 1000.; + else if (tlv.CosTheta() == -1.) partonHistory->auxdecor< float >(branchName) = 1000.; + else partonHistory->auxdecor< float >(branchName) = tlv.Eta(); + return; } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarGammaPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarGammaPartonHistory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..dd36186154b3892ab65ec56a6b00c6179a5e6017 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarGammaPartonHistory.cxx @@ -0,0 +1,400 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopPartons/CalcTtbarGammaPartonHistory.h" +#include "TopConfiguration/TopConfig.h" +#include "TopPartons/PartonHistoryUtils.h" + +namespace top { + CalcTtbarGammaPartonHistory::CalcTtbarGammaPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + void CalcTtbarGammaPartonHistory::ttbarGammaHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* ttbarGammaPartonHistory) { + ttbarGammaPartonHistory->IniVarTtGamma(); + TLorentzVector ph_t; + bool has_ph_t; + int branchtype_t = -1; + int branchtype_tbar = -1; + /// Definition of top-branch type: also applicable for branchtype_tbar + /// -1:undefined + /// 0: missing top + /// 1: missing W + /// 10: leptonic branch without photon + /// 12: leptonic branch with photon from top + /// 14: leptonic branch with photon from W + /// 15: leptonic branch with photon from ISR + /// 18: leptonic branch with photon from b + /// 50: hadronic branch without photon + /// 52: hadronic branch with photon from top + /// 54: hadronic branch with photon from W + /// 55: hadronic branch with photon from ISR + /// 58: hadronic branch with photon from b + int init_type = -1; + /// Initial parton definition: + /// -1:undefined + /// 0: missing top (only one of them) + /// 1: gg (gluon fusion) + /// 2: qq (quark annihilation) + TLorentzVector t_before, t_after; + TLorentzVector Wp; + TLorentzVector b; + TLorentzVector WpDecay1; + TLorentzVector WpDecay2; + int WpDecay1_pdgId; + int WpDecay2_pdgId; + bool missTop; + bool missTbar; + bool event_top = CalcTopPartonHistory::topPhWb(truthParticles, 6, t_before, t_after, ph_t, Wp, b, WpDecay1, + WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId, has_ph_t, branchtype_t, + init_type, missTbar); + + TLorentzVector ph_tbar; + bool has_ph_tbar; + TLorentzVector tbar_before, tbar_after; + TLorentzVector Wm; + TLorentzVector bbar; + TLorentzVector WmDecay1; + TLorentzVector WmDecay2; + int WmDecay1_pdgId; + int WmDecay2_pdgId; + bool event_topbar = CalcTopPartonHistory::topPhWb(truthParticles, -6, tbar_before, tbar_after, ph_tbar, Wm, bbar, + WmDecay1, WmDecay1_pdgId, WmDecay2, WmDecay2_pdgId, has_ph_tbar, + branchtype_tbar, init_type, missTop); + + if (event_top && missTbar && has_ph_t && branchtype_t != 10 && branchtype_t != 50 && branchtype_t != 15 && + branchtype_t != 55) { + bool Wonshell = false; + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->barcode() != 3) continue; + for (size_t q = 0; q < particle->nChildren(); q++) { + if (particle->child(q) && particle->child(q)->pdgId() == -5) bbar =PartonHistoryUtils::findAfterFSR(particle->child( + q))-> + p4(); + if (particle->child(q) && particle->child(q)->pdgId() == -24) { + Wm = particle->child(q)->p4(); + Wonshell = true; + for (size_t Wc = 0; Wc < particle->child(q)->nChildren(); Wc++) { + if (particle->child(q)->child(Wc)->pdgId() > 0) { + WmDecay1 = PartonHistoryUtils::findAfterFSR(particle->child(q)->child(Wc))->p4(); + WmDecay1_pdgId = particle->child(q)->child(Wc)->pdgId(); + } + if (particle->child(q)->child(Wc)->pdgId() < 0) { + WmDecay2 = PartonHistoryUtils::findAfterFSR(particle->child(q)->child(Wc))->p4(); + WmDecay2_pdgId = particle->child(q)->child(Wc)->pdgId(); + } + } + } + if (!Wonshell) { + if (particle->child(q) && particle->child(q)->pdgId() != 6 && particle->child(q)->pdgId() != 22 && + particle->child(q)->pdgId() > 0) { + WmDecay1 = PartonHistoryUtils::findAfterFSR(particle->child(q))->p4(); + WmDecay1_pdgId = particle->child(q)->pdgId(); + } + if (particle->child(q) && particle->child(q)->pdgId() != -6 && particle->child(q)->pdgId() != 22 && + particle->child(q)->pdgId() < 0) { + WmDecay2 = PartonHistoryUtils::findAfterFSR(particle->child(q))->p4(); + WmDecay2_pdgId = particle->child(q)->pdgId(); + } + Wm = WmDecay1 + WmDecay2; + } + } + if (WmDecay1_pdgId >= 1 && WmDecay1_pdgId <= 4) branchtype_tbar = 50; + else if (WmDecay1_pdgId >= 11 && WmDecay1_pdgId <= 16) branchtype_tbar = 10; + + if (branchtype_tbar == 50 || branchtype_tbar == 10) { + event_topbar = true; + has_ph_tbar = false; + } + } + } else if (event_topbar && missTop && has_ph_tbar && branchtype_tbar != 10 && branchtype_tbar != 50 && + branchtype_tbar != 15 && branchtype_tbar != 55) { + bool Wonshell = false; + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->barcode() != 3) continue; + for (size_t q = 0; q < particle->nChildren(); q++) { + if (particle->child(q) && particle->child(q)->pdgId() == 5) b = PartonHistoryUtils::findAfterFSR(particle->child( + q))->p4(); + + if (particle->child(q) && particle->child(q)->pdgId() == 24) { + Wp = particle->child(q)->p4(); + Wonshell = true; + for (size_t Wc = 0; Wc < particle->child(q)->nChildren(); Wc++) { + if (particle->child(q)->child(Wc)->pdgId() > 0) { + WmDecay1 = PartonHistoryUtils::findAfterFSR(particle->child(q)->child(Wc))->p4(); + WmDecay1_pdgId = particle->child(q)->child(Wc)->pdgId(); + } + if (particle->child(q)->child(Wc)->pdgId() < 0) { + WmDecay2 = PartonHistoryUtils::findAfterFSR(particle->child(q)->child(Wc))->p4(); + WmDecay2_pdgId = particle->child(q)->child(Wc)->pdgId(); + } + } + } + if (!Wonshell) { + if (particle->child(q) && particle->child(q)->pdgId() != 6 && particle->child(q)->pdgId() != 22 && + particle->child(q)->pdgId() > 0) { + WmDecay1 = PartonHistoryUtils::findAfterFSR(particle->child(q))->p4(); + WmDecay1_pdgId = particle->child(q)->pdgId(); + } + if (particle->child(q) && particle->child(q)->pdgId() != -6 && particle->child(q)->pdgId() != 22 && + particle->child(q)->pdgId() < 0) { + WmDecay2 = PartonHistoryUtils::findAfterFSR(particle->child(q))->p4(); + WmDecay2_pdgId = particle->child(q)->pdgId(); + } + Wp = WpDecay1 + WpDecay2; + } + } + if (abs(WmDecay1_pdgId) >= 1 && abs(WmDecay1_pdgId) <= 4) branchtype_t = 50; + else if (abs(WmDecay1_pdgId) >= 11 && abs(WmDecay1_pdgId) <= 16) branchtype_t = 10; + if (branchtype_t == 50 || branchtype_t == 10) { + event_top = true; + has_ph_t = false; + } + } + } + + TLorentzVector ph; + int ph_source = -1; + /// photon source definition: + /// -1:undefined + /// 0: ISR + /// 1: top + /// 2: antitop + /// 3: missing top (only one of them) + int category = -2; + /// event category: + /// -2: undefined + /// -1: missing W (only if the corresponding top radiates) + /// 0: missing top + /// 1: Single Lepton inital quark radiation + /// 2: Single Lepton virtual top radiation + /// 3: Single Lepton leptonic top radiation + /// 4: Single Lepton hadronic top radiation + /// 5: Single Lepton leptonic W radiation + /// 6: Single Lepton hadronic W radiation + /// 7: Single Lepton leptonic b radiation + /// 8: Single Lepton hadronic b radiation + /// 9: Dilepton quark radiation + /// 10: Dilepton virtual top radiation + /// 11: Dilepton top radiation + /// 12: Dilepton W radiation + /// 13: Dilepton b radiation + + if ((event_top && !event_topbar) || (!event_top && event_topbar) || (!event_top && !event_topbar)) {// missing top + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->barcode() != 3) continue; + if (abs(particle->pdgId()) == 21) init_type = 1; //gg + else if (abs(particle->pdgId()) < 6) init_type = 2; //qq + } + category = 0; + ph_source = 3; + branchtype_t = 0; + branchtype_tbar = 0; + ttbarGammaPartonHistory->auxdecor< int >("MC_branchtype_t") = branchtype_t; + ttbarGammaPartonHistory->auxdecor< int >("MC_branchtype_tbar") = branchtype_tbar; + ttbarGammaPartonHistory->auxdecor< int >("MC_initial_parton") = init_type; + ttbarGammaPartonHistory->auxdecor< int >("MC_Event_Category") = category; + ttbarGammaPartonHistory->auxdecor< int >("MC_ph_from_t_tbar") = ph_source; + }// one of the top is virtual + else if (event_top && event_topbar) { // && (has_ph_t || has_ph_tbar) + if (has_ph_t && has_ph_tbar) {// isr should give the same photon to both tops + if (ph_t.Pt() > ph_tbar.Pt()) { + ph = ph_t; + }// FOR EXTRA SAFETY + else { + ph = ph_tbar; + } + ph_source = 0; // isr + } else if (has_ph_t) { + ph = ph_t; + ph_source = 1; + }// top + else if (has_ph_tbar) { + ph = ph_tbar; + ph_source = 2; + }// antitop + else if (!has_ph_t && !has_ph_tbar) { + ph_source = -1; + } + + // determination of event category + // ISR + if (ph_source == 0) { + if (init_type == 2) { + category = 1; + if (branchtype_t == 15 && branchtype_tbar == 15) { + category = 9; + } // ISR_qq_DL + } //ISR_qq + else if (init_type == 1) { + category = 2; + if (branchtype_t == 15 && branchtype_tbar == 15) { + category = 10; + } // ISR_gg_DL + } //ISR_gg/top + } else if (ph_source == 1 || ph_source == 2) { + if ((branchtype_t == 12 && branchtype_tbar == 50) || (branchtype_t == 50 && branchtype_tbar == 12)) { + category = 3; + }// top Radiation leptonic + else if ((branchtype_t == 52 && branchtype_tbar == 10) || (branchtype_t == 10 && branchtype_tbar == 52)) { + category = 4; + }// top Radiation hadronic + else if ((branchtype_t == 14 && branchtype_tbar == 50) || (branchtype_t == 50 && branchtype_tbar == 14)) { + category = 5; + }// W Radiation leptonic + else if ((branchtype_t == 54 && branchtype_tbar == 10) || (branchtype_t == 10 && branchtype_tbar == 54)) { + category = 6; + }// W Radiation hadronic + else if ((branchtype_t == 18 && branchtype_tbar == 50) || (branchtype_t == 50 && branchtype_tbar == 18)) { + category = 7; + }// b Radiation leptonic + else if ((branchtype_t == 58 && branchtype_tbar == 10) || (branchtype_t == 10 && branchtype_tbar == 58)) { + category = 8; + }// b Radiation hadronic + else if ((branchtype_t == 12 && branchtype_tbar == 10) || (branchtype_t == 10 && branchtype_tbar == 12)) { + category = 11; + }// Top Radiation dileptonic + else if ((branchtype_t == 14 && branchtype_tbar == 10) || (branchtype_t == 10 && branchtype_tbar == 14)) { + category = 12; + }// W Radiation dileptonic + else if ((branchtype_t == 18 && branchtype_tbar == 10) || (branchtype_t == 10 && branchtype_tbar == 18)) { + category = 13; + }// W Radiation dileptonic + else if (branchtype_t == 1 || branchtype_tbar == 1) { + category = -1; + }// missing W + else { + category = 0; + }// missing top + } else if (ph_source == -1) { + category = -2; + } // undefined + +//------------------------------------------------------------------------------------------ + ttbarGammaPartonHistory->auxdecor< float >("MC_ph_m") = ph.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_ph_pt") = ph.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_ph_phi") = ph.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_ph_eta", ph); + + ttbarGammaPartonHistory->auxdecor< int >("MC_branchtype_t") = branchtype_t; + ttbarGammaPartonHistory->auxdecor< int >("MC_branchtype_tbar") = branchtype_tbar; + ttbarGammaPartonHistory->auxdecor< int >("MC_initial_parton") = init_type; + ttbarGammaPartonHistory->auxdecor< int >("MC_ph_from_t_tbar") = ph_source; + ttbarGammaPartonHistory->auxdecor< int >("MC_Event_Category") = category; +//------------------------------------------------------------------------------------------ + + TLorentzVector temp = t_before + tbar_before; + ttbarGammaPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_m") = temp.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_pt") = temp.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_phi") = temp.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_ttbar_beforeFSR_eta", temp); + + temp = WmDecay1 + WmDecay2 + b + WpDecay1 + WpDecay2 + bbar + ph; + ttbarGammaPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_m") = temp.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_pt") = temp.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_phi") = temp.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_ttbar_afterFSR_eta", temp); + } + +//------------------------------------------------------------------------------------------ + if (event_top) { + ttbarGammaPartonHistory->auxdecor< float >("MC_t_beforeFSR_m") = t_before.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_t_beforeFSR_pt") = t_before.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_t_beforeFSR_phi") = t_before.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_t_beforeFSR_eta", t_before); + + ttbarGammaPartonHistory->auxdecor< float >("MC_t_afterFSR_m") = t_after.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_t_afterFSR_pt") = t_after.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_t_afterFSR_phi") = t_after.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_t_afterFSR_eta", t_after); + + ttbarGammaPartonHistory->auxdecor< float >("MC_W_from_t_m") = Wp.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_W_from_t_pt") = Wp.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_W_from_t_phi") = Wp.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_W_from_t_eta", Wp); + + ttbarGammaPartonHistory->auxdecor< float >("MC_b_from_t_m") = b.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_b_from_t_pt") = b.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_b_from_t_phi") = b.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_b_from_t_eta", b); + + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_m") = WpDecay1.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_pt") = WpDecay1.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_phi") = WpDecay1.Phi(); + ttbarGammaPartonHistory->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = WpDecay1_pdgId; + fillEtaBranch(ttbarGammaPartonHistory, "MC_Wdecay1_from_t_eta", WpDecay1); + + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_m") = WpDecay2.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_pt") = WpDecay2.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_phi") = WpDecay2.Phi(); + ttbarGammaPartonHistory->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = WpDecay2_pdgId; + fillEtaBranch(ttbarGammaPartonHistory, "MC_Wdecay2_from_t_eta", WpDecay2); + } + + +//------------------------------------------------------------------------------------------- + if (event_topbar) { + ttbarGammaPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_m") = tbar_before.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_pt") = tbar_before.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_phi") = tbar_before.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_tbar_beforeFSR_eta", tbar_before); + + ttbarGammaPartonHistory->auxdecor< float >("MC_tbar_afterFSR_m") = tbar_after.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_tbar_afterFSR_pt") = tbar_after.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_tbar_afterFSR_phi") = tbar_after.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_tbar_afterFSR_eta", tbar_after); + + ttbarGammaPartonHistory->auxdecor< float >("MC_W_from_tbar_m") = Wm.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_W_from_tbar_pt") = Wm.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_W_from_tbar_phi") = Wm.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_W_from_tbar_eta", Wm); + + ttbarGammaPartonHistory->auxdecor< float >("MC_b_from_tbar_m") = bbar.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_b_from_tbar_pt") = bbar.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_b_from_tbar_phi") = bbar.Phi(); + fillEtaBranch(ttbarGammaPartonHistory, "MC_b_from_tbar_eta", bbar); + + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_m") = WmDecay1.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_pt") = WmDecay1.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_phi") = WmDecay1.Phi(); + ttbarGammaPartonHistory->auxdecor< int >("MC_Wdecay1_from_tbar_pdgId") = WmDecay1_pdgId; + fillEtaBranch(ttbarGammaPartonHistory, "MC_Wdecay1_from_tbar_eta", WmDecay1); + + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_m") = WmDecay2.M(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_pt") = WmDecay2.Pt(); + ttbarGammaPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_phi") = WmDecay2.Phi(); + ttbarGammaPartonHistory->auxdecor< int >("MC_Wdecay2_from_tbar_pdgId") = WmDecay2_pdgId; + fillEtaBranch(ttbarGammaPartonHistory, "MC_Wdecay2_from_tbar_eta", WmDecay2); + } + } + + StatusCode CalcTtbarGammaPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + std::unique_ptr<xAOD::PartonHistoryAuxContainer> partonAuxCont(new xAOD::PartonHistoryAuxContainer()); + std::unique_ptr<xAOD::PartonHistoryContainer> partonCont(new xAOD::PartonHistoryContainer()); + partonCont->setStore(partonAuxCont.release()); + + xAOD::PartonHistory* ttbarGammaPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(ttbarGammaPartonHistory); + + // Recover the parton history for ttbargamma events + ttbarGammaHistorySaver(truthParticles, ttbarGammaPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont.release(), outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont.release(), outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarLightPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarLightPartonHistory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..5cb8f5e5ed755d80bb8bcaef3472899e385b0fb5 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarLightPartonHistory.cxx @@ -0,0 +1,165 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopPartons/CalcTtbarLightPartonHistory.h" +#include "TopConfiguration/TopConfig.h" + +namespace top { + CalcTtbarLightPartonHistory::CalcTtbarLightPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + void CalcTtbarLightPartonHistory::ttbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* ttbarPartonHistory) { + ttbarPartonHistory->IniVarTtbarLight(); + + TLorentzVector t_before, t_after, t_after_SC; + TLorentzVector Wp; + TLorentzVector q; + int q_pdgId; + TLorentzVector WpDecay1; + TLorentzVector WpDecay2; + int WpDecay1_pdgId; + int WpDecay2_pdgId; + bool event_top = CalcTopPartonHistory::topWq(truthParticles, 6, t_before, t_after, Wp, q, q_pdgId, WpDecay1, + WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); + bool event_top_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, 6, t_after_SC); + + TLorentzVector tbar_before, tbar_after, tbar_after_SC; + TLorentzVector Wm; + TLorentzVector qbar; + int qbar_pdgId; + TLorentzVector WmDecay1; + TLorentzVector WmDecay2; + int WmDecay1_pdgId; + int WmDecay2_pdgId; + bool event_topbar = CalcTopPartonHistory::topWq(truthParticles, -6, tbar_before, tbar_after, Wm, qbar, qbar_pdgId, + WmDecay1, WmDecay1_pdgId, WmDecay2, WmDecay2_pdgId); + bool event_topbar_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, -6, tbar_after_SC); + + if (event_top && event_topbar) { + TLorentzVector temp = t_before + tbar_before; + ttbarPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_m") = temp.M(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_pt") = temp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_phi") = temp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_ttbar_beforeFSR_eta", temp); + + temp = WmDecay1 + WmDecay2 + q + WpDecay1 + WpDecay2 + qbar; + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_m") = temp.M(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_pt") = temp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_phi") = temp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_ttbar_afterFSR_eta", temp); + }//if + if (event_top) { + ttbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_m") = t_before.M(); + ttbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_pt") = t_before.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_phi") = t_before.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_t_beforeFSR_eta", t_before); + + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_m") = t_after.M(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_pt") = t_after.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_phi") = t_after.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_t_afterFSR_eta", t_after); + + if (event_top_SC) { + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_m") = t_after_SC.M(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_pt") = t_after_SC.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_phi") = t_after_SC.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_t_afterFSR_SC_eta", t_after_SC); + } + + ttbarPartonHistory->auxdecor< float >("MC_W_from_t_m") = Wp.M(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_t_pt") = Wp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_t_phi") = Wp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_W_from_t_eta", Wp); + + ttbarPartonHistory->auxdecor< float >("MC_q_from_t_m") = q.M(); + ttbarPartonHistory->auxdecor< float >("MC_q_from_t_pt") = q.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_q_from_t_phi") = q.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_q_from_t_pdgId") = q_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_q_from_t_eta", q); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_m") = WpDecay1.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_pt") = WpDecay1.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_phi") = WpDecay1.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = WpDecay1_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay1_from_t_eta", WpDecay1); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_m") = WpDecay2.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_pt") = WpDecay2.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_phi") = WpDecay2.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = WpDecay2_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay2_from_t_eta", WpDecay2); + }//if + if (event_topbar) { + ttbarPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_m") = tbar_before.M(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_pt") = tbar_before.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_phi") = tbar_before.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_tbar_beforeFSR_eta", tbar_before); + + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_m") = tbar_after.M(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_pt") = tbar_after.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_phi") = tbar_after.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_tbar_afterFSR_eta", tbar_after); + + if (event_topbar_SC) { + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_SC_m") = tbar_after_SC.M(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_SC_pt") = tbar_after_SC.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_SC_phi") = tbar_after_SC.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_tbar_afterFSR_SC_eta", tbar_after_SC); + } + + ttbarPartonHistory->auxdecor< float >("MC_W_from_tbar_m") = Wm.M(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_tbar_pt") = Wm.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_tbar_phi") = Wm.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_W_from_tbar_eta", Wm); + + ttbarPartonHistory->auxdecor< float >("MC_q_from_tbar_m") = qbar.M(); + ttbarPartonHistory->auxdecor< float >("MC_q_from_tbar_pt") = qbar.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_q_from_tbar_phi") = qbar.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_q_from_tbar_pdgId") = qbar_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_q_from_tbar_eta", qbar); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_m") = WmDecay1.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_pt") = WmDecay1.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_phi") = WmDecay1.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay1_from_tbar_pdgId") = WmDecay1_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay1_from_tbar_eta", WmDecay1); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_m") = WmDecay2.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_pt") = WmDecay2.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_phi") = WmDecay2.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay2_from_tbar_pdgId") = WmDecay2_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay2_from_tbar_eta", WmDecay2); + }//if + } + + StatusCode CalcTtbarLightPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* ttbarPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(ttbarPartonHistory); + + // Recover the parton history for ttbar events + ttbarHistorySaver(truthParticles, ttbarPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarPartonHistory.cxx index 4b269fa12e77f21806ff31ebf99523f071936e49..c2a2272abe6fcf553cae0421b30eafbaff4f3f0a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarPartonHistory.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTtbarPartonHistory.cxx @@ -1,162 +1,184 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopPartons/CalcTtbarPartonHistory.h" #include "TopConfiguration/TopConfig.h" -namespace top{ - - CalcTtbarPartonHistory::CalcTtbarPartonHistory(const std::string& name) : CalcTopPartonHistory( name ){} - - void CalcTtbarPartonHistory::ttbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* ttbarPartonHistory){ - - ttbarPartonHistory->IniVarTtbar(); - - TLorentzVector t_before, t_after, t_after_SC; - TLorentzVector Wp; - TLorentzVector b; - TLorentzVector WpDecay1; - TLorentzVector WpDecay2; - int WpDecay1_pdgId; - int WpDecay2_pdgId; - bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, Wp, b, WpDecay1, WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); - bool event_top_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, 6, t_after_SC); - - TLorentzVector tbar_before, tbar_after, tbar_after_SC; - TLorentzVector Wm; - TLorentzVector bbar; - TLorentzVector WmDecay1; - TLorentzVector WmDecay2; - int WmDecay1_pdgId; - int WmDecay2_pdgId; - bool event_topbar = CalcTopPartonHistory::topWb(truthParticles, -6, tbar_before, tbar_after, Wm, bbar, WmDecay1, WmDecay1_pdgId, WmDecay2, WmDecay2_pdgId); - bool event_topbar_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, -6, tbar_after_SC); - - if (event_top && event_topbar){ - TLorentzVector temp = t_before+tbar_before; - ttbarPartonHistory->auxdecor< float >( "MC_ttbar_beforeFSR_m" ) = temp.M(); - ttbarPartonHistory->auxdecor< float >( "MC_ttbar_beforeFSR_pt" ) = temp.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_ttbar_beforeFSR_phi" ) = temp.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_ttbar_beforeFSR_eta", temp); - - temp = WmDecay1+WmDecay2+b + WpDecay1+WpDecay2+bbar; - ttbarPartonHistory->auxdecor< float >( "MC_ttbar_afterFSR_m" ) = temp.M(); - ttbarPartonHistory->auxdecor< float >( "MC_ttbar_afterFSR_pt" ) = temp.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_ttbar_afterFSR_phi" ) = temp .Phi(); - fillEtaBranch(ttbarPartonHistory, "MC_ttbar_afterFSR_eta", temp); - }//if - if (event_top){ - ttbarPartonHistory->auxdecor< float >( "MC_t_beforeFSR_m" ) = t_before.M(); - ttbarPartonHistory->auxdecor< float >( "MC_t_beforeFSR_pt" ) = t_before.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_t_beforeFSR_phi" ) = t_before.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_t_beforeFSR_eta", t_before); - - ttbarPartonHistory->auxdecor< float >( "MC_t_afterFSR_m" ) = t_after.M(); - ttbarPartonHistory->auxdecor< float >( "MC_t_afterFSR_pt" ) = t_after.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_t_afterFSR_phi" ) = t_after.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_t_afterFSR_eta", t_after); - - if (event_top_SC) { - ttbarPartonHistory->auxdecor< float >( "MC_t_afterFSR_SC_m" ) = t_after_SC.M(); - ttbarPartonHistory->auxdecor< float >( "MC_t_afterFSR_SC_pt" ) = t_after_SC.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_t_afterFSR_SC_phi" ) = t_after_SC.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_t_afterFSR_SC_eta", t_after_SC); - } - - ttbarPartonHistory->auxdecor< float >( "MC_W_from_t_m" ) = Wp.M(); - ttbarPartonHistory->auxdecor< float >( "MC_W_from_t_pt" ) = Wp.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_W_from_t_phi" ) = Wp.Phi(); - fillEtaBranch(ttbarPartonHistory, "MC_W_from_t_eta", Wp); - - ttbarPartonHistory->auxdecor< float >( "MC_b_from_t_m" ) = b.M(); - ttbarPartonHistory->auxdecor< float >( "MC_b_from_t_pt" ) = b.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_b_from_t_phi" ) = b.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_b_from_t_eta", b); - - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_t_m" ) = WpDecay1.M(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_t_pt" ) = WpDecay1.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_t_phi" ) = WpDecay1.Phi(); - ttbarPartonHistory->auxdecor< int >( "MC_Wdecay1_from_t_pdgId" ) = WpDecay1_pdgId; - fillEtaBranch(ttbarPartonHistory,"MC_Wdecay1_from_t_eta", WpDecay1); - - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_t_m" ) = WpDecay2.M(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_t_pt" ) = WpDecay2.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_t_phi" ) = WpDecay2.Phi(); - ttbarPartonHistory->auxdecor< int >( "MC_Wdecay2_from_t_pdgId" ) = WpDecay2_pdgId; - fillEtaBranch(ttbarPartonHistory,"MC_Wdecay2_from_t_eta", WpDecay2); - }//if - if (event_topbar){ - - ttbarPartonHistory->auxdecor< float >( "MC_tbar_beforeFSR_m" ) = tbar_before.M(); - ttbarPartonHistory->auxdecor< float >( "MC_tbar_beforeFSR_pt" ) = tbar_before.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_tbar_beforeFSR_phi" ) = tbar_before.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_tbar_beforeFSR_eta", tbar_before); - - ttbarPartonHistory->auxdecor< float >( "MC_tbar_afterFSR_m" ) = tbar_after.M(); - ttbarPartonHistory->auxdecor< float >( "MC_tbar_afterFSR_pt" ) = tbar_after.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_tbar_afterFSR_phi" ) = tbar_after.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_tbar_afterFSR_eta", tbar_after); - - if (event_topbar_SC) { - ttbarPartonHistory->auxdecor< float >( "MC_tbar_afterFSR_SC_m" ) = tbar_after_SC.M(); - ttbarPartonHistory->auxdecor< float >( "MC_tbar_afterFSR_SC_pt" ) = tbar_after_SC.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_tbar_afterFSR_SC_phi" ) = tbar_after_SC.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_tbar_afterFSR_SC_eta", tbar_after_SC); - } - - ttbarPartonHistory->auxdecor< float >( "MC_W_from_tbar_m" ) = Wm.M(); - ttbarPartonHistory->auxdecor< float >( "MC_W_from_tbar_pt" ) = Wm.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_W_from_tbar_phi" ) = Wm.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_W_from_tbar_eta", Wm); - - ttbarPartonHistory->auxdecor< float >( "MC_b_from_tbar_m" ) = bbar.M(); - ttbarPartonHistory->auxdecor< float >( "MC_b_from_tbar_pt" ) = bbar.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_b_from_tbar_phi" ) = bbar.Phi(); - fillEtaBranch(ttbarPartonHistory,"MC_b_from_tbar_eta", bbar); - - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_tbar_m" ) = WmDecay1.M(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_tbar_pt" ) = WmDecay1.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay1_from_tbar_phi" ) = WmDecay1.Phi(); - ttbarPartonHistory->auxdecor< int >( "MC_Wdecay1_from_tbar_pdgId" ) = WmDecay1_pdgId; - fillEtaBranch(ttbarPartonHistory,"MC_Wdecay1_from_tbar_eta", WmDecay1); - - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_tbar_m" ) = WmDecay2.M(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_tbar_pt" ) = WmDecay2.Pt(); - ttbarPartonHistory->auxdecor< float >( "MC_Wdecay2_from_tbar_phi" ) = WmDecay2.Phi(); - ttbarPartonHistory->auxdecor< int >( "MC_Wdecay2_from_tbar_pdgId" ) = WmDecay2_pdgId; - fillEtaBranch(ttbarPartonHistory,"MC_Wdecay2_from_tbar_eta", WmDecay2); - }//if - +namespace top { + CalcTtbarPartonHistory::CalcTtbarPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + void CalcTtbarPartonHistory::ttbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* ttbarPartonHistory) { + ttbarPartonHistory->IniVarTtbar(); + + TLorentzVector t_before, t_after, t_after_SC; + TLorentzVector Wp; + TLorentzVector b; + TLorentzVector WpDecay1; + TLorentzVector WpDecay2; + int WpDecay1_pdgId; + int WpDecay2_pdgId; + + bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, Wp, b, WpDecay1, WpDecay1_pdgId, + WpDecay2, WpDecay2_pdgId); + bool event_top_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, 6, t_after_SC); + + TLorentzVector tbar_before, tbar_after, tbar_after_SC; + TLorentzVector Wm; + TLorentzVector bbar; + TLorentzVector WmDecay1; + TLorentzVector WmDecay2; + int WmDecay1_pdgId; + int WmDecay2_pdgId; + + bool event_topbar = CalcTopPartonHistory::topWb(truthParticles, -6, tbar_before, tbar_after, Wm, bbar, WmDecay1, + WmDecay1_pdgId, WmDecay2, WmDecay2_pdgId); + bool event_topbar_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, -6, tbar_after_SC); + + if (event_top && event_topbar) { + TLorentzVector temp = t_before + tbar_before; + ttbarPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_m") = temp.M(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_pt") = temp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_beforeFSR_phi") = temp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_ttbar_beforeFSR_eta", temp); + + temp = t_after + tbar_after; + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_m") = temp.M(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_pt") = temp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_phi") = temp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_ttbar_afterFSR_beforeDecay_eta", temp); + + temp = WmDecay1 + WmDecay2 + b + WpDecay1 + WpDecay2 + bbar; + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_m") = temp.M(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_pt") = temp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_ttbar_afterFSR_phi") = temp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_ttbar_afterFSR_eta", temp); + }//if + if (event_top) { + ttbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_m") = t_before.M(); + ttbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_pt") = t_before.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_t_beforeFSR_phi") = t_before.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_t_beforeFSR_eta", t_before); + + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_m") = t_after.M(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_pt") = t_after.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_phi") = t_after.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_t_afterFSR_eta", t_after); + + if (event_top_SC) { + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_m") = t_after_SC.M(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_pt") = t_after_SC.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_phi") = t_after_SC.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_t_afterFSR_SC_eta", t_after_SC); + } + + ttbarPartonHistory->auxdecor< float >("MC_W_from_t_m") = Wp.M(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_t_pt") = Wp.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_t_phi") = Wp.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_W_from_t_eta", Wp); + + ttbarPartonHistory->auxdecor< float >("MC_b_from_t_m") = b.M(); + ttbarPartonHistory->auxdecor< float >("MC_b_from_t_pt") = b.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_b_from_t_phi") = b.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_b_from_t_eta", b); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_m") = WpDecay1.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_pt") = WpDecay1.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_phi") = WpDecay1.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = WpDecay1_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay1_from_t_eta", WpDecay1); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_m") = WpDecay2.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_pt") = WpDecay2.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_phi") = WpDecay2.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = WpDecay2_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay2_from_t_eta", WpDecay2); + }//if + if (event_topbar) { + ttbarPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_m") = tbar_before.M(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_pt") = tbar_before.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_beforeFSR_phi") = tbar_before.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_tbar_beforeFSR_eta", tbar_before); + + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_m") = tbar_after.M(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_pt") = tbar_after.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_phi") = tbar_after.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_tbar_afterFSR_eta", tbar_after); + + if (event_topbar_SC) { + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_SC_m") = tbar_after_SC.M(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_SC_pt") = tbar_after_SC.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_tbar_afterFSR_SC_phi") = tbar_after_SC.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_tbar_afterFSR_SC_eta", tbar_after_SC); + } + + ttbarPartonHistory->auxdecor< float >("MC_W_from_tbar_m") = Wm.M(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_tbar_pt") = Wm.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_W_from_tbar_phi") = Wm.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_W_from_tbar_eta", Wm); + + ttbarPartonHistory->auxdecor< float >("MC_b_from_tbar_m") = bbar.M(); + ttbarPartonHistory->auxdecor< float >("MC_b_from_tbar_pt") = bbar.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_b_from_tbar_phi") = bbar.Phi(); + fillEtaBranch(ttbarPartonHistory, "MC_b_from_tbar_eta", bbar); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_m") = WmDecay1.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_pt") = WmDecay1.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay1_from_tbar_phi") = WmDecay1.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay1_from_tbar_pdgId") = WmDecay1_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay1_from_tbar_eta", WmDecay1); + + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_m") = WmDecay2.M(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_pt") = WmDecay2.Pt(); + ttbarPartonHistory->auxdecor< float >("MC_Wdecay2_from_tbar_phi") = WmDecay2.Phi(); + ttbarPartonHistory->auxdecor< int >("MC_Wdecay2_from_tbar_pdgId") = WmDecay2_pdgId; + fillEtaBranch(ttbarPartonHistory, "MC_Wdecay2_from_tbar_eta", WmDecay2); + }//if } - StatusCode CalcTtbarPartonHistory::execute() - { - // Get the Truth Particles - const xAOD::TruthParticleContainer* truthParticles(nullptr); - ATH_CHECK( evtStore()->retrieve( truthParticles , m_config->sgKeyMCParticle() ) ); - - // Create the partonHistory xAOD object - xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer{}; - xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer{}; - partonCont->setStore( partonAuxCont ); - - xAOD::PartonHistory* ttbarPartonHistory = new xAOD::PartonHistory{}; - partonCont->push_back( ttbarPartonHistory ); - - // Recover the parton history for ttbar events - ttbarHistorySaver(truthParticles, ttbarPartonHistory); - - // Save to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyTopPartonHistory(); - std::string outputSGKeyAux = outputSGKey + "Aux."; + StatusCode CalcTtbarPartonHistory::execute() { + // Get the Truth Particles + + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + if(m_config->getDerivationStream() == "PHYS") //in DAOD_PHYS we don't have the truth particles container + { + //the functions ued in this class always start from the top, so it's enough to do the following + std::vector<std::string> collections = {"TruthTop"}; + ATH_CHECK(buildContainerFromMultipleCollections(collections,"AT_TTbarPartonHistory_TruthParticles")); + ATH_CHECK(evtStore()->retrieve(truthParticles, "AT_TTbarPartonHistory_TruthParticles")); - xAOD::TReturnCode save = evtStore()->tds()->record( partonCont , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( partonAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } + //we need to be able to navigate from the Ws to their decayProducts, see CalcTopPartonHistory.h for details + ATH_CHECK(linkBosonCollections()); + + } + else //otherwise we retrieve the container as usual + { + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + } + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* ttbarPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(ttbarPartonHistory); + + // Recover the parton history for ttbar events + ttbarHistorySaver(truthParticles, ttbarPartonHistory); - return StatusCode::SUCCESS; - } + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTzqPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTzqPartonHistory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..f5e8b8ca6582398119e2b0997622bd50d63fe81f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcTzqPartonHistory.cxx @@ -0,0 +1,208 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopPartons/CalcTzqPartonHistory.h" +#include "TopPartons/CalcTopPartonHistory.h" +#include "TopConfiguration/TopConfig.h" +#include <iostream> + + +namespace top { + CalcTzqPartonHistory::CalcTzqPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + const xAOD::TruthParticle* CalcTzqPartonHistory::findAfterGamma(const xAOD::TruthParticle* particle) { + bool isAfterGamma(false); + const int particle_ID = particle->pdgId(); + int forLoop; + + while (!isAfterGamma) { + forLoop = 0; + for (size_t j = 0; j < particle->nChildren(); j++) { + const xAOD::TruthParticle* tmp_children = particle->child(j); + if (tmp_children && tmp_children->pdgId() == particle_ID && tmp_children->pdgId() != 22) { + particle = particle->child(j); + forLoop++; + break; + }//if + }//for + + if (forLoop == 0) isAfterGamma = true; + }//while + return particle; + } + + int CalcTzqPartonHistory::sign(int a) { + if (a < 0) { + return -1; + } else return 1; + } + + bool CalcTzqPartonHistory::bottom(const xAOD::TruthParticleContainer* truthParticles, int start) { + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->pdgId() != start) { + continue; + } + tZ.b_p4 = particle->p4(); + tZ.b_pdgId = particle->pdgId(); + return true; + } + return false; + } + + bool CalcTzqPartonHistory::Zllqq(const xAOD::TruthParticleContainer* truthParticles, int start) { + + for (const xAOD::TruthParticle* particle : *truthParticles) { + if (particle->pdgId() != start || particle->nChildren() != 2) { + continue; + } + tZ.Z_p4 = particle->p4(); + + for (size_t k = 0; k < particle->nChildren(); k++) { + + const xAOD::TruthParticle* ZChildren = particle->child(k); + if (ZChildren->pdgId() > 0) { + tZ.Zdecay1_p4 = findAfterGamma(ZChildren)->p4(); + tZ.Zdecay1_pdgId = ZChildren->pdgId(); + tZ.Zdecay1_status = ZChildren->status(); + } else { + tZ.Zdecay2_p4 = findAfterGamma(ZChildren)->p4(); + tZ.Zdecay2_pdgId = ZChildren->pdgId(); + tZ.Zdecay1_status = ZChildren->status(); + } + } //for + // here we ask to return true if it identifies the particle and its children correctly. + return true; + } + return false; + } + + void CalcTzqPartonHistory::TZHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* TzqPartonHistory) { + TzqPartonHistory->IniVarTzq(); + TLorentzVector t_before, t_after, t_after_SC; + TLorentzVector Wp; + TLorentzVector b; + TLorentzVector WpDecay1; + TLorentzVector WpDecay2; + int WpDecay1_pdgId; + int WpDecay2_pdgId; + + bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, Wp, b, WpDecay1, WpDecay1_pdgId, + WpDecay2, WpDecay2_pdgId); + bool event_top_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, 6, t_after_SC); + bool event_topbar = CalcTopPartonHistory::topWb(truthParticles, -6, t_before, t_after, Wp, b, WpDecay1, + WpDecay1_pdgId, WpDecay2, WpDecay2_pdgId); + bool event_topbar_SC = CalcTopPartonHistory::topAfterFSR_SC(truthParticles, -6, t_after_SC); + bool event_Z = CalcTzqPartonHistory::Zllqq(truthParticles, 23); + bool event_bottom = CalcTzqPartonHistory::bottom(truthParticles, 5); + bool event_bottombar = CalcTzqPartonHistory::bottom(truthParticles, -5); + + + if (event_Z) { + if ((event_top && event_bottombar) || (event_topbar && event_bottom)) { + TzqPartonHistory->auxdecor< float >("MC_t_beforeFSR_m") = t_before.M(); + TzqPartonHistory->auxdecor< float >("MC_t_beforeFSR_pt") = t_before.Pt(); + TzqPartonHistory->auxdecor< float >("MC_t_beforeFSR_phi") = t_before.Phi(); + fillEtaBranch(TzqPartonHistory, "MC_t_beforeFSR_eta", t_before); + + TzqPartonHistory->auxdecor< float >("MC_t_afterFSR_m") = t_after.M(); + TzqPartonHistory->auxdecor< float >("MC_t_afterFSR_pt") = t_after.Pt(); + TzqPartonHistory->auxdecor< float >("MC_t_afterFSR_phi") = t_after.Phi(); + fillEtaBranch(TzqPartonHistory, "MC_t_afterFSR_eta", t_after); + + if (event_top_SC || event_topbar_SC) { + TzqPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_m") = t_after_SC.M(); + TzqPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_pt") = t_after_SC.Pt(); + TzqPartonHistory->auxdecor< float >("MC_t_afterFSR_SC_phi") = t_after_SC.Phi(); + fillEtaBranch(TzqPartonHistory, "MC_t_afterFSR_SC_eta", t_after_SC); + } + + TzqPartonHistory->auxdecor< float >("MC_W_from_t_m") = Wp.M(); + TzqPartonHistory->auxdecor< float >("MC_W_from_t_pt") = Wp.Pt(); + TzqPartonHistory->auxdecor< float >("MC_W_from_t_phi") = Wp.Phi(); + fillEtaBranch(TzqPartonHistory, "MC_W_from_t_eta", Wp); + + TzqPartonHistory->auxdecor< float >("MC_b_from_t_m") = b.M(); + TzqPartonHistory->auxdecor< float >("MC_b_from_t_pt") = b.Pt(); + TzqPartonHistory->auxdecor< float >("MC_b_from_t_phi") = b.Phi(); + fillEtaBranch(TzqPartonHistory, "MC_b_from_t_eta", b); + + TzqPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_m") = WpDecay1.M(); + TzqPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_pt") = WpDecay1.Pt(); + TzqPartonHistory->auxdecor< float >("MC_Wdecay1_from_t_phi") = WpDecay1.Phi(); + TzqPartonHistory->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = WpDecay1_pdgId; + fillEtaBranch(TzqPartonHistory, "MC_Wdecay1_from_t_eta", WpDecay1); + + TzqPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_m") = WpDecay2.M(); + TzqPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_pt") = WpDecay2.Pt(); + TzqPartonHistory->auxdecor< float >("MC_Wdecay2_from_t_phi") = WpDecay2.Phi(); + TzqPartonHistory->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = WpDecay2_pdgId; + fillEtaBranch(TzqPartonHistory, "MC_Wdecay2_from_t_eta", WpDecay2); + + //Z-Variables + TzqPartonHistory->auxdecor< float >("MC_Z_m") = tZ.Z_p4.M(); + TzqPartonHistory->auxdecor< float >("MC_Z_pt") = tZ.Z_p4.Pt(); + TzqPartonHistory->auxdecor< float >("MC_Z_phi") = tZ.Z_p4.Phi(); + fillEtaBranch(TzqPartonHistory, "MC_Z_eta", tZ.Z_p4); + + + //First Decay (Zdecay1) + TzqPartonHistory->auxdecor< float >("MC_Zdecay1_m") = tZ.Zdecay1_p4.M(); + TzqPartonHistory->auxdecor< float >("MC_Zdecay1_pt") = tZ.Zdecay1_p4.Pt(); + TzqPartonHistory->auxdecor< float >("MC_Zdecay1_phi") = tZ.Zdecay1_p4.Phi(); + TzqPartonHistory->auxdecor< int >("MC_Zdecay1_pdgId") = tZ.Zdecay1_pdgId; + TzqPartonHistory->auxdecor< int >("MC_Zdecay1_status") = tZ.Zdecay1_status; + fillEtaBranch(TzqPartonHistory, "MC_Zdecay1_eta", tZ.Zdecay1_p4); + + //Second Decay (Zdecay2) + TzqPartonHistory->auxdecor< float >("MC_Zdecay2_m") = tZ.Zdecay2_p4.M(); + TzqPartonHistory->auxdecor< float >("MC_Zdecay2_pt") = tZ.Zdecay2_p4.Pt(); + TzqPartonHistory->auxdecor< float >("MC_Zdecay2_phi") = tZ.Zdecay2_p4.Phi(); + TzqPartonHistory->auxdecor< int >("MC_Zdecay2_pdgId") = tZ.Zdecay2_pdgId; + TzqPartonHistory->auxdecor< int >("MC_Zdecay2_status") = tZ.Zdecay2_status; + fillEtaBranch(TzqPartonHistory, "MC_Zdecay2_eta", tZ.Zdecay2_p4); + + + + //b quark + TzqPartonHistory->auxdecor< float >("MC_b_m") = tZ.b_p4.M(); + TzqPartonHistory->auxdecor< float >("MC_b_pt") = tZ.b_p4.Pt(); + TzqPartonHistory->auxdecor< float >("MC_b_phi") = tZ.b_p4.Phi(); + TzqPartonHistory->auxdecor< int >("MC_b_pdgId") = tZ.b_pdgId; + fillEtaBranch(TzqPartonHistory, "MC_b_eta", tZ.b_p4); + + + } + } + } + + StatusCode CalcTzqPartonHistory::execute() { + //Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* TzqPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(TzqPartonHistory); + + // Recover the parton history for TZ events + TZHistorySaver(truthParticles, TzqPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWlvPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWlvPartonHistory.cxx index b99e3f04aa253cbd6661dce75ef2e57af367f199..ba9ee65c9fe8189697408a3c18b787ab28f2441a 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWlvPartonHistory.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWlvPartonHistory.cxx @@ -1,76 +1,73 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #include "TopPartons/CalcWlvPartonHistory.h" #include "TopConfiguration/TopConfig.h" -namespace top{ - - CalcWlvPartonHistory::CalcWlvPartonHistory(const std::string& name) : CalcTopPartonHistory( name ){} - - void CalcWlvPartonHistory::WlvHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* wlvPartonHistory){ - - wlvPartonHistory->IniVarWlv(); - - TLorentzVector W; - TLorentzVector WDecay1; - TLorentzVector WDecay2; - int WDecay1_pdgId; - int WDecay2_pdgId; - bool goodevent = CalcTopPartonHistory::Wlv(truthParticles, W, WDecay1, WDecay1_pdgId, WDecay2, WDecay2_pdgId); - - - if (goodevent){ - wlvPartonHistory->auxdecor< float >( "MC_W_m" ) = W.M(); - wlvPartonHistory->auxdecor< float >( "MC_W_pt" ) = W.Pt(); - wlvPartonHistory->auxdecor< float >( "MC_W_phi" ) = W.Phi(); - fillEtaBranch(wlvPartonHistory, "MC_W_eta", W); - - - wlvPartonHistory->auxdecor< float >( "MC_l_m" ) = WDecay1.M(); - wlvPartonHistory->auxdecor< float >( "MC_l_pt" ) = WDecay1.Pt(); - wlvPartonHistory->auxdecor< float >( "MC_l_phi" ) = WDecay1.Phi(); - wlvPartonHistory->auxdecor< int >( "MC_l_pdgId" ) = WDecay1_pdgId; - fillEtaBranch(wlvPartonHistory,"MC_l_eta", WDecay1); - - wlvPartonHistory->auxdecor< float >( "MC_v_m" ) = WDecay2.M(); - wlvPartonHistory->auxdecor< float >( "MC_v_pt" ) = WDecay2.Pt(); - wlvPartonHistory->auxdecor< float >( "MC_v_phi" ) = WDecay2.Phi(); - wlvPartonHistory->auxdecor< int >( "MC_v_pdgId" ) = WDecay2_pdgId; - fillEtaBranch(wlvPartonHistory,"MC_v_eta", WDecay2); - }//if - - +namespace top { + CalcWlvPartonHistory::CalcWlvPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + void CalcWlvPartonHistory::WlvHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* wlvPartonHistory) { + wlvPartonHistory->IniVarWlv(); + + TLorentzVector W; + TLorentzVector WDecay1; + TLorentzVector WDecay2; + int WDecay1_pdgId; + int WDecay2_pdgId; + bool goodevent = CalcTopPartonHistory::Wlv(truthParticles, W, WDecay1, WDecay1_pdgId, WDecay2, WDecay2_pdgId); + + + if (goodevent) { + wlvPartonHistory->auxdecor< float >("MC_W_m") = W.M(); + wlvPartonHistory->auxdecor< float >("MC_W_pt") = W.Pt(); + wlvPartonHistory->auxdecor< float >("MC_W_phi") = W.Phi(); + fillEtaBranch(wlvPartonHistory, "MC_W_eta", W); + + + wlvPartonHistory->auxdecor< float >("MC_l_m") = WDecay1.M(); + wlvPartonHistory->auxdecor< float >("MC_l_pt") = WDecay1.Pt(); + wlvPartonHistory->auxdecor< float >("MC_l_phi") = WDecay1.Phi(); + wlvPartonHistory->auxdecor< int >("MC_l_pdgId") = WDecay1_pdgId; + fillEtaBranch(wlvPartonHistory, "MC_l_eta", WDecay1); + + wlvPartonHistory->auxdecor< float >("MC_v_m") = WDecay2.M(); + wlvPartonHistory->auxdecor< float >("MC_v_pt") = WDecay2.Pt(); + wlvPartonHistory->auxdecor< float >("MC_v_phi") = WDecay2.Phi(); + wlvPartonHistory->auxdecor< int >("MC_v_pdgId") = WDecay2_pdgId; + fillEtaBranch(wlvPartonHistory, "MC_v_eta", WDecay2); + }//if } - StatusCode CalcWlvPartonHistory::execute() - { - // Get the Truth Particles - const xAOD::TruthParticleContainer* truthParticles(nullptr); - ATH_CHECK( evtStore()->retrieve( truthParticles , m_config->sgKeyMCParticle() ) ); - - // Create the partonHistory xAOD object - xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer{}; - xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer{}; - partonCont->setStore( partonAuxCont ); - - xAOD::PartonHistory* wlvPartonHistory = new xAOD::PartonHistory{}; - partonCont->push_back( wlvPartonHistory ); - - // Recover the parton history for wlv events - WlvHistorySaver(truthParticles, wlvPartonHistory); - - // Save to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyTopPartonHistory(); - std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( partonCont , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( partonAuxCont , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } - - return StatusCode::SUCCESS; + StatusCode CalcWlvPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* wlvPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(wlvPartonHistory); + + // Recover the parton history for wlv events + WlvHistorySaver(truthParticles, wlvPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWtbPartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWtbPartonHistory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..2b87b3cbf03ced2a101e9ff31a103f35b60dc4fd --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/CalcWtbPartonHistory.cxx @@ -0,0 +1,184 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopPartons/CalcWtbPartonHistory.h" +#include "TopConfiguration/TopConfig.h" + +namespace top { + CalcWtbPartonHistory::CalcWtbPartonHistory(const std::string& name) : CalcTopPartonHistory(name) {} + + void CalcWtbPartonHistory::wtbHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* wtbPartonHistory) { + wtbPartonHistory->IniVarWtb(); + + TLorentzVector t_before, t_after; + TLorentzVector antit_before, antit_after; + TLorentzVector WfromTop; + TLorentzVector bFromTop; + TLorentzVector WfromTopDecay1; + TLorentzVector WfromTopDecay2; + int WfromTopDecay1_pdgId; + int WfromTopDecay2_pdgId; + + bool event_top = CalcTopPartonHistory::topWb(truthParticles, 6, t_before, t_after, WfromTop, bFromTop, + WfromTopDecay1, WfromTopDecay1_pdgId, WfromTopDecay2, + WfromTopDecay2_pdgId); + + TLorentzVector WfromAntiTop; + TLorentzVector bFromAntiTop; + TLorentzVector WfromAntiTopDecay1; + TLorentzVector WfromAntiTopDecay2; + int WfromAntiTopDecay1_pdgId; + int WfromAntiTopDecay2_pdgId; + + bool event_antitop = CalcTopPartonHistory::topWb(truthParticles, -6, antit_before, antit_after, WfromAntiTop, + bFromAntiTop, WfromAntiTopDecay1, WfromAntiTopDecay1_pdgId, + WfromAntiTopDecay2, WfromAntiTopDecay2_pdgId); + + TLorentzVector WnotFromTop; + TLorentzVector WnotFromTopDecay1; + TLorentzVector WnotFromTopDecay2; + int WnotFromTop_pdgId; + int WnotFromTopDecay1_pdgId; + int WnotFromTopDecay2_pdgId; + + bool event_WnotTop = CalcTopPartonHistory::Wt_W(truthParticles, WnotFromTop, WnotFromTop_pdgId, WnotFromTopDecay1, + WnotFromTopDecay1_pdgId, WnotFromTopDecay2, + WnotFromTopDecay2_pdgId); + + TLorentzVector bNotFromTop_before; + TLorentzVector bNotFromTop_after; + int bNotFromTop_pdgId; + + bool event_b = CalcTopPartonHistory::Wt_b(truthParticles, bNotFromTop_before, bNotFromTop_after, bNotFromTop_pdgId); + + if (event_top && !event_antitop) { + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_pt") = t_before.Pt(); + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_eta") = t_before.Eta(); + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_phi") = t_before.Phi(); + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_m") = t_before.M(); + + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_pt") = t_after.Pt(); + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_eta") = t_after.Eta(); + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_phi") = t_after.Phi(); + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_m") = t_after.M(); + + wtbPartonHistory->auxdecor< float >("MC_b_from_top_pt") = bFromTop.Pt(); + wtbPartonHistory->auxdecor< float >("MC_b_from_top_eta") = bFromTop.Eta(); + wtbPartonHistory->auxdecor< float >("MC_b_from_top_phi") = bFromTop.Phi(); + wtbPartonHistory->auxdecor< float >("MC_b_from_top_m") = bFromTop.M(); + + wtbPartonHistory->auxdecor< float >("MC_W_from_top_pt") = WfromTop.Pt(); + wtbPartonHistory->auxdecor< float >("MC_W_from_top_eta") = WfromTop.Eta(); + wtbPartonHistory->auxdecor< float >("MC_W_from_top_phi") = WfromTop.Phi(); + wtbPartonHistory->auxdecor< float >("MC_W_from_top_m") = WfromTop.M(); + + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_pt") = WfromTopDecay1.Pt(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_eta") = WfromTopDecay1.Eta(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_phi") = WfromTopDecay1.Phi(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_m") = WfromTopDecay1.M(); + wtbPartonHistory->auxdecor< int >("MC_Wdecay1_from_top_pdgId") = WfromTopDecay1_pdgId; + + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_pt") = WfromTopDecay2.Pt(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_eta") = WfromTopDecay2.Eta(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_phi") = WfromTopDecay2.Phi(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_m") = WfromTopDecay2.M(); + wtbPartonHistory->auxdecor< int >("MC_Wdecay2_from_top_pdgId") = WfromTopDecay2_pdgId; + } else if (!event_top && event_antitop) { + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_pt") = antit_before.Pt(); + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_eta") = antit_before.Eta(); + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_phi") = antit_before.Phi(); + wtbPartonHistory->auxdecor< float >("MC_top_beforeFSR_m") = antit_before.M(); + + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_pt") = antit_after.Pt(); + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_eta") = antit_after.Eta(); + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_phi") = antit_after.Phi(); + wtbPartonHistory->auxdecor< float >("MC_top_afterFSR_m") = antit_after.M(); + + wtbPartonHistory->auxdecor< float >("MC_b_from_top_pt") = bFromAntiTop.Pt(); + wtbPartonHistory->auxdecor< float >("MC_b_from_top_eta") = bFromAntiTop.Eta(); + wtbPartonHistory->auxdecor< float >("MC_b_from_top_phi") = bFromAntiTop.Phi(); + wtbPartonHistory->auxdecor< float >("MC_b_from_top_m") = bFromAntiTop.M(); + + wtbPartonHistory->auxdecor< float >("MC_W_from_top_pt") = WfromAntiTop.Pt(); + wtbPartonHistory->auxdecor< float >("MC_W_from_top_eta") = WfromAntiTop.Eta(); + wtbPartonHistory->auxdecor< float >("MC_W_from_top_phi") = WfromAntiTop.Phi(); + wtbPartonHistory->auxdecor< float >("MC_W_from_top_m") = WfromAntiTop.M(); + + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_pt") = WfromAntiTopDecay1.Pt(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_eta") = WfromAntiTopDecay1.Eta(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_phi") = WfromAntiTopDecay1.Phi(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_from_top_m") = WfromAntiTopDecay1.M(); + wtbPartonHistory->auxdecor< int >("MC_Wdecay1_from_top_pdgId") = WfromAntiTopDecay1_pdgId; + + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_pt") = WfromAntiTopDecay2.Pt(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_eta") = WfromAntiTopDecay2.Eta(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_phi") = WfromAntiTopDecay2.Phi(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_from_top_m") = WfromAntiTopDecay2.M(); + wtbPartonHistory->auxdecor< int >("MC_Wdecay2_from_top_pdgId") = WfromAntiTopDecay2_pdgId; + } + + if (((event_top && !event_antitop) || (!event_top && event_antitop)) && event_WnotTop) { + wtbPartonHistory->auxdecor< float >("MC_W_not_from_top_pt") = WnotFromTop.Pt(); + wtbPartonHistory->auxdecor< float >("MC_W_not_from_top_eta") = WnotFromTop.Eta(); + wtbPartonHistory->auxdecor< float >("MC_W_not_from_top_phi") = WnotFromTop.Phi(); + wtbPartonHistory->auxdecor< float >("MC_W_not_from_top_m") = WnotFromTop.M(); + + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_not_from_top_pt") = WnotFromTopDecay1.Pt(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_not_from_top_eta") = WnotFromTopDecay1.Eta(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_not_from_top_phi") = WnotFromTopDecay1.Phi(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay1_not_from_top_m") = WnotFromTopDecay1.M(); + wtbPartonHistory->auxdecor< int >("MC_Wdecay1_not_from_top_pdgId") = WnotFromTopDecay1_pdgId; + + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_not_from_top_pt") = WnotFromTopDecay2.Pt(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_not_from_top_eta") = WnotFromTopDecay2.Eta(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_not_from_top_phi") = WnotFromTopDecay2.Phi(); + wtbPartonHistory->auxdecor< float >("MC_Wdecay2_not_from_top_m") = WnotFromTopDecay2.M(); + wtbPartonHistory->auxdecor< int >("MC_Wdecay2_not_from_top_pdgId") = WnotFromTopDecay2_pdgId; + }//if + + if (((event_top && !event_antitop) || (!event_top && event_antitop)) && event_b) { + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_beforeFSR_pt") = bNotFromTop_before.Pt(); + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_beforeFSR_eta") = bNotFromTop_before.Eta(); + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_beforeFSR_phi") = bNotFromTop_before.Phi(); + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_beforeFSR_m") = bNotFromTop_before.M(); + wtbPartonHistory->auxdecor< int >("MC_b_not_from_top_pdgId") = bNotFromTop_pdgId; + + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_afterFSR_pt") = bNotFromTop_after.Pt(); + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_afterFSR_eta") = bNotFromTop_after.Eta(); + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_afterFSR_phi") = bNotFromTop_after.Phi(); + wtbPartonHistory->auxdecor< float >("MC_b_not_from_top_afterFSR_m") = bNotFromTop_after.M(); + } + } + + StatusCode CalcWtbPartonHistory::execute() { + // Get the Truth Particles + const xAOD::TruthParticleContainer* truthParticles(nullptr); + + ATH_CHECK(evtStore()->retrieve(truthParticles, m_config->sgKeyMCParticle())); + + // Create the partonHistory xAOD object + xAOD::PartonHistoryAuxContainer* partonAuxCont = new xAOD::PartonHistoryAuxContainer {}; + xAOD::PartonHistoryContainer* partonCont = new xAOD::PartonHistoryContainer {}; + partonCont->setStore(partonAuxCont); + + xAOD::PartonHistory* wtbPartonHistory = new xAOD::PartonHistory {}; + partonCont->push_back(wtbPartonHistory); + + // Recover the parton history for Wt SingleTop events + wtbHistorySaver(truthParticles, wtbPartonHistory); + + // Save to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyTopPartonHistory(); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(partonCont, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(partonAuxCont, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/LinkDef.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/LinkDef.h index c5ad90ea174f7dbeb95caf611abf10fdc5da0526..aa61c603d751979df867cf20923380ebb4691848 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/LinkDef.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/LinkDef.h @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ #include "TopPartons/PartonHistory.h" diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistory.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistory.cxx index 89085e0bb9bd1c8c6ab317aa72a5c6eb9baafe5f..5ffdcbc102b0a6b63daff945b125a2ad7bff6440 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistory.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistory.cxx @@ -1,193 +1,622 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ // $Id: PartonHistory.cxx 800464 2017-03-13 18:06:24Z tpelzer $ #include "TopPartons/PartonHistory.h" #include "xAODCore/AddDVProxy.h" -namespace xAOD{ - /// Aux Container +namespace xAOD { + /// Aux Container PartonHistoryAuxContainer::PartonHistoryAuxContainer() : - AuxContainerBase() - { + AuxContainerBase() { } - + /// Interface class PartonHistory::PartonHistory() : - SG::AuxElement() - { + SG::AuxElement() { } //Initialize variables for ttbar events - void PartonHistory::IniVarTtbar(){ - - //ttbar variables - this->auxdecor< float >( "MC_ttbar_beforeFSR_m" ) = -1; - this->auxdecor< float >( "MC_ttbar_beforeFSR_pt") = -1; - this->auxdecor< float >( "MC_ttbar_beforeFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_ttbar_beforeFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_ttbar_afterFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_ttbar_afterFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_ttbar_afterFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_ttbar_afterFSR_phi" ) = -1000 ; - - //t variables - this->auxdecor< float >( "MC_t_beforeFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_t_beforeFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_t_beforeFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_t_beforeFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_t_afterFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_t_afterFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_t_afterFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_t_afterFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_t_afterFSR_SC_m" ) = -1 ; - this->auxdecor< float >( "MC_t_afterFSR_SC_pt" ) = -1 ; - this->auxdecor< float >( "MC_t_afterFSR_SC_eta" ) = -1000 ; - this->auxdecor< float >( "MC_t_afterFSR_SC_phi" ) = -1000 ; - - //tbar variables - this->auxdecor< float >( "MC_tbar_beforeFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_tbar_beforeFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_tbar_beforeFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_tbar_beforeFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_tbar_afterFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_tbar_afterFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_tbar_afterFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_tbar_afterFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_tbar_afterFSR_SC_m" ) = -1 ; - this->auxdecor< float >( "MC_tbar_afterFSR_SC_pt" ) = -1 ; - this->auxdecor< float >( "MC_tbar_afterFSR_SC_eta" ) = -1000 ; - this->auxdecor< float >( "MC_tbar_afterFSR_SC_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_W_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_W_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_W_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_W_from_t_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_W_from_tbar_m" ) = -1 ; - this->auxdecor< float >( "MC_W_from_tbar_pt" ) = -1 ; - this->auxdecor< float >( "MC_W_from_tbar_eta" ) = -1000 ; - this->auxdecor< float >( "MC_W_from_tbar_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_b_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_b_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_b_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_b_from_t_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_b_from_tbar_m" ) = -1 ; - this->auxdecor< float >( "MC_b_from_tbar_pt" ) = -1 ; - this->auxdecor< float >( "MC_b_from_tbar_eta" ) = -1000 ; - this->auxdecor< float >( "MC_b_from_tbar_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_Wdecay1_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay1_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay1_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_Wdecay1_from_t_phi" ) = -1000 ; - this->auxdecor< int >( "MC_Wdecay1_from_t_pdgId") = 0 ; - - this->auxdecor< float >( "MC_Wdecay1_from_tbar_m" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay1_from_tbar_pt" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay1_from_tbar_eta" ) = -1000 ; - this->auxdecor< float >( "MC_Wdecay1_from_tbar_phi" ) = -1000 ; - this->auxdecor< int >( "MC_Wdecay1_from_tbar_pdgId") = 0 ; - - this->auxdecor< float >( "MC_Wdecay2_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay2_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay2_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_Wdecay2_from_t_phi" ) = -1000 ; - this->auxdecor< int >( "MC_Wdecay2_from_t_pdgId") = 0 ; - - this->auxdecor< float >( "MC_Wdecay2_from_tbar_m" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay2_from_tbar_pt" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay2_from_tbar_eta" ) = -1000 ; - this->auxdecor< float >( "MC_Wdecay2_from_tbar_phi" ) = -1000 ; - this->auxdecor< int >( "MC_Wdecay2_from_tbar_pdgId") = 0 ; + void PartonHistory::IniVarTtbar() { + //ttbar variables + this->auxdecor< float >("MC_ttbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_ttbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_ttbar_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_ttbar_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_ttbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_ttbar_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_m") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_pt") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_eta") = -1000; + this->auxdecor< float >("MC_ttbar_afterFSR_beforeDecay_phi") = -1000; + + //t variables + this->auxdecor< float >("MC_t_beforeFSR_m") = -1; + this->auxdecor< float >("MC_t_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_t_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_m") = -1; + this->auxdecor< float >("MC_t_afterFSR_pt") = -1; + this->auxdecor< float >("MC_t_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_SC_m") = -1; + this->auxdecor< float >("MC_t_afterFSR_SC_pt") = -1; + this->auxdecor< float >("MC_t_afterFSR_SC_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_phi") = -1000; + + //tbar variables + this->auxdecor< float >("MC_tbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_tbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_tbar_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_tbar_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_tbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_tbar_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_tbar_afterFSR_SC_m") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_SC_pt") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_SC_eta") = -1000; + this->auxdecor< float >("MC_tbar_afterFSR_SC_phi") = -1000; + + this->auxdecor< float >("MC_W_from_t_m") = -1; + this->auxdecor< float >("MC_W_from_t_pt") = -1; + this->auxdecor< float >("MC_W_from_t_eta") = -1000; + this->auxdecor< float >("MC_W_from_t_phi") = -1000; + + this->auxdecor< float >("MC_W_from_tbar_m") = -1; + this->auxdecor< float >("MC_W_from_tbar_pt") = -1; + this->auxdecor< float >("MC_W_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_W_from_tbar_phi") = -1000; + + this->auxdecor< float >("MC_b_from_t_m") = -1; + this->auxdecor< float >("MC_b_from_t_pt") = -1; + this->auxdecor< float >("MC_b_from_t_eta") = -1000; + this->auxdecor< float >("MC_b_from_t_phi") = -1000; + + this->auxdecor< float >("MC_b_from_tbar_m") = -1; + this->auxdecor< float >("MC_b_from_tbar_pt") = -1; + this->auxdecor< float >("MC_b_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_b_from_tbar_phi") = -1000; + + this->auxdecor< float >("MC_Wdecay1_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay1_from_tbar_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_tbar_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_tbar_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_tbar_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay2_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay2_from_tbar_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_tbar_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_tbar_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_tbar_pdgId") = 0; + } + + //Initialize variables for ttbar events + void PartonHistory::IniVarTtbarLight() { + //ttbar variables + this->auxdecor< float >("MC_ttbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_ttbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_ttbar_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_ttbar_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_ttbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_ttbar_afterFSR_phi") = -1000; + //t variables + this->auxdecor< float >("MC_t_beforeFSR_m") = -1; + this->auxdecor< float >("MC_t_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_t_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_m") = -1; + this->auxdecor< float >("MC_t_afterFSR_pt") = -1; + this->auxdecor< float >("MC_t_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_SC_m") = -1; + this->auxdecor< float >("MC_t_afterFSR_SC_pt") = -1; + this->auxdecor< float >("MC_t_afterFSR_SC_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_phi") = -1000; + + //tbar variables + this->auxdecor< float >("MC_tbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_tbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_tbar_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_tbar_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_tbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_tbar_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_tbar_afterFSR_SC_m") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_SC_pt") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_SC_eta") = -1000; + this->auxdecor< float >("MC_tbar_afterFSR_SC_phi") = -1000; + + this->auxdecor< float >("MC_W_from_t_m") = -1; + this->auxdecor< float >("MC_W_from_t_pt") = -1; + this->auxdecor< float >("MC_W_from_t_eta") = -1000; + this->auxdecor< float >("MC_W_from_t_phi") = -1000; + + this->auxdecor< float >("MC_W_from_tbar_m") = -1; + this->auxdecor< float >("MC_W_from_tbar_pt") = -1; + this->auxdecor< float >("MC_W_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_W_from_tbar_phi") = -1000; + + this->auxdecor< float >("MC_q_from_t_m") = -1; + this->auxdecor< float >("MC_q_from_t_pt") = -1; + this->auxdecor< float >("MC_q_from_t_eta") = -1000; + this->auxdecor< float >("MC_q_from_t_phi") = -1000; + this->auxdecor< int >("MC_q_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_q_from_tbar_m") = -1; + this->auxdecor< float >("MC_q_from_tbar_pt") = -1; + this->auxdecor< float >("MC_q_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_q_from_tbar_phi") = -1000; + this->auxdecor< int >("MC_q_from_tbar_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay1_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay1_from_tbar_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_tbar_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_tbar_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_tbar_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay2_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay2_from_tbar_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_tbar_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_tbar_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_tbar_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_tbar_pdgId") = 0; } //Initialize variables for tbbar events - void PartonHistory::IniVarTbbar(){ - - //ttbar variables - this->auxdecor< float >( "MC_tbbar_beforeFSR_m" ) = -1; - this->auxdecor< float >( "MC_tbbar_beforeFSR_pt") = -1; - this->auxdecor< float >( "MC_tbbar_beforeFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_tbbar_beforeFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_tbbar_afterFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_tbbar_afterFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_tbbar_afterFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_tbbar_afterFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_t_beforeFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_t_beforeFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_t_beforeFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_t_beforeFSR_phi" ) = -1000 ; - - //tbbar variables - this->auxdecor< float >( "MC_b_beforeFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_b_beforeFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_b_beforeFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_b_beforeFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_b_afterFSR_m" ) = -1 ; - this->auxdecor< float >( "MC_b_afterFSR_pt" ) = -1 ; - this->auxdecor< float >( "MC_b_afterFSR_eta" ) = -1000 ; - this->auxdecor< float >( "MC_b_afterFSR_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_W_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_W_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_W_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_W_from_t_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_b_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_b_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_b_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_b_from_t_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_Wdecay1_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay1_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay1_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_Wdecay1_from_t_phi" ) = -1000 ; - this->auxdecor< int >( "MC_Wdecay1_from_t_pdgId") = 0 ; - - this->auxdecor< float >( "MC_Wdecay2_from_t_m" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay2_from_t_pt" ) = -1 ; - this->auxdecor< float >( "MC_Wdecay2_from_t_eta" ) = -1000 ; - this->auxdecor< float >( "MC_Wdecay2_from_t_phi" ) = -1000 ; - this->auxdecor< int >( "MC_Wdecay2_from_t_pdgId") = 0 ; + void PartonHistory::IniVarTbbar() { + //ttbar variables + this->auxdecor< float >("MC_tbbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_tbbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_tbbar_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_tbbar_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_tbbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_tbbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_tbbar_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_tbbar_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_beforeFSR_m") = -1; + this->auxdecor< float >("MC_t_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_t_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_phi") = -1000; + + //tbbar variables + this->auxdecor< float >("MC_b_beforeFSR_m") = -1; + this->auxdecor< float >("MC_b_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_b_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_b_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_b_afterFSR_m") = -1; + this->auxdecor< float >("MC_b_afterFSR_pt") = -1; + this->auxdecor< float >("MC_b_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_b_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_W_from_t_m") = -1; + this->auxdecor< float >("MC_W_from_t_pt") = -1; + this->auxdecor< float >("MC_W_from_t_eta") = -1000; + this->auxdecor< float >("MC_W_from_t_phi") = -1000; + this->auxdecor< float >("MC_b_from_t_m") = -1; + this->auxdecor< float >("MC_b_from_t_pt") = -1; + this->auxdecor< float >("MC_b_from_t_eta") = -1000; + this->auxdecor< float >("MC_b_from_t_phi") = -1000; + + this->auxdecor< float >("MC_Wdecay1_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay2_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = 0; } - - //Initialize variables for Wlv events - void PartonHistory::IniVarWlv(){ - - // W - this->auxdecor< float >( "MC_W_m" ) = -1 ; - this->auxdecor< float >( "MC_W_pt" ) = -1 ; - this->auxdecor< float >( "MC_W_eta" ) = -1000 ; - this->auxdecor< float >( "MC_W_phi" ) = -1000 ; - - this->auxdecor< float >( "MC_l_m" ) = -1 ; - this->auxdecor< float >( "MC_l_pt" ) = -1 ; - this->auxdecor< float >( "MC_l_eta" ) = -1000 ; - this->auxdecor< float >( "MC_l_phi" ) = -1000 ; - this->auxdecor< int >( "MC_l_pdgId") = 0 ; - - this->auxdecor< float >( "MC_v_m" ) = -1 ; - this->auxdecor< float >( "MC_v_pt" ) = -1 ; - this->auxdecor< float >( "MC_v_eta" ) = -1000 ; - this->auxdecor< float >( "MC_v_phi" ) = -1000 ; - this->auxdecor< int >( "MC_v_pdgId") = 0 ; + //Initialize variables for Wlv events + void PartonHistory::IniVarWlv() { + // W + this->auxdecor< float >("MC_W_m") = -1; + this->auxdecor< float >("MC_W_pt") = -1; + this->auxdecor< float >("MC_W_eta") = -1000; + this->auxdecor< float >("MC_W_phi") = -1000; + + this->auxdecor< float >("MC_l_m") = -1; + this->auxdecor< float >("MC_l_pt") = -1; + this->auxdecor< float >("MC_l_eta") = -1000; + this->auxdecor< float >("MC_l_phi") = -1000; + this->auxdecor< int >("MC_l_pdgId") = 0; + + this->auxdecor< float >("MC_v_m") = -1; + this->auxdecor< float >("MC_v_pt") = -1; + this->auxdecor< float >("MC_v_eta") = -1000; + this->auxdecor< float >("MC_v_phi") = -1000; + this->auxdecor< int >("MC_v_pdgId") = 0; + } + + // Initialize variable for Wt ST events + void PartonHistory::IniVarWtb() { + // top or antitop + this->auxdecor< float >("MC_top_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_top_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_top_beforeFSR_phi") = -1000; + this->auxdecor< float >("MC_top_beforeFSR_m") = -1; + this->auxdecor< float >("MC_top_afterFSR_pt") = -1; + this->auxdecor< float >("MC_top_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_top_afterFSR_phi") = -1000; + this->auxdecor< float >("MC_top_afterFSR_m") = -1; + + // b from top + this->auxdecor< float >("MC_b_from_top_pt") = -1; + this->auxdecor< float >("MC_b_from_top_eta") = -1000; + this->auxdecor< float >("MC_b_from_top_phi") = -1000; + this->auxdecor< float >("MC_b_from_top_m") = -1; + + // W from top + this->auxdecor< float >("MC_W_from_top_pt") = -1; + this->auxdecor< float >("MC_W_from_top_eta") = -1000; + this->auxdecor< float >("MC_W_from_top_phi") = -1000; + this->auxdecor< float >("MC_W_from_top_m") = -1; + + // W from top decay product 1 + this->auxdecor< float >("MC_Wdecay1_from_top_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_top_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_top_phi") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_top_m") = -1; + this->auxdecor< int >("MC_Wdecay1_from_top_pdgId") = 0; + + // W from top decay product 2 + this->auxdecor< float >("MC_Wdecay2_from_top_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_top_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_top_phi") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_top_m") = -1; + this->auxdecor< int >("MC_Wdecay2_from_top_pdgId") = 0; + + // W NOT from top + this->auxdecor< float >("MC_W_not_from_top_pt") = -1; + this->auxdecor< float >("MC_W_not_from_top_eta") = -1000; + this->auxdecor< float >("MC_W_not_from_top_phi") = -1000; + this->auxdecor< float >("MC_W_not_from_top_m") = -1; + + // W NOT from top decay product 1 + this->auxdecor< float >("MC_Wdecay1_not_from_top_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_not_from_top_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_not_from_top_phi") = -1000; + this->auxdecor< float >("MC_Wdecay1_not_from_top_m") = -1; + this->auxdecor< int >("MC_Wdecay1_not_from_top_pdgId") = 0; + + // W NOT from top decay product 2 + this->auxdecor< float >("MC_Wdecay2_not_from_top_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_not_from_top_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_not_from_top_phi") = -1000; + this->auxdecor< float >("MC_Wdecay2_not_from_top_m") = -1; + this->auxdecor< int >("MC_Wdecay2_not_from_top_pdgId") = 0; + + // b not from top, for Wtb events + this->auxdecor< float >("MC_b_not_from_top_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_b_not_from_top_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_b_not_from_top_beforeFSR_phi") = -1000; + this->auxdecor< float >("MC_b_not_from_top_beforeFSR_m") = -1; + this->auxdecor< float >("MC_b_not_from_top_afterFSR_pt") = -1; + this->auxdecor< float >("MC_b_not_from_top_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_b_not_from_top_afterFSR_phi") = -1000; + this->auxdecor< float >("MC_b_not_from_top_afterFSR_m") = -1; + this->auxdecor< int >("MC_b_not_from_top_pdgId") = 0; + } + + // Initialize variables for an additional final-state Z. + void PartonHistory::IniVarZ() { + this->auxdecor< float >("MC_Z_m") = -1; + this->auxdecor< float >("MC_Z_pt") = -1; + this->auxdecor< float >("MC_Z_eta") = -1000; + this->auxdecor< float >("MC_Z_phi") = -1000; + + this->auxdecor< float >("MC_Zdecay1_m") = -1; + this->auxdecor< float >("MC_Zdecay1_pt") = -1; + this->auxdecor< float >("MC_Zdecay1_eta") = -1000; + this->auxdecor< float >("MC_Zdecay1_phi") = -1000; + this->auxdecor< int >("MC_Zdecay1_pdgId") = 0; + + this->auxdecor< float >("MC_Zdecay2_m") = -1; + this->auxdecor< float >("MC_Zdecay2_pt") = -1; + this->auxdecor< float >("MC_Zdecay2_eta") = -1000; + this->auxdecor< float >("MC_Zdecay2_phi") = -1000; + this->auxdecor< int >("MC_Zdecay2_pdgId") = 0; + + this->auxdecor< int >("MC_Z_AncestryCorrupted") = -1; + this->auxdecor< int >("MC_Z_IsOnShell") = -1; + } + + //Initialize variables for ttbargamma events + void PartonHistory::IniVarTtGamma() { + //ttbar variables + this->auxdecor< float >("MC_ttbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_ttbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_ttbar_beforeFSR_eta") = -10; + this->auxdecor< float >("MC_ttbar_beforeFSR_phi") = -10; + + this->auxdecor< float >("MC_ttbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_ttbar_afterFSR_eta") = -10; + this->auxdecor< float >("MC_ttbar_afterFSR_phi") = -10; + + //t variables + this->auxdecor< float >("MC_t_beforeFSR_m") = -1; + this->auxdecor< float >("MC_t_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_t_beforeFSR_eta") = -10; + this->auxdecor< float >("MC_t_beforeFSR_phi") = -10; + + this->auxdecor< float >("MC_t_afterFSR_m") = -1; + this->auxdecor< float >("MC_t_afterFSR_pt") = -1; + this->auxdecor< float >("MC_t_afterFSR_eta") = -10; + this->auxdecor< float >("MC_t_afterFSR_phi") = -10; + + //tbar variables + this->auxdecor< float >("MC_tbar_beforeFSR_m") = -1; + this->auxdecor< float >("MC_tbar_beforeFSR_pt") = -1; + this->auxdecor< float >("MC_tbar_beforeFSR_eta") = -10; + this->auxdecor< float >("MC_tbar_beforeFSR_phi") = -10; + + this->auxdecor< float >("MC_tbar_afterFSR_m") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_pt") = -1; + this->auxdecor< float >("MC_tbar_afterFSR_eta") = -10; + this->auxdecor< float >("MC_tbar_afterFSR_phi") = -10; + + //W variables + this->auxdecor< float >("MC_W_from_t_m") = -1; + this->auxdecor< float >("MC_W_from_t_pt") = -1; + this->auxdecor< float >("MC_W_from_t_eta") = -10; + this->auxdecor< float >("MC_W_from_t_phi") = -10; + + this->auxdecor< float >("MC_W_from_tbar_m") = -1; + this->auxdecor< float >("MC_W_from_tbar_pt") = -1; + this->auxdecor< float >("MC_W_from_tbar_eta") = -10; + this->auxdecor< float >("MC_W_from_tbar_phi") = -10; + + //b variables + this->auxdecor< float >("MC_b_from_t_m") = -1; + this->auxdecor< float >("MC_b_from_t_pt") = -1; + this->auxdecor< float >("MC_b_from_t_eta") = -10; + this->auxdecor< float >("MC_b_from_t_phi") = -10; + + this->auxdecor< float >("MC_b_from_tbar_m") = -1; + this->auxdecor< float >("MC_b_from_tbar_pt") = -1; + this->auxdecor< float >("MC_b_from_tbar_eta") = -10; + this->auxdecor< float >("MC_b_from_tbar_phi") = -10; + + //Wdecay1 variables + this->auxdecor< float >("MC_Wdecay1_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_t_eta") = -10; + this->auxdecor< float >("MC_Wdecay1_from_t_phi") = -10; + this->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay1_from_tbar_m") = -1; + this->auxdecor< float >("MC_Wdecay1_from_tbar_pt") = -1; + this->auxdecor< float >("MC_Wdecay1_from_tbar_eta") = -10; + this->auxdecor< float >("MC_Wdecay1_from_tbar_phi") = -10; + this->auxdecor< int >("MC_Wdecay1_from_tbar_pdgId") = 0; + + //Wdecay2 variables + this->auxdecor< float >("MC_Wdecay2_from_t_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_t_eta") = -10; + this->auxdecor< float >("MC_Wdecay2_from_t_phi") = -10; + this->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = 0; + + this->auxdecor< float >("MC_Wdecay2_from_tbar_m") = -1; + this->auxdecor< float >("MC_Wdecay2_from_tbar_pt") = -1; + this->auxdecor< float >("MC_Wdecay2_from_tbar_eta") = -10; + this->auxdecor< float >("MC_Wdecay2_from_tbar_phi") = -10; + this->auxdecor< int >("MC_Wdecay2_from_tbar_pdgId") = 0; + + //photon variables + this->auxdecor< float >("MC_ph_m") = -1; + this->auxdecor< float >("MC_ph_pt") = -1; + this->auxdecor< float >("MC_ph_eta") = -10; + this->auxdecor< float >("MC_ph_phi") = -10; + + this->auxdecor< int >("MC_branchtype_t") = -1; + this->auxdecor< int >("MC_branchtype_tbar") = -1; + this->auxdecor< int >("MC_initial_parton") = -1; + this->auxdecor< int >("MC_ph_from_t_tbar") = -1; + this->auxdecor< int >("MC_Event_Category") = -1; + } + + // Initialize variables for thqtautau events + void PartonHistory::IniVarThq() { + //t variables + this->auxdecor< float >("MC_t_beforeFSR_m") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_pt") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_m") = -1000; + this->auxdecor< float >("MC_t_afterFSR_pt") = -1000; + this->auxdecor< float >("MC_t_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_SC_m") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_pt") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_phi") = -1000; + + this->auxdecor< float >("MC_W_from_t_m") = -1000; + this->auxdecor< float >("MC_W_from_t_pt") = -1000; + this->auxdecor< float >("MC_W_from_t_eta") = -1000; + this->auxdecor< float >("MC_W_from_t_phi") = -1000; + + this->auxdecor< float >("MC_b_from_t_m") = -1000; + this->auxdecor< float >("MC_b_from_t_pt") = -1000; + this->auxdecor< float >("MC_b_from_t_eta") = -1000; + this->auxdecor< float >("MC_b_from_t_phi") = -1000; + + this->auxdecor< float >("MC_Wdecay1_from_t_m") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_pt") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = -9999; + + this->auxdecor< float >("MC_Wdecay2_from_t_m") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_pt") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = -9999; + + // Higgs variables + this->auxdecor< float >("MC_Higgs_m") = -1000; + this->auxdecor< float >("MC_Higgs_pt") = -1000; + this->auxdecor< float >("MC_Higgs_eta") = -1000; + this->auxdecor< float >("MC_Higgs_phi") = -1000; + + this->auxdecor< float >("MC_Higgs_decay1_m") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_pt") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_phi") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_eta") = -1000; + this->auxdecor< int >("MC_Higgs_tau_decay1_isHadronic") = -1000; + this->auxdecor< int >("MC_Higgs_decay1_pdgId") = -1000; + + this->auxdecor< float >("MC_Higgs_decay2_m") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_pt") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_phi") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_eta") = -1000; + this->auxdecor< int >("MC_Higgs_tau_decay2_isHadronic") = -1000; + this->auxdecor< int >("MC_Higgs_decay2_pdgId") = -1000; + + this->auxdecor< float >("MC_Higgs_decay1_from_decay1_m") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_from_decay1_pt") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_from_decay1_phi") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_from_decay1_eta") = -1000; + this->auxdecor< int >("MC_Higgs_tau_decay1_from_decay1_isHadronic") = -1000; + this->auxdecor< int >("MC_Higgs_decay1_from_decay1_pdgId") = -1000; + + this->auxdecor< float >("MC_Higgs_decay2_from_decay1_m") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_from_decay1_pt") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_from_decay1_phi") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_from_decay1_eta") = -1000; + this->auxdecor< int >("MC_Higgs_tau_decay2_from_decay1_isHadronic") = -1000; + this->auxdecor< int >("MC_Higgs_decay2_from_decay1_pdgId") = -1000; + + this->auxdecor< float >("MC_Higgs_decay1_from_decay2_m") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_from_decay2_pt") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_from_decay2_phi") = -1000; + this->auxdecor< float >("MC_Higgs_decay1_from_decay2_eta") = -1000; + this->auxdecor< int >("MC_Higgs_tau_decay1_from_decay2_isHadronic") = -1000; + this->auxdecor< int >("MC_Higgs_decay1_from_decay2_pdgId") = -1000; + + this->auxdecor< float >("MC_Higgs_decay2_from_decay2_m") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_from_decay2_pt") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_from_decay2_phi") = -1000; + this->auxdecor< float >("MC_Higgs_decay2_from_decay2_eta") = -1000; + this->auxdecor< int >("MC_Higgs_tau_decay2_from_decay2_isHadronic") = -1000; + this->auxdecor< int >("MC_Higgs_decay2_from_decay2_pdgId") = -1000; } + + // Initialize variables for tZq events + void PartonHistory::IniVarTzq() { + //t variables + this->auxdecor< float >("MC_t_beforeFSR_m") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_pt") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_eta") = -1000; + this->auxdecor< float >("MC_t_beforeFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_m") = -1000; + this->auxdecor< float >("MC_t_afterFSR_pt") = -1000; + this->auxdecor< float >("MC_t_afterFSR_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_phi") = -1000; + + this->auxdecor< float >("MC_t_afterFSR_SC_m") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_pt") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_eta") = -1000; + this->auxdecor< float >("MC_t_afterFSR_SC_phi") = -1000; + this->auxdecor< float >("MC_W_from_t_m") = -1000; + this->auxdecor< float >("MC_W_from_t_pt") = -1000; + this->auxdecor< float >("MC_W_from_t_eta") = -1000; + this->auxdecor< float >("MC_W_from_t_phi") = -1000; + this->auxdecor< float >("MC_b_from_t_m") = -1000; + this->auxdecor< float >("MC_b_from_t_pt") = -1000; + this->auxdecor< float >("MC_b_from_t_eta") = -1000; + this->auxdecor< float >("MC_b_from_t_phi") = -1000; + + this->auxdecor< float >("MC_Wdecay1_from_t_m") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_pt") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay1_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay1_from_t_pdgId") = -9999; + + this->auxdecor< float >("MC_Wdecay2_from_t_m") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_pt") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_eta") = -1000; + this->auxdecor< float >("MC_Wdecay2_from_t_phi") = -1000; + this->auxdecor< int >("MC_Wdecay2_from_t_pdgId") = -9999; + + //Z variables + this->auxdecor< float >("MC_Z_m") = -1000; + this->auxdecor< float >("MC_Z_pt") = -1000; + this->auxdecor< float >("MC_Z_eta") = -1000; + this->auxdecor< float >("MC_Z_phi") = -1000; + + + this->auxdecor< float >("MC_Zdecay1_m") = -1000; + this->auxdecor< float >("MC_Zdecay1_pt") = -1000; + this->auxdecor< float >("MC_Zdecay1_eta") = -1000; + this->auxdecor< float >("MC_Zdecay1_phi") = -1000; + this->auxdecor< int >("MC_Zdecay1_pdgId") = -9999; + this->auxdecor< int >("MC_Zdecay1_status") = -9999; + + this->auxdecor< float >("MC_Zdecay2_m") = -1000; + this->auxdecor< float >("MC_Zdecay2_pt") = -1000; + this->auxdecor< float >("MC_Zdecay2_eta") = -1000; + this->auxdecor< float >("MC_Zdecay2_phi") = -1000; + this->auxdecor< int >("MC_Zdecay2_pdgId") = -9999; + this->auxdecor< int >("MC_Zdecay2_status") = -9999; + + + } } -ADD_NS_DV_PROXY( xAOD , PartonHistoryContainer ); +ADD_NS_DV_PROXY(xAOD, PartonHistoryContainer); diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistoryUtils.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistoryUtils.cxx new file mode 100644 index 0000000000000000000000000000000000000000..9f28637d85b2d2a64ce7398fe3ba1264ca7fa81f --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/Root/PartonHistoryUtils.cxx @@ -0,0 +1,183 @@ +#include "TopPartons/PartonHistoryUtils.h" + +namespace top { +namespace PartonHistoryUtils { + + const xAOD::TruthParticle* findAfterFSR(const xAOD::TruthParticle* particle) { + bool isAfterFSR(false); + const int particle_ID = particle->pdgId(); + int forLoop = 0; + + while (!isAfterFSR) { + forLoop = 0; + for (size_t j = 0; j < particle->nChildren(); j++) { + const xAOD::TruthParticle* tmp_children = particle->child(j); + if (tmp_children && tmp_children->pdgId() == particle_ID) { + particle = particle->child(j); + forLoop++; + break; + }//if + }//for + if (forLoop == 0) isAfterFSR = true; + }//while + return particle; + } + + bool hasParticleIdenticalParent(const xAOD::TruthParticle* particle) { + bool skipit(false); + + for (size_t i = 0; i < particle->nParents(); i++) { + const xAOD::TruthParticle* parent = particle->parent(i); + if (parent && parent->pdgId() == particle->pdgId()) { + skipit = true; + break; + }//if + }//for + return skipit; + } + + HiggsDecay AnalyzeHiggsDecay(const xAOD::TruthParticle* higgs) { + + HiggsDecay result; + + if (higgs->pdgId() != 25) return result; + + /// identify after FSR higgs (just to be sure) + const xAOD::TruthParticle* higgs_fsr = findAfterFSR(higgs); + if (higgs_fsr->nChildren() != 2) return result; + + /// identify direct higgs decays + result.decay1_vector = higgs_fsr->child(0)->p4(); + result.decay2_vector = higgs_fsr->child(1)->p4(); + result.decay1_pdgId = higgs_fsr->child(0)->pdgId(); + result.decay2_pdgId = higgs_fsr->child(1)->pdgId(); + + /// check if higgs decays into tau, W or Z + const bool isZ = (result.decay1_pdgId == 23 || result.decay2_pdgId == 23) ? true : false; + const bool isW = (std::abs(result.decay1_pdgId) == 24 || std::abs(result.decay2_pdgId) == 24) ? true : false; + + /// Function to translate the result of the investigation into an integer status + /// status -1 = problem with the truth record + /// status 1 = tau decays hadronically + /// status 0 = tau decays leptonically + auto tauHadronicIndex = [&result](const xAOD::TruthParticle* particle) { + bool isOk(false); + const bool isHadronic = TauIsHadronic(particle, isOk); + if (!isOk) { + return -1; + } + + if (isHadronic) return 1; + + return 0; + }; + + if (std::abs(result.decay1_pdgId) == 15) { + result.tau_decay1_isHadronic = tauHadronicIndex(higgs_fsr->child(0)); + } + if (std::abs(result.decay2_pdgId) == 15) { + result.tau_decay2_isHadronic = tauHadronicIndex(higgs_fsr->child(1)); + } + + if (!isZ && !isW) return result; + + const xAOD::TruthParticle* decay1 = findAfterFSR(higgs->child(0)); + if (decay1->nChildren() != 2) return result; + const xAOD::TruthParticle* decay2 = findAfterFSR(higgs->child(1)); + if (decay2->nChildren() != 2) return result; + + /// decays of W/Z + result.decay1_from_decay1_vector = decay1->child(0)->p4(); + result.decay2_from_decay1_vector = decay1->child(1)->p4(); + result.decay1_from_decay1_pdgId = decay1->child(0)->pdgId(); + result.decay2_from_decay1_pdgId = decay1->child(1)->pdgId(); + + result.decay1_from_decay2_vector = decay2->child(0)->p4(); + result.decay2_from_decay2_vector = decay2->child(1)->p4(); + result.decay1_from_decay2_pdgId = decay2->child(0)->pdgId(); + result.decay2_from_decay2_pdgId = decay2->child(1)->pdgId(); + + if (std::abs(result.decay1_from_decay1_pdgId) == 15) { + result.tau_decay1_from_decay1_isHadronic = tauHadronicIndex(decay1->child(0)); + } + if (std::abs(result.decay2_from_decay1_pdgId) == 15) { + result.tau_decay2_from_decay1_isHadronic = tauHadronicIndex(decay1->child(1)); + } + if (std::abs(result.decay1_from_decay2_pdgId) == 15) { + result.tau_decay1_from_decay2_isHadronic = tauHadronicIndex(decay2->child(0)); + } + if (std::abs(result.decay2_from_decay2_pdgId) == 15) { + result.tau_decay2_from_decay2_isHadronic = tauHadronicIndex(decay2->child(1)); + } + + return result; + } + + bool TauIsHadronic(const xAOD::TruthParticle* tau, bool &isOk) { + + if (!tau) { + isOk = false; + return false; + } + + if (std::abs(tau->pdgId()) != 15) { + isOk = false; + return false; + } + + const xAOD::TruthParticle* afterFsr = findAfterFSR(tau); + + if (afterFsr->nChildren() != 2) { + isOk = false; + return false; + } + + const xAOD::TruthParticle* child1 = findAfterFSR(afterFsr->child(0)); + const xAOD::TruthParticle* child2 = findAfterFSR(afterFsr->child(1)); + + if (std::abs(child1->pdgId()) == 16) { + // it means the other particle ahs to be W + if (std::abs(child2->pdgId()) != 24) { + isOk = false; + return false; + } + + // child2 is W + if (child2->nChildren() != 2) { + isOk = false; + return false; + } + + isOk = true; + + // everything is fine, check if the W decays hadronically or leptonically + if (std::abs(child2->child(0)->pdgId()) < 16) { + return true; + } else { + return false; + } + } else { + // it means the other particle has to be nu + if (std::abs(child2->pdgId()) != 16) { + isOk = false; + return false; + } + + // child1 is W + if (child1->nChildren() != 2) { + isOk = false; + return false; + } + + isOk = true; + + // everything is fine, check if the W decays hadronically or leptonically + if (std::abs(child1->child(0)->pdgId()) < 16) { + return true; + } else { + return false; + } + } + } +} +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTTZPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTTZPartonHistory.h new file mode 100644 index 0000000000000000000000000000000000000000..ca5223d272346cc3bd9e168cedebcd2c5cb8c3bb --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTTZPartonHistory.h @@ -0,0 +1,54 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_CALCTTZPARTONHISTORY_H +#define ANALYSISTOP_TOPPARTONS_CALCTTZPARTONHISTORY_H + +/** + * @author Knut Zoch <kzoch@cern.ch> + * @brief CalcTTZPartonHistory + * Class derived from CalcTopPartonHistory, used to store ttZ variables + * + * Class definition follows that of class CalcTtbarHistory. + **/ + + +// Framework include(s): +#include "TopPartons/CalcTtbarPartonHistory.h" +#include "xAODTruth/TruthParticleContainer.h" +#include "TopPartons/PartonHistory.h" + +// forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class CalcTTZPartonHistory: public CalcTtbarPartonHistory { + public: + explicit CalcTTZPartonHistory(const std::string& name); + virtual ~CalcTTZPartonHistory() {} + + CalcTTZPartonHistory(const CalcTTZPartonHistory& rhs) = delete; + CalcTTZPartonHistory(CalcTTZPartonHistory&& rhs) = delete; + CalcTTZPartonHistory& operator = (const CalcTTZPartonHistory& rhs) = delete; + + void zHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* ttbarPartonHistory); + + virtual StatusCode execute(); + + const xAOD::TruthParticle* getFlavourSibling(const xAOD::TruthParticle* particle); + bool getZ(const xAOD::TruthParticleContainer* truthParticles, + TLorentzVector* Z, + TLorentzVector* ZDecay1, + int* ZDecay1_pdgId, + TLorentzVector* ZDecay2, + int* ZDecay2_pdgId, + bool* is_on_shell); + private: + bool m_ancestry_corrupted; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTbbarPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTbbarPartonHistory.h index 693903d0181f4771bbcdbc3ef1227f8e5ba9f962..980d4deede996794687edc6bafa3e25211a9bb1c 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTbbarPartonHistory.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTbbarPartonHistory.h @@ -1,22 +1,22 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPPARTONS_CALCTBBARPARTONHISTORY_H #define ANALYSISTOP_TOPPARTONS_CALCTBBARPARTONHISTORY_H /** - * @author John Morris <john.morris@cern.ch> - * @author Silvestre Marino Romano <sromanos@cern.ch> - * @author Samuel Calvet <scalvet@cern.ch> - * - * @brief CalcTbbarPartonHistory - * Class derived from CalcTopPartonHistory, used to store tbbar variables - * - * $Revision: 777122 $ - * $Date: 2016-10-07 15:57:57 +0200 (Fri, 07 Oct 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * + * @brief CalcTbbarPartonHistory + * Class derived from CalcTopPartonHistory, used to store tbbar variables + * + * $Revision: 777122 $ + * $Date: 2016-10-07 14:57:57 +0100 (Fri, 07 Oct 2016) $ + * + **/ // Framework include(s): @@ -25,28 +25,25 @@ #include "TopPartons/PartonHistory.h" // forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class CalcTbbarPartonHistory : public CalcTopPartonHistory{ - public: - explicit CalcTbbarPartonHistory( const std::string& name ); - virtual ~CalcTbbarPartonHistory() {} - - //Storing parton history for tbbar resonance analysis - CalcTbbarPartonHistory(const CalcTbbarPartonHistory& rhs) = delete; - CalcTbbarPartonHistory(CalcTbbarPartonHistory&& rhs) = delete; - CalcTbbarPartonHistory& operator=(const CalcTbbarPartonHistory& rhs) = delete; - - void tbbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* tbbarPartonHistory); - - virtual StatusCode execute(); - +namespace top { + class CalcTbbarPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcTbbarPartonHistory(const std::string& name); + virtual ~CalcTbbarPartonHistory() {} + + //Storing parton history for tbbar resonance analysis + CalcTbbarPartonHistory(const CalcTbbarPartonHistory& rhs) = delete; + CalcTbbarPartonHistory(CalcTbbarPartonHistory&& rhs) = delete; + CalcTbbarPartonHistory& operator = (const CalcTbbarPartonHistory& rhs) = delete; + + void tbbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* tbbarPartonHistory); + + virtual StatusCode execute(); }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcThqPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcThqPartonHistory.h new file mode 100644 index 0000000000000000000000000000000000000000..b68a76cd1a628a97ac3cf6d6f0ed44f64531a7e6 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcThqPartonHistory.h @@ -0,0 +1,61 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_CALCThqPARTONHISTORY_H +#define ANALYSISTOP_TOPPARTONS_CALCThqPARTONHISTORY_H + + +// Framework include(s): +#include "TopPartons/CalcTopPartonHistory.h" +#include "xAODTruth/TruthParticleContainer.h" +#include "TopPartons/PartonHistory.h" + +// forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class CalcThqPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcThqPartonHistory(const std::string& name); + virtual ~CalcThqPartonHistory() {} + + struct tH_values { + //Higgs + TLorentzVector Higgs_p4; + TLorentzVector decay1_p4; + TLorentzVector decay2_p4; + int decay1_pdgId; + int decay2_pdgId; + int tau_decay1_isHadronic; + int tau_decay2_isHadronic; + TLorentzVector decay1_from_decay1_p4; + TLorentzVector decay2_from_decay1_p4; + int decay1_from_decay1_pdgId; + int decay2_from_decay1_pdgId; + TLorentzVector decay1_from_decay2_p4; + TLorentzVector decay2_from_decay2_p4; + int decay1_from_decay2_pdgId; + int decay2_from_decay2_pdgId; + int tau_decay1_from_decay1_isHadronic; + int tau_decay2_from_decay1_isHadronic; + int tau_decay1_from_decay2_isHadronic; + int tau_decay2_from_decay2_isHadronic; + } tH; + //Storing parton history for ttbar resonance analysis + CalcThqPartonHistory(const CalcThqPartonHistory& rhs) = delete; + CalcThqPartonHistory(CalcThqPartonHistory&& rhs) = delete; + CalcThqPartonHistory& operator = (const CalcThqPartonHistory& rhs) = delete; + + void THHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* ThqPartonHistory); + + ///Store the four-momentum of several particles in the Higgs decay chain + bool HiggsAndDecay(const xAOD::TruthParticleContainer* truthParticles); + + virtual StatusCode execute(); + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTopPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTopPartonHistory.h index 859d7ae41d5df2a0d19f80a952ff509c4467885e..4a9ae48a3718992c99e798f8d8090438428b3345 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTopPartonHistory.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTopPartonHistory.h @@ -1,23 +1,23 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ // $Id: CalcTopPartonHistory.h 800464 2017-03-13 18:06:24Z tpelzer $ #ifndef ANALYSISTOP_TOPPARTONS_CALCTOPPARTONHISTORY_H #define ANALYSISTOP_TOPPARTONS_CALCTOPPARTONHISTORY_H /** - * @author John Morris <john.morris@cern.ch> - * @author Silvestre Marino Romano <sromanos@cern.ch> - * @author Samuel Calvet <scalvet@cern.ch> - * - * @brief CalcTopPartonHistory - * Determine the history of the top partons - * - * $Revision: 800464 $ - * $Date: 2017-03-13 19:06:24 +0100 (Mon, 13 Mar 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * + * @brief CalcTopPartonHistory + * Determine the history of the top partons + * + * $Revision: 800464 $ + * $Date: 2017-03-13 18:06:24 +0000 (Mon, 13 Mar 2017) $ + * + **/ // system include(s): #include <memory> @@ -31,48 +31,86 @@ #include "TopPartons/PartonHistory.h" // forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class CalcTopPartonHistory : public asg::AsgTool { - public: - explicit CalcTopPartonHistory( const std::string& name ); - virtual ~CalcTopPartonHistory() {} - - CalcTopPartonHistory(const CalcTopPartonHistory& rhs) = delete; - CalcTopPartonHistory(CalcTopPartonHistory&& rhs) = delete; - CalcTopPartonHistory& operator=(const CalcTopPartonHistory& rhs) = delete; - - ///Store the four-momentum of the post-FSR top or anti-top found using statusCodes - ///This would only work if there is at most one "true" top of each charge (i.e. won't work for SS tops or 4 tops) - ///This code was adapted from the 7TeV parton-level differential ttbar routine: https://svnweb.cern.ch/trac/atlasphys-top/browser/Physics/Top/Software/MCvalidation/Rivet/Rivet2.X/trunk/routines/ATLAS_2014_I1304289/ATLAS_2014_I1304289.cc - bool topAfterFSR_SC(const xAOD::TruthParticleContainer* truthParticles, int start, TLorentzVector& top_afterFSR_SC_p4); - - ///Store the four-momentum of several particles in the top decay chain - bool topWb(const xAOD::TruthParticleContainer* truthParticles, int start, TLorentzVector& t_beforeFSR_p4, TLorentzVector& t_afterFSR_p4, TLorentzVector& W_p4, TLorentzVector& b_p4, TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId); - - ///Store the four-momentum of b (not from tops_ before and after FSR - bool b(const xAOD::TruthParticleContainer* truthParticles, TLorentzVector& b_beforeFSR, TLorentzVector& b_afterFSR); - - ///Store the four-momentum of several particles in the W decay chain - bool Wlv(const xAOD::TruthParticleContainer* truthParticles, TLorentzVector& W_p4, TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId); - - ///Return particle after FSR (before the decay vertex) - const xAOD::TruthParticle* findAfterFSR(const xAOD::TruthParticle* particle); - - ///Return true when particle is a top before FSR - bool hasParticleIdenticalParent(const xAOD::TruthParticle* particle); - - virtual StatusCode execute(); - protected: - std::shared_ptr<top::TopConfig> m_config; - - void fillEtaBranch(xAOD::PartonHistory* partonHistory,std:: string branchName, TLorentzVector &tlv); - - }; +namespace top { + class CalcTopPartonHistory: public asg::AsgTool { + public: + explicit CalcTopPartonHistory(const std::string& name); + virtual ~CalcTopPartonHistory() {}; + + CalcTopPartonHistory(const CalcTopPartonHistory& rhs) = delete; + CalcTopPartonHistory(CalcTopPartonHistory&& rhs) = delete; + CalcTopPartonHistory& operator = (const CalcTopPartonHistory& rhs) = delete; + + /** Store the four-momentum of the post-FSR top or anti-top found using statusCodes + * This would only work if there is at most one "true" top of each charge (i.e. won't work for SS tops or 4 tops) + * This code was adapted from the 7TeV parton-level differential ttbar routine: + * https://svnweb.cern.ch/trac/atlasphys-top/browser/Physics/Top/Software/MCvalidation/Rivet/Rivet2.X/trunk/routines/ATLAS_2014_I1304289/ATLAS_2014_I1304289.cc + */ + bool topAfterFSR_SC(const xAOD::TruthParticleContainer* truthParticles, int start, + TLorentzVector& top_afterFSR_SC_p4); + + ///Store the four-momentum of several particles in the top decay chain + bool topWb(const xAOD::TruthParticleContainer* truthParticles, int start, TLorentzVector& t_beforeFSR_p4, + TLorentzVector& t_afterFSR_p4, TLorentzVector& W_p4, TLorentzVector& b_p4, TLorentzVector& Wdecay1_p4, + int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId); + bool topWq(const xAOD::TruthParticleContainer* truthParticles, int start, TLorentzVector& t_beforeFSR_p4, + TLorentzVector& t_afterFSR_p4, TLorentzVector& W_p4, TLorentzVector& q_p4, int& q_pdgId, + TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId); + + ///Store the four-momentum of b (not from tops_ before and after FSR + bool b(const xAOD::TruthParticleContainer* truthParticles, TLorentzVector& b_beforeFSR, TLorentzVector& b_afterFSR); + + ///Store the four-momentum of several particles in the W decay chain + bool Wlv(const xAOD::TruthParticleContainer* truthParticles, TLorentzVector& W_p4, TLorentzVector& Wdecay1_p4, + int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId); + + /// Store the four-momentum of several particles in W decay chain for W that is NOT from top in Wt ST events + bool Wt_W(const xAOD::TruthParticleContainer* truthParticles, TLorentzVector& W_p4, int& W_pdgId, + TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId); + + /// Store the four-momentum of b quark that is NOT from top in Wt(b) ST events + bool Wt_b(const xAOD::TruthParticleContainer* truthParticles, TLorentzVector& b_beforeFSR, + TLorentzVector& b_afterFSR, int& b_pdgId); + + /// Store the four-momentum of photon coming from virtual top in ttgamma events + bool topPhWb(const xAOD::TruthParticleContainer* truthParticles, int topId, TLorentzVector& t_beforeFSR_p4, + TLorentzVector& t_afterFSR_p4, TLorentzVector& Ph_p4, TLorentzVector& W_p4, TLorentzVector& b_p4, + TLorentzVector& Wdecay1_p4, int& Wdecay1_pdgId, TLorentzVector& Wdecay2_p4, int& Wdecay2_pdgId, + bool& has_ph, int& BranchType, int& IniPartonType, bool& missingTop); + + virtual StatusCode execute(); + protected: + std::shared_ptr<top::TopConfig> m_config; + + void fillEtaBranch(xAOD::PartonHistory* partonHistory, std:: string branchName, TLorentzVector& tlv); + + /** used to build container from multiple collections + * in DAOD_PHYS we don't have the TruthParticles collection, so we have to build a TruthParticleContainer (named out_contName) by merging several collections; this is stored in the evtStore + * this method has to use some tricks, like the helper m_tempParticles ConstDataVector, due to the desing of DataVector, see https://twiki.cern.ch/twiki/bin/view/AtlasComputing/DataVector + */ + StatusCode buildContainerFromMultipleCollections(const std::vector<std::string> &collections, const std::string& out_contName); + + /** currently in DAOD_PHYS TruthTop have links to Ws from the TruthBoson collection, which have no link to their decay products; + * we have therefore to associate the W from the TruthBoson collections to those in the TruthBosonsWithDecayParticles collection. + * This method will use the helper method decorateCollectionWithLinksToAnotherCollection to decorate bosons in the TruthBoson collection with + * "AT_linkToTruthBosonsWithDecayParticles", which is a link to the same bosons in the TruthBosonsWithDecayParticles collection + */ + StatusCode linkBosonCollections(); + + ///helper method to handle retriveing the truth particle linked in the decoration of another particle + const xAOD::TruthParticle* getTruthParticleLinkedFromDecoration(const xAOD::TruthParticle* part, const std::string &decorationName); + + private: + /**helper method currently used in DAOD_PHYS to link particles from a given collection to the same particles included in another collection; + * needed because particles may be duplicated in different collections, but their navigation links may only be there in some of them... + */ + StatusCode decorateCollectionWithLinksToAnotherCollection(const std::string &collectionToDecorate, const std::string &collectionToLink, const std::string &nameOfDecoration); + + }; } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarGammaPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarGammaPartonHistory.h new file mode 100644 index 0000000000000000000000000000000000000000..235f5c300805194b74f059d4d3bb5d569b06a57b --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarGammaPartonHistory.h @@ -0,0 +1,50 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_CalcTtbarGammaPartonHistory_H +#define ANALYSISTOP_TOPPARTONS_CalcTtbarGammaPartonHistory_H + +/** + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * + * @brief CalcTtbarGammaPartonHistory + * Class derived from CalcTopPartonHistory, used to store ttbargamma variables + * + * $Revision: 658996 $ + * $Date: 2015-04-04 16:57:15 +0100 (Sat, 04 Apr 2015) $ + * + **/ + + +// Framework include(s): +#include "TopPartons/CalcTopPartonHistory.h" +#include "xAODTruth/TruthParticleContainer.h" +#include "TopPartons/PartonHistory.h" + +// forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class CalcTtbarGammaPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcTtbarGammaPartonHistory(const std::string& name); + virtual ~CalcTtbarGammaPartonHistory() {} + + //Storing parton history for ttbargamma analysis + CalcTtbarGammaPartonHistory(const CalcTtbarGammaPartonHistory& rhs) = delete; + CalcTtbarGammaPartonHistory(CalcTtbarGammaPartonHistory&& rhs) = delete; + CalcTtbarGammaPartonHistory& operator = (const CalcTtbarGammaPartonHistory& rhs) = delete; + + void ttbarGammaHistorySaver(const xAOD::TruthParticleContainer* truthParticles, + xAOD::PartonHistory* ttbarGammaPartonHistory); + + virtual StatusCode execute(); + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarLightPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarLightPartonHistory.h new file mode 100644 index 0000000000000000000000000000000000000000..2eed96151099e4279a0e13730072013faa467742 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarLightPartonHistory.h @@ -0,0 +1,48 @@ +/* + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_CALCTTBARLIGHTPARTONHISTORY_H +#define ANALYSISTOP_TOPPARTONS_CALCTTBARLIGHTPARTONHISTORY_H + +/** + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * @author Sonja Zeissner <sonja.zeissner@cern.ch> + * + * @brief CalcTtbarLightPartonHistory + * Class derived from CalcTopPartonHistory, used to store ttbar variables + * + * + **/ + + +// Framework include(s): +#include "TopPartons/CalcTopPartonHistory.h" +#include "xAODTruth/TruthParticleContainer.h" +#include "TopPartons/PartonHistory.h" + +// forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class CalcTtbarLightPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcTtbarLightPartonHistory(const std::string& name); + virtual ~CalcTtbarLightPartonHistory() {} + + //Storing parton history for ttbar resonance analysis + CalcTtbarLightPartonHistory(const CalcTtbarLightPartonHistory& rhs) = delete; + CalcTtbarLightPartonHistory(CalcTtbarLightPartonHistory&& rhs) = delete; + CalcTtbarLightPartonHistory& operator = (const CalcTtbarLightPartonHistory& rhs) = delete; + + void ttbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* ttbarPartonHistory); + + virtual StatusCode execute(); + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarPartonHistory.h index 2b0e7cbac023b273ccf61d4065ad3a3fb77c313f..46f112cc91a9502c1f15151bf337d2a4c6a5028b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarPartonHistory.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTtbarPartonHistory.h @@ -1,22 +1,22 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPPARTONS_CALCTTBARPARTONHISTORY_H #define ANALYSISTOP_TOPPARTONS_CALCTTBARPARTONHISTORY_H /** - * @author John Morris <john.morris@cern.ch> - * @author Silvestre Marino Romano <sromanos@cern.ch> - * @author Samuel Calvet <scalvet@cern.ch> - * - * @brief CalcTtbarPartonHistory - * Class derived from CalcTopPartonHistory, used to store ttbar variables - * - * $Revision: 658996 $ - * $Date: 2015-04-04 17:57:15 +0200 (Sat, 04 Apr 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * + * @brief CalcTtbarPartonHistory + * Class derived from CalcTopPartonHistory, used to store ttbar variables + * + * $Revision: 658996 $ + * $Date: 2015-04-04 16:57:15 +0100 (Sat, 04 Apr 2015) $ + * + **/ // Framework include(s): @@ -25,28 +25,25 @@ #include "TopPartons/PartonHistory.h" // forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class CalcTtbarPartonHistory : public CalcTopPartonHistory{ - public: - explicit CalcTtbarPartonHistory( const std::string& name ); - virtual ~CalcTtbarPartonHistory() {} - - //Storing parton history for ttbar resonance analysis - CalcTtbarPartonHistory(const CalcTtbarPartonHistory& rhs) = delete; - CalcTtbarPartonHistory(CalcTtbarPartonHistory&& rhs) = delete; - CalcTtbarPartonHistory& operator=(const CalcTtbarPartonHistory& rhs) = delete; - - void ttbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* ttbarPartonHistory); - - virtual StatusCode execute(); - +namespace top { + class CalcTtbarPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcTtbarPartonHistory(const std::string& name); + virtual ~CalcTtbarPartonHistory() {} + + //Storing parton history for ttbar resonance analysis + CalcTtbarPartonHistory(const CalcTtbarPartonHistory& rhs) = delete; + CalcTtbarPartonHistory(CalcTtbarPartonHistory&& rhs) = delete; + CalcTtbarPartonHistory& operator = (const CalcTtbarPartonHistory& rhs) = delete; + + void ttbarHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* ttbarPartonHistory); + + virtual StatusCode execute(); }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTzqPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTzqPartonHistory.h new file mode 100644 index 0000000000000000000000000000000000000000..5a480851276e39a3256e0218f6096bbdd3a2bc28 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcTzqPartonHistory.h @@ -0,0 +1,64 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_CALCTzqPARTONHISTORY_H +#define ANALYSISTOP_TOPPARTONS_CALCTzqPARTONHISTORY_H + + +// Framework include(s): +#include "TopPartons/CalcTopPartonHistory.h" +#include "xAODTruth/TruthParticleContainer.h" +#include "TopPartons/PartonHistory.h" + +// forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class CalcTzqPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcTzqPartonHistory(const std::string& name); + virtual ~CalcTzqPartonHistory() {} + + struct tZ_values { + //Z boson + TLorentzVector Z_p4; + TLorentzVector Zdecay1_p4; + int Zdecay1_pdgId; + int Zdecay1_status; + TLorentzVector Zdecay2_p4; + int Zdecay2_pdgId; + int Zdecay2_status; + + + + + //b + TLorentzVector b_p4; + int b_pdgId; + } tZ; + //Storing parton history for ttbar resonance analysis + CalcTzqPartonHistory(const CalcTzqPartonHistory& rhs) = delete; + CalcTzqPartonHistory(CalcTzqPartonHistory&& rhs) = delete; + CalcTzqPartonHistory& operator = (const CalcTzqPartonHistory& rhs) = delete; + + void TZHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* TzqPartonHistory); + + //handle gamma radiation of taus + const xAOD::TruthParticle* findAfterGamma(const xAOD::TruthParticle* particle); + + ///Store the four-momentum of several particles in the Z decay chain + bool Zllqq(const xAOD::TruthParticleContainer* truthParticles, int start); + + //Store four-momentum of bottom quark + bool bottom(const xAOD::TruthParticleContainer* truthParticles, int start); + + int sign(int a); + + virtual StatusCode execute(); + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWlvPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWlvPartonHistory.h index 2946584d035cbf1ac07d04e4b0bda58a5789e18a..4c3bffb873da4a463b8636d08efd1bd9185b3056 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWlvPartonHistory.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWlvPartonHistory.h @@ -1,22 +1,22 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ #ifndef ANALYSISTOP_TOPPARTONS_CALCWLVPARTONHISTORY_H #define ANALYSISTOP_TOPPARTONS_CALCWLVPARTONHISTORY_H /** - * @author John Morris <john.morris@cern.ch> - * @author Silvestre Marino Romano <sromanos@cern.ch> - * @author Samuel Calvet <scalvet@cern.ch> - * - * @brief CalcWlvPartonHistory - * Class derived from CalcTopPartonHistory, used to store ttbar variables - * - * $Revision: 782353 $ - * $Date: 2016-11-04 13:11:17 +0100 (Fri, 04 Nov 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * + * @brief CalcWlvPartonHistory + * Class derived from CalcTopPartonHistory, used to store ttbar variables + * + * $Revision: 782353 $ + * $Date: 2016-11-04 12:11:17 +0000 (Fri, 04 Nov 2016) $ + * + **/ // Framework include(s): @@ -25,28 +25,25 @@ #include "TopPartons/PartonHistory.h" // forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class CalcWlvPartonHistory : public CalcTopPartonHistory{ - public: - explicit CalcWlvPartonHistory( const std::string& name ); - virtual ~CalcWlvPartonHistory() {} - - //Storing parton history for ttbar resonance analysis - CalcWlvPartonHistory(const CalcWlvPartonHistory& rhs) = delete; - CalcWlvPartonHistory(CalcWlvPartonHistory&& rhs) = delete; - CalcWlvPartonHistory& operator=(const CalcWlvPartonHistory& rhs) = delete; - - void WlvHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* wlvPartonHistory); - - virtual StatusCode execute(); - +namespace top { + class CalcWlvPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcWlvPartonHistory(const std::string& name); + virtual ~CalcWlvPartonHistory() {} + + //Storing parton history for ttbar resonance analysis + CalcWlvPartonHistory(const CalcWlvPartonHistory& rhs) = delete; + CalcWlvPartonHistory(CalcWlvPartonHistory&& rhs) = delete; + CalcWlvPartonHistory& operator = (const CalcWlvPartonHistory& rhs) = delete; + + void WlvHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* wlvPartonHistory); + + virtual StatusCode execute(); }; - } #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWtbPartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWtbPartonHistory.h new file mode 100644 index 0000000000000000000000000000000000000000..c26d0fd4889e214efc60be5c360a85aa068a453d --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/CalcWtbPartonHistory.h @@ -0,0 +1,46 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_CALCWTBPARTONHISTORY_H +#define ANALYSISTOP_TOPPARTONS_CALCWTBPARTONHISTORY_H + +/** + * @author Tomas Dado <tomas.dado@cern.ch> + * + * @brief CalcWtbPartonHistory + * Class derived from CalcTopPartonHistory, used to store Wt SingleTop variables + * + * $Revision: 658996 $ + * $Date: 2015-04-04 16:57:15 +0100 (Sat, 04 Apr 2015) $ + * + **/ + + +// Framework include(s): +#include "TopPartons/CalcTopPartonHistory.h" +#include "xAODTruth/TruthParticleContainer.h" +#include "TopPartons/PartonHistory.h" + +// forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class CalcWtbPartonHistory: public CalcTopPartonHistory { + public: + explicit CalcWtbPartonHistory(const std::string& name); + + //Storing parton history for Wtb SingleTop analysis + CalcWtbPartonHistory(const CalcWtbPartonHistory& rhs) = delete; + CalcWtbPartonHistory(CalcWtbPartonHistory&& rhs) = delete; + CalcWtbPartonHistory& operator = (const CalcWtbPartonHistory& rhs) = delete; + + void wtbHistorySaver(const xAOD::TruthParticleContainer* truthParticles, xAOD::PartonHistory* wtSTPartonHistory); + + virtual StatusCode execute() override; + }; +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistory.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistory.h index 5bbfdb28caed1ad1d53db8c93c0f7e2e1efae79b..796e8fca2b21cb0100d863755302b55628d33d20 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistory.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistory.h @@ -1,33 +1,33 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ // $Id: PartonHistory.h 782353 2016-11-04 12:11:17Z scalvet $ #ifndef ANALYSISTOP_TOPPARTONS_PARTONHISORTY_H #define ANALYSISTOP_TOPPARTONS_PARTONHISORTY_H /** - * @author John Morris <john.morris@cern.ch> - * @author Silvestre Marino Romano <sromanos@cern.ch> - * @author Samuel Calvet <scalvet@cern.ch> - * - * @brief PartonHistory - * A simple xAOD class which we can persist into a mini-xAOD - * The xAOD EDM is way too complex, so let's simplify it - * It's not like ROOT can do schema evolution...... - * - * In order for this object to be used by any - * PartonHistory factory, it contains no AuxElements - * Everything should be done via decoration - * - * This really should be an AuxInfoBase type of xAOD object - * But John can't figure out how to copy these to the - * output mini-xAOD.....yet - * - * $Revision: 782353 $ - * $Date: 2016-11-04 13:11:17 +0100 (Fri, 04 Nov 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * @author Silvestre Marino Romano <sromanos@cern.ch> + * @author Samuel Calvet <scalvet@cern.ch> + * + * @brief PartonHistory + * A simple xAOD class which we can persist into a mini-xAOD + * The xAOD EDM is way too complex, so let's simplify it + * It's not like ROOT can do schema evolution...... + * + * In order for this object to be used by any + * PartonHistory factory, it contains no AuxElements + * Everything should be done via decoration + * + * This really should be an AuxInfoBase type of xAOD object + * But John can't figure out how to copy these to the + * output mini-xAOD.....yet + * + * $Revision: 782353 $ + * $Date: 2016-11-04 12:11:17 +0000 (Fri, 04 Nov 2016) $ + * + **/ // EDM include(s): #include "AthContainers/DataVector.h" @@ -36,34 +36,38 @@ #include "xAODCore/CLASS_DEF.h" #include <vector> -namespace xAOD{ - - /// Aux Container - class PartonHistoryAuxContainer : public AuxContainerBase { - public: - /// Default constructor - PartonHistoryAuxContainer(); +namespace xAOD { + /// Aux Container + class PartonHistoryAuxContainer: public AuxContainerBase { + public: + /// Default constructor + PartonHistoryAuxContainer(); }; // end Aux container - + /// Interface class - class PartonHistory : public SG::AuxElement { - public: - /// Default constructor - PartonHistory(); - /// Default desturctor - virtual ~PartonHistory(){} + class PartonHistory: public SG::AuxElement { + public: + /// Default constructor + PartonHistory(); + /// Default desturctor + virtual ~PartonHistory() {} - void IniVarTtbar(); - void IniVarTbbar(); - void IniVarWlv(); - - }; - typedef DataVector < xAOD::PartonHistory > PartonHistoryContainer; + void IniVarTtbar(); + void IniVarTzq(); + void IniVarTtbarLight(); + void IniVarTbbar(); + void IniVarWlv(); + void IniVarWtb(); + void IniVarZ(); + void IniVarTtGamma(); + void IniVarThq(); + }; + typedef DataVector < xAOD::PartonHistory > PartonHistoryContainer; } // Dictonaries -CLASS_DEF( xAOD::PartonHistory , 135846343 , 1 ) -CLASS_DEF( xAOD::PartonHistoryContainer , 1219079565 , 1 ) -CLASS_DEF( xAOD::PartonHistoryAuxContainer , 1244378748 , 1 ) +CLASS_DEF(xAOD::PartonHistory, 135846343, 1) +CLASS_DEF(xAOD::PartonHistoryContainer, 1219079565, 1) +CLASS_DEF(xAOD::PartonHistoryAuxContainer, 1244378748, 1) #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistoryUtils.h b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistoryUtils.h new file mode 100644 index 0000000000000000000000000000000000000000..d9a35340a8f1592bb1a73d7167bd0ae7372c4a65 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopPartons/TopPartons/PartonHistoryUtils.h @@ -0,0 +1,56 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPPARTONS_TOPPARTONUTILS_H +#define ANALYSISTOP_TOPPARTONS_TOPPARTONUTILS_H + +#include "xAODTruth/TruthParticleContainer.h" + +#include "TLorentzVector.h" + +namespace top { +namespace PartonHistoryUtils { + + struct HiggsDecay { + /// direct higgs decay + TLorentzVector decay1_vector; + int decay1_pdgId; + TLorentzVector decay2_vector; + int decay2_pdgId; + int tau_decay1_isHadronic; + int tau_decay2_isHadronic; + + /// subsequent decays of W/Z + TLorentzVector decay1_from_decay1_vector; + int decay1_from_decay1_pdgId; + TLorentzVector decay2_from_decay1_vector; + int decay2_from_decay1_pdgId; + TLorentzVector decay1_from_decay2_vector; + int decay1_from_decay2_pdgId; + TLorentzVector decay2_from_decay2_vector; + int decay2_from_decay2_pdgId; + int tau_decay1_from_decay1_isHadronic; + int tau_decay2_from_decay1_isHadronic; + int tau_decay1_from_decay2_isHadronic; + int tau_decay2_from_decay2_isHadronic; + }; + + ///Return particle after FSR (before the decay vertex) + const xAOD::TruthParticle* findAfterFSR(const xAOD::TruthParticle* particle); + + ///Return true when particle is a top before FSR + bool hasParticleIdenticalParent(const xAOD::TruthParticle* particle); + + ///handle gamma radiation of taus + const xAOD::TruthParticle* findAfterGamma(const xAOD::TruthParticle* particle); + + /// Store higgs decay information + HiggsDecay AnalyzeHiggsDecay(const xAOD::TruthParticle* higgs); + + /// Check if tau decays hadronically or not + bool TauIsHadronic(const xAOD::TruthParticle* tau, bool &isOk); +} +} + +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/CMakeLists.txt b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/CMakeLists.txt index 1f3581b88c2f386e6f3432669e1fc791b395bc43..7b3550af079b9a1aaf1ff6274c8ad0cbac8c56f2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/CMakeLists.txt +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/CMakeLists.txt @@ -1,7 +1,5 @@ -# Auto-generated on: 2017-03-08 14:47:39.125284 - # Declare the name of this package: -atlas_subdir( TopSystematicObjectMaker None ) +atlas_subdir( TopSystematicObjectMaker ) # This package depends on other packages: atlas_depends_on_subdirs( PUBLIC @@ -13,11 +11,10 @@ atlas_depends_on_subdirs( PUBLIC xAODEgamma xAODMuon xAODJet + xAODTracking ElectronPhotonFourMomentumCorrection ElectronPhotonSelectorTools ElectronPhotonShowerShapeFudgeTool - MuonMomentumCorrections - MuonSelectorTools TauAnalysisTools JetCalibTools JetCPInterfaces @@ -30,15 +27,15 @@ atlas_depends_on_subdirs( PUBLIC TopConfiguration TopEvent TopJetSubstructure - xAODTracking - InDetTrackSystematicsTools ) + TopParticleLevel + InDetTrackSystematicsTools + MuonAnalysisInterfaces + MuonMomentumCorrections + FTagAnalysisInterfaces) # This package uses ROOT: find_package( ROOT REQUIRED COMPONENTS Core Gpad Tree Hist RIO MathCore Graf ) -# Custom definitions needed for this package: -add_definitions( -g ) - # Build a library that other components can link against: atlas_add_library( TopSystematicObjectMaker Root/*.cxx Root/*.h Root/*.icc TopSystematicObjectMaker/*.h TopSystematicObjectMaker/*.icc TopSystematicObjectMaker/*/*.h @@ -55,12 +52,10 @@ atlas_add_library( TopSystematicObjectMaker Root/*.cxx Root/*.h Root/*.icc ElectronPhotonFourMomentumCorrectionLib ElectronPhotonSelectorToolsLib ElectronPhotonShowerShapeFudgeToolLib - MuonMomentumCorrectionsLib - MuonSelectorToolsLib TauAnalysisToolsLib JetCalibToolsLib JetCPInterfaces - JetResolutionLib + #JetResolutionLib JetInterface METInterface METUtilitiesLib @@ -69,8 +64,13 @@ atlas_add_library( TopSystematicObjectMaker Root/*.cxx Root/*.h Root/*.icc TopConfiguration TopEvent TopJetSubstructure + TopParticleLevel xAODTracking InDetTrackSystematicsToolsLib + MuonAnalysisInterfacesLib + MuonMomentumCorrectionsLib + FTagAnalysisInterfacesLib + #BoostedJetTaggersLib ${ROOT_LIBRARIES} INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} ) diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/EgammaObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/EgammaObjectCollectionMaker.cxx index f4a2bb43595701e0b7ad212365564d04080ac595..d681bd8f1597e5a5b92bb4481535f555c603e875 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/EgammaObjectCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/EgammaObjectCollectionMaker.cxx @@ -1,12 +1,14 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ -// $Id: EgammaObjectCollectionMaker.cxx 802735 2017-04-11 16:38:01Z tpelzer $ +// $Id: EgammaObjectCollectionMaker.cxx 811374 2017-10-24 13:04:52Z iconnell $ #include "TopSystematicObjectMaker/EgammaObjectCollectionMaker.h" #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" #include "TopEvent/EventTools.h" +#include "AthContainers/AuxElement.h" #include "xAODEventInfo/EventInfo.h" #include "xAODEgamma/ElectronContainer.h" #include "xAODEgamma/ElectronAuxContainer.h" @@ -19,143 +21,225 @@ #include <list> -namespace top{ - - EgammaObjectCollectionMaker::EgammaObjectCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + EgammaObjectCollectionMaker::EgammaObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - + m_specifiedSystematicsPhotons(), m_specifiedSystematicsElectrons(), + m_specifiedSystematicsFwdElectrons(), m_recommendedSystematicsPhotons(), m_recommendedSystematicsElectrons(), + m_recommendedSystematicsFwdElectrons(), m_calibrationTool("CP::EgammaCalibrationAndSmearingTool"), m_photonFudgeTool("PhotonFudgeTool"), - + m_isolationTool_LooseTrackOnly("CP::IsolationTool_LooseTrackOnly"), m_isolationTool_Loose("CP::IsolationTool_Loose"), + m_isolationTool_PflowLoose("CP::IsolationTool_PflowLoose"), + m_isolationTool_Tight("CP::IsolationTool_Tight"), + m_isolationTool_PflowTight("CP::IsolationTool_PflowTight"), m_isolationTool_Gradient("CP::IsolationTool_Gradient"), m_isolationTool_GradientLoose("CP::IsolationTool_GradientLoose"), m_isolationTool_FixedCutTight("CP::IsolationTool_FixedCutTight"), m_isolationTool_FixedCutTightTrackOnly("CP::IsolationTool_FixedCutTightTrackOnly"), + m_isolationTool_TightTrackOnly("CP::IsolationTool_TightTrackOnly"), + m_isolationTool_TightTrackOnly_FixedRad("CP::IsolationTool_TightTrackOnly_FixedRad"), m_isolationTool_FixedCutTightCaloOnly("CP::IsolationTool_FixedCutTightCaloOnly"), + m_isolationTool_TightCaloOnly("CP::IsolationTool_TightCaloOnly"), m_isolationTool_FixedCutLoose("CP::IsolationTool_FixedCutLoose"), - m_isolationCorr("CP::IsolationCorrectionTool") - { - declareProperty( "config" , m_config ); - - declareProperty( "EgammaCalibrationAndSmearingTool" , m_calibrationTool ); - - declareProperty( "IsolationTool_LooseTrackOnly" , m_isolationTool_LooseTrackOnly ); - declareProperty( "IsolationTool_Loose" , m_isolationTool_Loose ); - declareProperty( "IsolationTool_Gradient" , m_isolationTool_Gradient ); - declareProperty( "IsolationTool_GradientLoose" , m_isolationTool_GradientLoose ); - declareProperty( "IsolationTool_FixedCutTight" , m_isolationTool_FixedCutTight ); - declareProperty( "IsolationTool_FixedCutTightTrackOnly" , m_isolationTool_FixedCutTightTrackOnly ); - declareProperty( "IsolationTool_FixedCutTightCaloOnly" , m_isolationTool_FixedCutTightCaloOnly ); - declareProperty( "IsolationTool_FixedCutLoose" , m_isolationTool_FixedCutLoose ); - declareProperty( "IsolationCorrectionTool", m_isolationCorr ); - } - - StatusCode EgammaObjectCollectionMaker::initialize() - { - ATH_MSG_INFO(" top::EgammaObjectCollectionMaker initialize" ); - - top::check( m_calibrationTool.retrieve() , "Failed to retrieve egamma calibration tool" ); - + m_isolationTool_FixedCutHighPtCaloOnly("CP::IsolationTool_FixedCutHighPtCaloOnly"), + m_isolationTool_FCHighPtCaloOnly("CP::IsolationTool_FCHighPtCaloOnly"), + m_isolationTool_HighPtCaloOnly("CP::IsolationTool_HighPtCaloOnly"), + m_isolationTool_FCTight("CP::IsolationTool_FCTight"), + m_isolationTool_FCLoose("CP::IsolationTool_FCLoose"), + m_isolationTool_PLVTight("CP::IsolationTool_PLVTight"), + m_isolationTool_PLVLoose("CP::IsolationTool_PLVLoose"), +// m_isolationTool_LowPtPLV("CP::IsolationTool_LowPtPLV"), + m_isolationCorr("CP::IsolationCorrectionTool") { + declareProperty("config", m_config); + + declareProperty("EgammaCalibrationAndSmearingTool", m_calibrationTool); + + declareProperty("IsolationTool_LooseTrackOnly", m_isolationTool_LooseTrackOnly); + declareProperty("IsolationTool_Loose", m_isolationTool_Loose); + declareProperty("IsolationTool_PflowLoose", m_isolationTool_PflowLoose); + declareProperty("IsolationTool_Tight", m_isolationTool_Tight); + declareProperty("IsolationTool_PflowTight", m_isolationTool_PflowTight); + declareProperty("IsolationTool_Gradient", m_isolationTool_Gradient); + declareProperty("IsolationTool_GradientLoose", m_isolationTool_GradientLoose); + declareProperty("IsolationTool_FixedCutTight", m_isolationTool_FixedCutTight); + declareProperty("IsolationTool_FixedCutTightTrackOnly", m_isolationTool_FixedCutTightTrackOnly); + declareProperty("IsolationTool_TightTrackOnly", m_isolationTool_TightTrackOnly); + declareProperty("IsolationTool_TightTrackOnly_FixedRad", m_isolationTool_TightTrackOnly_FixedRad); + declareProperty("IsolationTool_FixedCutTightCaloOnly", m_isolationTool_FixedCutTightCaloOnly); + declareProperty("IsolationTool_TightCaloOnly", m_isolationTool_TightCaloOnly); + declareProperty("IsolationTool_FixedCutLoose", m_isolationTool_FixedCutLoose); + declareProperty("IsolationTool_FixedCutHighPtCaloOnly", m_isolationTool_FixedCutHighPtCaloOnly); + declareProperty("IsolationTool_FCHighPtCaloOnly", m_isolationTool_FCHighPtCaloOnly); + declareProperty("IsolationTool_HighPtCaloOnly", m_isolationTool_HighPtCaloOnly); + declareProperty("IsolationTool_FCTight", m_isolationTool_FCTight); + declareProperty("IsolationTool_FCLoose", m_isolationTool_FCLoose); + declareProperty("IsolationTool_PLVTight", m_isolationTool_PLVTight); + declareProperty("IsolationTool_PLVLoose", m_isolationTool_PLVLoose); +// declareProperty("IsolationTool_LowPtPLV", m_isolationTool_LowPtPLV); + declareProperty("IsolationCorrectionTool", m_isolationCorr); + } + + StatusCode EgammaObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::EgammaObjectCollectionMaker initialize"); + + top::check(m_calibrationTool.retrieve(), "Failed to retrieve egamma calibration tool"); + + // These flags were for early R21 when we were asked not to calibrate egamma objects + calibrateElectrons = true; + calibrateFwdElectrons = true; + calibratePhotons = true; + if (m_config->usePhotons()) { top::check(m_isolationTool_FixedCutTight.retrieve(), - "Failed to retrieve Isolation Tool" ); + "Failed to retrieve Isolation Tool"); top::check(m_isolationTool_FixedCutTightCaloOnly.retrieve(), "Failed to retrieve Isolation Tool"); top::check(m_isolationTool_FixedCutLoose.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Tight.retrieve(), + "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_TightCaloOnly.retrieve(), + "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Loose.retrieve(), + "Failed to retrieve Isolation Tool"); top::check(m_photonFudgeTool.retrieve(), "Failed to retrieve photon shower shape fudge tool"); } if (m_config->useElectrons()) { - top::check( m_isolationTool_LooseTrackOnly.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_Loose.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_Gradient.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_GradientLoose.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_FixedCutTight.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_FixedCutTightTrackOnly.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_FixedCutLoose.retrieve() , "Failed to retrieve Isolation Tool" ); + top::check(m_isolationTool_Gradient.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCTight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCLoose.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCHighPtCaloOnly.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_HighPtCaloOnly.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Loose.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Tight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_TightTrackOnly.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_TightTrackOnly_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PflowLoose.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PflowTight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PLVTight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PLVLoose.retrieve(), "Failed to retrieve Isolation Tool"); +// top::check(m_isolationTool_LowPtPLV.retrieve(), "Failed to retrieve Isolation Tool"); } - - top::check( m_isolationCorr.retrieve() , "Failed to retrieve Isolation Correction Tool" ); + + top::check(m_isolationCorr.retrieve(), "Failed to retrieve Isolation Correction Tool"); std::set<std::string> systPhoton; - std::set<std::string> systElectron; + std::set<std::string> systElectron; + std::set<std::string> systFwdElectron; const std:: string& syststr = m_config->systematics(); - std::set<std::string> syst; + std::set<std::string> syst; - if( !m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr) ){ + if (!m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)) { bool ok = m_config->getSystematicsList(syststr, syst); - if(!ok){ - ATH_MSG_ERROR(" top::EgammaObjectCollectionMaker could not determine systematic list" ); - return StatusCode::FAILURE; + if (!ok) { + ATH_MSG_ERROR(" top::EgammaObjectCollectionMaker could not determine systematic list"); + return StatusCode::FAILURE; } - if(!m_config->contains(syst, "AllElectrons")){ - systElectron=syst; + //here the idea is that if the user specifies AllXXX, we leave syst as an empty string, so that all recommended CP + // systematics are then used + if (!m_config->contains(syst, "AllElectrons")) { + systElectron = syst; } - if(!m_config->contains(syst, "AllPhotons")){ - systPhoton=syst; + if (!m_config->contains(syst, "AllPhotons")) { + systPhoton = syst; + } + if (!m_config->contains(syst, "AllFwdElectrons")) { + systFwdElectron = syst; } } - specifiedSystematicsPhotons( systPhoton ); - specifiedSystematicsElectrons( systElectron ); - + specifiedSystematicsPhotons(systPhoton); + specifiedSystematicsElectrons(systElectron); + specifiedSystematicsFwdElectrons(systFwdElectron); + if (m_config->usePhotons()) { - m_config->systematicsPhotons( specifiedSystematicsPhotons() ); + m_config->systematicsPhotons(specifiedSystematicsPhotons()); } if (m_config->useElectrons()) { - m_config->systematicsElectrons( specifiedSystematicsElectrons() ); + m_config->systematicsElectrons(specifiedSystematicsElectrons()); + } + if (m_config->useFwdElectrons()) { + m_config->systematicsFwdElectrons(specifiedSystematicsFwdElectrons()); } + // bool to decide whether to use certain Egamma tools + m_recomputePhotonFudge = m_config->recomputeCPvars(); + return StatusCode::SUCCESS; } - - StatusCode EgammaObjectCollectionMaker::executePhotons() - { + + StatusCode EgammaObjectCollectionMaker::executePhotons(bool executeNominal) { ///-- Get base photons from xAOD --/// const xAOD::PhotonContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyPhotons() ) , "Failed to retrieve Photons" ); + + top::check(evtStore()->retrieve(xaod, m_config->sgKeyPhotons()), "Failed to retrieve Photons"); ///-- Loop over all systematics --/// - for( auto systematic : m_specifiedSystematicsPhotons ){ - + for (auto systematic : m_specifiedSystematicsPhotons) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + ///-- Tell tool which systematic to use --/// - top::check( m_calibrationTool->applySystematicVariation( systematic ) , "Failed to applySystematicVariation" ); - + top::check(m_calibrationTool->applySystematicVariation(systematic), "Failed to applySystematicVariation"); + ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::PhotonContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); - + std::pair< xAOD::PhotonContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( + *xaod); + ///-- Loop over the xAOD Container and apply corrections--/// - for( auto photon : *(shallow_xaod_copy.first) ){ - + for (auto photon : *(shallow_xaod_copy.first)) { ///-- Apply correction to object --/// - // Needs a calo cluster so carry on if no cluster - if (!photon->caloCluster()) continue; - top::check( m_calibrationTool->applyCorrection( *photon ) , "Failed to applyCorrection" ); - - top::check(m_isolationCorr->applyCorrection(*photon), - "Failed to apply photon isolation leakage correction"); - - // Only apply shower shape fudging on full simulation MC - if (m_config->isMC() && !m_config->isAFII()) { - top::check(m_photonFudgeTool->applyCorrection(*photon), - "Failed to apply photon shower shape fudge tool"); + // Needs a calo cluster so carry on if no cluster + if (!photon->caloCluster()) continue; + + if (calibratePhotons) { + top::check(m_calibrationTool->applyCorrection(*photon), + "Failed to applyCorrection"); + top::check(m_isolationCorr->applyCorrection(*photon), + "Failed to apply photon isolation leakage correction"); + + // Only apply shower shape fudging on full simulation MC + if (m_config->isMC() && !m_config->isAFII() && m_recomputePhotonFudge && m_config->getDerivationStream() != "PHYS") { + if (m_photonFudgeTool->applyCorrection(*photon) == 0) { // 0: error, 1: OutOfRange (not possible), 2: OK + // ElectronPhotonShowerShapeFudgeTool::applyCorrection can return an error for 3 reasons + // 1) shower shapes not all found, 2) bad cluster, 3) shower shapes not all set. + // 1 & 3 are most likely due to the smart slimming (no PhotonsDetailedCPContent), whereas 2 is an actual + // issue. + // Check for case 2 now: + if (photon->caloCluster() == nullptr) { + ATH_MSG_ERROR("Photon " << photon << " had no calo cluster - this is bad!"); + return StatusCode::FAILURE; + } else { + // We're now in case 1 or 3 + ATH_MSG_WARNING( + " Didn't find the necessary photon shower shapes variables for the ElectronPhotonShowerShapeFudgeTool! (but don't worry, you're still getting correctly ID'd photons)"); + // Keep going, but don't try to use the tool anymore + m_recomputePhotonFudge = false; + } + } + } } - ///-- Isolation selection --/// + static const SG::AuxElement::ConstAccessor<float> ptcone20_TightTTVA_pt1000("ptcone20_TightTTVA_pt1000"); char passIsol_FixedCutTight(0); char passIsol_FixedCutTightCaloOnly(0); char passIsol_FixedCutLoose(0); + char passIsol_Tight(0); + char passIsol_TightCaloOnly(0); + char passIsol_Loose(0); if (m_isolationTool_FixedCutTight->accept(*photon)) { passIsol_FixedCutTight = 1; } @@ -165,220 +249,415 @@ namespace top{ if (m_isolationTool_FixedCutLoose->accept(*photon)) { passIsol_FixedCutLoose = 1; } + if (m_isolationTool_TightCaloOnly->accept(*photon)) { + passIsol_TightCaloOnly = 1; + } + if (ptcone20_TightTTVA_pt1000.isAvailable(*photon)) { + if (m_isolationTool_Tight->accept(*photon)) { + passIsol_Tight = 1; + } + if (m_isolationTool_Loose->accept(*photon)) { + passIsol_Loose = 1; + } + } photon->auxdecor<char>("AnalysisTop_Isol_FixedCutTight") = passIsol_FixedCutTight; photon->auxdecor<char>("AnalysisTop_Isol_FixedCutTightCaloOnly") = passIsol_FixedCutTightCaloOnly; photon->auxdecor<char>("AnalysisTop_Isol_FixedCutLoose") = passIsol_FixedCutLoose; + photon->auxdecor<char>("AnalysisTop_Isol_Tight") = passIsol_Tight; + photon->auxdecor<char>("AnalysisTop_Isol_TightCaloOnly") = passIsol_TightCaloOnly; + photon->auxdecor<char>("AnalysisTop_Isol_Loose") = passIsol_Loose; } ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for photons, MET recalculation may struggle" ); - + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for photons, MET recalculation may struggle"); + ///-- Save corrected xAOD Container to StoreGate / TStore --/// - std::string outputSGKey = m_config->sgKeyPhotons( systematic.hash() ); + std::string outputSGKey = m_config->sgKeyPhotons(systematic.hash()); std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { return StatusCode::FAILURE; } - } // Loop over all systematics - + } // Loop over all systematics return StatusCode::SUCCESS; - } - - StatusCode EgammaObjectCollectionMaker::executeElectrons() - { + } + + StatusCode EgammaObjectCollectionMaker::executeElectrons(bool executeNominal) { + static const SG::AuxElement::ConstAccessor<float> ptcone20_TightTTVALooseCone_pt1000("ptcone20_TightTTVALooseCone_pt1000"); + static const SG::AuxElement::ConstAccessor<float> ptvarcone20_TightTTVA_pt1000("ptvarcone20_TightTTVA_pt1000"); + static const SG::AuxElement::ConstAccessor<float> ptvarcone30_TightTTVALooseCone_pt1000("ptvarcone30_TightTTVALooseCone_pt1000"); + static const SG::AuxElement::ConstAccessor<float> ptvarcone30_TightTTVALooseCone_pt500("ptvarcone30_TightTTVALooseCone_pt500"); + static const SG::AuxElement::ConstAccessor<float> neflowisol20("neflowisol20"); + static const SG::AuxElement::ConstAccessor<short> PLV_TrackJetNTrack("PromptLeptonInput_TrackJetNTrack"); + static const SG::AuxElement::ConstAccessor<float> PLV_DRlj("PromptLeptonInput_DRlj"); + static const SG::AuxElement::ConstAccessor<float> PLV_PtRel("PromptLeptonInput_PtRel"); + static const SG::AuxElement::ConstAccessor<float> PLV_PtFrac("PromptLeptonInput_PtFrac"); + static const SG::AuxElement::ConstAccessor<float> PLV_PromptLeptonVeto("PromptLeptonVeto"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_FCTight("AnalysisTop_Isol_FCTight"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_FCLoose("AnalysisTop_Isol_FCLoose"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_Tight("AnalysisTop_Isol_Tight"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_Loose("AnalysisTop_Isol_Loose"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_TightTrackOnly("AnalysisTop_Isol_TightTrackOnly"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_TightTrackOnly_FixedRad("AnalysisTop_Isol_TightTrackOnly_FixedRad"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_PflowTight("AnalysisTop_Isol_PflowTight"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_PflowLoose("AnalysisTop_Isol_PflowLoose"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_PLVTight("AnalysisTop_Isol_PLVTight"); + static SG::AuxElement::Accessor<char> AnalysisTop_Isol_PLVLoose("AnalysisTop_Isol_PLVLoose"); +// static SG::AuxElement::Decorator<float> byhand_LowPtPLV("LowPtPLV"); const xAOD::EventInfo* eventInfo(nullptr); - top::check( evtStore()->retrieve( eventInfo, m_config->sgKeyEventInfo() ), "Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); float beam_pos_sigma_x = eventInfo->beamPosSigmaX(); float beam_pos_sigma_y = eventInfo->beamPosSigmaY(); float beam_pos_sigma_xy = eventInfo->beamPosSigmaXY(); - + ///-- Get base electrons from xAOD --/// const xAOD::ElectronContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyElectrons() ) , "Failed to retrieve Electrons" ); - + top::check(evtStore()->retrieve(xaod, m_config->sgKeyElectrons()), "Failed to retrieve Electrons"); + ///-- Loop over all systematics --/// - for( auto systematic : m_specifiedSystematicsElectrons ){ - + for (auto systematic : m_specifiedSystematicsElectrons) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + ///-- Tell tool which systematic to use -/// - top::check( m_calibrationTool->applySystematicVariation( systematic ) , "Failed to applySystematicVariation" ); - + top::check(m_calibrationTool->applySystematicVariation(systematic), "Failed to applySystematicVariation"); + ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::ElectronContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); - + std::pair< xAOD::ElectronContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( + *xaod); + ///-- Loop over the xAOD Container --/// - for( auto electron : *(shallow_xaod_copy.first) ){ - - // Apply correction to object + for (auto electron : *(shallow_xaod_copy.first)) { + // Apply correction to object // should not affect derivations if there is no CC or track thinning - if (electron->caloCluster() != nullptr && electron->trackParticle() != nullptr) { // derivations might remove CC and tracks for low pt electrons - top::check( m_calibrationTool->applyCorrection( *electron ) , "Failed to applyCorrection" ); - - top::check( m_isolationCorr->applyCorrection( *electron ), "Failed to apply leakage correction" ); - - double d0sig = xAOD::TrackingHelpers::d0significance( electron->trackParticle(), - beam_pos_sigma_x, - beam_pos_sigma_y, - beam_pos_sigma_xy ); - electron->auxdecor<float>("d0sig") = d0sig; - - if( eventInfo->isAvailable<float>("AnalysisTop_PRIVTX_z_position") ){ - float vtx_z = eventInfo->auxdata<float>("AnalysisTop_PRIVTX_z_position"); - float delta_z0 = electron->trackParticle()->z0() + electron->trackParticle()->vz() - vtx_z; - electron->auxdecor<float>("delta_z0") = delta_z0; - electron->auxdecor<float>("delta_z0_sintheta") = delta_z0*std::sin( electron->trackParticle()->theta() ); - - } - } - + if (electron->caloCluster() != nullptr && electron->trackParticle() != nullptr) { // derivations might remove CC + // and tracks for low pt + // electrons + if (calibrateElectrons) { + top::check(m_calibrationTool->applyCorrection(*electron), "Failed to applyCorrection"); + top::check(m_isolationCorr->applyCorrection(*electron), "Failed to apply leakage correction"); + } + + double d0sig = xAOD::TrackingHelpers::d0significance(electron->trackParticle(), + beam_pos_sigma_x, + beam_pos_sigma_y, + beam_pos_sigma_xy); + electron->auxdecor<float>("d0sig") = d0sig; + + if (eventInfo->isAvailable<float>("AnalysisTop_PRIVTX_z_position")) { + float vtx_z = eventInfo->auxdata<float>("AnalysisTop_PRIVTX_z_position"); + float delta_z0 = electron->trackParticle()->z0() + electron->trackParticle()->vz() - vtx_z; + electron->auxdecor<float>("delta_z0") = delta_z0; + electron->auxdecor<float>("delta_z0_sintheta") = delta_z0 * std::sin(electron->trackParticle()->theta()); + } + } + ///-- Isolation selection --/// - char passIsol_LooseTrackOnly(0),passIsol_Loose(0),passIsol_FixedCutTight(0),passIsol_FixedCutTightTrackOnly(0),passIsol_FixedCutLoose(0); - char passIsol_Gradient(0),passIsol_GradientLoose(0); - if (m_isolationTool_LooseTrackOnly->accept( *electron )) {passIsol_LooseTrackOnly = 1;} - if (m_isolationTool_Loose->accept( *electron )) {passIsol_Loose = 1;} - if (m_isolationTool_Gradient->accept( *electron )) {passIsol_Gradient = 1;} - if (m_isolationTool_GradientLoose->accept( *electron )) {passIsol_GradientLoose = 1;} - if (m_isolationTool_FixedCutTight->accept( *electron )) {passIsol_FixedCutTight = 1;} - if (m_isolationTool_FixedCutTightTrackOnly->accept( *electron )) {passIsol_FixedCutTightTrackOnly = 1;} - if (m_isolationTool_FixedCutLoose->accept( *electron )) {passIsol_FixedCutLoose = 1;} - - electron->auxdecor<char>("AnalysisTop_Isol_LooseTrackOnly") = passIsol_LooseTrackOnly; - electron->auxdecor<char>("AnalysisTop_Isol_Loose") = passIsol_Loose; + char passIsol_Gradient(0); + char passIsol_FCHighPtCaloOnly(0); + char passIsol_HighPtCaloOnly(0); + if (m_isolationTool_Gradient->accept(*electron)) { + passIsol_Gradient = 1; + } + if (m_isolationTool_FCHighPtCaloOnly->accept(*electron)) { + passIsol_FCHighPtCaloOnly = 1; + } + if (m_isolationTool_HighPtCaloOnly->accept(*electron)) { + passIsol_HighPtCaloOnly = 1; + } + electron->auxdecor<char>("AnalysisTop_Isol_Gradient") = passIsol_Gradient; - electron->auxdecor<char>("AnalysisTop_Isol_GradientLoose") = passIsol_GradientLoose; - electron->auxdecor<char>("AnalysisTop_Isol_FixedCutTight") = passIsol_FixedCutTight; - electron->auxdecor<char>("AnalysisTop_Isol_FixedCutTightTrackOnly") = passIsol_FixedCutTightTrackOnly; - electron->auxdecor<char>("AnalysisTop_Isol_FixedCutLoose") = passIsol_FixedCutLoose; - + electron->auxdecor<char>("AnalysisTop_Isol_FCHighPtCaloOnly") = passIsol_FCHighPtCaloOnly; + electron->auxdecor<char>("AnalysisTop_Isol_HighPtCaloOnly") = passIsol_HighPtCaloOnly; + if (ptvarcone20_TightTTVA_pt1000.isAvailable(*electron)) { + AnalysisTop_Isol_FCTight(*electron) = (m_isolationTool_FCTight->accept(*electron) ? 1 : 0); + AnalysisTop_Isol_FCLoose(*electron) = (m_isolationTool_FCLoose->accept(*electron) ? 1 : 0); + } + if (ptvarcone30_TightTTVALooseCone_pt1000.isAvailable(*electron)) { + AnalysisTop_Isol_Tight(*electron) = (m_isolationTool_Tight->accept(*electron) ? 1 : 0); + AnalysisTop_Isol_Loose(*electron) = (m_isolationTool_Loose->accept(*electron) ? 1 : 0); + AnalysisTop_Isol_TightTrackOnly(*electron) = (m_isolationTool_TightTrackOnly->accept(*electron) ? 1 : 0); + if (ptcone20_TightTTVALooseCone_pt1000.isAvailable(*electron)) { + AnalysisTop_Isol_TightTrackOnly_FixedRad(*electron) = (m_isolationTool_TightTrackOnly_FixedRad->accept(*electron) ? 1 : 0); + } + } + if (ptvarcone30_TightTTVALooseCone_pt500.isAvailable(*electron) && neflowisol20.isAvailable(*electron)) { + AnalysisTop_Isol_PflowTight(*electron) = (m_isolationTool_PflowTight->accept(*electron) ? 1 : 0); + AnalysisTop_Isol_PflowLoose(*electron) = (m_isolationTool_PflowLoose->accept(*electron) ? 1 : 0); + } + // Prompt Electron Tagging (PLV): https://twiki.cern.ch/twiki/bin/view/AtlasProtected/PromptLeptonTagging + // This is not recommended, purely experimental! (no plans for electron SFs from e/gamma any time soon, unless + // strong motivation from analyses) + // The r20.7 BDT is called "Iso", the r21 one is "Veto". The cut on the BDT weight is <-0.5, with the + // FixedCutLoose WP. But this WP is no longer + // supported by e/gamma, so here let's just decorate that check, and we'll let the user access the BDT weights + // themselves if needed. + if (electron->isAvailable<float>("PromptLeptonIso")) // r20.7 + electron->auxdecor<char>("AnalysisTop_Isol_PromptLeptonIso") = + (electron->auxdata<float>("PromptLeptonIso") < -0.5) ? 1 : 0; + if (electron->isAvailable<float>("PromptLeptonVeto")) // r21 + electron->auxdecor<char>("AnalysisTop_Isol_PromptLeptonVeto") = + (electron->auxdata<float>("PromptLeptonVeto") < -0.5) ? 1 : 0; + + // New PLV: https://twiki.cern.ch/twiki/bin/view/AtlasProtected/PromptLeptonTaggerIFF + // For PLV isolation, we need to compute additional variables in the low-pT regime (<12 GeV) +//if ( PLV_TrackJetNTrack.isAvailable(*electron) && +// PLV_DRlj.isAvailable(*electron) && +// PLV_PtRel.isAvailable(*electron) && +// PLV_PtFrac.isAvailable(*electron) ) +// top::check(m_isolationTool_LowPtPLV->augmentPLV(*electron), "Failed to augment electron with LowPtPLV decorations"); +// else +// byhand_LowPtPLV(*electron) = 1.1; // decorate the electron ourselves following IFF default + if ( PLV_PromptLeptonVeto.isAvailable(*electron) && + ptvarcone30_TightTTVALooseCone_pt1000.isAvailable(*electron) ) { + AnalysisTop_Isol_PLVTight(*electron) = (m_isolationTool_PLVTight->accept(*electron) ? 1 : 0); + AnalysisTop_Isol_PLVLoose(*electron) = (m_isolationTool_PLVLoose->accept(*electron) ? 1 : 0); + } + else { + // decorate with special character to indicate failure to retrieve necessary variables + AnalysisTop_Isol_PLVTight(*electron) = 'n'; + AnalysisTop_Isol_PLVLoose(*electron) = 'n'; + } } - + ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for electrons, MET recalculation may struggle" ); - + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for electrons, MET recalculation may struggle"); + // Save corrected xAOD Container to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyElectronsStandAlone( systematic.hash() ); + std::string outputSGKey = m_config->sgKeyElectronsStandAlone(systematic.hash()); std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { return StatusCode::FAILURE; } - } // Loop over all systematics - + } // Loop over all systematics + return StatusCode::SUCCESS; } - - StatusCode EgammaObjectCollectionMaker::printoutPhotons() - { - // Loop over all systematics - for( auto s : m_specifiedSystematicsPhotons ){ + + StatusCode EgammaObjectCollectionMaker::executeFwdElectrons(bool executeNominal) { + const xAOD::EventInfo* eventInfo(nullptr); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + + ///-- Get base electrons from xAOD --/// + const xAOD::ElectronContainer* xaod(nullptr); + top::check(evtStore()->retrieve(xaod, m_config->sgKeyFwdElectrons()), "Failed to retrieve Fwd Electrons"); + + ///-- Loop over all systematics --/// + for (auto systematic : m_specifiedSystematicsFwdElectrons) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + + ///-- Tell tool which systematic to use -/// + top::check(m_calibrationTool->applySystematicVariation(systematic), "Failed to applySystematicVariation"); + + ///-- Shallow copy of the xAOD --/// + std::pair< xAOD::ElectronContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( + *xaod); + + ///-- Loop over the xAOD Container --/// + for (auto electron : *(shallow_xaod_copy.first)) { + // Apply correction to object + // should not affect derivations if there is no CC or track thinning + if (electron->caloCluster() != nullptr) { // derivations might remove CC for low pt electrons + if (calibrateFwdElectrons) { + top::check(m_calibrationTool->applyCorrection(*electron), "Failed to applyCorrection to fwd electrons"); + } + } + }//end of loop on electrons + + ///-- set links to original objects- needed for MET calculation --/// + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for fwd electrons"); + + // Save corrected xAOD Container to StoreGate / TStore + std::string outputSGKey = m_config->sgKeyFwdElectronsStandAlone(systematic.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + } // Loop over all systematics + + return StatusCode::SUCCESS; + } + + StatusCode EgammaObjectCollectionMaker::printoutPhotons() { + // Loop over all systematics + for (auto s : m_specifiedSystematicsPhotons) { const xAOD::PhotonContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyPhotons( s.hash() ) ) , "Failed to retrieve Photons" ); - - ATH_MSG_INFO(" Photons with sgKey = "<<m_config->sgKeyPhotons( s.hash() ) ); - for( auto x : *xaod ){ + top::check(evtStore()->retrieve(xaod, m_config->sgKeyPhotons(s.hash())), "Failed to retrieve Photons"); + + ATH_MSG_INFO(" Photons with sgKey = " << m_config->sgKeyPhotons(s.hash())); + for (auto x : *xaod) { float ptcone30(0.); - x->isolationValue( ptcone30 , xAOD::Iso::ptcone30 ); - ATH_MSG_INFO(" ph pT , eta , ptcone30 = "<<x->pt()<<" , "<<x->eta()<<" , "<<ptcone30 ); + x->isolationValue(ptcone30, xAOD::Iso::ptcone30); + ATH_MSG_INFO(" ph pT , eta , ptcone30 = " << x->pt() << " , " << x->eta() << " , " << ptcone30); } } - - return StatusCode::SUCCESS; - } - - - StatusCode EgammaObjectCollectionMaker::printoutElectrons() - { - // Loop over all systematics - for( auto s : m_specifiedSystematicsElectrons ){ + + return StatusCode::SUCCESS; + } + + StatusCode EgammaObjectCollectionMaker::printoutElectrons() { + // Loop over all systematics + for (auto s : m_specifiedSystematicsElectrons) { const xAOD::ElectronContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyElectronsStandAlone( s.hash() ) ), "Failed to retrieve Electrons" ); - - ATH_MSG_INFO(" Electrons with sgKey = "<<m_config->sgKeyElectronsStandAlone( s.hash() ) ); - for( auto x : *xaod ){ + top::check(evtStore()->retrieve(xaod, m_config->sgKeyElectronsStandAlone( + s.hash())), "Failed to retrieve Electrons"); + + ATH_MSG_INFO(" Electrons with sgKey = " << m_config->sgKeyElectronsStandAlone(s.hash())); + for (auto x : *xaod) { float ptcone30(0.); - x->isolationValue( ptcone30 , xAOD::Iso::ptcone30 ); - ATH_MSG_INFO(" El pT , eta , ptcone30 = "<<x->pt()<<" , "<<x->eta()<<" , "<<ptcone30 ); + x->isolationValue(ptcone30, xAOD::Iso::ptcone30); + ATH_MSG_INFO(" El pT , eta , ptcone30 = " << x->pt() << " , " << x->eta() << " , " << ptcone30); } } - - return StatusCode::SUCCESS; + + return StatusCode::SUCCESS; } - - void EgammaObjectCollectionMaker::specifiedSystematicsPhotons ( const std::set<std::string>& specifiedSystematics ) - { + + StatusCode EgammaObjectCollectionMaker::printoutFwdElectrons() { + // Loop over all systematics + for (auto s : m_specifiedSystematicsFwdElectrons) { + const xAOD::ElectronContainer* xaod(nullptr); + top::check(evtStore()->retrieve(xaod, m_config->sgKeyFwdElectronsStandAlone( + s.hash())), "Failed to retrieve Fwd Electrons"); + + ATH_MSG_INFO(" Fwd Electrons with sgKey = " << m_config->sgKeyFwdElectronsStandAlone(s.hash())); + for (auto x : *xaod) { + ATH_MSG_INFO(" El pT , eta = " << x->pt() << " , " << x->eta()); + } + } + + return StatusCode::SUCCESS; + } + + void EgammaObjectCollectionMaker::specifiedSystematicsPhotons(const std::set<std::string>& specifiedSystematics) { ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( m_calibrationTool->recommendedSystematics() ); - + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_calibrationTool->recommendedSystematics()); + for (auto s : systList) { + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter m_recommendedSystematicsPhotons.push_back(s); if (s.name() == "") { m_specifiedSystematicsPhotons.push_back(s); } - + ///-- MC only --/// if (m_config->isMC()) { ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (!m_config->isSystNominal( m_config->systematics() )) { + if (!m_config->isSystNominal(m_config->systematics())) { if (specifiedSystematics.size() == 0) { m_specifiedSystematicsPhotons.push_back(s); } - if (specifiedSystematics.size() > 0) { + if (specifiedSystematics.size() > 0) { for (auto i : specifiedSystematics) { - if ( i == s.name() ) { - m_specifiedSystematicsPhotons.push_back(s); + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematicsPhotons.push_back(s); } } } } } - } - m_recommendedSystematicsPhotons.sort(); + } + m_recommendedSystematicsPhotons.sort(); m_recommendedSystematicsPhotons.unique(); m_specifiedSystematicsPhotons.sort(); - m_specifiedSystematicsPhotons.unique(); + m_specifiedSystematicsPhotons.unique(); } - - void EgammaObjectCollectionMaker::specifiedSystematicsElectrons( const std::set<std::string>& specifiedSystematics ) - { + + void EgammaObjectCollectionMaker::specifiedSystematicsElectrons(const std::set<std::string>& specifiedSystematics) { ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( m_calibrationTool->recommendedSystematics() ); - + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_calibrationTool->recommendedSystematics()); + for (auto s : systList) { + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter m_recommendedSystematicsElectrons.push_back(s); if (s.name() == "") { m_specifiedSystematicsElectrons.push_back(s); } - + ///-- MC only --/// if (m_config->isMC()) { ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (!m_config->isSystNominal( m_config->systematics() )) { + if (!m_config->isSystNominal(m_config->systematics())) { if (specifiedSystematics.size() == 0) { m_specifiedSystematicsElectrons.push_back(s); } - if (specifiedSystematics.size() > 0) { + if (specifiedSystematics.size() > 0) { for (auto i : specifiedSystematics) { - if ( i == s.name() ) { - m_specifiedSystematicsElectrons.push_back(s); + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematicsElectrons.push_back(s); } } } } } - } - m_recommendedSystematicsElectrons.sort(); + } + m_recommendedSystematicsElectrons.sort(); m_recommendedSystematicsElectrons.unique(); m_specifiedSystematicsElectrons.sort(); m_specifiedSystematicsElectrons.unique(); } - + + void EgammaObjectCollectionMaker::specifiedSystematicsFwdElectrons(const std::set<std::string>& specifiedSystematics) + { + ///-- Get the recommended systematics from the tool, in std::vector format --/// + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_calibrationTool->recommendedSystematics()); + + for (auto s : systList) { + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter + m_recommendedSystematicsFwdElectrons.push_back(s); + if (s.name() == "") { + m_specifiedSystematicsFwdElectrons.push_back(s); + } + + ///-- MC only --/// + if (m_config->isMC()) { + ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// + if (!m_config->isSystNominal(m_config->systematics())) { + if (specifiedSystematics.size() == 0) { + m_specifiedSystematicsFwdElectrons.push_back(s); + } + if (specifiedSystematics.size() > 0) { + for (auto i : specifiedSystematics) { + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematicsFwdElectrons.push_back(s); + } + } + } + } + } + } + m_recommendedSystematicsFwdElectrons.sort(); + m_recommendedSystematicsFwdElectrons.unique(); + m_specifiedSystematicsFwdElectrons.sort(); + m_specifiedSystematicsFwdElectrons.unique(); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ElectronInJetSubtractionCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ElectronInJetSubtractionCollectionMaker.cxx index 00a827c1153dc1ad18ef57229e1054a29fd069f4..4eb0fdae80ecb6188dd40bae76f76d6e2d9b77ad 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ElectronInJetSubtractionCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ElectronInJetSubtractionCollectionMaker.cxx @@ -1,8 +1,8 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: ElectronInJetSubtractionCollectionMaker.cxx 680332 2015-07-04 01:25:47Z morrisj $ +// $Id: ElectronInJetSubtractionCollectionMaker.cxx 806051 2017-06-07 00:32:41Z tpelzer $ #include "TopSystematicObjectMaker/ElectronInJetSubtractionCollectionMaker.h" #include "TopConfiguration/TopConfig.h" #include "TopEvent/EventTools.h" @@ -11,107 +11,107 @@ #include "xAODJet/JetAuxContainer.h" #include "xAODCore/ShallowCopy.h" -namespace top{ - - ElectronInJetSubtractionCollectionMaker::ElectronInJetSubtractionCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + ElectronInJetSubtractionCollectionMaker::ElectronInJetSubtractionCollectionMaker(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - m_doLooseCuts(false) - { - declareProperty( "config" , m_config ); + m_doLooseCuts(false) { + declareProperty("config", m_config); } - - StatusCode ElectronInJetSubtractionCollectionMaker::initialize() - { - if (!m_config->isMC()) - m_doLooseCuts = true; - - if (m_config->doOverlapRemovalOnLooseLeptonDef()) - m_doLooseCuts = true; - - if (m_config->doLooseEvents()) - m_doLooseCuts = true; - - return StatusCode::SUCCESS; + + StatusCode ElectronInJetSubtractionCollectionMaker::initialize() { + if (!m_config->isMC()) m_doLooseCuts = true; + + if (m_config->doOverlapRemovalOnLooseLeptonDef()) m_doLooseCuts = true; + + if (m_config->doLooseEvents()) m_doLooseCuts = true; + + return StatusCode::SUCCESS; } - - StatusCode ElectronInJetSubtractionCollectionMaker::execute() - { + + StatusCode ElectronInJetSubtractionCollectionMaker::execute(bool executeNominal) { // Loop over nominal, all electron syst and all jet syst // For each: - // Create a shallow electron and a shallow jet collection + // Create a shallow electron and a shallow jet collection // Run the subtraction algorithm: // - Modify some jet 4-momentum // - Veto some electrons // Place modified shallow collections into TStore - + for (auto currentSystematic : *m_config->systHashElectronInJetSubtraction()) { - + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(currentSystematic))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(currentSystematic))) continue; + // Get the Electrons const xAOD::ElectronContainer* electrons(nullptr); - top::check(evtStore()->retrieve(electrons, m_config->sgKeyElectronsStandAlone( currentSystematic ) ) , "ElectronInJetSubtractionCollectionMaker::execute() Failed to retrieve electrons" ); - - // Get the Jets + top::check(evtStore()->retrieve(electrons, m_config->sgKeyElectronsStandAlone( + currentSystematic)), + "ElectronInJetSubtractionCollectionMaker::execute() Failed to retrieve electrons"); + + // Get the Jets const xAOD::JetContainer* jets(nullptr); - top::check(evtStore()->retrieve(jets, m_config->sgKeyJetsStandAlone( currentSystematic ) ) , "ElectronInJetSubtractionCollectionMaker::execute() Failed to retrieve jets" ); - + top::check(evtStore()->retrieve(jets, m_config->sgKeyJetsStandAlone( + currentSystematic)), + "ElectronInJetSubtractionCollectionMaker::execute() Failed to retrieve jets"); + // Shallow copy the electrons - std::pair< xAOD::ElectronContainer*, xAOD::ShallowAuxContainer* > shallow_electrons = xAOD::shallowCopyContainer( *electrons ); + std::pair< xAOD::ElectronContainer*, xAOD::ShallowAuxContainer* > shallow_electrons = xAOD::shallowCopyContainer( + *electrons); // Shallow copy the jets - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer( *jets ); - + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jets = xAOD::shallowCopyContainer(*jets); + // Apply the Electron In Jet Subtraction // The actual calculation is performed in another package - m_subtractionAlgorithm.apply( shallow_electrons.first , shallow_jets.first ); - + m_subtractionAlgorithm.apply(shallow_electrons.first, shallow_jets.first); + // Save the modified electrons to TStore - std::string outputElectronsSGKey = m_config->sgKeyElectrons( currentSystematic ); + std::string outputElectronsSGKey = m_config->sgKeyElectrons(currentSystematic); std::string outputElectronsSGKeyAux = outputElectronsSGKey + "Aux."; - - xAOD::TReturnCode saveElectrons = evtStore()->tds()->record( shallow_electrons.first , outputElectronsSGKey ); - xAOD::TReturnCode saveElectronsAux = evtStore()->tds()->record( shallow_electrons.second , outputElectronsSGKeyAux ); - if( !saveElectrons || !saveElectronsAux ){ + + xAOD::TReturnCode saveElectrons = evtStore()->tds()->record(shallow_electrons.first, outputElectronsSGKey); + xAOD::TReturnCode saveElectronsAux = evtStore()->tds()->record(shallow_electrons.second, outputElectronsSGKeyAux); + if (!saveElectrons || !saveElectronsAux) { return StatusCode::FAILURE; - } - + } + // Save the modified jets to TStore - std::string outputJetsSGKey = m_config->sgKeyJets( currentSystematic , false ); + std::string outputJetsSGKey = m_config->sgKeyJets(currentSystematic, false); std::string outputJetsSGKeyAux = outputJetsSGKey + "Aux."; - - xAOD::TReturnCode saveJets = evtStore()->tds()->record( shallow_jets.first , outputJetsSGKey ); - xAOD::TReturnCode saveJetsAux = evtStore()->tds()->record( shallow_jets.second , outputJetsSGKeyAux ); - if( !saveJets || !saveJetsAux ){ + + xAOD::TReturnCode saveJets = evtStore()->tds()->record(shallow_jets.first, outputJetsSGKey); + xAOD::TReturnCode saveJetsAux = evtStore()->tds()->record(shallow_jets.second, outputJetsSGKeyAux); + if (!saveJets || !saveJetsAux) { return StatusCode::FAILURE; } - - + + // If we are using loose lepton definitions anywhere, we'd better make more jet colelctions // We subtract loose leptons from these jets - // We now have loose jets! fun fun fun, we all love combinatorics - + // We now have loose jets! fun fun fun, we all love combinatorics + if (m_doLooseCuts) { // Shallow copy the jets - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jetsLoose = xAOD::shallowCopyContainer( *jets ); - + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_jetsLoose = xAOD::shallowCopyContainer( + *jets); + // Apply the Electron In Jet Subtraction // The actual calculation is performed in another package - m_subtractionAlgorithm.apply( shallow_electrons.first , shallow_jetsLoose.first , m_doLooseCuts ); + m_subtractionAlgorithm.apply(shallow_electrons.first, shallow_jetsLoose.first, m_doLooseCuts); // Save the modified jets to TStore - std::string outputJetsLooseSGKey = m_config->sgKeyJets( currentSystematic , m_doLooseCuts ); + std::string outputJetsLooseSGKey = m_config->sgKeyJets(currentSystematic, m_doLooseCuts); std::string outputJetsLooseSGKeyAux = outputJetsLooseSGKey + "Aux."; - - xAOD::TReturnCode saveJetsLoose = evtStore()->tds()->record( shallow_jetsLoose.first , outputJetsLooseSGKey ); - xAOD::TReturnCode saveJetsLooseAux = evtStore()->tds()->record( shallow_jetsLoose.second , outputJetsLooseSGKeyAux ); - if( !saveJetsLoose || !saveJetsLooseAux ){ + + xAOD::TReturnCode saveJetsLoose = evtStore()->tds()->record(shallow_jetsLoose.first, outputJetsLooseSGKey); + xAOD::TReturnCode saveJetsLooseAux = + evtStore()->tds()->record(shallow_jetsLoose.second, outputJetsLooseSGKeyAux); + if (!saveJetsLoose || !saveJetsLooseAux) { return StatusCode::FAILURE; - } + } } - - } - - return StatusCode::SUCCESS; + + return StatusCode::SUCCESS; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/GhostTrackSystematicsMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/GhostTrackSystematicsMaker.cxx index 6391f63cb8d6b2acf77dcd5456267b436db3f000..91ad9e93e508bf979e95e3ee758407ef99d2b419 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/GhostTrackSystematicsMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/GhostTrackSystematicsMaker.cxx @@ -1,20 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ - -// Filename: GhostTrackSystematicsMaker.cxx -// Description: -// Author: Fabian Wilk -// Created: Mon Oct 24 16:59:28 2016 -// -// (c) by Fabian Wilk <mail@fabianwilk.de> -// The ATLAS Collaboration -// -// This file is licensed under a Creative Commons Attribution-ShareAlike 4.0 -// International License. -// -// You should have received a copy of the license along with this work. -// If not, see <http://creativecommons.org/licenses/by-sa/4.0/>. + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ #include "TopSystematicObjectMaker/GhostTrackSystematicsMaker.h" @@ -31,6 +17,7 @@ #include "TopEvent/EventTools.h" #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" #include "InDetTrackSystematicsTools/InDetTrackSystematics.h" #include "InDetTrackSystematicsTools/InDetTrackSmearingTool.h" @@ -40,475 +27,552 @@ #include "InDetTrackSystematicsTools/JetTrackFilterTool.h" namespace top { - - /* explicit */ GhostTrackSystematicsMaker::GhostTrackSystematicsMaker(const std::string & name) - : ::asg::AsgTool(name), - m_config(nullptr), - m_runPeriods(), - m_specifiedSystematics(), - m_recommendedSystematics(), - m_nominalSystematicSet(), - m_tools() { - - declareProperty("config" , m_config); + /* explicit */ + GhostTrackSystematicsMaker::GhostTrackSystematicsMaker(const std::string& name) + : ::asg::AsgTool(name), + m_config(nullptr), + m_jetPtCut(0.), + m_jetEtaCut(0.), + m_runPeriods(), + m_specifiedSystematics(), + m_recommendedSystematics(), + m_nominalSystematicSet(), + m_tools() { + declareProperty("config", m_config); + } + + /* virtual */ GhostTrackSystematicsMaker::~GhostTrackSystematicsMaker() { + } + + StatusCode GhostTrackSystematicsMaker::initialize() { + ATH_MSG_INFO(" top::GhostTrackSystematicsMaker initialize"); + + ATH_MSG_WARNING("Usage of ghost tracks in AnalysisTop is purely EXPERIMENTAL!\n"); + + m_runPeriods = m_config->runPeriodsJetGhostTrack(); + + // Retrieve the systematics tools. Each individual function will cause + // program abortion upon failure. This is intended as there's no + // meaningful method of recovery. + // These tools are setup and initialised in the TopCPTools package, and we just retrieve them here. + top::check(retrieveGhostTrackCPTool(), + "Failed to retrieve the ghost track CP tools"); + + // Setup the recommended systematics. This utilises the tools that were + // setup before. + const std:: string& syststr = m_config->systematics(); + + if (m_config->isSystNominal(syststr)) { + specifiedSystematics({}); + } else if (m_config->isSystAll(syststr)) { + specifiedSystematics({"AllGhostTrack"}); + } else { + std::set<std::string> syst; + bool ok = m_config->getSystematicsList(syststr, syst); + if (!ok) { + ATH_MSG_ERROR(" top::GhostTrackSystematicsMaker could not determine systematic list"); + return StatusCode::FAILURE; + } + + // No need to manually handle the AllGhostTrack case in here. + specifiedSystematics(syst); } - /* virtual */ GhostTrackSystematicsMaker::~GhostTrackSystematicsMaker(){ + // Pass the systematics list back to the top::TopConfig object. + m_config->systematicsJetGhostTrack(specifiedSystematics()); - } - StatusCode GhostTrackSystematicsMaker::initialize(){ - ATH_MSG_INFO(" top::GhostTrackSystematicsMaker initialize" ); - - m_runPeriods = m_config->runPeriodsJetGhostTrack(); - - // Retrieve the systematics tools. Each individual function will cause - // program abortion upon failure. This is intended as there's no - // meaningful method of recovery. - // These tools are setup and initialised in the TopCPTools package, and we just retrieve them here. - top::check(retrieveGhostTrackCPTool(), - "Failed to retrieve the ghost track CP tools"); - - // Setup the recommended systematics. This utilises the tools that were - // setup before. - const std:: string & syststr = m_config->systematics(); - - if (m_config->isSystNominal(syststr)){ - specifiedSystematics({}); - } else if (m_config->isSystAll(syststr)){ - specifiedSystematics({"AllGhostTrack"}); - } else { - std::set<std::string> syst; - bool ok = m_config->getSystematicsList(syststr, syst); - if (not ok) { - ATH_MSG_ERROR(" top::GhostTrackSystematicsMaker could not determine systematic list" ); - return StatusCode::FAILURE; - } + m_jetPtCut = m_config->jetPtGhostTracks(); + m_jetEtaCut = m_config->jetEtaGhostTracks(); - // No need to manually handle the AllGhostTrack case in here. - specifiedSystematics(syst); - } + ATH_MSG_INFO( + " top::GhostTrackSystematicsMaker: Systematic variations of ghost tracks will be done only for jets with pt >= " << m_jetPtCut << " MeV and eta <= " << m_jetEtaCut << + "."); - // Pass the systematics list back to the top::TopConfig object. - m_config->systematicsJetGhostTrack(specifiedSystematics()); + ATH_MSG_INFO(" top::GhostTrackSystematicsMaker completed initialize"); + return StatusCode::SUCCESS; + } - ATH_MSG_INFO(" top::GhostTrackSystematicsMaker completed initialize" ); - return StatusCode::SUCCESS; - } + StatusCode GhostTrackSystematicsMaker::applyNoOpSystematic(xAOD::JetContainer* nominal, + const CP::SystematicSet& syst) const { + ///-- Loop over the xAOD Container --/// + + static int warningCounter=0; + const int warningLimit=20; + + for (const auto& jet : *nominal) { + if ((jet->pt() < m_jetPtCut) || (std::abs(jet->eta()) > m_jetEtaCut)) continue; + // Copy nominal ghost track container into the systematic variation. - StatusCode GhostTrackSystematicsMaker::applyNoOpSystematic(xAOD::JetContainer * nominal, - const CP::SystematicSet & syst) const { - ///-- Loop over the xAOD Container --/// - for(const auto & jet : * nominal ){ - // Copy nominal ghost track container into the systematic variation. - const auto & nominalGhostTracks = - jet->getAssociatedObjects<xAOD::IParticle>(m_config->decoKeyJetGhostTrack()); - jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), - nominalGhostTracks); - } + const auto& ghostTracks = + jet->getAssociatedObjects<xAOD::IParticle>(m_config->decoKeyJetGhostTrack()); + std::vector<const xAOD::IParticle*> newGhosts; - return StatusCode::SUCCESS; - } + for (std::size_t iGhost = 0; iGhost < ghostTracks.size(); ++iGhost) { + if (ghostTracks[iGhost] == nullptr) continue; - StatusCode GhostTrackSystematicsMaker::applyTruthFilterSystematic(xAOD::JetContainer * nominal, - InDet::InDetTrackTruthFilterTool * tool, - const CP::SystematicSet & syst) const { - ///-- Inform the tool --/// - top::check(tool->applySystematicVariation(syst), - "Failed to configure tool for systematic variation"); - - ///-- Loop over the xAOD Container --/// - for(const auto & jet : * nominal ){ - const auto & ghostTracks = - jet->getAssociatedObjects<xAOD::IParticle>(m_config->decoKeyJetGhostTrack()); - std::vector<const xAOD::IParticle *> newGhosts; - - for (std::size_t iGhost=0; iGhost<ghostTracks.size(); ++iGhost){ - const xAOD::TrackParticle * - tp{dynamic_cast<const xAOD::TrackParticle*>(ghostTracks[iGhost])}; - top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); - - if (not tool->accept(tp)){ - continue; - } - - // We can re-use the existing xAOD::IParticle. - newGhosts.push_back(ghostTracks[iGhost]); - } + // We can re-use the existing xAOD::IParticle. + newGhosts.push_back(ghostTracks[iGhost]); + } - jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); - } + if (newGhosts.size() == 0 && warningCounter<warningLimit) { + ATH_MSG_WARNING( + "in GhostTrackSystematicsMaker: All ghost tracks are null pointers. There may be something wrong with your configuration or derivation. Jet pt: " << jet->pt() << " Jet eta: " << + jet->eta()); + warningCounter++; + } - return StatusCode::SUCCESS; + jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), + newGhosts); } - StatusCode GhostTrackSystematicsMaker::applyJetTrackFilterSystematic(xAOD::JetContainer * nominal, - InDet::JetTrackFilterTool * tool, - const CP::SystematicSet & syst) const { - ///-- Inform the tool --/// - top::check(tool->applySystematicVariation(syst), - "Failed to configure tool for systematic variation"); - - ///-- Loop over the xAOD Container --/// - for(const auto & jet : * nominal ){ - const auto & ghostTracks = jet->getAssociatedObjects<xAOD::IParticle>(m_config->decoKeyJetGhostTrack()); - std::vector<const xAOD::IParticle *> newGhosts; - - for (std::size_t iGhost=0; iGhost<ghostTracks.size(); ++iGhost){ - const xAOD::TrackParticle * - tp{dynamic_cast<const xAOD::TrackParticle*>(ghostTracks[iGhost])}; - top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); - - if (not tool->accept(tp, nominal)){ - continue; - } - - // We can re-use the existing xAOD::IParticle. - newGhosts.push_back(ghostTracks[iGhost]); - } - - jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); + return StatusCode::SUCCESS; + } + + StatusCode GhostTrackSystematicsMaker::applyTruthFilterSystematic(xAOD::JetContainer* nominal, + InDet::InDetTrackTruthFilterTool* tool, + const CP::SystematicSet& syst) const { + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), + "Failed to configure tool for systematic variation"); + + ///-- Loop over the xAOD Container --/// + for (const auto& jet : *nominal) { + if ((jet->pt() < m_jetPtCut) || (std::abs(jet->eta()) > m_jetEtaCut)) continue; + const auto& ghostTracks = + jet->getAssociatedObjects<xAOD::IParticle>(m_config->decoKeyJetGhostTrack()); + std::vector<const xAOD::IParticle*> newGhosts; + + for (std::size_t iGhost = 0; iGhost < ghostTracks.size(); ++iGhost) { + if (ghostTracks[iGhost] == nullptr) continue; + const xAOD::TrackParticle* + tp { + dynamic_cast<const xAOD::TrackParticle*>(ghostTracks[iGhost]) + }; + top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); + + if (!tool->accept(tp)) { + continue; } - return StatusCode::SUCCESS; - } - - StatusCode GhostTrackSystematicsMaker::applySmearingSystematic(xAOD::JetContainer * nominal, - InDet::InDetTrackSmearingTool * tool, - const CP::SystematicSet & syst) const { - ///-- Inform the tool --/// - top::check(tool->applySystematicVariation(syst), - "Failed to configure tool for systematic variation"); - - const std::string sgKey{m_config->decoKeyJetGhostTrack() + - "_Particles_" + syst.name()}; - const std::string sgKeyAux{sgKey + "Aux."}; - - - ///-- Loop over the xAOD Container --/// - xAOD::TrackParticleContainer * newTrackParticles = new xAOD::TrackParticleContainer; - top::check(evtStore()->record(newTrackParticles, sgKey), - "Failed to record systematically varied track particle container" ); - xAOD::TrackParticleAuxContainer * newTrackParticlesAux = new xAOD::TrackParticleAuxContainer; - top::check(evtStore()->record(newTrackParticlesAux, sgKeyAux), - "Failed to record systematically varied track particle container" ); - newTrackParticles->setStore(newTrackParticlesAux); - - for (const auto & jet : * nominal){ - const auto & ghostTracks = jet->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack()); + // We can re-use the existing xAOD::IParticle. + newGhosts.push_back(ghostTracks[iGhost]); + } - std::vector<const xAOD::IParticle *> newGhosts; - - for (std::size_t iGhost=0; iGhost<ghostTracks.size(); ++iGhost){ - const xAOD::TrackParticle * - tp{dynamic_cast<const xAOD::TrackParticle*>(ghostTracks.at(iGhost))}; - top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); - - xAOD::TrackParticle * newTp{nullptr}; - top::check(tool->correctedCopy(* tp, newTp), - "Failure to apply ghost track systematic"); - top::check(newTp, "Systematically varied xAOD::TrackParticle is nullptr"); - - newTrackParticles->push_back(newTp); - newGhosts.push_back(newTp); - } - - jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); - } - - return StatusCode::SUCCESS; + jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); } - StatusCode GhostTrackSystematicsMaker::applyBiasingSystematic(xAOD::JetContainer * nominal, - InDet::InDetTrackBiasingTool * tool, - const CP::SystematicSet & syst) const { - ///-- Inform the tool --/// - top::check(tool->applySystematicVariation(syst), - "Failed to configure tool for systematic variation"); + return StatusCode::SUCCESS; + } + + StatusCode GhostTrackSystematicsMaker::applyJetTrackFilterSystematic(xAOD::JetContainer* nominal, + InDet::JetTrackFilterTool* tool, + const CP::SystematicSet& syst) const { + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), + "Failed to configure tool for systematic variation"); + + ///-- Loop over the xAOD Container --/// + for (const auto& jet : *nominal) { + if ((jet->pt() < m_jetPtCut) || (std::abs(jet->eta()) > m_jetEtaCut)) continue; + const auto& ghostTracks = jet->getAssociatedObjects<xAOD::IParticle>(m_config->decoKeyJetGhostTrack()); + std::vector<const xAOD::IParticle*> newGhosts; + + + for (std::size_t iGhost = 0; iGhost < ghostTracks.size(); ++iGhost) { + if (ghostTracks[iGhost] == nullptr) continue; + const xAOD::TrackParticle* + tp { + dynamic_cast<const xAOD::TrackParticle*>(ghostTracks[iGhost]) + }; + top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); + + if (!tool->accept(tp, nominal)) { + continue; + } - const std::string sgKey{m_config->decoKeyJetGhostTrack() + - "_Particles_" + syst.name()}; - const std::string sgKeyAux{sgKey + "Aux."}; + // We can re-use the existing xAOD::IParticle. + newGhosts.push_back(ghostTracks[iGhost]); + } + jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); + } - ///-- Loop over the xAOD Container --/// - xAOD::TrackParticleContainer * newTrackParticles = new xAOD::TrackParticleContainer; - top::check(evtStore()->record(newTrackParticles, sgKey), - "Failed to record systematically varied track particle container" ); - xAOD::TrackParticleAuxContainer * newTrackParticlesAux = new xAOD::TrackParticleAuxContainer; - top::check(evtStore()->record(newTrackParticlesAux, sgKeyAux), - "Failed to record systematically varied track particle container" ); - newTrackParticles->setStore(newTrackParticlesAux); + return StatusCode::SUCCESS; + } + + StatusCode GhostTrackSystematicsMaker::applySmearingSystematic(xAOD::JetContainer* nominal, + InDet::InDetTrackSmearingTool* tool, + const CP::SystematicSet& syst) const { + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), + "Failed to configure tool for systematic variation"); + + const std::string sgKey { + m_config->decoKeyJetGhostTrack() + + "_Particles_" + syst.name() + }; + const std::string sgKeyAux { + sgKey + "Aux." + }; + + + ///-- Loop over the xAOD Container --/// + xAOD::TrackParticleContainer* newTrackParticles = new xAOD::TrackParticleContainer; + top::check(evtStore()->record(newTrackParticles, sgKey), + "Failed to record systematically varied track particle container"); + xAOD::TrackParticleAuxContainer* newTrackParticlesAux = new xAOD::TrackParticleAuxContainer; + top::check(evtStore()->record(newTrackParticlesAux, sgKeyAux), + "Failed to record systematically varied track particle container"); + newTrackParticles->setStore(newTrackParticlesAux); + + for (const auto& jet : *nominal) { + if ((jet->pt() < m_jetPtCut) || (std::abs(jet->eta()) > m_jetEtaCut)) continue; + const auto& ghostTracks = jet->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack()); + + std::vector<const xAOD::IParticle*> newGhosts; + + for (std::size_t iGhost = 0; iGhost < ghostTracks.size(); ++iGhost) { + if (ghostTracks[iGhost] == nullptr) continue; + + const xAOD::TrackParticle* + tp { + dynamic_cast<const xAOD::TrackParticle*>(ghostTracks.at(iGhost)) + }; + top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); + + xAOD::TrackParticle* newTp { + nullptr + }; + top::check(tool->correctedCopy(*tp, newTp), + "Failure to apply ghost track systematic"); + top::check(newTp, "Systematically varied xAOD::TrackParticle is nullptr"); + + newTrackParticles->push_back(newTp); + newGhosts.push_back(newTp); + } + + jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); + } - for (const auto & jet : * nominal){ - const auto & ghostTracks = jet->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack()); + return StatusCode::SUCCESS; + } + + StatusCode GhostTrackSystematicsMaker::applyBiasingSystematic(xAOD::JetContainer* nominal, + InDet::InDetTrackBiasingTool* tool, + const CP::SystematicSet& syst) const { + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), + "Failed to configure tool for systematic variation"); + + const std::string sgKey { + m_config->decoKeyJetGhostTrack() + + "_Particles_" + syst.name() + }; + const std::string sgKeyAux { + sgKey + "Aux." + }; + + + ///-- Loop over the xAOD Container --/// + xAOD::TrackParticleContainer* newTrackParticles = new xAOD::TrackParticleContainer; + top::check(evtStore()->record(newTrackParticles, sgKey), + "Failed to record systematically varied track particle container"); + xAOD::TrackParticleAuxContainer* newTrackParticlesAux = new xAOD::TrackParticleAuxContainer; + top::check(evtStore()->record(newTrackParticlesAux, sgKeyAux), + "Failed to record systematically varied track particle container"); + newTrackParticles->setStore(newTrackParticlesAux); + + for (const auto& jet : *nominal) { + if ((jet->pt() < m_jetPtCut) || (std::abs(jet->eta()) > m_jetEtaCut)) continue; + const auto& ghostTracks = jet->getAssociatedObjects<xAOD::TrackParticle>(m_config->decoKeyJetGhostTrack()); + + std::vector<const xAOD::IParticle*> newGhosts; + + for (std::size_t iGhost = 0; iGhost < ghostTracks.size(); ++iGhost) { + if (ghostTracks[iGhost] == nullptr) continue; + + const xAOD::TrackParticle* + tp { + dynamic_cast<const xAOD::TrackParticle*>(ghostTracks.at(iGhost)) + }; + top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); + + xAOD::TrackParticle* newTp { + nullptr + }; + top::check(tool->correctedCopy(*tp, newTp), + "Failure to apply ghost track systematic"); + top::check(newTp, "Systematically varied xAOD::TrackParticle is nullptr"); + + newTrackParticles->push_back(newTp); + newGhosts.push_back(newTp); + } + + jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); + } - std::vector<const xAOD::IParticle *> newGhosts; + return StatusCode::SUCCESS; + } - for (std::size_t iGhost=0; iGhost<ghostTracks.size(); ++iGhost){ - const xAOD::TrackParticle * - tp{dynamic_cast<const xAOD::TrackParticle*>(ghostTracks.at(iGhost))}; - top::check(tp, "Failed to convert xAOD::IParticle to xAOD::TrackParticle for ghost track"); + StatusCode GhostTrackSystematicsMaker::execute(bool executeNominal) { + ATH_MSG_DEBUG(" top::GhostTrackSystematicsMaker execute:"); - xAOD::TrackParticle * newTp{nullptr}; - top::check(tool->correctedCopy(* tp, newTp), - "Failure to apply ghost track systematic"); - top::check(newTp, "Systematically varied xAOD::TrackParticle is nullptr"); - newTrackParticles->push_back(newTp); - newGhosts.push_back(newTp); - } + ///-- Get nominal jets --/// + xAOD::JetContainer* nominalJets(nullptr); + top::check(evtStore()->retrieve(nominalJets, + m_config->sgKeyJetsStandAlone(m_nominalSystematicSet.hash())), + "Failed to retrieve Jets"); - jet->setAssociatedObjects(m_config->decoKeyJetGhostTrack(syst.hash()), newGhosts); - } + // applyNoOpSystematic is used just to remove ghost track vector from thinned jets + top::check(applyNoOpSystematic(nominalJets, m_nominalSystematicSet), + "Failure to apply GhostTrackSystematic"); - return StatusCode::SUCCESS; + // We don't want to do anything on Data -> bail early so that we can + // rely on the inputs to be MC. + if (!m_config->isMC()) { + return StatusCode::SUCCESS; } - StatusCode GhostTrackSystematicsMaker::execute(){ - ATH_MSG_DEBUG(" top::GhostTrackSystematicsMaker execute:" ); + ///-- Only run this on the systematic execution --/// + if (executeNominal) return StatusCode::SUCCESS; - // We don't want to do anything on Data -> bail early so that we can - // rely on the inputs to be MC. - if (not m_config->isMC()){ - return StatusCode::SUCCESS; - } - - ///-- Get nominal jets --/// - xAOD::JetContainer * nominalJets(nullptr); - top::check(evtStore()->retrieve(nominalJets, - m_config->sgKeyJetsStandAlone(m_nominalSystematicSet.hash())), - "Failed to retrieve Jets"); + ///-- SMEARING --/// + for (const auto& syst : m_systs.smearing) { + top::check(applySmearingSystematic(nominalJets, &(*m_tools.smearing), syst), + "Failure to apply GhostTrackSystematic"); + } - ///-- SMEARING --/// - for (const auto & syst : m_systs.smearing){ - // std::cout << "[A] SYSTEMATIC = " << m_config->systematicName(syst.hash()) << std::endl; - top::check(applySmearingSystematic(nominalJets, &(* m_tools.smearing), syst), - "Failure to apply GhostTrackSystematic"); - } - - ///-- BIASING --/// - InDet::InDetTrackBiasingTool * biasingTool{nullptr}; - if (m_runPeriods.size() == 1){ - biasingTool = &(* m_tools.bias[0]); - - top::check(biasingTool, "Failure to selected biasing tool"); - for (const auto & syst : m_systs.bias){ - // std::cout << "[B] SYSTEMATIC = " << m_config->systematicName(syst.hash()) << std::endl; - top::check(applyBiasingSystematic(nominalJets, biasingTool, syst), - "Failure to apply GhostTrackSystematic"); - } - } else { - const xAOD::EventInfo * ei{nullptr}; - top::check(evtStore()->retrieve(ei, "EventInfo"), - "Failure to retrieve EventInfo"); - - top::check(ei->isAvailable<unsigned int>("RandomRunNumber"), - "Require that RandomRunNumber decoration is available."); - auto randomRunNumber = ei->auxdataConst<unsigned int>("RandomRunNumber"); - - if (randomRunNumber == 0){ - for (const auto & syst : m_systs.bias){ - // std::cout << "[B.1] SYSTEMATIC = " << m_config->systematicName(syst.hash()) << std::endl; - top::check(applyNoOpSystematic(nominalJets, syst), - "Failure to apply GhostTrackSystematic"); - } - } else { - top::check(m_runPeriods[0] <= randomRunNumber, - "RandomRunNumber is below valid range."); - top::check(randomRunNumber < m_runPeriods[m_runPeriods.size() - 1], - "RandomRunNumber is above valid range."); - - for (std::size_t i=1; i<m_runPeriods.size(); ++i){ - if (randomRunNumber < m_runPeriods[i]){ - biasingTool = &(* m_tools.bias[i - 1]); - break; - } - } - top::check(biasingTool, "Failure to selected biasing tool"); - for (const auto & syst : m_systs.bias){ - // std::cout << "[B.2] SYSTEMATIC = " << m_config->systematicName(syst.hash()) << std::endl; - top::check(applyBiasingSystematic(nominalJets, biasingTool, syst), - "Failure to apply GhostTrackSystematic"); - } - } + ///-- BIASING --/// + InDet::InDetTrackBiasingTool* biasingTool { + nullptr + }; + if (m_runPeriods.size() == 1) { + biasingTool = &(*m_tools.bias[0]); + + top::check(biasingTool, "Failure to selected biasing tool"); + for (const auto& syst : m_systs.bias) { + top::check(applyBiasingSystematic(nominalJets, biasingTool, syst), + "Failure to apply GhostTrackSystematic"); + } + } else { + const xAOD::EventInfo* ei { + nullptr + }; + top::check(evtStore()->retrieve(ei, "EventInfo"), + "Failure to retrieve EventInfo"); + + top::check(ei->isAvailable<unsigned int>("RandomRunNumber"), + "Require that RandomRunNumber decoration is available."); + auto randomRunNumber = ei->auxdataConst<unsigned int>("RandomRunNumber"); + + if (randomRunNumber == 0) { + for (const auto& syst : m_systs.bias) { + top::check(applyNoOpSystematic(nominalJets, syst), + "Failure to apply GhostTrackSystematic"); } - - ///-- TRUTH FILTER --/// - for (const auto & syst : m_systs.truthFilter){ - // std::cout << "[C] SYSTEMATIC = " << m_config->systematicName(syst.hash()) << std::endl; - top::check(applyTruthFilterSystematic(nominalJets, &(* m_tools.truthFilter), syst), - "Failure to apply GhostTrackSystematic"); + } else { + top::check(m_runPeriods[0] <= randomRunNumber, + "RandomRunNumber is below valid range."); + top::check(randomRunNumber < m_runPeriods[m_runPeriods.size() - 1], + "RandomRunNumber is above valid range."); + + for (std::size_t i = 1; i < m_runPeriods.size(); ++i) { + if (randomRunNumber < m_runPeriods[i]) { + biasingTool = &(*m_tools.bias[i - 1]); + break; + } } - - ///-- JET TRACK FILTER --/// - for (const auto & syst : m_systs.jetTrackFilter){ - // std::cout << "[D] SYSTEMATIC = " << m_config->systematicName(syst.hash()) << std::endl; - top::check(applyJetTrackFilterSystematic(nominalJets, &(* m_tools.jetTrackFilter), syst), - "Failure to apply GhostTrackSystematic"); + top::check(biasingTool, "Failure to selected biasing tool"); + for (const auto& syst : m_systs.bias) { + top::check(applyBiasingSystematic(nominalJets, biasingTool, syst), + "Failure to apply GhostTrackSystematic"); } + } + } - ATH_MSG_DEBUG(" top::GhostTrackSystematicsMaker completed execute" ); - return StatusCode::SUCCESS; + ///-- TRUTH FILTER --/// + for (const auto& syst : m_systs.truthFilter) { + top::check(applyTruthFilterSystematic(nominalJets, &(*m_tools.truthFilter), syst), + "Failure to apply GhostTrackSystematic"); } + ///-- JET TRACK FILTER --/// + for (const auto& syst : m_systs.jetTrackFilter) { + top::check(applyJetTrackFilterSystematic(nominalJets, &(*m_tools.jetTrackFilter), syst), + "Failure to apply GhostTrackSystematic"); + } - void GhostTrackSystematicsMaker::specifiedSystematics(const std::set<std::string> & specifiedSystematics) { - // NOTE: For this function -- unlike the "proper" ObjectCollectionMakers in AnalysisTop -- an empty specifiedSystematics input is considered to represent "No Systematics". All GhostTrack systematics can be requested with the string "AllGhostTrack". - const bool allGhostTrackSystematics = m_config->contains(specifiedSystematics, - "AllGhostTrack"); - - // Acquire the recommended systematics from the various tools and put - // into containers that store the per-tool systematics as well as a - // global container. At a later point we'll make the per-tool containers - // unique and check that the containers for various tools are - // orthogonal. - std::set<CP::SystematicSet> systs; - - // SMEARING - m_systs.smearing = - CP::make_systematics_vector(m_tools.smearing->recommendedSystematics()); - systs.insert(m_systs.smearing.begin(), m_systs.smearing.end()); - - // BIAS - for (const auto & tool : m_tools.bias){ - m_systs.bias = - CP::make_systematics_vector(tool->recommendedSystematics()); - systs.insert(m_systs.bias.begin(), m_systs.bias.end()); - } + ATH_MSG_DEBUG(" top::GhostTrackSystematicsMaker completed execute"); + return StatusCode::SUCCESS; + } + + void GhostTrackSystematicsMaker::specifiedSystematics(const std::set<std::string>& specSys) { + // NOTE: For this function -- unlike the "proper" ObjectCollectionMakers in AnalysisTop -- an empty + // specifiedSystematics input is considered to represent "No Systematics". All GhostTrack systematics can be + // requested with the string "AllGhostTrack". + const bool allGhostTrackSystematics = m_config->contains(specSys, + "AllGhostTrack"); + + // Acquire the recommended systematics from the various tools and put + // into containers that store the per-tool systematics as well as a + // global container. At a later point we'll make the per-tool containers + // unique and check that the containers for various tools are + // orthogonal. + std::set<CP::SystematicSet> systs; + + // SMEARING + m_systs.smearing = + CP::make_systematics_vector(m_tools.smearing->recommendedSystematics()); + systs.insert(m_systs.smearing.begin(), m_systs.smearing.end()); + + // BIAS + for (const auto& tool : m_tools.bias) { + m_systs.bias = + CP::make_systematics_vector(tool->recommendedSystematics()); + systs.insert(m_systs.bias.begin(), m_systs.bias.end()); + } - // TRUTH FILTER - m_systs.truthFilter = - CP::make_systematics_vector(m_tools.truthFilter->recommendedSystematics()); - systs.insert(m_systs.truthFilter.begin(), m_systs.truthFilter.end()); - - // JET TRACK FILTER - m_systs.jetTrackFilter = - CP::make_systematics_vector(m_tools.jetTrackFilter->recommendedSystematics()); - systs.insert(m_systs.jetTrackFilter.begin(), m_systs.jetTrackFilter.end()); - - // PUT INTO RECOMMENDED AND SPECIFIED - for (const auto & s : systs){ - // We don't want nominal. - if (s.name() == ""){ - continue; - } + // TRUTH FILTER + m_systs.truthFilter = + CP::make_systematics_vector(m_tools.truthFilter->recommendedSystematics()); + systs.insert(m_systs.truthFilter.begin(), m_systs.truthFilter.end()); + + // JET TRACK FILTER + m_systs.jetTrackFilter = + CP::make_systematics_vector(m_tools.jetTrackFilter->recommendedSystematics()); + systs.insert(m_systs.jetTrackFilter.begin(), m_systs.jetTrackFilter.end()); + + // PUT INTO RECOMMENDED AND SPECIFIED + for (const auto& s : systs) { + // We don't want nominal. + if (s.name() == "") { + continue; + } + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter + m_recommendedSystematics.push_back(s); + + ///-- MC only --/// + if (m_config->isMC()) { + ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// + if (!m_config->isSystNominal(m_config->systematics())) { + if (allGhostTrackSystematics) { + m_specifiedSystematics.push_back(s); + continue; + } - m_recommendedSystematics.push_back(s); - - ///-- MC only --/// - if (m_config->isMC()) { - ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (not m_config->isSystNominal(m_config->systematics())) { - if (allGhostTrackSystematics) { - m_specifiedSystematics.push_back(s); - continue; - } - - for (const auto & i : specifiedSystematics) { - if (i == s.name()) { - m_specifiedSystematics.push_back(s); - } - } - } + for (const auto& i : specSys) { + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematics.push_back(s); } + } } + } + } - m_recommendedSystematics.sort(); - m_recommendedSystematics.unique(); + m_recommendedSystematics.sort(); + m_recommendedSystematics.unique(); + + m_specifiedSystematics.sort(); + m_specifiedSystematics.unique(); + + // Make the sublists unique and remove any elements that have not "been specified". + m_systs.makeUnique(); + m_systs.removeNonSpecified(m_specifiedSystematics); + + // Lastly, let use introduce a safeguard which ensures that the + // systematics selected for the various tools are orthogonal. This is + // done by asserting that the sum of the sizes of the individual + // systematics lists equals the size of the list of specified + // systematics. We can do this because we've made the individual + // per-tool containers unique (in makeUnique). + top::check(m_systs.numSystematics() == m_specifiedSystematics.size(), + "Sanity check failed"); + } + + StatusCode GhostTrackSystematicsMaker::retrieveGhostTrackCPTool() { + ATH_MSG_INFO(" Retrieving ghost track CPTools"); + + std::string smearingToolName { + "top::GhostTrackCPTools::InDetTrackSmearingTool" + }; + if (asg::ToolStore::contains<InDet::InDetTrackSmearingTool>(smearingToolName)) { + m_tools.smearing = + asg::ToolStore::get<InDet::InDetTrackSmearingTool>(smearingToolName); + } else { + ATH_MSG_ERROR(" Impossible to retrieve " + smearingToolName); + return StatusCode::FAILURE; + } - m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); + std::string biasToolPrefix { + "top::GhostTrackCPTools::InDetTrackBiasingTool" + }; + top::check(!m_runPeriods.empty(), "Assertion failed"); + // Two cases are possible: + // - Either a single run number was specified to the runPeriods + // parameter in which case we'll use exactly that run number, or + // - at least two numbers have been specified, which then define + // (potentially multiple) run number ranges. + unsigned int end = 0; + if (m_runPeriods.size() == 1) { + end = 1; + m_tools.bias.resize(1); + } else { + end = m_runPeriods.size() - 1; + m_tools.bias.resize(m_runPeriods.size() - 1); + } + for (unsigned int i = 0; i < end; i++) { + std::string biasToolName { + "" + }; + if (m_runPeriods.size() == 1) { + biasToolName = biasToolPrefix + "_" + std::to_string(m_runPeriods[0]); + } else { + biasToolName = biasToolPrefix + "_" + std::to_string(m_runPeriods[i]) + "_" + + std::to_string(m_runPeriods[i + 1]); + } + if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)) { + m_tools.bias[i] = asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + } else { + ATH_MSG_ERROR(" Impossible to retrieve " + biasToolName); + return StatusCode::FAILURE; + } + } - // Make the sublists unique and remove any elements that have not "been specified". - m_systs.makeUnique(); - m_systs.removeNonSpecified(m_specifiedSystematics); + std::string truthOriginToolName { + "top::GhostTrackCPTools::InDetTrackTruthOriginTool" + }; + if (asg::ToolStore::contains<InDet::InDetTrackTruthOriginTool>(truthOriginToolName)) { + m_tools.truthOrigin = asg::ToolStore::get<InDet::InDetTrackTruthOriginTool>(truthOriginToolName); + } else { + ATH_MSG_ERROR(" Impossible to retrieve " + truthOriginToolName); + return StatusCode::FAILURE; + } - // Lastly, let use introduce a safeguard which ensures that the - // systematics selected for the various tools are orthogonal. This is - // done by asserting that the sum of the sizes of the individual - // systematics lists equals the size of the list of specified - // systematics. We can do this because we've made the individual - // per-tool containers unique (in makeUnique). - top::check(m_systs.numSystematics() == m_specifiedSystematics.size(), - "Sanity check failed"); + std::string truthFilterToolName { + "top::GhostTrackCPTools::InDetTrackTruthFilterTool" + }; + if (asg::ToolStore::contains<InDet::InDetTrackTruthFilterTool>(truthFilterToolName)) { + m_tools.truthFilter = asg::ToolStore::get<InDet::InDetTrackTruthFilterTool>(truthFilterToolName); + } else { + ATH_MSG_ERROR(" Impossible to retrieve " + truthFilterToolName); + return StatusCode::FAILURE; } - StatusCode GhostTrackSystematicsMaker::retrieveGhostTrackCPTool(){ - ATH_MSG_INFO(" Retrieving ghost track CPTools" ); - - std::string smearingToolName{"top::GhostTrackCPTools::InDetTrackSmearingTool"}; - if (asg::ToolStore::contains<InDet::InDetTrackSmearingTool>(smearingToolName)) { - m_tools.smearing = - asg::ToolStore::get<InDet::InDetTrackSmearingTool>(smearingToolName); - } - else { - ATH_MSG_ERROR(" Impossible to retrieve " + smearingToolName ); - return StatusCode::FAILURE; - } - - std::string biasToolPrefix{"top::GhostTrackCPTools::InDetTrackBiasingTool"}; - top::check(not m_runPeriods.empty(), "Assertion failed"); - // Two cases are possible: - // - Either a single run number was specified to the runPeriods - // parameter in which case we'll use exactly that run number, or - // - at least two numbers have been specified, which then define - // (potentially multiple) run number ranges. - unsigned int end = 0; - if (m_runPeriods.size() == 1) { - end = 1; - m_tools.bias.resize(1); - } - else { - end = m_runPeriods.size()-1; - m_tools.bias.resize(m_runPeriods.size()-1); - } - for (unsigned int i = 0; i<end; i++) { - std::string biasToolName{""}; - if (m_runPeriods.size() == 1) { - biasToolName = biasToolPrefix + "_" + std::to_string(m_runPeriods[0]); - } - else { - biasToolName = biasToolPrefix + "_" + std::to_string(m_runPeriods[i]) + "_" + std::to_string(m_runPeriods[i + 1]); - } - if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)){ - m_tools.bias[i] = asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); - } - else { - ATH_MSG_ERROR(" Impossible to retrieve " + biasToolName ); - return StatusCode::FAILURE; - } - } - - std::string truthOriginToolName{"top::GhostTrackCPTools::InDetTrackTruthOriginTool"}; - if (asg::ToolStore::contains<InDet::InDetTrackTruthOriginTool>(truthOriginToolName)){ - m_tools.truthOrigin = asg::ToolStore::get<InDet::InDetTrackTruthOriginTool>(truthOriginToolName); - } - else { - ATH_MSG_ERROR(" Impossible to retrieve " + truthOriginToolName ); - return StatusCode::FAILURE; - } - - std::string truthFilterToolName{"top::GhostTrackCPTools::InDetTrackTruthFilterTool"}; - if (asg::ToolStore::contains<InDet::InDetTrackTruthFilterTool>(truthFilterToolName)){ - m_tools.truthFilter = asg::ToolStore::get<InDet::InDetTrackTruthFilterTool>(truthFilterToolName); - } - else { - ATH_MSG_ERROR(" Impossible to retrieve " + truthFilterToolName ); - return StatusCode::FAILURE; - } - - std::string jetTrackFilterToolName{"top::GhostTrackCPTools::JetTrackFilterTool"}; - if (asg::ToolStore::contains<InDet::JetTrackFilterTool>(jetTrackFilterToolName)){ - m_tools.jetTrackFilter = asg::ToolStore::get<InDet::JetTrackFilterTool>(jetTrackFilterToolName); - } - else { - ATH_MSG_ERROR(" Impossible to retrieve " + jetTrackFilterToolName ); - return StatusCode::FAILURE; - } - - return StatusCode::SUCCESS; + std::string jetTrackFilterToolName { + "top::GhostTrackCPTools::JetTrackFilterTool" + }; + if (asg::ToolStore::contains<InDet::JetTrackFilterTool>(jetTrackFilterToolName)) { + m_tools.jetTrackFilter = asg::ToolStore::get<InDet::JetTrackFilterTool>(jetTrackFilterToolName); + } else { + ATH_MSG_ERROR(" Impossible to retrieve " + jetTrackFilterToolName); + return StatusCode::FAILURE; } + return StatusCode::SUCCESS; + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/JetObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/JetObjectCollectionMaker.cxx index 7c1bdf02d213f4a4ea0815b118d0ee08f52d97c3..21f5fe7c7c049bec58ec7c541716dd9343ff2a03 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/JetObjectCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/JetObjectCollectionMaker.cxx @@ -1,10 +1,11 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration */ -// $Id: JetObjectCollectionMaker.cxx 802997 2017-04-17 01:24:36Z tpelzer $ +// $Id: JetObjectCollectionMaker.cxx 809674 2017-08-23 14:10:24Z iconnell $ #include "TopSystematicObjectMaker/JetObjectCollectionMaker.h" #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" #include "TopEvent/EventTools.h" #include "xAODJet/JetContainer.h" @@ -19,722 +20,882 @@ #include "TopJetSubstructure/LargeJetTrimmer.h" #include "TopJetSubstructure/SubjetMaker.h" -namespace top{ - -JetObjectCollectionMaker::JetObjectCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), - m_config(nullptr), - m_doJER(false), - m_doFull_JER(false), - - m_specifiedSystematics(), - m_specifiedSystematicsLargeR(), - m_specifiedSystematicsTrackJets(), - m_recommendedSystematics(), - m_nominalSystematicSet(), - - m_jetCalibrationTool("JetCalibrationTool"), - m_jetCalibrationToolLargeR("JetCalibrationToolLargeR"), - - m_jetUncertaintiesTool("JetUncertaintiesTool"), - m_jetUncertaintiesToolReducedNPScenario1("JetUncertaintiesToolReducedNPScenario1"), - m_jetUncertaintiesToolReducedNPScenario2("JetUncertaintiesToolReducedNPScenario2"), - m_jetUncertaintiesToolReducedNPScenario3("JetUncertaintiesToolReducedNPScenario3"), - m_jetUncertaintiesToolReducedNPScenario4("JetUncertaintiesToolReducedNPScenario4"), - - m_jetUncertaintiesToolLargeR_strong("JetUncertaintiesToolLargeR_Strong"), - m_jetUncertaintiesToolLargeR_medium("JetUncertaintiesToolLargeR_Medium"), - m_jetUncertaintiesToolLargeR_weak("JetUncertaintiesToolLargeR_Weak"), - - m_jetJERSmearingTool("JetJERSmearingTool"), - m_jetUpdateJvtTool("JetUpdateJvtTool"), - m_fjvtTool("fJVTTool"), - - m_jetSubstructure(nullptr), - - m_systMap_AllNP(), - m_systMap_ReducedNPScenario1(), - m_systMap_ReducedNPScenario2(), - m_systMap_ReducedNPScenario3(), - m_systMap_ReducedNPScenario4(), - m_systMap_LargeR_strong(), - m_systMap_JER() -{ - declareProperty( "config" , m_config ); - - declareProperty( "JetCalibrationTool" , m_jetCalibrationTool ); - declareProperty( "JetCalibrationToolLargeR" , m_jetCalibrationToolLargeR ); - - declareProperty( "JetUncertaintiesToolLargeR" , m_jetUncertaintiesToolLargeR_strong); - declareProperty( "JetUncertaintiesTool" , m_jetUncertaintiesTool); - declareProperty( "JetUncertaintiesToolReducedNPScenario1" , m_jetUncertaintiesToolReducedNPScenario1 ); - declareProperty( "JetUncertaintiesToolReducedNPScenario2" , m_jetUncertaintiesToolReducedNPScenario2 ); - declareProperty( "JetUncertaintiesToolReducedNPScenario3" , m_jetUncertaintiesToolReducedNPScenario3 ); - declareProperty( "JetUncertaintiesToolReducedNPScenario4" , m_jetUncertaintiesToolReducedNPScenario4 ); - - declareProperty( "JetJERSmearingTool" , m_jetJERSmearingTool ); - declareProperty( "JetUpdateJvtTool" , m_jetUpdateJvtTool ); - - declareProperty( "TruthJetCollectionForHSTagging" , m_truthJetCollForHS = "AntiKt4TruthJets" ); -} - -StatusCode JetObjectCollectionMaker::initialize() { - ATH_MSG_INFO(" top::JetObjectCollectionMaker initialize" ); - - ///-- Lets do the nominal systematics --/// - ///-- JetObjectCollectionMaker is a little different from the others --/// - m_specifiedSystematics.push_back(CP::SystematicSet()); - m_specifiedSystematicsLargeR.push_back(CP::SystematicSet()); - m_specifiedSystematicsTrackJets.push_back(CP::SystematicSet()); - m_recommendedSystematics.push_back(CP::SystematicSet()); - - - top::check( m_jetCalibrationTool.retrieve() , "Failed to retrieve JetCalibrationTool" ); - if (m_config->useLargeRJets()) { - top::check( m_jetCalibrationToolLargeR.retrieve(), - "Failed to retrieve JetCalibrationToolLargeR" ); - top::check( m_jetUncertaintiesToolLargeR_strong.retrieve(), - "Failed to retrieve JetUncertaintiesToolLargeR_Strong" ); - top::check( m_jetUncertaintiesToolLargeR_medium.retrieve(), - "Failed to retrieve JetUncertaintiesToolLargeR_Medium" ); - top::check( m_jetUncertaintiesToolLargeR_weak.retrieve(), - "Failed to retrieve JetUncertaintiesToolLargeR_Weak" ); +namespace top { + JetObjectCollectionMaker::JetObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + m_doJER(false), + m_doFull_JER(false), + m_doFull_JER_Pseudodata(false), + m_isMC(false), + m_doMultipleJES(false), + + m_specifiedSystematics(), + m_specifiedSystematicsLargeR(), + m_specifiedSystematicsTrackJets(), + m_recommendedSystematics(), + m_nominalSystematicSet(), + + m_jetCalibrationTool("JetCalibrationTool"), + m_jetCalibrationToolLargeR("JetCalibrationToolLargeR"), + + m_jetUncertaintiesTool("JetUncertaintiesTool"), + m_jetUncertaintiesToolFrozenJMS("JetUncertaintiesToolFrozenJMS"), + m_jetUncertaintiesToolReducedNPScenario1("JetUncertaintiesToolReducedNPScenario1"), + m_jetUncertaintiesToolReducedNPScenario2("JetUncertaintiesToolReducedNPScenario2"), + m_jetUncertaintiesToolReducedNPScenario3("JetUncertaintiesToolReducedNPScenario3"), + m_jetUncertaintiesToolReducedNPScenario4("JetUncertaintiesToolReducedNPScenario4"), + m_jetUncertaintiesToolLargeR("JetUncertaintiesToolLargeR"), + + m_jetUpdateJvtTool("JetUpdateJvtTool"), + m_jetSelectfJvtTool("JetSelectfJvtTool"), + + m_jetSubstructure(nullptr), + + m_systMap_AllNP(), + m_systMap_AllNP_FrozenJMS(), + m_systMap_ReducedNPScenario1(), + m_systMap_ReducedNPScenario2(), + m_systMap_ReducedNPScenario3(), + m_systMap_ReducedNPScenario4(), + m_systMap_LargeR() { + declareProperty("config", m_config); + + declareProperty("JetCalibrationTool", m_jetCalibrationTool); + declareProperty("JetCalibrationToolLargeR", m_jetCalibrationToolLargeR); + + declareProperty("JetUncertaintiesTool", m_jetUncertaintiesTool); + declareProperty("JetUncertaintiesToolFrozenJMS", m_jetUncertaintiesToolFrozenJMS); + declareProperty("JetUncertaintiesToolReducedNPScenario1", m_jetUncertaintiesToolReducedNPScenario1); + declareProperty("JetUncertaintiesToolReducedNPScenario2", m_jetUncertaintiesToolReducedNPScenario2); + declareProperty("JetUncertaintiesToolReducedNPScenario3", m_jetUncertaintiesToolReducedNPScenario3); + declareProperty("JetUncertaintiesToolReducedNPScenario4", m_jetUncertaintiesToolReducedNPScenario4); + declareProperty("JetUncertaintiesToolLargeR", m_jetUncertaintiesToolLargeR); + + declareProperty("JetUpdateJvtTool", m_jetUpdateJvtTool); + + declareProperty("TruthJetCollectionForHSTagging", m_truthJetCollForHS = "AntiKt4TruthJets"); } - // If we are using particle flow jets then we - // don't have any uncertainties so skip the retrieval. - if (!m_config->useParticleFlowJets()) { - ///-- JER uncertainties model --/// - if (m_config->jetJERSmearingModel() == "Full") - m_doFull_JER = true; - if (m_config->jetJERSmearingModel() == "Simple") - m_doFull_JER = false; + StatusCode JetObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::JetObjectCollectionMaker initialize"); - ///-- Are we doing JER? Let's not repeat this logic over and over --/// - if (m_config->isMC()) - m_doJER = true; - if (!m_config->isMC() && m_doFull_JER) - m_doJER = true; + ///-- Lets do the nominal systematics --/// + ///-- JetObjectCollectionMaker is a little different from the others --/// + m_specifiedSystematics.push_back(CP::SystematicSet()); + m_specifiedSystematicsLargeR.push_back(CP::SystematicSet()); + m_specifiedSystematicsTrackJets.push_back(CP::SystematicSet()); + m_recommendedSystematics.push_back(CP::SystematicSet()); - if (m_config->isMC()) { - if (!m_config->doMultipleJES()) { - top::check( m_jetUncertaintiesTool.retrieve() , "Failed to retrieve JetUncertaintiesToolAllNP" ); - } - if (m_config->doMultipleJES()) { - top::check( m_jetUncertaintiesToolReducedNPScenario1.retrieve() , "Failed to retrieve JetUncertaintiesToolReducedNPScenario1" ); - top::check( m_jetUncertaintiesToolReducedNPScenario2.retrieve() , "Failed to retrieve JetUncertaintiesToolReducedNPScenario2" ); - top::check( m_jetUncertaintiesToolReducedNPScenario3.retrieve() , "Failed to retrieve JetUncertaintiesToolReducedNPScenario3" ); - top::check( m_jetUncertaintiesToolReducedNPScenario4.retrieve() , "Failed to retrieve JetUncertaintiesToolReducedNPScenario4" ); - } + top::check(m_jetCalibrationTool.retrieve(), "Failed to retrieve JetCalibrationTool"); + if (m_config->useLargeRJets()) { + top::check(m_jetCalibrationToolLargeR.retrieve(), + "Failed to retrieve JetCalibrationToolLargeR"); + top::check(m_jetUncertaintiesToolLargeR.retrieve(), + "Failed to retrieve JetUncertaintiesToolLargeR"); } - top::check( m_jetJERSmearingTool.retrieve() , "Failed to retrieve JetJERSmearingTool" ); - } - - top::check( m_jetUpdateJvtTool.retrieve() , "Failed to retrieve JetUpdateJvtTool" ); - top::check(m_fjvtTool.retrieve(), "Failed to retrieve fJVTTool"); + if (m_config->getDerivationStream() == "PHYS") { + m_truthJetCollForHS = "AntiKt4TruthDressedWZJets"; + } - // Take this from the TopConfiguration - // A blank vector will setup all systematics + ///-- JER uncertainties model --/// + if (m_config->jetJERSmearingModel() == "Full" || m_config->jetJERSmearingModel() == "All") m_doFull_JER = true; + if (m_config->jetJERSmearingModel() == "Simple") m_doFull_JER = false; + if (m_config->jetJERSmearingModel() == "Full_PseudoData" || + m_config->jetJERSmearingModel() == "All_PseudoData") m_doFull_JER_Pseudodata = true; + else m_doFull_JER_Pseudodata = false; - const std:: string& syststr = m_config->systematics(); - std::set<std::string> syst,systLargeR; - if( !m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)){ - bool ok = m_config->getSystematicsList(syststr, syst); - bool okLargeR = m_config->getSystematicsList(syststr, systLargeR); - if (!ok || !okLargeR) { - ATH_MSG_ERROR(" top::JetObjectCollectionMaker could not determine systematic list" ); - return StatusCode::FAILURE; - } - if (m_config->contains(syst, "AllJets")) { - syst.clear(); - systLargeR.clear(); - } - } + m_isMC = m_config->isMC(); + m_doMultipleJES = m_config->doMultipleJES(); - // If we are using particle flow jets then we - // don't have any uncertainties so skip - // trying to use the tools - if (!m_config->useParticleFlowJets()) { - ///-- JES systematics --/// - if (m_config->isMC()) { - std::string allNP("JET_"+m_config->jetUncertainties_NPModel()+"_"),np1("JET_NPScenario1_"),np2("JET_NPScenario2_"),np3("JET_NPScenario3_"),np4("JET_NPScenario4_"); - std::string largeR_strong("LARGERJET_Strong_"), - largeR_medium("LARGERJET_Medium_"), - largeR_weak("LARGERJET_Weak_"); - - if (!m_config->doMultipleJES()) { - specifiedSystematics( syst , m_jetUncertaintiesTool , m_systMap_AllNP , allNP ); - } - if (m_config->doMultipleJES()) { - specifiedSystematics( syst , m_jetUncertaintiesToolReducedNPScenario1 , m_systMap_ReducedNPScenario1 , np1 ); - specifiedSystematics( syst , m_jetUncertaintiesToolReducedNPScenario2 , m_systMap_ReducedNPScenario2 , np2 ); - specifiedSystematics( syst , m_jetUncertaintiesToolReducedNPScenario3 , m_systMap_ReducedNPScenario3 , np3 ); - specifiedSystematics( syst , m_jetUncertaintiesToolReducedNPScenario4 , m_systMap_ReducedNPScenario4 , np4 ); - } - if (m_config->useLargeRJets()) { - specifiedSystematics( syst , m_jetUncertaintiesToolLargeR_strong , m_systMap_LargeR_strong , largeR_strong , true); - specifiedSystematics( syst , m_jetUncertaintiesToolLargeR_medium , m_systMap_LargeR_medium , largeR_medium , true); - specifiedSystematics( syst , m_jetUncertaintiesToolLargeR_weak , m_systMap_LargeR_weak , largeR_weak , true); + ///-- Are we doing JER? Let's not repeat this logic over and over --/// + if (m_isMC) m_doJER = true; + if (!m_isMC && m_doFull_JER) m_doJER = true; + /// NB: for "Full_PseudoData", no need to smear the data, so m_doJER is false on data unless it's "Full" + + if (m_isMC || m_doFull_JER) { + if (!m_doMultipleJES) { + top::check(m_jetUncertaintiesTool.retrieve(), "Failed to retrieve JetUncertaintiesTool"); + if (m_config->jetCalibSequence() == "JMS") { + top::check(m_jetUncertaintiesToolFrozenJMS.retrieve(), "Failed to retrieve JetUncertaintiesTool (FrozenJMS)"); + } + } else { + top::check( + m_jetUncertaintiesToolReducedNPScenario1.retrieve(), + "Failed to retrieve JetUncertaintiesToolReducedNPScenario1"); + top::check( + m_jetUncertaintiesToolReducedNPScenario2.retrieve(), + "Failed to retrieve JetUncertaintiesToolReducedNPScenario2"); + top::check( + m_jetUncertaintiesToolReducedNPScenario3.retrieve(), + "Failed to retrieve JetUncertaintiesToolReducedNPScenario3"); + top::check( + m_jetUncertaintiesToolReducedNPScenario4.retrieve(), + "Failed to retrieve JetUncertaintiesToolReducedNPScenario4"); } } - ///-- JER systematics --/// - if (m_doJER) - specifiedSystematics( syst , m_jetJERSmearingTool , m_systMap_JER ); - } - - // See http://cern.ch/go/nHF6 for more information - if (m_config->doLargeRSmallRCorrelations()) { - systMap* smallR_systs = &m_systMap_AllNP; - if (m_config->doMultipleJES()) { - smallR_systs = &m_systMap_ReducedNPScenario1; - } - addCorrelation("CORR_LargeRSmallR_A", *smallR_systs, - "JET_GroupedNP_2", - m_systMap_LargeR_strong, "JET_Top_Run1_Tau32"); - - addCorrelation("CORR_LargeRSmallR_B", *smallR_systs, - "JET_GroupedNP_2", - m_systMap_LargeR_weak, "JET_Rtrk_Baseline_pT"); - - addCorrelation("CORR_LargeRSmallR_C__1up", m_systMap_LargeR_weak, - "JET_Rtrk_Baseline_mass__1up-JET_Top_Run1_Tau32__1up", - m_specifiedSystematicsLargeR); - - addCorrelation("CORR_LargeRSmallR_C__1down", m_systMap_LargeR_weak, - "JET_Rtrk_Baseline_mass__1down-JET_Top_Run1_Tau32__1down", - m_specifiedSystematicsLargeR); - } - ///-- Large R jet substructure --/// - if (m_config->jetSubstructureName() == "Trimmer") - m_jetSubstructure.reset(new top::LargeJetTrimmer); - if (m_config->jetSubstructureName() == "SubjetMaker") - m_jetSubstructure.reset(new top::SubjetMaker); - m_config->systematicsJets( specifiedSystematics() ); - m_config->systematicsLargeRJets( specifiedSystematicsLargeR() ); - m_config->systematicsTrackJets( m_specifiedSystematicsTrackJets ); - return StatusCode::SUCCESS; -} -StatusCode JetObjectCollectionMaker::executeJets() { - bool isLargeR(false); - return execute( isLargeR ); -} + top::check(m_jetUpdateJvtTool.retrieve(), "Failed to retrieve JetUpdateJvtTool"); + //fJVT tool isn't setup unless requested + if (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None") { + top::check(m_jetSelectfJvtTool.retrieve(), "Failed to retrieve JetSelectfJvtTool"); + } + // Take this from the TopConfiguration + // A blank vector will setup all systematics -StatusCode JetObjectCollectionMaker::executeLargeRJets() { - bool isLargeR(true); - return execute( isLargeR ); -} + const std:: string& syststr = m_config->systematics(); + std::set<std::string> syst, systLargeR; -StatusCode JetObjectCollectionMaker::execute( const bool isLargeR ) { - // decorating the HS jets with truth info on which are HS jets - if (!isLargeR & m_config->isMC()) { - top::check( decorateHSJets() , "Failed to decorate jets with truth info of which are HS - this is needed for JVT scale-factors!"); - } - - ///-- First calibrate the nominal jets, everything else comes from this, so let's only do it once not 3000 times --/// - top::check( calibrate( isLargeR ) , "Failed to calibrate jets"); + if (!m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)) { + bool ok = m_config->getSystematicsList(syststr, syst); + bool okLargeR = m_config->getSystematicsList(syststr, systLargeR); + if (!ok || !okLargeR) { + ATH_MSG_ERROR(" top::JetObjectCollectionMaker could not determine systematic list"); + return StatusCode::FAILURE; + } + //here the idea is that if the user specifies AllXXX, we leave syst as an empty string, so that all recommended CP + // systematics are then used + if (m_config->contains(syst, "AllJets")) { + syst.clear(); + systLargeR.clear(); + } + if (m_config->contains(syst, "AllSmallRJets")) { + syst.clear(); + } + if (m_config->contains(systLargeR, "AllLargeRJets")) { + systLargeR.clear(); + } + } - // No uncertainties yet for pflow - // - return SUCCESS after calibration - if (m_config->useParticleFlowJets()) - return StatusCode::SUCCESS; - ///-- JES, JER regular atk4 for now --/// - if (!isLargeR) { - ///-- JES --/// - if (m_config->isMC()) { - if (!m_config->doMultipleJES()) { - top::check( applySystematic( m_jetUncertaintiesTool , m_systMap_AllNP ) , "Failed to apply JES"); + ///-- JES systematics --/// + if (m_isMC || m_doFull_JER) { + std::string allNP(m_config->jetUncertainties_NPModel() + "_"), + np1("SR_Scenario1_"), np2("SR_Scenario2_"), np3("SR_Scenario3_"), np4("SR_Scenario4_"); + std::string allNP_FrozenJMS(m_config->jetUncertainties_NPModel() + "_FrozenJMS_"); + + bool onlyJER = ((!m_isMC) && m_doFull_JER) || (m_isMC && m_doFull_JER_Pseudodata); + + if (!m_doMultipleJES) { + addSystematics(syst, m_jetUncertaintiesTool->recommendedSystematics(), m_systMap_AllNP, allNP, false, onlyJER); + if (m_config->jetCalibSequence() == "JMS") { + addSystematics(syst, + m_jetUncertaintiesToolFrozenJMS->recommendedSystematics(), m_systMap_AllNP_FrozenJMS, allNP_FrozenJMS, false, + onlyJER); + } + } else { + addSystematics(syst, + m_jetUncertaintiesToolReducedNPScenario1->recommendedSystematics(), m_systMap_ReducedNPScenario1, np1, false, + onlyJER); + addSystematics(syst, + m_jetUncertaintiesToolReducedNPScenario2->recommendedSystematics(), m_systMap_ReducedNPScenario2, np2, false, + onlyJER); + addSystematics(syst, + m_jetUncertaintiesToolReducedNPScenario3->recommendedSystematics(), m_systMap_ReducedNPScenario3, np3, false, + onlyJER); + addSystematics(syst, + m_jetUncertaintiesToolReducedNPScenario4->recommendedSystematics(), m_systMap_ReducedNPScenario4, np4, false, + onlyJER); } - if (m_config->doMultipleJES()) { - top::check( applySystematic( m_jetUncertaintiesToolReducedNPScenario1 , m_systMap_ReducedNPScenario1 ) , "Failed to apply JES"); - top::check( applySystematic( m_jetUncertaintiesToolReducedNPScenario2 , m_systMap_ReducedNPScenario2 ) , "Failed to apply JES"); - top::check( applySystematic( m_jetUncertaintiesToolReducedNPScenario3 , m_systMap_ReducedNPScenario3 ) , "Failed to apply JES"); - top::check( applySystematic( m_jetUncertaintiesToolReducedNPScenario4 , m_systMap_ReducedNPScenario4 ) , "Failed to apply JES"); + } + ///-- Large-R JES systematics --/// + std::string largeRModName = getLargeRModName(m_config->largeRJetUncertainties_NPModel()); + CP::SystematicSet largeRsysts; + if (m_config->useLargeRJets() && m_config->isMC()) { //No JES uncertainties for Data at the moment + if ((m_config->largeRJESJMSConfig() == "CombMass") || (m_config->largeRJESJMSConfig() == "TCCMass")) { //TA mass + // and + // combined + // mass not + // supported + // for + // JMS/JMR + // for now + largeRsysts.insert(m_jetUncertaintiesToolLargeR->recommendedSystematics()); + } else { + ATH_MSG_WARNING( + "TA Mass & Calo Mass are not supported for large-R jet uncertainties at the moment. Large-R jet systemtatics skipped!"); } } - ///-- JER --/// - if (m_doJER) - top::check( applySystematic ( m_jetJERSmearingTool , m_systMap_JER ) , "Failed to apply JER" ); - } else { - if (m_config->isMC()) { - top::check( applySystematic( m_jetUncertaintiesToolLargeR_strong , m_systMap_LargeR_strong, true ) , "Failed to apply large-R syst."); - top::check( applySystematic( m_jetUncertaintiesToolLargeR_medium , m_systMap_LargeR_medium, true ) , "Failed to apply large-R syst."); - top::check( applySystematic( m_jetUncertaintiesToolLargeR_weak , m_systMap_LargeR_weak, true ) , "Failed to apply large-R syst."); + ///-- Large R jet tagger scale factor uncertainties -- /// + if (m_config->isMC() && m_config->useLargeRJets()) { + for (const std::pair<std::string, std::string>& name : m_config->boostedTaggerSFnames()) { + ToolHandle<ICPJetUncertaintiesTool> tmp_SF_uncert_tool("JetSFuncert_" + name.first); + if (tmp_SF_uncert_tool.retrieve()) { + largeRsysts.insert(tmp_SF_uncert_tool->recommendedSystematics()); + m_tagSFuncertTool[name.first] = tmp_SF_uncert_tool; + } + } } - } - return StatusCode::SUCCESS; -} + // add the merged set of systematics for large-R jets including the tagging SF systs + addSystematics(systLargeR, largeRsysts, m_systMap_LargeR, largeRModName, true); + + ///-- Large R jet substructure --/// + if (m_config->jetSubstructureName() == "Trimmer") m_jetSubstructure.reset(new top::LargeJetTrimmer); + + if (m_config->jetSubstructureName() == "SubjetMaker") m_jetSubstructure.reset(new top::SubjetMaker); + + ///-- Large R jet truth labeling --/// +// m_jetTruthLabelingTool = nullptr; +// if (m_config->isMC() && m_config->useLargeRJets()) { +// m_jetTruthLabelingTool = std::unique_ptr<JetTruthLabelingTool>(new JetTruthLabelingTool("JetTruthLabeling")); +// // For DAOD_PHYS we need to pass few more arguments as it uses TRUTH3 +// if (m_config->getDerivationStream() == "PHYS") { +// top::check(m_jetTruthLabelingTool->setProperty("UseTRUTH3", true), "Failed to set UseTRUTH3 for m_jetTruthLabelingTool"); +// top::check(m_jetTruthLabelingTool->setProperty("TruthBosonContainerName", "TruthBoson"), "Failed to set truth container name for m_jetTruthLabelingTool"); +// top::check(m_jetTruthLabelingTool->setProperty("TruthTopQuarkContainerName", "TruthTop"), "Failed to set truth container name for m_jetTruthLabelingTool"); +// } +// top::check(m_jetTruthLabelingTool->initialize(), "Failed to initialize m_jetTruthLabelingTool"); +// } + + // set the systematics list + m_config->systematicsJets(specifiedSystematics()); + m_config->systematicsLargeRJets(specifiedSystematicsLargeR()); + m_config->systematicsTrackJets(m_specifiedSystematicsTrackJets); + + ///-- DL1 Decoration --/// + for (const std::pair<std::string, std::string>& algo : m_config->bTagAlgo_selToolNames()) { + m_btagSelToolsDL1Decor[algo.first] = algo.second; + top::check(m_btagSelToolsDL1Decor[algo.first].retrieve(), "Failed to retrieve " + algo.first + " btagging selector for " + m_config->sgKeyJets() + ". This is required for b-tagging score decorations in EventSaver!"); + if (DLx.count(algo.first) == 0) { + DLx.emplace(algo.first, SG::AuxElement::Decorator<float>("AnalysisTop_" + algo.first)); + } + } -StatusCode JetObjectCollectionMaker::calibrate(const bool isLargeR) { - ///-- Get base jets from xAOD --/// - std::string sgKey = isLargeR ? m_config->sgKeyLargeRJets() : m_config->sgKeyJets(); + if (m_config->useTrackJets()) { + for (const std::pair<std::string, std::string>& algo : m_config->bTagAlgo_selToolNames_trkJet()) { + m_btagSelToolsDL1Decor_trkJet[algo.first] = algo.second; + top::check(m_btagSelToolsDL1Decor_trkJet[algo.first].retrieve(), "Failed to retrieve " + algo.first + " btagging selector for " + m_config->sgKeyTrackJets() + ". This is required for b-tagging score decorations in EventSaver!"); + if (DLx.count(algo.first) == 0) { + DLx.emplace(algo.first, SG::AuxElement::Decorator<float>("AnalysisTop_" + algo.first)); + } + } + } + + // initialize boosted jet taggers -- we have to do it here instead pf TopObjectSelectionTools + // because we have to apply tagger inbetween JES uncertainty tool and the tagging SF tool + if (m_config->useLargeRJets()) { + for (const std::pair<std::string, std::string>& name : m_config->boostedJetTaggers()) { + std::string fullName = name.first + "_" + name.second; + m_boostedJetTaggers[fullName] = ToolHandle<IJetSelectorTool>(fullName); + top::check(m_boostedJetTaggers[fullName].retrieve(), "Failed to retrieve " + fullName); + } + } - const xAOD::JetContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , sgKey ) , "Failed to retrieve Jets" ); + return StatusCode::SUCCESS; + } - ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); + StatusCode JetObjectCollectionMaker::executeJets(bool executeNominal) { + bool isLargeR(false); - ///-- Loop over the xAOD Container --/// - for( auto jet : *(shallow_xaod_copy.first) ){ + return execute(isLargeR, executeNominal); + } - if (!isLargeR) { ///-- small-R jets used in most analyses --/// - ///-- Calibrate jet --/// - - top::check(m_jetCalibrationTool->applyCalibration(*jet), "Failed to applyCalibration"); - - // only multiply by JSF and bJSF if one of them != 1.0 (used by top mass analysis) - float JSF = m_config -> JSF(); - float bJSF = m_config -> bJSF(); + StatusCode JetObjectCollectionMaker::executeLargeRJets(bool executeNominal) { + bool isLargeR(true); - if(JSF != 1.0 || bJSF != 1.0){ + return execute(isLargeR, executeNominal); + } - int truthflav = -1; - if(jet->isAvailable<int>("HadronConeExclTruthLabelID")){ - jet->getAttribute("HadronConeExclTruthLabelID", truthflav); + StatusCode JetObjectCollectionMaker::execute(const bool isLargeR, bool executeNominal) { + ///-- Run nominal first, if executing nominal + if (executeNominal) { + // decorating the HS jets with truth info on which are HS jets + if (!isLargeR & m_isMC) { + top::check( + decorateHSJets(), + "Failed to decorate jets with truth info of which are HS - this is needed for JVT scale-factors!"); + if (m_isMC && m_config->jetResponseMatchingDeltaR() > 0) { + top::check(decorateMatchedTruth(), "Failed to decorate matched jet"); } - - xAOD::JetFourMom_t jet_p4 = jet->jetP4()*JSF; - if(truthflav == 5) jet_p4 = jet_p4*bJSF; - - jet -> setJetP4(jet_p4); - } - // end application JSF/bJSF + // Decorate the DL1 variable + top::check(decorateDL1(), "Failed to decorate jets with DL1 b-tagging discriminant"); - top::check(decorateBJets(*jet), "Failed to decorate if b-jet"); + ///-- First calibrate the nominal jets, everything else comes from this, so let's only do it once not 3000 times + // --/// + top::check(calibrate(isLargeR), "Failed to calibrate jets"); + + ///-- Return after calibrating the nominal --/// + return StatusCode::SUCCESS; } - if (isLargeR && m_jetSubstructure.get() != nullptr) { - m_jetSubstructure->correctJet( *jet ); + ///-- Systematics from here --/// + + ///-- JES, JER regular atk4 for now --/// + if (!isLargeR) { + ///-- JES --/// + if (m_isMC || m_doFull_JER) { + if (!m_doMultipleJES) { + top::check(applySystematic(m_jetUncertaintiesTool, m_systMap_AllNP), "Failed to apply JES"); + if (m_config->jetCalibSequence() == "JMS") { + top::check(applySystematic(m_jetUncertaintiesToolFrozenJMS, + m_systMap_AllNP_FrozenJMS), "Failed to apply JES Frozen JMS"); + } + } + if (m_doMultipleJES) { + top::check(applySystematic(m_jetUncertaintiesToolReducedNPScenario1, + m_systMap_ReducedNPScenario1), "Failed to apply JES"); + top::check(applySystematic(m_jetUncertaintiesToolReducedNPScenario2, + m_systMap_ReducedNPScenario2), "Failed to apply JES"); + top::check(applySystematic(m_jetUncertaintiesToolReducedNPScenario3, + m_systMap_ReducedNPScenario3), "Failed to apply JES"); + top::check(applySystematic(m_jetUncertaintiesToolReducedNPScenario4, + m_systMap_ReducedNPScenario4), "Failed to apply JES"); + } + } + } else { + // tag calibrated (nominal) jets -- the tagging information will be available + // for systematically-shifted shallow copies as well + top::check(tagNominalLargeRJets(), "Failed to tag large-R jets"); + if (m_config->isMC()) { + top::check(applySystematic(m_jetUncertaintiesToolLargeR, m_systMap_LargeR, + true), "Failed to apply large-R syst."); + } } - if (isLargeR) { - ///-- Calibrate jet --/// + return StatusCode::SUCCESS; + } - float tau3 = jet->getAttribute<float>("Tau3_wta"); - float tau2 = jet->getAttribute<float>("Tau2_wta"); - float tau1 = jet->getAttribute<float>("Tau1_wta"); + StatusCode JetObjectCollectionMaker::calibrate(const bool isLargeR) { + ///-- Get base jets from xAOD --/// + std::string sgKey = isLargeR ? m_config->sgKeyLargeRJets() : m_config->sgKeyJets(); - jet -> auxdecor<float>("Tau32_wta") = fabs(tau2) > 1.e-6 ? (tau3/tau2) : -999; // 999 to match JetSubStructureMomentTools/NSubjettinessRatiosTool - jet -> auxdecor<float>("Tau21_wta") = fabs(tau1) > 1.e-6 ? (tau2/tau1) : -999; // 999 to match JetSubStructureMomentTools/NSubjettinessRatiosTool + const xAOD::JetContainer* xaod(nullptr); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve Jets"); + + ///-- Shallow copy of the xAOD --/// + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer(*xaod); + + ///-- Loop over the xAOD Container --/// +// for (const auto jet : *(shallow_xaod_copy.first)) { +// if (!isLargeR) { ///-- small-R jets used in most analyses --/// +// ///-- Calibrate jet --/// +// +// top::check(m_jetCalibrationTool->applyCalibration(*jet), "Failed to applyCalibration"); +// +// // only multiply by JSF and bJSF if one of them != 1.0 (used by top mass analysis) +// float JSF = m_config->JSF(); +// float bJSF = m_config->bJSF(); +// +// if (JSF != 1.0 || bJSF != 1.0) { +// int truthflav = -1; +// if (jet->isAvailable<int>("PartonTruthLabelID")) { +// jet->getAttribute("PartonTruthLabelID", truthflav); +// } +// +// xAOD::JetFourMom_t jet_p4 = jet->jetP4() * JSF; +// if (truthflav == 5) jet_p4 = jet_p4 * bJSF; +// +// jet->setJetP4(jet_p4); +// } +// // end application JSF/bJSF +// +// +// top::check(decorateBJets(*jet), "Failed to decorate if b-jet"); +// } +// +// if (isLargeR && m_jetSubstructure.get() != nullptr) { +// m_jetSubstructure->correctJet(*jet); +// } +// +// if (isLargeR) { +// ///-- Calibrate jet --/// +// +// float tau3 = jet->getAttribute<float>("Tau3_wta"); +// float tau2 = jet->getAttribute<float>("Tau2_wta"); +// float tau1 = jet->getAttribute<float>("Tau1_wta"); +// float ECF1 = jet->getAttribute<float>("ECF1"); +// float ECF2 = jet->getAttribute<float>("ECF2"); +// float ECF3 = jet->getAttribute<float>("ECF3"); +// +// jet->auxdecor<float>("Tau32_wta") = fabs(tau2) > 1.e-6 ? (tau3 / tau2) : -999; // 999 to match +// // JetSubStructureMomentTools/NSubjettinessRatiosTool +// jet->auxdecor<float>("Tau21_wta") = fabs(tau1) > 1.e-6 ? (tau2 / tau1) : -999; // 999 to match +// // JetSubStructureMomentTools/NSubjettinessRatiosTool +// // Same definition as in JetSubStructureMomentTools/Root/EnergyCorrelatorRatiosTool.cxx +// jet->auxdecor<float>("D2") = (ECF2 > 1e-8) ? (ECF3*ECF1*ECF1*ECF1) / (ECF2*ECF2*ECF2) : -999; +// jet->auxdecor<float>("C2") = (ECF2 > 1e-8) ? (ECF3*ECF1) / (ECF2*ECF2) : -999; +// jet->auxdecor<float>("E3") = (ECF1 > 1e-8) ? ECF3 / (ECF1*ECF1*ECF1) : -999; +// +// +// top::check(m_jetCalibrationToolLargeR->applyCalibration(*jet), "Failed to applyCalibration"); +// +// ///-- for TA mass or calo mass, the calibrated mass or pt needs special treatment --/// +// const std::string calibChoice = m_config->largeRJESJMSConfig(); +// if (m_config->isMC()) { +// ///-- Truth labeling required by the large-R jet uncertainties --/// +//// top::check(m_jetTruthLabelingTool->modifyJet(*jet), "Failed to do truth labeling for large-R jet"); +// if (calibChoice == "TAMass") { +// xAOD::JetFourMom_t jet_calib_p4; +// jet->getAttribute<xAOD::JetFourMom_t>("JetJMSScaleMomentumTA", jet_calib_p4); +// jet->setJetP4(jet_calib_p4); +// } +// } else { //For data, there's only one config file so special method is required for TA mass and Calos mass +// if (calibChoice == "CaloMass") { +// xAOD::JetFourMom_t jetInsituP4_calo; +// jet->getAttribute<xAOD::JetFourMom_t>("JetInsituScaleMomentumCalo", jetInsituP4_calo); +// jet->setJetP4(jetInsituP4_calo); +// } else if (calibChoice == "TAMass") { +// xAOD::JetFourMom_t jetInsituP4_ta; +// jet->getAttribute<xAOD::JetFourMom_t>("JetInsituScaleMomentumTA", jetInsituP4_ta); +// jet->setJetP4(jetInsituP4_ta); +// } +// } +// } +// +// ///-- Update JVT --/// +// if (!isLargeR) { +// jet->auxdecor<float>("AnalysisTop_JVT") = m_jetUpdateJvtTool->updateJvt(*jet); +// } +// } + + // Check if the derivation we are running on contains + // MET_Track (once), if so apply the fJVT decoration + // if not then don't + if (!isLargeR && (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None")) { + static bool checked_track_MET = false; + if (!checked_track_MET) { + if (evtStore()->contains<xAOD::MissingETContainer>("MET_Track")) { + m_do_fjvt = true; + } else { + ATH_MSG_ERROR(" Cannot retrieve MET_Track, fJVT values can't be calculated correctly!!"); + return StatusCode::FAILURE; + } + checked_track_MET = true; + } + } + if (m_do_fjvt) { + top::check(!m_jetSelectfJvtTool->modify(*shallow_xaod_copy.first), + "Failed to apply fJVT decoration"); + } - top::check( m_jetCalibrationToolLargeR->applyCalibration( *jet ) , "Failed to applyCalibration" ); + if (!isLargeR) { + ///-- Save calibrated jet to TStore --/// + ///-- set links to original objects- needed for MET calculation --/// + // NOTE, if we use one of the b-tagging re-trained collections, we need to load + // the original uncalibrated jet container to which the b-tagging shallow-copy is pointing to + const xAOD::JetContainer* xaod_original(nullptr); + // for small-R jet collections, set links to uncalibrated *original* jets (not BTagging shallow-copy) + if (m_config->sgKeyJets() != m_config->sgKeyJetsType()) { + top::check(evtStore()->retrieve(xaod_original, + m_config->sgKeyJetsType()), + "Failed to retrieve uncalibrated Jets for METMaker!"); + } else { + xaod_original = xaod; + } + bool setLinks = xAOD::setOriginalObjectLink(*xaod_original, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for jets, MET recalculation may struggle"); } - ///-- Update JVT --/// + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey; if (!isLargeR) { - jet->auxdecor<float>("AnalysisTop_JVT") = m_jetUpdateJvtTool->updateJvt( *jet ); + outputSGKey = m_config->sgKeyJetsStandAlone(m_nominalSystematicSet.hash()); } - - } - - // Check if the derivation we are running on contains - // MET_Track (once), if so apply the fJVT decoration - // if not then don't - static bool checked_track_MET = false; - if (!checked_track_MET) { - if (evtStore()->contains<xAOD::MissingETContainer>("MET_Track")) { - m_do_fjvt = true; + if (isLargeR) { + outputSGKey = m_config->sgKeyLargeRJets(m_nominalSystematicSet.hash()); } - else { - if (m_config->fwdJetAndMET() == "fJVT") - ATH_MSG_ERROR(" Cannot retrieve MET_Track while fJVT is to be applied on forward jets" ); - else - ATH_MSG_WARNING(" Cannot retrieve MET_Track, so fJVT information will probably be wrong in output" ); + + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; } - checked_track_MET = true; - } - if (m_do_fjvt) { - top::check(!m_fjvtTool->modify(*shallow_xaod_copy.first), - "Failed to apply fJVT decoration"); + return StatusCode::SUCCESS; } - ///-- Save calibrated jet to TStore --/// - ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for jets, MET recalculation may struggle" ); + StatusCode JetObjectCollectionMaker::applySystematic(ToolHandle<ICPJetUncertaintiesTool>& tool, + const std::unordered_map<CP::SystematicSet, + CP::SystematicSet>& map, + bool isLargeR) { + ///-- Get calibrated jets --/// + const xAOD::JetContainer* xaod(nullptr); - ///-- Save corrected xAOD Container to StoreGate / TStore --/// - std::string outputSGKey; - if (!isLargeR) { - outputSGKey = m_config->sgKeyJetsStandAlone( m_nominalSystematicSet.hash() ); - } - if (isLargeR) { - outputSGKey = m_config->sgKeyLargeRJets( m_nominalSystematicSet.hash() ); - } + if (!isLargeR) { + top::check(evtStore()->retrieve(xaod, m_config->sgKeyJetsStandAlone( + m_nominalSystematicSet.hash())), "Failed to retrieve Jets"); + } else { + top::check(evtStore()->retrieve(xaod, m_config->sgKeyLargeRJets( + m_nominalSystematicSet.hash())), "Failed to retrieve Jets"); + } - std::string outputSGKeyAux = outputSGKey + "Aux."; + ///-- Loop over the systematics --/// - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } + for (Itr syst = map.begin(); syst != map.end(); ++syst) { + ///-- Don't do the nominal, we've already done that --/// + if ((*syst).second.hash() != m_nominalSystematicSet.hash()) { + ///-- Tell the tool which systematic to use --/// + ///-- Here we use the second, original CP::SystematicSet --/// + top::check(tool->applySystematicVariation((*syst).second), + "Failed to applySystematicVariation"); - return StatusCode::SUCCESS; -} + if (isLargeR && m_config->isMC()) { + // for boosted tagging SFs, apply syst variation for all initialized WPs + for (std::pair<const std::string, ToolHandle<ICPJetUncertaintiesTool> >& tagSF : m_tagSFuncertTool) { + top::check(tagSF.second->applySystematicVariation((*syst).second), "Failed to applySystematicVariation"); + } + } + ///-- Shallow copy of the xAOD --/// + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > + shallow_xaod_copy = xAOD::shallowCopyContainer(*xaod); + + ///-- Loop over the xAOD Container --/// + for (auto jet : *(shallow_xaod_copy.first)) { + if (isLargeR && m_config->isMC()) { //JES for large-R jets only exist for MC + ///-- Only large R jets with the following properties can be calibrated.--/// + bool calibratable_jet = (std::fabs(jet->eta()) <= 2.0 + && jet->pt() > 175e3); //lower than 200e3 to allow studying on migration + std::string jetCalibrationNameLargeR = m_config->sgKeyLargeRJets(); + if (jetCalibrationNameLargeR.find("TrackCaloCluster") != std::string::npos) { //TCC jet + calibratable_jet = (jet->m() / jet->pt() <= 1. + && jet->m() / jet->pt() >= 0. + && std::fabs(jet->eta()) <= 2.0 + && jet->pt() > 150e3 + && jet->pt() < 3000e3); + } + if (!calibratable_jet) continue; + } + ///-- Apply Corrrection --/// + if (!(isLargeR && !m_config->isMC())) { //Large-R jet uncertainties don't apply to Data + top::check(tool->applyCorrection(*jet), "Failed to applyCorrection"); + } + ///-- Update JVT --/// + if (!isLargeR) jet->auxdecor<float>("AnalysisTop_JVT") = m_jetUpdateJvtTool->updateJvt(*jet); + + ///-- Decorate fJVT for systematics too --/// + // Check if the derivation we are running on contains + // MET_Track (once) before applying the fJVT decoration + if (!isLargeR && (m_config->doForwardJVTinMET() || m_config->getfJVTWP() != "None")) { + static bool checked_track_MET = false; + if (!checked_track_MET) { + if (evtStore()->contains<xAOD::MissingETContainer>("MET_Track")) { + m_do_fjvt = true; + } else { + ATH_MSG_ERROR(" Cannot retrieve MET_Track, fJVT values can't be calculated correctly!!"); + return StatusCode::FAILURE; + } + checked_track_MET = true; + } + } + if (m_do_fjvt) { + top::check(!m_jetSelectfJvtTool->modify(*shallow_xaod_copy.first), + "Failed to apply fJVT decoration"); + } + + + ///-- Apply large-R jet tagging SF uncertainties --/// + if (isLargeR && m_config->isMC()) { + for (std::pair<const std::string, ToolHandle<ICPJetUncertaintiesTool> >& tagSF : m_tagSFuncertTool) { + top::check(tagSF.second->applyCorrection(*jet), "Failed to applyCorrection"); + } + } + } -StatusCode JetObjectCollectionMaker::applySystematic(ToolHandle<ICPJetUncertaintiesTool>& tool, - const std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map, - bool isLargeR ) { - ///-- Get calibrated jets --/// - const xAOD::JetContainer* xaod(nullptr); - if (!isLargeR) { - top::check( evtStore()->retrieve( xaod , m_config->sgKeyJetsStandAlone( m_nominalSystematicSet.hash() ) ) , "Failed to retrieve Jets" ); - } else { - top::check( evtStore()->retrieve( xaod , m_config->sgKeyLargeRJets( m_nominalSystematicSet.hash() ) ) , "Failed to retrieve Jets" ); - } + ///-- set links to original objects- needed for MET calculation --/// + bool setLinks = xAOD::setOriginalObjectLink(*xaod, + *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links" + " for jets, MET recalculation may struggle"); - ///-- Loop over the systematics --/// - - for (Itr syst=map.begin();syst!=map.end();++syst) { - ///-- Don't do the nominal, we've already done that --/// - if ((*syst).second.hash() != m_nominalSystematicSet.hash()) { - - ///-- Tell the tool which systematic to use --/// - ///-- Here we use the second, original CP::SystematicSet --/// - top::check( tool->applySystematicVariation((*syst).second) , - "Failed to applySystematicVariation" ); - - ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > - shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); - - ///-- Loop over the xAOD Container --/// - for( auto jet : *(shallow_xaod_copy.first) ){ - + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + ///-- Here we use the first, AnalysisTop modified CP::SystematicSer --/// + ///-- This allows us to run multiple JES scenarios, which all have the same hash values --/// + std::string outputSGKey; if (isLargeR) { - - if ((*syst).first.name().find("LARGER") == std::string::npos) - continue; - - ///-- Only large R jets with the following properties can be calibrated.--/// - bool calibratable_jet = (jet->m()/jet->pt() <= 1 - && std::fabs(jet->eta()) <= 2.0 - && jet->pt() > 150e3 - && jet->pt() < 3000e3); - if(!calibratable_jet) - continue; + outputSGKey = m_config->sgKeyLargeRJets((*syst).first.hash()); + } else { + outputSGKey = m_config->sgKeyJetsStandAlone((*syst).first.hash()); } - ///-- Apply Corrrection --/// - top::check( tool->applyCorrection( *jet ) , "Failed to applyCorrection" ); - ///-- Update JVT --/// - if (!isLargeR) jet->auxdecor<float>("AnalysisTop_JVT") = m_jetUpdateJvtTool->updateJvt( *jet ); - } - - ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink(*xaod, - *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links" - " for jets, MET recalculation may struggle" ); - - ///-- Save corrected xAOD Container to StoreGate / TStore --/// - ///-- Here we use the first, AnalysisTop modified CP::SystematicSer --/// - ///-- This allows us to run multiple JES scenarios, which all have the same hash values --/// - std::string outputSGKey; - if (isLargeR) { - outputSGKey = m_config->sgKeyLargeRJets( (*syst).first.hash() ); - } else { - outputSGKey = m_config->sgKeyJetsStandAlone( (*syst).first.hash() ); - } - std::string outputSGKeyAux = outputSGKey + "Aux."; + std::string outputSGKeyAux = outputSGKey + "Aux."; - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } } } - } - return StatusCode::SUCCESS; -} + return StatusCode::SUCCESS; + } + StatusCode JetObjectCollectionMaker::executeTrackJets(bool executeNominal) { + ///-- No calibrations or systematics yet --/// + ///-- Only run this on the nominal execution --/// + if (!executeNominal) return StatusCode::SUCCESS; + top::check(decorateDL1(true), "Failed to decorate track jets with DL1 b-tagging discriminant"); -StatusCode JetObjectCollectionMaker::applySystematic(ToolHandle<IJERSmearingTool>& tool, - const std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map ) { - ///-- Get calibrated jets --/// - const xAOD::JetContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyJetsStandAlone( m_nominalSystematicSet.hash() ) ) , "Failed to retrieve Jets" ); - ///-- Loop over the systematics --/// + ///-- Just make a shallow copy to keep these in line with everything else --/// - for (Itr syst=map.begin();syst!=map.end();++syst) { - ///-- Don't do the nominal, we've already done that --/// - if ((*syst).second.hash() != m_nominalSystematicSet.hash()) { + const xAOD::JetContainer* xaod(nullptr); + top::check(evtStore()->retrieve(xaod, m_config->sgKeyTrackJets()), "Failed to retrieve Jets"); - ///-- Tell the tool which systematic to use --/// - ///-- Here we use the second, original CP::SystematicSet --/// - top::check( tool->applySystematicVariation( (*syst).second ) , "Failed to apply systematic" ); + ///-- Shallow copy of the xAOD --/// + std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer(*xaod); - ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); + ///-- set links to original objects --/// + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for track jets"); - ///-- Loop over the xAOD Container --/// - for( auto jet : *(shallow_xaod_copy.first) ){ - ///-- Apply Corrrection --/// - top::check( tool->applyCorrection( *jet ) , "Failed to applyCorrection" ); - ///-- Update JVT --/// - jet->auxdecor<float>("AnalysisTop_JVT") = m_jetUpdateJvtTool->updateJvt( *jet ); - } + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeyTrackJets(m_config->nominalHashValue()); + std::string outputSGKeyAux = outputSGKey + "Aux."; - ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for jets, MET recalculation may struggle" ); - - ///-- Save corrected xAOD Container to StoreGate / TStore --/// - ///-- Here we use the first, AnalysisTop modified CP::SystematicSer --/// - ///-- This allows us to run multiple JES scenarios, which all have the same hash values --/// - std::string outputSGKey = m_config->sgKeyJetsStandAlone( (*syst).first.hash() ); - std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; } + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} + StatusCode JetObjectCollectionMaker::printoutJets() { + bool isLargeR(false); -StatusCode JetObjectCollectionMaker::executeTrackJets() { - ///-- No calibrations or systematics yet --/// - ///-- Just make a shallow copy to keep these in line with everything else --/// - - const xAOD::JetContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyTrackJets() ) , "Failed to retrieve Jets" ); - - ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::JetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); - - ///-- set links to original objects --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for track jets" ); + return this->printout(isLargeR); + } - ///-- Save corrected xAOD Container to StoreGate / TStore --/// - std::string outputSGKey = m_config->sgKeyTrackJets( m_config->nominalHashValue() ); - std::string outputSGKeyAux = outputSGKey + "Aux."; + StatusCode JetObjectCollectionMaker::printoutLargeRJets() { + bool isLargeR(true); - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ - return StatusCode::FAILURE; + return this->printout(isLargeR); } - return StatusCode::SUCCESS; -} - -StatusCode JetObjectCollectionMaker::printoutJets() { - bool isLargeR(false); - return this->printout( isLargeR ); -} - -StatusCode JetObjectCollectionMaker::printoutLargeRJets() { - bool isLargeR(true); - return this->printout( isLargeR ); -} - -StatusCode JetObjectCollectionMaker::printout( const bool isLargeR ) { - ///-- Loop over all systematics --/// - for( auto s : m_specifiedSystematics ){ - std::string sgKey = isLargeR ? m_config->sgKeyLargeRJets() : m_config->sgKeyJets(); - const xAOD::JetContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , sgKey ) , "Failed to retrieve Jets" ); + StatusCode JetObjectCollectionMaker::printout(const bool isLargeR) { + ///-- Loop over all systematics --/// + for (auto s : m_specifiedSystematics) { + std::string sgKey = isLargeR ? m_config->sgKeyLargeRJets() : m_config->sgKeyJets(); - ATH_MSG_INFO(" Jets with sgKey = "<<sgKey ); - for( auto x : *xaod ){ - ATH_MSG_INFO(" Jet pT , eta = "<<x->pt()<<" , "<<x->eta() ); - } - } + const xAOD::JetContainer* xaod(nullptr); + top::check(evtStore()->retrieve(xaod, sgKey), "Failed to retrieve Jets"); - return StatusCode::SUCCESS; -} + ATH_MSG_INFO(" Jets with sgKey = " << sgKey); + for (auto x : *xaod) { + ATH_MSG_INFO(" Jet pT , eta = " << x->pt() << " , " << x->eta()); + } + } + return StatusCode::SUCCESS; + } -void JetObjectCollectionMaker::specifiedSystematics(const std::set<std::string>& specifiedSystematics, - const ToolHandle<ICPJetUncertaintiesTool>& tool, - std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map, - const std::string& modName, bool isLargeR ) { + std::string JetObjectCollectionMaker::getLargeRModName(const std::string& NPModel) const { + if (NPModel.find("CategoryReduction")!=std::string::npos) return "CategoryReduction_"; + return NPModel+"_"; + } - ///-- MC only --/// - if (m_config->isMC()) { + void JetObjectCollectionMaker::addSystematics(const std::set<std::string>& specifiedSystematics, + const CP::SystematicSet& recommendedSysts, + std::unordered_map<CP::SystematicSet, CP::SystematicSet>& map, + const std::string& modName, bool isLargeR, bool onlyJER) { ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( tool->recommendedSystematics() ); + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector(recommendedSysts); + - for (auto s : systList) { + for (const CP::SystematicSet& s : systList) { if (s.size() == 1) { CP::SystematicSet::const_iterator ss = s.begin(); - CP::SystematicSet modSet( modName + ss->name() ); + if(!m_config->getTreeFilter()->filterTree(modName + ss->name())) continue; // Applying tree filter + + if (onlyJER && ss->name().find("JER") == std::string::npos) continue; + + CP::SystematicSet modSet(modName + ss->name()); m_recommendedSystematics.push_back(modSet); - if (!m_config->isSystNominal( m_config->systematics() )) { + if (!m_config->isSystNominal(m_config->systematics())) { if (specifiedSystematics.size() == 0) { - if (!isLargeR) - m_specifiedSystematics.push_back(modSet); - else - m_specifiedSystematicsLargeR.push_back(modSet); - map.insert( std::make_pair(modSet,s) ); - } else if (specifiedSystematics.size() > 0) { - for (auto i : specifiedSystematics) { - if ( i == modSet.name() ) { - if (!isLargeR) - m_specifiedSystematics.push_back(modSet); - else - m_specifiedSystematicsLargeR.push_back(modSet); - map.insert( std::make_pair(modSet,s) ); + if (!isLargeR) m_specifiedSystematics.push_back(modSet); + else m_specifiedSystematicsLargeR.push_back(modSet); + map.insert(std::make_pair(modSet, s)); + } else if (specifiedSystematics.size() > 0) { + for (std::string i : specifiedSystematics) { + TreeFilter filter(i); + if (!filter.filterTree(modSet.name())) { + if (!isLargeR) m_specifiedSystematics.push_back(modSet); + else m_specifiedSystematicsLargeR.push_back(modSet); + map.insert(std::make_pair(modSet, s)); } } } // User has specified a systematic - } // Don't do anything if the user requests nominal only } // size() == 1 -- this means that there is a CP::SystematicVariation } // Loop over systList - } // MC only - m_recommendedSystematics.sort(); - m_recommendedSystematics.unique(); - - m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); - - m_specifiedSystematicsLargeR.sort(); - m_specifiedSystematicsLargeR.unique(); -} + m_recommendedSystematics.sort(); + m_recommendedSystematics.unique(); + m_specifiedSystematics.sort(); + m_specifiedSystematics.unique(); + m_specifiedSystematicsLargeR.sort(); + m_specifiedSystematicsLargeR.unique(); + } -///-- Don't really need to do this, but would rather stay consistent with JetObjectCollectionMaker --/// -///-- This could be done like all the other xyzObjectCollectionMakers, but would need to change the way execute() works --/// -void JetObjectCollectionMaker::specifiedSystematics( const std::set<std::string>& specifiedSystematics, - const ToolHandle<IJERSmearingTool>& tool, - std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map ) { - ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( tool->recommendedSystematics() ); + StatusCode JetObjectCollectionMaker::tagNominalLargeRJets() { + const xAOD::JetContainer* xaod_calibrated_jets(nullptr); - for (auto s : systList) { - m_recommendedSystematics.push_back(s); + top::check(evtStore()->retrieve(xaod_calibrated_jets, m_config->sgKeyLargeRJets( + m_nominalSystematicSet.hash())), + "Failed to retrieve nominal calibrated large-R jets"); + for (const xAOD::Jet* jet : *xaod_calibrated_jets) { + top::check(tagLargeRJet(*jet), "Failed to tag large-R jet"); + } + return StatusCode::SUCCESS; + } - ///-- Are we doing JER? Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (m_doJER) { - if (!m_config->isSystNominal( m_config->systematics() )) { - if (specifiedSystematics.size() == 0) { - m_specifiedSystematics.push_back(s); - map.insert( std::make_pair(s,s) ); - } - if (specifiedSystematics.size() > 0) { - for (auto i : specifiedSystematics) { - if ( i == s.name() ) { - m_specifiedSystematics.push_back(s); - map.insert( std::make_pair(s,s) ); - } - } - } + StatusCode JetObjectCollectionMaker::tagLargeRJet(const xAOD::Jet& jet) { + //decorate with boosted-tagging flags + for (const std::pair<std::string, std::string>& name : m_config->boostedJetTaggers()) { + std::string fullName = name.first + "_" + name.second; +// const Root::TAccept& result = m_boostedJetTaggers[fullName]->tag(jet); + // TAccept has bool operator overloaded, but let's be more explicit in the output to char +// jet.auxdecor<char>("isTagged_" + fullName) = (result ? 1 : 0); + jet.auxdecor<char>("isTagged_" + fullName) = 0; + // for users to extract more detailed tagging result information in custom event saver + //jet.auxdecor<unsigned long>("TAccept_bitmap_" + fullName) = result.getCutResultBitSet().to_ulong(); + } + return StatusCode::SUCCESS; + } + + StatusCode JetObjectCollectionMaker::decorateBJets(xAOD::Jet& jet) { + // initialise decorator and accessor + static SG::AuxElement::Decorator<char> isbjet("IsBjet"); + static const std::string labelB = "PartonTruthLabelID"; + static SG::AuxElement::Accessor<int> truth_label(labelB); + + // Is b-jet if truth label == 5 and pT > 15 GeV + isbjet(jet) = (jet.pt() > 15000. && truth_label(jet) == 5); + + return StatusCode::SUCCESS; + } + + StatusCode JetObjectCollectionMaker::decorateHSJets() { + // initialise decorator + static SG::AuxElement::Decorator<char> isHS("AnalysisTop_isHS"); + + // retrieve small-R jets collection + const xAOD::JetContainer* jets(nullptr); + + top::check(evtStore()->retrieve(jets, + m_config->sgKeyJets()), + "Failed to retrieve small-R jet collection" + m_config->sgKeyJets()); + + // retrieve truth jet collection + const xAOD::JetContainer* truthJets = nullptr; + top::check(evtStore()->retrieve(truthJets, + m_truthJetCollForHS), + "Unable to retrieve truth jet container " + m_truthJetCollForHS + + " - this is needed to define HS jets for application of JVT"); + + for (const auto& jet : *jets) { + bool ishs = false; + for (const auto& tjet : *truthJets) { + if (tjet->p4().DeltaR(jet->p4()) < 0.3 && tjet->pt() > 10e3) ishs = true; } + isHS(*jet) = ishs; } + + return StatusCode::SUCCESS; } - m_recommendedSystematics.sort(); - m_recommendedSystematics.unique(); - m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); -} - -StatusCode JetObjectCollectionMaker::decorateBJets(xAOD::Jet& jet) { - // initialise decorator and accessor - static SG::AuxElement::Decorator<char> isbjet("IsBjet"); - static const std::string labelB = "HadronConeExclTruthLabelID"; - static SG::AuxElement::Accessor<int> truth_label(labelB); - - // Is b-jet if truth label == 5 and pT > 20 GeV - isbjet(jet) = (jet.pt() > 20000. && truth_label(jet) == 5); - - return StatusCode::SUCCESS; -} - -StatusCode JetObjectCollectionMaker::decorateHSJets() { - // initialise decorator - static SG::AuxElement::Decorator<char> isHS("AnalysisTop_isHS"); - // retrieve small-R jets collection - const xAOD::JetContainer* jets(nullptr); - top::check( evtStore()->retrieve( jets , m_config->sgKeyJets() ) , "Failed to retrieve small-R jet collection"+m_config->sgKeyJets() ); - - // retrieve truth jet collection - const xAOD::JetContainer *truthJets = nullptr; - top::check( evtStore()->retrieve(truthJets, m_truthJetCollForHS) , "Unable to retrieve truth jet container "+m_truthJetCollForHS+" - this is needed to define HS jets for application of JVT" ); - - for(const auto& jet : *jets) { - bool ishs = false; - for(const auto& tjet : *truthJets) { - if (tjet->p4().DeltaR(jet->p4())<0.3 && tjet->pt()>10e3) ishs = true; + StatusCode JetObjectCollectionMaker::decorateMatchedTruth() { + static const SG::AuxElement::Decorator<float> matchedPt("AnalysisTop_MatchedTruthJetPt"); + // retrieve small-R jets collection + const xAOD::JetContainer* jets(nullptr); + + top::check(evtStore()->retrieve(jets, + m_config->sgKeyJets()), + "Failed to retrieve small-R jet collection" + m_config->sgKeyJets()); + + const xAOD::JetContainer* truthJets = nullptr; + top::check(asg::AsgTool::evtStore()->retrieve(truthJets, m_config->sgKeyTruthJets()), "Failed to retrieve the truth jets"); + + const xAOD::Jet* matchedTruthJet = nullptr; + double deltaR(9999); + + for (const auto& jet : *jets) { + // loop over truth jets + for (const auto& iTruthJet : *truthJets) { + TLorentzVector truthJetTLV; + truthJetTLV.SetPtEtaPhiE(iTruthJet->pt(),iTruthJet->eta(),iTruthJet->phi(),iTruthJet->e()); + + // do the matching + if(!matchedTruthJet) { + matchedTruthJet = iTruthJet; + } else { + const double newdR = jet->p4().DeltaR(iTruthJet->p4()); + if(newdR < deltaR) { + deltaR = newdR; + matchedTruthJet = iTruthJet; + } + } + } + if (deltaR > m_config->jetResponseMatchingDeltaR()) { + matchedPt(*jet) = -9999; + continue; + } + if (!matchedTruthJet) { + matchedPt(*jet) = -9999; + continue; + } + matchedPt(*jet) = matchedTruthJet->pt(); } - isHS(*jet)=ishs; + + return StatusCode::SUCCESS; } - return StatusCode::SUCCESS; -} - -void JetObjectCollectionMaker::addCorrelation(const std::string& name, - systMap& map_one, - const std::string& syst_one_name, - systMap& map_two, - const std::string& syst_two_name) { - - std::vector<std::string> directions = {"__1up", "__1down"}; - for (const std::string& d : directions) { - std::string tree_name = name+d; - map_one.insert(std::make_pair(CP::SystematicSet(tree_name), - CP::SystematicSet(syst_one_name+d))); - map_two.insert(std::make_pair(CP::SystematicSet(tree_name), - CP::SystematicSet(syst_two_name+d))); - - m_specifiedSystematics.push_back(tree_name); - m_specifiedSystematicsLargeR.push_back(tree_name); - - } // loop through up and down + StatusCode JetObjectCollectionMaker::decorateDL1(bool trackJets) { + // retrieve small-R jets collection -- either calo or track jets + const xAOD::JetContainer* jets(nullptr); + + if (trackJets) { + top::check(evtStore()->retrieve(jets, + m_config->sgKeyTrackJets()), + "Failed to retrieve track jet collection" + m_config->sgKeyTrackJets()); + } else { + top::check(evtStore()->retrieve(jets, + m_config->sgKeyJets()), + "Failed to retrieve small-R jet collection" + m_config->sgKeyJets()); + } - m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); - - m_specifiedSystematicsLargeR.sort(); - m_specifiedSystematicsLargeR.unique(); - -} - -void JetObjectCollectionMaker::addCorrelation(const std::string& name, - systMap& map_one, - const std::string& syst_one_name, - std::list<CP::SystematicSet>& jet_specified) { - - map_one.insert(std::make_pair(CP::SystematicSet(name), - CP::SystematicSet(syst_one_name))); + for (const auto& jet : *jets) { + // loop over either calo or track jet btag selection tools to calculate the DL1x scores + const std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool>>& m_btagDecorTools \ + = (trackJets ? m_btagSelToolsDL1Decor_trkJet : m_btagSelToolsDL1Decor); + for (std::pair<std::string, ToolHandle<IBTaggingSelectionTool>> algo : m_btagDecorTools) { + double DL1_weight = -999.; + //double dl1_pb = -10.; + //double dl1_pc = -10.; + //double dl1_pu = -10.; + //if (jet->btagging()->pb(algo.first, dl1_pb) + // && jet->btagging()->pc(algo.first, dl1_pc) + // && jet->btagging()->pu(algo.first, dl1_pu)) { + // if (!algo.second->getTaggerWeight(dl1_pb, dl1_pc, dl1_pu, DL1_weight)) { + // DL1_weight = -999.; // value for errors from retrieving DL1x weight + // } + //} else { + // DL1_weight = -100.; // value for errors from nonexistence of probabilities + //} + DLx.at(algo.first)(*jet) = DL1_weight; + } + } - jet_specified.push_back(name); - - jet_specified.sort(); - jet_specified.unique(); - -} - + return StatusCode::SUCCESS; + } } // namespace top diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MissingETObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MissingETObjectCollectionMaker.cxx index d82fe4cb5f5412fdbc71b7caa69b59334bd527aa..7cb4f2beb9e1b58d77dcfbe3614ddb6244ce86c1 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MissingETObjectCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MissingETObjectCollectionMaker.cxx @@ -1,10 +1,11 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ -// $Id: MissingETObjectCollectionMaker.cxx 792986 2017-01-19 11:10:37Z grancagn $ +// $Id: MissingETObjectCollectionMaker.cxx 806051 2017-06-07 00:32:41Z tpelzer $ #include "TopSystematicObjectMaker/MissingETObjectCollectionMaker.h" #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" #include "TopEvent/EventTools.h" #include "TopEvent/SystematicEvent.h" @@ -20,311 +21,334 @@ #include "xAODCore/ShallowCopy.h" #include "PATInterfaces/SystematicsUtil.h" -namespace top{ - - MissingETObjectCollectionMaker::MissingETObjectCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), - m_config( nullptr ), +namespace top { + MissingETObjectCollectionMaker::MissingETObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), m_specifiedSystematics(), m_recommendedSystematics(), - - m_MET_core( "setMe" ), - m_MET_map( "setMe" ), + + m_MET_core("setMe"), + m_MET_map("setMe"), m_met_maker("met::METMaker"), - m_met_systematics("met::METSystematicsTool") - { - declareProperty( "config" , m_config ); - declareProperty( "METMaker" , m_met_maker ); - declareProperty( "met_systematics" , m_met_systematics ); + m_met_systematics("met::METSystematicsTool") { + declareProperty("config", m_config); + declareProperty("METMaker", m_met_maker); + declareProperty("met_systematics", m_met_systematics); } - StatusCode MissingETObjectCollectionMaker::initialize() - { - ATH_MSG_INFO(" top::MissingETObjectCollectionMaker initialize" ); + StatusCode MissingETObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::MissingETObjectCollectionMaker initialize"); - top::check( m_met_maker.retrieve() , "Failed to retrieve met maker tool" ); - top::check( m_met_systematics.retrieve() , "Failed to retrieve met systematic tool" ); + top::check(m_met_maker.retrieve(), "Failed to retrieve met maker tool"); + top::check(m_met_systematics.retrieve(), "Failed to retrieve met systematic tool"); - std::string jet_collection = m_config->sgKeyJets(); + std::string jet_collection = m_config->sgKeyJetsType(); jet_collection.erase(jet_collection.length() - 4); //erase "Jets" from jet collection name - m_MET_core = "MET_Core_"+jet_collection; - m_MET_map = "METAssoc_"+jet_collection; - + m_MET_core = "MET_Core_" + jet_collection; + m_MET_map = "METAssoc_" + jet_collection; + ///-- Set Systematics Information --/// const std:: string& syststr = m_config->systematics(); - std::set<std::string> syst; + std::set<std::string> syst; - if( !m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)){ + if (!m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)) { bool ok = m_config->getSystematicsList(syststr, syst); if (!ok) { - ATH_MSG_ERROR(" top::MissingETObjectCollectionMaker could not determine systematic list" ); + ATH_MSG_ERROR(" top::MissingETObjectCollectionMaker could not determine systematic list"); return StatusCode::FAILURE; } + //here the idea is that if the user specifies AllXXX, we leave syst as an empty string, so that all recommended CP + // systematics are then used if (m_config->contains(syst, "AllMET")) { syst.clear(); } } - - specifiedSystematics( syst ); - - m_config->systematicsMET( specifiedSystematics() ); + + specifiedSystematics(syst); + + m_config->systematicsMET(specifiedSystematics()); return StatusCode::SUCCESS; } - StatusCode MissingETObjectCollectionMaker::recalculateMET() - { - + StatusCode MissingETObjectCollectionMaker::recalculateMET(bool executeNominal) { // met core contains the soft terms we need to add to our met calculation const xAOD::MissingETContainer* xaod_met_core(nullptr); - top::check( evtStore()->retrieve( xaod_met_core , m_MET_core ) , "Failed to retrieve MET Core" ); + + top::check(evtStore()->retrieve(xaod_met_core, m_MET_core), "Failed to retrieve MET Core"); // This maps the met terms to objects - const xAOD::MissingETAssociationMap* xaod_met_map(nullptr); - top::check( evtStore()->retrieve( xaod_met_map , m_MET_map ) , "Failed to retrieve MET Association Map" ); + const xAOD::MissingETAssociationMap* xaod_met_map(nullptr); + top::check(evtStore()->retrieve(xaod_met_map, m_MET_map), "Failed to retrieve MET Association Map"); - if (!m_config->doLooseTreeOnly()) { + if (m_config->doTightEvents()) { // All the tight systematic events const xAOD::SystematicEventContainer* systEvents(nullptr); - top::check( evtStore()->retrieve(systEvents,m_config->sgKeyTopSystematicEvents()) , "Failed to retrieve TopEvents" ); - - for (auto x : *systEvents) - top::check( recalculateEventMET( x, xaod_met_core, xaod_met_map ), - "Failed to recalculate MET for event"); + if (executeNominal) { + top::check(evtStore()->retrieve(systEvents, + m_config->sgKeyTopSystematicEvents() + "Nominal"), + "Failed to retrieve nominal TopEvents"); + } else { + top::check(evtStore()->retrieve(systEvents, + m_config->sgKeyTopSystematicEvents()), "Failed to retrieve TopEvents"); + } + for (auto x : *systEvents) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(x->hashValue()))) continue; + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(x->hashValue()))) continue; + top::check(recalculateEventMET(x, xaod_met_core, xaod_met_map), "Failed to recalculate MET for event"); + if(m_config->writeMETBuiltWithLooseObjects()) top::check(recalculateEventMET(x, xaod_met_core, xaod_met_map, true, "WithLooseObjects"), "Failed to recalculate MET using loose leptons for event"); + } } // tight events if (m_config->doLooseEvents()) { // All the loose systematic events const xAOD::SystematicEventContainer* systEventsLoose(nullptr); - top::check( evtStore()->retrieve(systEventsLoose,m_config->sgKeyTopSystematicEventsLoose()) , "Failed to retrieve TopEventsLoose" ); + if (executeNominal) { + top::check(evtStore()->retrieve(systEventsLoose, + m_config->sgKeyTopSystematicEventsLoose() + "Nominal"), + "Failed to retrieve nominal TopEventsLoose"); + } else { + top::check(evtStore()->retrieve(systEventsLoose, + m_config->sgKeyTopSystematicEventsLoose()), + "Failed to retrieve TopEventsLoose"); + } - for (auto x : *systEventsLoose) - top::check( recalculateEventMET( x, xaod_met_core, xaod_met_map ), - "Failed to recalculate MET for loose event"); + for (auto x : *systEventsLoose) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(x->hashValue()))) continue; + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(x->hashValue()))) continue; + top::check(recalculateEventMET(x, xaod_met_core, xaod_met_map), "Failed to recalculate MET for loose event"); + if(m_config->writeMETBuiltWithLooseObjects()) top::check(recalculateEventMET(x, xaod_met_core, xaod_met_map, true, "WithLooseObjects"), "Failed to recalculate MET using loose leptons for event"); + } } // Loose events return StatusCode::SUCCESS; } - StatusCode MissingETObjectCollectionMaker::recalculateEventMET(xAOD::SystematicEvent* event, - const xAOD::MissingETContainer* xaod_met_core, - const xAOD::MissingETAssociationMap* xaod_met_map) { - - // decoration for objects that pass pre OR selection - std::string passPreORSelection = "passPreORSelection"; - - bool is_loose_event = (event->isLooseEvent() == 1 ? true : false); - - // default behaviour for top analysis - use the "Tight" definitions - bool looseLeptonOR(is_loose_event); - if (m_config->doOverlapRemovalOnLooseLeptonDef()) { - looseLeptonOR = true; - // change decoration we check - passPreORSelection = "passPreORSelectionLoose"; - } - - std::size_t hash = event->hashValue(); - - // Make a new MET container that we are going to use - xAOD::MissingETContainer * new_met_container = new xAOD::MissingETContainer(); - xAOD::MissingETAuxContainer * new_met_aux_container = new xAOD::MissingETAuxContainer(); - new_met_container->setStore(new_met_aux_container); - - // Reset all the met map associations - xaod_met_map->resetObjSelectionFlags(); - - // Apparently we need to add objects to the METMaker in a specific order - // Start by retrieving jet container, we need it to perform e-jet ghost-matching - xAOD::JetContainer* xaod_jet(nullptr); - top::check( evtStore()->retrieve( xaod_jet , m_config->sgKeyJets(hash,looseLeptonOR) ), "Failed to retrieve Jets" ); - // 1. Electrons - const xAOD::ElectronContainer* xaod_el(nullptr); - if(m_config->useElectrons()){ - // Get all calibrated electrons - top::check( evtStore()->retrieve( xaod_el , m_config->sgKeyElectrons(hash) ), "Failed to retrieve Electrons" ); - - // Add those that pass pre-overlap removal selection to met_electrons - ConstDataVector<xAOD::ElectronContainer> met_electrons(SG::VIEW_ELEMENTS); - for( const auto& el: *xaod_el ) - if ( el->isAvailable<char>(passPreORSelection) - && el->auxdata<char>(passPreORSelection) == 1 ) - met_electrons.push_back(el); - - // Recalculate electron MET term using electrons that pass overlap removal - top::check( m_met_maker->rebuildMET("RefEle", xAOD::Type::Electron, - new_met_container, met_electrons.asDataVector(), - xaod_met_map), "Failed to rebuild electron MET term"); - } - - // 2. Photons - if(m_config->usePhotons()){ - - // Get calibrated photons - const xAOD::PhotonContainer* xaod_photon(nullptr); - top::check( evtStore()->retrieve( xaod_photon , m_config->sgKeyPhotons(hash) ), "Failed to retrieve Photons" ); - - // Add those that pass pre-overlap removal to met_photons - ConstDataVector<xAOD::PhotonContainer> met_photons(SG::VIEW_ELEMENTS); - for( const auto& photon: *xaod_photon ) - if ( photon->isAvailable<char>(passPreORSelection) - && photon->auxdata<char>(passPreORSelection) == 1 ) - met_photons.push_back(photon); - - top::check( m_met_maker->rebuildMET("RefPhoton", xAOD::Type::Photon, - new_met_container, met_photons.asDataVector(), - xaod_met_map), "Failed to rebuild photon MET term" ); - } - - // 3. Taus - if(m_config->useTaus()){ - - // Get calibrated taus - const xAOD::TauJetContainer* xaod_tau(nullptr); - top::check( evtStore()->retrieve( xaod_tau , m_config->sgKeyTaus(hash) ), "Failed to retrieve Taus" ); - - // Add those that pass pre-overlap removal to met_taus - ConstDataVector<xAOD::TauJetContainer> met_taus(SG::VIEW_ELEMENTS); - for( const auto& tau: *xaod_tau ) - if ( tau->isAvailable<char>(passPreORSelection) - && tau->auxdata<char>(passPreORSelection) == 1 ) - met_taus.push_back(tau); - - top::check( m_met_maker->rebuildMET("RefTau", xAOD::Type::Tau, - new_met_container, met_taus.asDataVector(), - xaod_met_map), "Failed to rebuild tau MET term" ); - } - - // 4. Muons - const xAOD::MuonContainer* xaod_mu(nullptr); // Need these for ghost matching - if(m_config->useMuons()){ - // Get calibrated muons - top::check( evtStore()->retrieve( xaod_mu , m_config->sgKeyMuons(hash) ), "Failed to retrieve Muons" ); - - // Add those that pass pre-overlap removal to met_muons - ConstDataVector<xAOD::MuonContainer> met_muons(SG::VIEW_ELEMENTS); - for( const auto& mu: *xaod_mu ) - if ( mu->isAvailable<char>(passPreORSelection) - && mu->auxdata<char>(passPreORSelection) == 1 ) - met_muons.push_back(mu); - - // Recalculate muon MET term using muons that pass overlap removal - top::check( m_met_maker->rebuildMET("RefMuon", xAOD::Type::Muon, - new_met_container, met_muons.asDataVector(), - xaod_met_map), "Failed to rebuild muon MET term"); - - // Muon-jet ghost association - // performed after muon handing to METUtility, but before jets - if (xaod_mu) { - met::addGhostMuonsToJets(*xaod_mu, *xaod_jet); - } - } - - - // 5. Jets - // We do not perfom any selection on jets here. Give them all to the METMaker, it does its own thing - top::check( m_met_maker->rebuildJetMET("RefJet", "SoftClus", "PVSoftTrk", - new_met_container, xaod_jet, - xaod_met_core, xaod_met_map, - m_config->doJVTinMET() ), "Failed to rebuild jet MET term" ); - - - ///-- John thinks that the systematics go here --/// - ///-- This may well be wrong --/// - - for (auto systematic : m_specifiedSystematics) { - if (systematic.hash() == event->hashValue() && systematic.hash() != m_config->nominalHashValue() ){ - ///-- Tell tool which systematic to use --/// - top::check( m_met_systematics->applySystematicVariation( systematic ) , "Failed to applySystematicVariation" ); - - // code lifted and modified from: - // https://svnweb.cern.ch/trac/atlasoff/browser/Reconstruction/MET/METUtilities/tags/METUtilities-00-01-43/util/example_METMaker_METSystematicsTool.cxx - - //get the soft cluster term, and applyCorrection - xAOD::MissingET * softClusMet = (*new_met_container)["SoftClus"]; - if (softClusMet != nullptr) { //check we retrieved the clust term - top::check( m_met_systematics->applyCorrection(*softClusMet) , "Failed to applyCorrection" ); - } - - xAOD::MissingET * softTrkMet = (*new_met_container)["PVSoftTrk"]; - if (softTrkMet != nullptr) { //check we retrieved the soft trk - top::check( m_met_systematics->applyCorrection(*softTrkMet) , "Failed to applyCorrection" ); - } - - } - } - - /************************************************************ - We could use this to build TrackMET but should be careful as we would probably - want a different met_container and it shouldn't contain photons (and I don't think taus either...) - This function should NOT be used with the previous rebuildJetMET (one or the other) - - top::check( m_met_maker->rebuildTrackMET("RefJetTrk", "PVSoftTrk", - new_met_container, xaod_jet, - xaod_met_core, xaod_met_map, - false), "Failed to rebuild track MET term" ); - ************************************************************/ - - - // This will sum up all the contributions we've made so far e.g. - // Total MET = RefEle + RefPhoton + RefTau + RefMuon + RefJet + PVSoftTrk (Track Soft Term) - - top::check( m_met_maker->buildMETSum("FinalTrk" , new_met_container, MissingETBase::Source::Track), - "Failed to rebuild Final Track MET"); - - /************************************************************ - // We are only going to build a single MET Sum now for clarity. The final argument is the soft term we - // want to use. The recommended one is the track soft term (TST) as above. - - top::check( m_met_maker->buildMETSum("FinalClus", new_met_container, MissingETBase::Source::EMTopo), - "Failed to rebuild Final Cluster MET"); - ************************************************************/ - - // Save corrected xAOD Container to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyMissingEt(hash); - if( is_loose_event ) outputSGKey = m_config->sgKeyMissingEtLoose(hash); - std::string outputSGKeyAux = outputSGKey + "Aux."; - - xAOD::TReturnCode save = evtStore()->tds()->record( new_met_container, outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( new_met_aux_container, outputSGKeyAux ); - - if( !save || !saveAux ){ - return StatusCode::FAILURE; - } + StatusCode MissingETObjectCollectionMaker::recalculateEventMET(const xAOD::SystematicEvent* /*event*/, + const xAOD::MissingETContainer* /*xaod_met_core*/, + const xAOD::MissingETAssociationMap* /*xaod_met_map*/, + bool /*forceUseLooseObjects*/, + std::string /*outputContainerSuffix*/){ +// // decoration for objects that pass pre OR selection +// std::string passPreORSelection = "passPreORSelection"; +// +// bool is_loose_event = (event->isLooseEvent() == 1 ? true : false); +// +// // default behaviour for top analysis - use the "Tight" definitions +// bool looseLeptonOR(is_loose_event); +// if (m_config->doOverlapRemovalOnLooseLeptonDef() || (is_loose_event && m_config->useLooseObjectsInMETInLooseTree()) || (!is_loose_event && m_config->useLooseObjectsInMETInNominalTree()) || forceUseLooseObjects) { +// looseLeptonOR = true; +// // change decoration we check +// passPreORSelection = "passPreORSelectionLoose"; +// } +// +// std::size_t hash = event->hashValue(); +// +// // Make a new MET container that we are going to use +// xAOD::MissingETContainer* new_met_container = new xAOD::MissingETContainer(); +// xAOD::MissingETAuxContainer* new_met_aux_container = new xAOD::MissingETAuxContainer(); +// new_met_container->setStore(new_met_aux_container); +// +// // Reset all the met map associations +// //xaod_met_map->resetObjSelectionFlags(); +// +// // Apparently we need to add objects to the METMaker in a specific order +// // Start by retrieving jet container, we need it to perform e-jet ghost-matching +// xAOD::JetContainer* xaod_jet(nullptr); +// top::check(evtStore()->retrieve(xaod_jet, m_config->sgKeyJets(hash, looseLeptonOR)), "Failed to retrieve Jets"); +// // 1. Electrons +// const xAOD::ElectronContainer* xaod_el(nullptr); +// if (m_config->useElectrons()) { +// // Get all calibrated electrons +// top::check(evtStore()->retrieve(xaod_el, m_config->sgKeyElectrons(hash)), "Failed to retrieve Electrons"); +// +// // Add those that pass pre-overlap removal selection to met_electrons +// ConstDataVector<xAOD::ElectronContainer> met_electrons(SG::VIEW_ELEMENTS); +// for (const auto& el: *xaod_el) +// if (el->isAvailable<char>(passPreORSelection) +// && el->auxdata<char>(passPreORSelection) == 1) met_electrons.push_back(el); +// +// // Recalculate electron MET term using electrons that pass overlap removal +// top::check(m_met_maker->rebuildMET("RefEle", xAOD::Type::Electron, +// new_met_container, met_electrons.asDataVector(), +// xaod_met_map), "Failed to rebuild electron MET term"); +// } +// +// // 2. Photons +// if (m_config->usePhotons()) { +// // Get calibrated photons +// const xAOD::PhotonContainer* xaod_photon(nullptr); +// top::check(evtStore()->retrieve(xaod_photon, m_config->sgKeyPhotons(hash)), "Failed to retrieve Photons"); +// +// // Add those that pass pre-overlap removal to met_photons +// ConstDataVector<xAOD::PhotonContainer> met_photons(SG::VIEW_ELEMENTS); +// for (const auto& photon: *xaod_photon) +// if (photon->isAvailable<char>(passPreORSelection) +// && photon->auxdata<char>(passPreORSelection) == 1) met_photons.push_back(photon); +// +// top::check(m_met_maker->rebuildMET("RefPhoton", xAOD::Type::Photon, +// new_met_container, met_photons.asDataVector(), +// xaod_met_map), "Failed to rebuild photon MET term"); +// } +// +// // 3. Taus +// if (m_config->useTaus()) { +// // Get calibrated taus +// const xAOD::TauJetContainer* xaod_tau(nullptr); +// top::check(evtStore()->retrieve(xaod_tau, m_config->sgKeyTaus(hash)), "Failed to retrieve Taus"); +// +// // Add those that pass pre-overlap removal to met_taus +// ConstDataVector<xAOD::TauJetContainer> met_taus(SG::VIEW_ELEMENTS); +// for (const auto& tau: *xaod_tau) +// if (tau->isAvailable<char>(passPreORSelection) +// && tau->auxdata<char>(passPreORSelection) == 1) met_taus.push_back(tau); +// +// top::check(m_met_maker->rebuildMET("RefTau", xAOD::Type::Tau, +// new_met_container, met_taus.asDataVector(), +// xaod_met_map), "Failed to rebuild tau MET term"); +// } +// +// // 4. Muons +// const xAOD::MuonContainer* xaod_mu(nullptr); // Need these for ghost matching +// if (m_config->useMuons()) { +// // Get calibrated muons +// top::check(evtStore()->retrieve(xaod_mu, m_config->sgKeyMuons(hash)), "Failed to retrieve Muons"); +// +// // Add those that pass pre-overlap removal to met_muons +// ConstDataVector<xAOD::MuonContainer> met_muons(SG::VIEW_ELEMENTS); +// for (const auto& mu: *xaod_mu) +// if (mu->isAvailable<char>(passPreORSelection) +// && mu->auxdata<char>(passPreORSelection) == 1) met_muons.push_back(mu); +// +// // Recalculate muon MET term using muons that pass overlap removal +// top::check(m_met_maker->rebuildMET("RefMuon", xAOD::Type::Muon, +// new_met_container, met_muons.asDataVector(), +// xaod_met_map), "Failed to rebuild muon MET term"); +// +// // Muon-jet ghost association +// // performed after muon handing to METUtility, but before jets +// if (xaod_mu) { +// met::addGhostMuonsToJets(*xaod_mu, *xaod_jet); +// } +// } +// else +// { +// ConstDataVector<xAOD::MuonContainer> met_muons(SG::VIEW_ELEMENTS); +// top::check(m_met_maker->rebuildMET("RefMuon", xAOD::Type::Muon, +// new_met_container, met_muons.asDataVector(), +// xaod_met_map), "Failed to rebuild muon MET term"); +// } +// +// +// // 5. Jets +// // We do not perfom any selection on jets here. Give them all to the METMaker, it does its own thing +// top::check(m_met_maker->rebuildJetMET("RefJet", "SoftClus", "PVSoftTrk", +// new_met_container, xaod_jet, +// xaod_met_core, xaod_met_map, +// m_config->doJVTinMET()), "Failed to rebuild jet MET term"); +// +// +// ///-- John thinks that the systematics go here --/// +// ///-- This may well be wrong --/// +// +// for (auto systematic : m_specifiedSystematics) { +// if (systematic.hash() == event->hashValue() && systematic.hash() != m_config->nominalHashValue()) { +// ///-- Tell tool which systematic to use --/// +// top::check(m_met_systematics->applySystematicVariation(systematic), "Failed to applySystematicVariation"); +// +// // code lifted and modified from: +// // https://svnweb.cern.ch/trac/atlasoff/browser/Reconstruction/MET/METUtilities/tags/METUtilities-00-01-43/util/example_METMaker_METSystematicsTool.cxx +// +// //get the soft cluster term, and applyCorrection +// xAOD::MissingET* softClusMet = (*new_met_container)["SoftClus"]; +// if (softClusMet != nullptr) { //check we retrieved the clust term +// top::check(m_met_systematics->applyCorrection(*softClusMet), "Failed to applyCorrection"); +// } +// +// xAOD::MissingET* softTrkMet = (*new_met_container)["PVSoftTrk"]; +// if (softTrkMet != nullptr) { //check we retrieved the soft trk +// top::check(m_met_systematics->applyCorrection(*softTrkMet), "Failed to applyCorrection"); +// } +// } +// } +// +// /************************************************************ +// We could use this to build TrackMET but should be careful as we would probably +// want a different met_container and it shouldn't contain photons (and I don't think taus either...) +// This function should NOT be used with the previous rebuildJetMET (one or the other) +// +// top::check( m_met_maker->rebuildTrackMET("RefJetTrk", "PVSoftTrk", +// new_met_container, xaod_jet, +// xaod_met_core, xaod_met_map, +// false), "Failed to rebuild track MET term" ); +// ************************************************************/ +// +// +// // This will sum up all the contributions we've made so far e.g. +// // Total MET = RefEle + RefPhoton + RefTau + RefMuon + RefJet + PVSoftTrk (Track Soft Term) +// +// top::check(m_met_maker->buildMETSum("FinalTrk", new_met_container, MissingETBase::Source::Track), +// "Failed to rebuild Final Track MET"); +// +// /************************************************************ +// // We are only going to build a single MET Sum now for clarity. The final argument is the soft term we +// // want to use. The recommended one is the track soft term (TST) as above. +// +// top::check( m_met_maker->buildMETSum("FinalClus", new_met_container, MissingETBase::Source::EMTopo), +// "Failed to rebuild Final Cluster MET"); +// ************************************************************/ +// +// // Save corrected xAOD Container to StoreGate / TStore +// std::string outputSGKey = m_config->sgKeyMissingEt(hash); +// if (is_loose_event) outputSGKey = m_config->sgKeyMissingEtLoose(hash); +// +// outputSGKey+=outputContainerSuffix; +// std::string outputSGKeyAux = outputSGKey + "Aux."; +// +// xAOD::TReturnCode save = evtStore()->tds()->record(new_met_container, outputSGKey); +// xAOD::TReturnCode saveAux = evtStore()->tds()->record(new_met_aux_container, outputSGKeyAux); +// +// if (!save || !saveAux) { +// return StatusCode::FAILURE; +// } return StatusCode::SUCCESS; - } - - - void MissingETObjectCollectionMaker::specifiedSystematics( const std::set<std::string>& specifiedSystematics ) - { + + void MissingETObjectCollectionMaker::specifiedSystematics(const std::set<std::string>& specifiedSystematics) { ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( m_met_systematics->recommendedSystematics() ); - + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_met_systematics->recommendedSystematics()); + for (auto s : systList) { + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter + ///-- Recommendation is to use soft track terms and not soft calo terms --/// ///-- Soft calo systematics are irrelevant, let's ignore them --/// if (s.name().find("SoftCalo") == std::string::npos) { - m_recommendedSystematics.push_back(s); if (s.name() == "") { m_specifiedSystematics.push_back(s); } - + ///-- MC only --/// if (m_config->isMC()) { ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (!m_config->isSystNominal( m_config->systematics() )) { + if (!m_config->isSystNominal(m_config->systematics())) { if (specifiedSystematics.size() == 0) { m_specifiedSystematics.push_back(s); } - if (specifiedSystematics.size() > 0) { + if (specifiedSystematics.size() > 0) { for (auto i : specifiedSystematics) { - if ( i == s.name() ) { - m_specifiedSystematics.push_back(s); + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematics.push_back(s); } } } @@ -332,11 +356,9 @@ namespace top{ } } } - m_recommendedSystematics.sort(); + m_recommendedSystematics.sort(); m_recommendedSystematics.unique(); m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); - - } - + m_specifiedSystematics.unique(); + } } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MuonObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MuonObjectCollectionMaker.cxx index 737654d4492397041b17c11f1a0e026b24cf60c8..54744c284b2040661b4d2a7e99cb9050bd806a52 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MuonObjectCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/MuonObjectCollectionMaker.cxx @@ -1,12 +1,14 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ -// $Id: MuonObjectCollectionMaker.cxx 799839 2017-03-08 11:07:28Z grancagn $ +// $Id: MuonObjectCollectionMaker.cxx 810751 2017-09-29 14:41:39Z iconnell $ #include "TopSystematicObjectMaker/MuonObjectCollectionMaker.h" #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" #include "TopEvent/EventTools.h" +#include "AthContainers/AuxElement.h" #include "xAODEventInfo/EventInfo.h" #include "xAODMuon/MuonContainer.h" #include "xAODMuon/MuonAuxContainer.h" @@ -15,205 +17,380 @@ #include "xAODTracking/TrackParticlexAODHelpers.h" #include "PATInterfaces/SystematicsUtil.h" -namespace top{ - - MuonObjectCollectionMaker::MuonObjectCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + MuonObjectCollectionMaker::MuonObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), m_specifiedSystematics(), m_recommendedSystematics(), - m_calibrationTool("CP::MuonCalibrationAndSmearingTool"), - m_isolationTool_LooseTrackOnly("CP::IsolationTool_LooseTrackOnly"), - m_isolationTool_Loose("CP::IsolationTool_Loose"), - m_isolationTool_Gradient("CP::IsolationTool_Gradient"), - m_isolationTool_GradientLoose("CP::IsolationTool_GradientLoose"), - m_isolationTool_FixedCutTightTrackOnly("CP::IsolationTool_FixedCutTightTrackOnly"), - m_isolationTool_FixedCutLoose("CP::IsolationTool_FixedCutLoose"), - m_muonSelectionToolVeryLooseVeto("CP::MuonSelectionToolVeryLooseVeto") - { - declareProperty( "config" , m_config ); - - declareProperty( "MuonCalibrationAndSmearingTool" , m_calibrationTool ); - declareProperty( "IsolationTool_LooseTrackOnly" , m_isolationTool_LooseTrackOnly ); - declareProperty( "IsolationTool_Loose" , m_isolationTool_Loose ); - declareProperty( "IsolationTool_Gradient" , m_isolationTool_Gradient ); - declareProperty( "IsolationTool_GradientLoose" , m_isolationTool_GradientLoose ); - declareProperty( "IsolationTool_FixedCutTightTrackOnly" , m_isolationTool_FixedCutTightTrackOnly ); - declareProperty( "IsolationTool_FixedCutLoose" , m_isolationTool_FixedCutLoose ); - declareProperty( "MuonSelectionToolVeryLooseVeto" , m_muonSelectionToolVeryLooseVeto ); + m_calibrationPeriodTool("CP::MuonCalibrationPeriodTool"), + m_isolationTool_FCTight("CP::IsolationTool_FCTight"), + m_isolationTool_FCLoose("CP::IsolationTool_FCLoose"), + m_isolationTool_FCTightTrackOnly("CP::IsolationTool_FCTightTrackOnly"), + m_isolationTool_FCTightTrackOnly_FixedRad("CP::IsolationTool_FCTightTrackOnly_FixedRad"), + m_isolationTool_FCLoose_FixedRad("CP::IsolationTool_FCLoose_FixedRad"), + m_isolationTool_FCTight_FixedRad("CP::IsolationTool_FCTight_FixedRad"), + m_isolationTool_FixedCutPflowTight("CP::IsolationTool_FixedCutPflowTight"), + m_isolationTool_FixedCutPflowLoose("CP::IsolationTool_FixedCutPflowLoose"), + + m_isolationTool_PflowTight_FixedRad("CP::IsolationTool_PflowTight_FixedRad"), + m_isolationTool_PflowLoose_FixedRad("CP::IsolationTool_PflowLoose_FixedRad"), + m_isolationTool_PflowTight_VarRad("CP::IsolationTool_PflowTight_VarRad"), + m_isolationTool_PflowLoose_VarRad("CP::IsolationTool_PflowLoose_VarRad"), + m_isolationTool_HighPtTrackOnly("CP::IsolationTool_HighPtTrackOnly"), + m_isolationTool_TightTrackOnly_VarRad("CP::IsolationTool_TightTrackOnly_VarRad"), + m_isolationTool_TightTrackOnly_FixedRad("CP::IsolationTool_TightTrackOnly_FixedRad"), + m_isolationTool_PLVTight("CP::IsolationTool_PLVTight"), + m_isolationTool_PLVLoose("CP::IsolationTool_PLVLoose"), + m_isolationTool_Tight_VarRad("CP::IsolationTool_Tight_VarRad"), + m_isolationTool_Tight_FixedRad("CP::IsolationTool_Tight_FixedRad"), + m_isolationTool_Loose_VarRad("CP::IsolationTool_Loose_VarRad"), + m_isolationTool_Loose_FixedRad("CP::IsolationTool_Loose_FixedRad"), +// m_isolationTool_LowPtPLV("CP::IsolationTool_LowPtPLV"), + + m_muonSelectionToolVeryLooseVeto("CP::MuonSelectionToolVeryLooseVeto") { + declareProperty("config", m_config); + + declareProperty("MuonCalibrationPeriodTool", m_calibrationPeriodTool); + declareProperty("IsolationTool_FCTight", m_isolationTool_FCTight); + declareProperty("IsolationTool_FCLoose", m_isolationTool_FCLoose); + declareProperty("IsolationTool_FCTightTrackOnly", m_isolationTool_FCTightTrackOnly); + declareProperty("IsolationTool_FCTightTrackOnly_FixedRad", m_isolationTool_FCTightTrackOnly_FixedRad); + declareProperty("IsolationTool_FCLoose_FixedRad", m_isolationTool_FCLoose_FixedRad); + declareProperty("IsolationTool_FCTight_FixedRad", m_isolationTool_FCTight_FixedRad); + declareProperty("IsolationTool_FixedCutPflowTight", m_isolationTool_FixedCutPflowTight); + declareProperty("IsolationTool_FixedCutPflowLoose", m_isolationTool_FixedCutPflowLoose); + declareProperty("IsolationTool_PflowTight_FixedRad", m_isolationTool_PflowTight_FixedRad); + declareProperty("IsolationTool_PflowLoose_FixedRad", m_isolationTool_PflowLoose_FixedRad); + declareProperty("IsolationTool_PflowTight_VarRad", m_isolationTool_PflowTight_VarRad); + declareProperty("IsolationTool_PflowLoose_VarRad", m_isolationTool_PflowLoose_VarRad); + declareProperty("IsolationTool_HighPtTrackOnly", m_isolationTool_HighPtTrackOnly); + declareProperty("IsolationTool_TightTrackOnly_VarRad", m_isolationTool_TightTrackOnly_VarRad); + declareProperty("IsolationTool_TightTrackOnly_FixedRad", m_isolationTool_TightTrackOnly_FixedRad); + declareProperty("IsolationTool_PLVTight", m_isolationTool_PLVTight); + declareProperty("IsolationTool_PLVLoose", m_isolationTool_PLVLoose); + declareProperty("IsolationTool_Tight_VarRad", m_isolationTool_Tight_VarRad); + declareProperty("IsolationTool_Tight_FixedRad", m_isolationTool_Tight_FixedRad); + declareProperty("IsolationTool_Loose_VarRad", m_isolationTool_Loose_VarRad); + declareProperty("IsolationTool_Loose_FixedRad", m_isolationTool_Loose_FixedRad); +// declareProperty("IsolationTool_LowPtPLV", m_isolationTool_LowPtPLV); + declareProperty("MuonSelectionToolVeryLooseVeto", m_muonSelectionToolVeryLooseVeto); } - StatusCode MuonObjectCollectionMaker::initialize() - { - ATH_MSG_INFO(" top::MuonObjectCollectionMaker initialize" ); - - top::check( m_calibrationTool.retrieve() , "Failed to retrieve muon calibration tool" ); - top::check( m_isolationTool_LooseTrackOnly.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_Loose.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_Gradient.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_GradientLoose.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_FixedCutTightTrackOnly.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_isolationTool_FixedCutLoose.retrieve() , "Failed to retrieve Isolation Tool" ); - top::check( m_muonSelectionToolVeryLooseVeto.retrieve() , "Failed to retrieve Selection Tool" ); + StatusCode MuonObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::MuonObjectCollectionMaker initialize"); + + top::check(m_calibrationPeriodTool.retrieve(), "Failed to retrieve muon calibration tool"); + top::check(m_isolationTool_FCTight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCLoose.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCTightTrackOnly.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCTightTrackOnly_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCLoose_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FCTight_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FixedCutPflowTight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_FixedCutPflowLoose.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PflowTight_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PflowLoose_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PflowTight_VarRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PflowLoose_VarRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_HighPtTrackOnly.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_TightTrackOnly_VarRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_TightTrackOnly_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PLVTight.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_PLVLoose.retrieve(), "Failed to retrieve Isolation Tool"); +// top::check(m_isolationTool_LowPtPLV.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Tight_VarRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Tight_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Loose_VarRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_isolationTool_Loose_FixedRad.retrieve(), "Failed to retrieve Isolation Tool"); + top::check(m_muonSelectionToolVeryLooseVeto.retrieve(), "Failed to retrieve Selection Tool"); ///-- Set Systematics Information --/// const std:: string& syststr = m_config->systematics(); - std::set<std::string> syst; + std::set<std::string> syst; - if( !m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)){ + if (!m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)) { bool ok = m_config->getSystematicsList(syststr, syst); if (!ok) { - ATH_MSG_ERROR(" top::MuonObjectCollectionMaker could not determine systematic list" ); - return StatusCode::FAILURE; + ATH_MSG_ERROR(" top::MuonObjectCollectionMaker could not determine systematic list"); + return StatusCode::FAILURE; } + //here the idea is that if the user specifies AllXXX, we leave syst as an empty string, so that all recommended CP + // systematics are then used if (m_config->contains(syst, "AllMuons")) { - syst.clear(); + syst.clear(); } } - - specifiedSystematics( syst ); - - m_config->systematicsMuons( specifiedSystematics() ); - - ATH_MSG_INFO(" top::MuonObjectCollectionMaker completed initialize" ); + + specifiedSystematics(syst); + + m_config->systematicsMuons(specifiedSystematics()); + + m_isFirstEvent = true; + + ATH_MSG_INFO(" top::MuonObjectCollectionMaker completed initialize"); return StatusCode::SUCCESS; } - - StatusCode MuonObjectCollectionMaker::execute() - { + + StatusCode MuonObjectCollectionMaker::execute(bool executeNominal) { + + static const SG::AuxElement::ConstAccessor<float> ptvarcone30_TightTTVA_pt1000("ptvarcone30_TightTTVA_pt1000"); + static const SG::AuxElement::ConstAccessor<float> ptcone20_TightTTVA_pt1000("ptcone20_TightTTVA_pt1000"); + static const SG::AuxElement::ConstAccessor<float> ptcone20_TightTTVA_pt500("ptcone20_TightTTVA_pt500"); + static const SG::AuxElement::ConstAccessor<float> ptvarcone30_TightTTVA_pt500("ptvarcone30_TightTTVA_pt500"); + static const SG::AuxElement::ConstAccessor<float> neflowisol20("neflowisol20"); + static const SG::AuxElement::ConstAccessor<float> ptvarcone30_TightTTVALooseCone_pt1000("ptvarcone30_TightTTVALooseCone_pt1000"); + static const SG::AuxElement::ConstAccessor<int> chamberIndex("chamberIndex"); + static const SG::AuxElement::ConstAccessor<short> PLV_TrackJetNTrack("PromptLeptonInput_TrackJetNTrack"); + static const SG::AuxElement::ConstAccessor<float> PLV_DRlj("PromptLeptonInput_DRlj"); + static const SG::AuxElement::ConstAccessor<float> PLV_PtRel("PromptLeptonInput_PtRel"); + static const SG::AuxElement::ConstAccessor<float> PLV_PtFrac("PromptLeptonInput_PtFrac"); + static const SG::AuxElement::ConstAccessor<float> PLV_PromptLeptonVeto("PromptLeptonVeto"); +// static SG::AuxElement::Decorator<float> byhand_LowPtPLV("LowPtPLV"); const xAOD::EventInfo* eventInfo(nullptr); - top::check( evtStore()->retrieve( eventInfo, m_config->sgKeyEventInfo() ), "Failed to retrieve EventInfo"); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); float beam_pos_sigma_x = eventInfo->beamPosSigmaX(); float beam_pos_sigma_y = eventInfo->beamPosSigmaY(); float beam_pos_sigma_xy = eventInfo->beamPosSigmaXY(); - ///-- Get base muons and tracks from xAOD --/// + ///-- Get base muons and tracks from xAOD --/// const xAOD::MuonContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyMuons() ) , "Failed to retrieve Muons" ); - + top::check(evtStore()->retrieve(xaod, m_config->sgKeyMuons()), "Failed to retrieve Muons"); + ///-- Loop over all systematics --/// - for( auto systematic : m_specifiedSystematics ){ + for (auto systematic : m_specifiedSystematics) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; ///-- Tell tool which systematic to use --/// - top::check( m_calibrationTool->applySystematicVariation( systematic ) , "Failed to applySystematicVariation" ); - + top::check(m_calibrationPeriodTool->applySystematicVariation(systematic), "Failed to applySystematicVariation"); + ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::MuonContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); - + std::pair< xAOD::MuonContainer*, + xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer(*xaod); + ///-- Loop over the xAOD Container and apply corrections--/// - for( auto muon : *(shallow_xaod_copy.first) ){ + for (auto muon : *(shallow_xaod_copy.first)) { + + ///-- Check if chamberIndex is Available if UseMVALowPt is On in order to print some useful message before the crash + if ( m_isFirstEvent ) { + if ( (m_config->muonUseMVALowPt() || m_config->muonUseMVALowPtLoose() || m_config->softmuonUseMVALowPt()) && !chamberIndex.isAvailable(*muon) ) { + ATH_MSG_ERROR("MuonSegmentsAux.chamberIndex is not available in yout derivation so UseMVALowPt cannot be performed."); + ATH_MSG_ERROR("Please turn OFF UseMVALowPt or use more recent p-tag"); + ATH_MSG_ERROR("AnalysisTop will crash soon..."); + throw std::runtime_error("Missing MuonSegmentsAux.chamberIndex variable"); + } + m_isFirstEvent = false; + } - ///-- Apply momentum correction --/// + ///-- Apply momentum correction --/// if (muon->primaryTrackParticle()) { - top::check( m_calibrationTool->applyCorrection( *muon ) , "Failed to applyCorrection" ); - + top::check(m_calibrationPeriodTool->applyCorrection(*muon), "Failed to applyCorrection"); + // don't do the decorations unless the muons are at least Loose // this is because it may fail if the muons are at just VeryLoose if (m_muonSelectionToolVeryLooseVeto->accept(*muon)) { - double d0sig = xAOD::TrackingHelpers::d0significance( muon->primaryTrackParticle(), - beam_pos_sigma_x, - beam_pos_sigma_y, - beam_pos_sigma_xy ); + double d0sig = xAOD::TrackingHelpers::d0significance(muon->primaryTrackParticle(), + beam_pos_sigma_x, + beam_pos_sigma_y, + beam_pos_sigma_xy); muon->auxdecor<float>("d0sig") = d0sig; - if( eventInfo->isAvailable<float>("AnalysisTop_PRIVTX_z_position") ){ + if (eventInfo->isAvailable<float>("AnalysisTop_PRIVTX_z_position")) { float vtx_z = eventInfo->auxdata<float>("AnalysisTop_PRIVTX_z_position"); float delta_z0 = muon->primaryTrackParticle()->z0() + muon->primaryTrackParticle()->vz() - vtx_z; muon->auxdecor<float>("delta_z0") = delta_z0; - muon->auxdecor<float>("delta_z0_sintheta") = delta_z0*std::sin( muon->primaryTrackParticle()->theta() ); + muon->auxdecor<float>("delta_z0_sintheta") = delta_z0 * std::sin(muon->primaryTrackParticle()->theta()); } } - } - + } + ///-- Isolation selection --/// - char passIsol_LooseTrackOnly(0),passIsol_Loose(0),passIsol_FixedCutTightTrackOnly(0); - char passIsol_Gradient(0),passIsol_GradientLoose(0),passIsol_FixedCutLoose(0); - if (m_isolationTool_LooseTrackOnly->accept( *muon )) {passIsol_LooseTrackOnly = 1;} - if (m_isolationTool_Loose->accept( *muon )) {passIsol_Loose = 1;} - if (m_isolationTool_Gradient->accept( *muon )) {passIsol_Gradient = 1;} - if (m_isolationTool_GradientLoose->accept( *muon )) {passIsol_GradientLoose = 1;} - if (m_isolationTool_FixedCutTightTrackOnly->accept( *muon )) {passIsol_FixedCutTightTrackOnly = 1;} - if (m_isolationTool_FixedCutLoose->accept( *muon )) {passIsol_FixedCutLoose = 1;} - - muon->auxdecor<char>("AnalysisTop_Isol_LooseTrackOnly") = passIsol_LooseTrackOnly; - muon->auxdecor<char>("AnalysisTop_Isol_Loose") = passIsol_Loose; - muon->auxdecor<char>("AnalysisTop_Isol_Gradient") = passIsol_Gradient; - muon->auxdecor<char>("AnalysisTop_Isol_GradientLoose") = passIsol_GradientLoose; - muon->auxdecor<char>("AnalysisTop_Isol_FixedCutTightTrackOnly") = passIsol_FixedCutTightTrackOnly; - muon->auxdecor<char>("AnalysisTop_Isol_FixedCutLoose") = passIsol_FixedCutLoose; + char passIsol_FCTight(0), passIsol_FCLoose(0), passIsol_FCTightTrackOnly(0); + char passIsol_FCTightTrackOnly_FixedRad(0), passIsol_FCLoose_FixedRad(0), passIsol_FCTight_FixedRad(0); + char passIsol_FixedCutPflowTight(0), passIsol_FixedCutPflowLoose(0); + + char passIsol_PflowTight_FixedRad(0), passIsol_PflowLoose_FixedRad(0), passIsol_PflowTight_VarRad(0), passIsol_PflowLoose_VarRad(0); + char passIsol_HighPtTrackOnly(0), passIsol_TightTrackOnly_VarRad(0), passIsol_TightTrackOnly_FixedRad(0); + char passIsol_PLVTight(0), passIsol_PLVLoose(0); + char passIsol_Tight_VarRad(0), passIsol_Tight_FixedRad(0), passIsol_Loose_VarRad(0), passIsol_Loose_FixedRad(0); + + //initializing al the passIsol_* variable to -1 + passIsol_FCTight = -1; + passIsol_FCLoose = -1; + passIsol_FCTightTrackOnly = -1; + passIsol_FCTightTrackOnly_FixedRad = -1; + passIsol_FCLoose_FixedRad = -1; + passIsol_FCTight_FixedRad = -1; + passIsol_FixedCutPflowTight = -1; + passIsol_FixedCutPflowLoose = -1; + passIsol_PflowTight_FixedRad = -1; + passIsol_PflowLoose_FixedRad = -1; + passIsol_PflowTight_VarRad = -1; + passIsol_PflowLoose_VarRad = -1; + passIsol_HighPtTrackOnly = -1; + passIsol_TightTrackOnly_VarRad = -1; + passIsol_TightTrackOnly_FixedRad = -1; + passIsol_PLVTight = -1; + passIsol_PLVLoose = -1; + passIsol_Tight_FixedRad = -1; + passIsol_Loose_FixedRad = -1; + passIsol_Tight_VarRad = -1; + passIsol_Loose_VarRad = -1; + + passIsol_FCTight = m_isolationTool_FCTight->accept(*muon) ? 1 : 0; + passIsol_FCLoose = m_isolationTool_FCLoose->accept(*muon) ? 1 : 0; + passIsol_FCTightTrackOnly = m_isolationTool_FCTightTrackOnly->accept(*muon) ? 1 : 0; + passIsol_FCTightTrackOnly_FixedRad = m_isolationTool_FCTightTrackOnly_FixedRad->accept(*muon) ? 1 : 0; + passIsol_FCLoose_FixedRad = m_isolationTool_FCLoose_FixedRad->accept(*muon) ? 1 : 0; + passIsol_FCTight_FixedRad = m_isolationTool_FCTight_FixedRad->accept(*muon) ? 1 : 0; + passIsol_FixedCutPflowTight = m_isolationTool_FixedCutPflowTight->accept(*muon) ? 1 : 0; + passIsol_FixedCutPflowLoose = m_isolationTool_FixedCutPflowLoose->accept(*muon) ? 1 : 0; + + //new Iso WPs + if (ptvarcone30_TightTTVA_pt500.isAvailable(*muon) && neflowisol20.isAvailable(*muon) && ptcone20_TightTTVA_pt500.isAvailable(*muon)) { + passIsol_PflowTight_FixedRad = m_isolationTool_PflowTight_FixedRad->accept(*muon) ? 1 : 0; + passIsol_PflowLoose_FixedRad = m_isolationTool_PflowLoose_FixedRad->accept(*muon) ? 1 : 0; + } + if (ptvarcone30_TightTTVA_pt500.isAvailable(*muon) && neflowisol20.isAvailable(*muon)) { + passIsol_PflowTight_VarRad = m_isolationTool_PflowTight_VarRad->accept(*muon) ? 1 : 0; + passIsol_PflowLoose_VarRad = m_isolationTool_PflowLoose_VarRad->accept(*muon) ? 1 : 0; + } + if (ptcone20_TightTTVA_pt1000.isAvailable(*muon)) { + passIsol_HighPtTrackOnly = m_isolationTool_HighPtTrackOnly->accept(*muon) ? 1 : 0; + } + if (ptvarcone30_TightTTVA_pt500.isAvailable(*muon)) { + passIsol_TightTrackOnly_VarRad = m_isolationTool_TightTrackOnly_VarRad->accept(*muon) ? 1 : 0; + } + if (ptvarcone30_TightTTVA_pt500.isAvailable(*muon) && ptcone20_TightTTVA_pt500.isAvailable(*muon)) { + passIsol_TightTrackOnly_FixedRad = m_isolationTool_TightTrackOnly_FixedRad->accept(*muon) ? 1 : 0; + } + if (ptvarcone30_TightTTVA_pt500.isAvailable(*muon)) { +// if ( PLV_TrackJetNTrack.isAvailable(*muon) && +// PLV_DRlj.isAvailable(*muon) && +// PLV_PtRel.isAvailable(*muon) && +// PLV_PtFrac.isAvailable(*muon) ) +// top::check(m_isolationTool_LowPtPLV->augmentPLV(*muon), "Failed to agument muon with LowPtPLV decorations"); +// else +// byhand_LowPtPLV(*muon) = 1.1; + if (PLV_PromptLeptonVeto.isAvailable(*muon)) { + passIsol_PLVTight = m_isolationTool_PLVTight->accept(*muon) ? 1 : 0; + passIsol_PLVLoose = m_isolationTool_PLVLoose->accept(*muon) ? 1 : 0; + } + } + if (ptvarcone30_TightTTVA_pt1000.isAvailable(*muon) && ptcone20_TightTTVA_pt1000.isAvailable(*muon)) { + passIsol_Tight_FixedRad = m_isolationTool_Tight_FixedRad->accept(*muon) ? 1 : 0; + passIsol_Loose_FixedRad = m_isolationTool_Loose_FixedRad->accept(*muon) ? 1 : 0; + } + if (ptvarcone30_TightTTVA_pt1000.isAvailable(*muon)) { + passIsol_Tight_VarRad = m_isolationTool_Tight_VarRad->accept(*muon) ? 1 : 0; + passIsol_Loose_VarRad = m_isolationTool_Loose_VarRad->accept(*muon) ? 1 : 0; + } + + muon->auxdecor<char>("AnalysisTop_Isol_FCTight") = passIsol_FCTight; + muon->auxdecor<char>("AnalysisTop_Isol_FCLoose") = passIsol_FCLoose; + muon->auxdecor<char>("AnalysisTop_Isol_FCTightTrackOnly") = passIsol_FCTightTrackOnly; + muon->auxdecor<char>("AnalysisTop_Isol_FCTightTrackOnly_FixedRad") = passIsol_FCTightTrackOnly_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_FCLoose_FixedRad") = passIsol_FCLoose_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_FCTight_FixedRad") = passIsol_FCTight_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_FixedCutPflowTight") = passIsol_FixedCutPflowTight; + muon->auxdecor<char>("AnalysisTop_Isol_FixedCutPflowLoose") = passIsol_FixedCutPflowLoose; + + muon->auxdecor<char>("AnalysisTop_Isol_PflowTight_FixedRad") = passIsol_PflowTight_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_PflowLoose_FixedRad") = passIsol_PflowLoose_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_PflowTight_VarRad") = passIsol_PflowTight_VarRad; + muon->auxdecor<char>("AnalysisTop_Isol_PflowLoose_VarRad") = passIsol_PflowLoose_VarRad; + muon->auxdecor<char>("AnalysisTop_Isol_HighPtTrackOnly") = passIsol_HighPtTrackOnly; + muon->auxdecor<char>("AnalysisTop_Isol_TightTrackOnly_VarRad") = passIsol_TightTrackOnly_VarRad; + muon->auxdecor<char>("AnalysisTop_Isol_TightTrackOnly_FixedRad") = passIsol_TightTrackOnly_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_PLVTight") = passIsol_PLVTight; + muon->auxdecor<char>("AnalysisTop_Isol_PLVLoose") = passIsol_PLVLoose; + muon->auxdecor<char>("AnalysisTop_Isol_Tight_VarRad") = passIsol_Tight_VarRad; + muon->auxdecor<char>("AnalysisTop_Isol_Tight_FixedRad") = passIsol_Tight_FixedRad; + muon->auxdecor<char>("AnalysisTop_Isol_Loose_VarRad") = passIsol_Loose_VarRad; + muon->auxdecor<char>("AnalysisTop_Isol_Loose_FixedRad") = passIsol_Loose_FixedRad; + + // PromptLeptonIsolation - Some protection incase things change in R21 + if (muon->isAvailable<float>("PromptLeptonIso_TagWeight")) { + muon->auxdecor<char>("AnalysisTop_Isol_PromptLepton") = + (muon->auxdata<float>("PromptLeptonIso_TagWeight") < -0.5) ? 1 : 0; + } else { + muon->auxdecor<char>("AnalysisTop_Isol_PromptLepton") = 0; + } } ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for muons, MET recalculation may struggle" ); - + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for muons, MET recalculation may struggle"); + ///-- Save corrected xAOD Container to StoreGate / TStore --/// - std::string outputSGKey = m_config->sgKeyMuons( systematic.hash() ); + std::string outputSGKey = m_config->sgKeyMuons(systematic.hash()); std::string outputSGKeyAux = outputSGKey + "Aux."; - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + if (!save || !saveAux) { return StatusCode::FAILURE; - } - } // Loop over all systematics - + } + } // Loop over all systematics + return StatusCode::SUCCESS; } - - StatusCode MuonObjectCollectionMaker::printout() - { + + StatusCode MuonObjectCollectionMaker::printout() { ///-- Loop over all systematics --/// - for( auto systematic : m_specifiedSystematics ){ + for (auto systematic : m_specifiedSystematics) { const xAOD::MuonContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyMuons( systematic.hash() ) ) , "Failed to retrieve Muons" ); - - ATH_MSG_INFO(" Muons with sgKey = "<< m_config->sgKeyMuons( systematic.hash() ) ); - for( auto muon : *xaod ){ - ATH_MSG_INFO(" MU pT , eta = "<< muon->pt() <<" , "<< muon->eta() ); + top::check(evtStore()->retrieve(xaod, m_config->sgKeyMuons(systematic.hash())), "Failed to retrieve Muons"); + + ATH_MSG_INFO(" Muons with sgKey = " << m_config->sgKeyMuons(systematic.hash())); + for (auto muon : *xaod) { + ATH_MSG_INFO(" MU pT , eta = " << muon->pt() << " , " << muon->eta()); } } - - return StatusCode::SUCCESS; + + return StatusCode::SUCCESS; } - - - void MuonObjectCollectionMaker::specifiedSystematics( const std::set<std::string>& specifiedSystematics ) - { + + void MuonObjectCollectionMaker::specifiedSystematics(const std::set<std::string>& specifiedSystematics) { ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( m_calibrationTool->recommendedSystematics() ); - + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_calibrationPeriodTool->recommendedSystematics()); + for (auto s : systList) { + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter m_recommendedSystematics.push_back(s); if (s.name() == "") { m_specifiedSystematics.push_back(s); } - + ///-- MC only --/// if (m_config->isMC()) { ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (!m_config->isSystNominal( m_config->systematics() )) { + if (!m_config->isSystNominal(m_config->systematics())) { if (specifiedSystematics.size() == 0) { m_specifiedSystematics.push_back(s); } - if (specifiedSystematics.size() > 0) { + if (specifiedSystematics.size() > 0) { for (auto i : specifiedSystematics) { - if ( i == s.name() ) { - m_specifiedSystematics.push_back(s); + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematics.push_back(s); } } } } } } - m_recommendedSystematics.sort(); + m_recommendedSystematics.sort(); m_recommendedSystematics.unique(); m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); + m_specifiedSystematics.unique(); } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ObjectCollectionMaker.cxx index fd1bfbf2b435957e11d10d12bc101640c9c801b6..a3a889298737de58c65b13300af05f30be97ee82 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ObjectCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/ObjectCollectionMaker.cxx @@ -1,6 +1,6 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: ObjectCollectionMaker.cxx 790414 2016-12-19 00:49:08Z tpelzer $ #include "TopSystematicObjectMaker/ObjectCollectionMaker.h" @@ -13,139 +13,270 @@ #include "xAODMuon/MuonContainer.h" #include "xAODTau/TauJetContainer.h" #include "xAODJet/JetContainer.h" +#include "xAODTracking/TrackParticleContainer.h" -namespace top{ - ObjectCollectionMaker::ObjectCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + ObjectCollectionMaker::ObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), m_egammaMaker(nullptr), m_muonMaker(nullptr), + m_softmuonMaker(nullptr), m_tauMaker(nullptr), m_jetMaker(nullptr), - m_metMaker(nullptr) + m_metMaker(nullptr), + m_trackSystMaker(nullptr) { - declareProperty( "config" , m_config ); + declareProperty("config", m_config); } - StatusCode ObjectCollectionMaker::initialize() - { - ATH_MSG_INFO(" top::ObjectCollectionMaker initialize" ); + StatusCode ObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::ObjectCollectionMaker initialize"); + + m_egammaMaker = + std::unique_ptr<top::EgammaObjectCollectionMaker> (new top::EgammaObjectCollectionMaker( + "top::EgammaObjectCollectionMaker")); + m_muonMaker = + std::unique_ptr<top::MuonObjectCollectionMaker> (new top::MuonObjectCollectionMaker( + "top::MuonObjectCollectionMaker")); + m_softmuonMaker = + std::unique_ptr<top::SoftMuonObjectCollectionMaker> (new top::SoftMuonObjectCollectionMaker( + "top::SoftMuonObjectCollectionMaker")); + m_tauMaker = + std::unique_ptr<top::TauObjectCollectionMaker> (new top::TauObjectCollectionMaker( + "top::TauObjectCollectionMaker")); + m_jetMaker = + std::unique_ptr<top::JetObjectCollectionMaker> (new top::JetObjectCollectionMaker( + "top::JetObjectCollectionMaker")); + m_metMaker = + std::unique_ptr<top::MissingETObjectCollectionMaker> (new top::MissingETObjectCollectionMaker( + "top::MissingETObjectCollectionMaker")); + m_ghostTrackSystMaker = + std::unique_ptr<top::GhostTrackSystematicsMaker> (new top::GhostTrackSystematicsMaker( + "top::GhostTrackSystematicsMaker")); + + m_trackSystMaker = + std::unique_ptr<top::TrackSystematicsMaker> (new top::TrackSystematicsMaker( + "top::TrackSystematicsMaker")); - m_egammaMaker = std::unique_ptr<top::EgammaObjectCollectionMaker> ( new top::EgammaObjectCollectionMaker ( "top::EgammaObjectCollectionMaker" ) ); - m_muonMaker = std::unique_ptr<top::MuonObjectCollectionMaker> ( new top::MuonObjectCollectionMaker ( "top::MuonObjectCollectionMaker" ) ); - m_tauMaker = std::unique_ptr<top::TauObjectCollectionMaker> ( new top::TauObjectCollectionMaker ( "top::TauObjectCollectionMaker" ) ); - m_jetMaker = std::unique_ptr<top::JetObjectCollectionMaker> ( new top::JetObjectCollectionMaker ( "top::JetObjectCollectionMaker" ) ); - m_metMaker = std::unique_ptr<top::MissingETObjectCollectionMaker> ( new top::MissingETObjectCollectionMaker( "top::MissingETObjectCollectionMaker" ) ); - m_ghostTrackSystMaker = std::unique_ptr<top::GhostTrackSystematicsMaker> ( new top::GhostTrackSystematicsMaker("top::GhostTrackSystematicsMaker") ); - if( m_config->usePhotons() || m_config->useElectrons() ){ - top::check( m_egammaMaker->setProperty( "config" , m_config ) , "Failed to setProperty" ); - top::check( m_egammaMaker->initialize() , "Failed to initialize" ); + if (m_config->usePhotons() || m_config->useElectrons() || m_config->useFwdElectrons()) { + top::check(m_egammaMaker->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_egammaMaker->initialize(), "Failed to initialize"); } - if( m_config->useMuons() ){ - top::check( m_muonMaker->setProperty( "config" , m_config ) , "Failed to setProperty" ); - top::check( m_muonMaker->initialize() , "Failed to initialize" ); + if (m_config->useMuons()) { + top::check(m_muonMaker->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_muonMaker->initialize(), "Failed to initialize"); } - if( m_config->useTaus() ){ - top::check( m_tauMaker->setProperty( "config" , m_config ) , "Failed to setProperty" ); - top::check( m_tauMaker->initialize() , "Failed to initialize" ); + if (m_config->useSoftMuons()) { + top::check(m_softmuonMaker->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_softmuonMaker->initialize(), "Failed to initialize"); } - if( m_config->useJets() || m_config->useLargeRJets() ){ - top::check( m_jetMaker->setProperty( "config" , m_config ) , "Failed to setProperty" ); - top::check( m_jetMaker->initialize() , "Failed to initialize" ); + if (m_config->useTaus()) { + top::check(m_tauMaker->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_tauMaker->initialize(), "Failed to initialize"); } - if( m_config->useJets() && m_config->useJetGhostTrack() ){ - top::check( m_ghostTrackSystMaker->setProperty( "config" , m_config ), - "Failed to setProperty" ); + if (m_config->useJets() || m_config->useLargeRJets()) { + top::check(m_jetMaker->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_jetMaker->initialize(), "Failed to initialize"); + } - top::check( m_ghostTrackSystMaker->initialize() , - "Failed to initialize" ); + if (m_config->useJets() && m_config->useJetGhostTrack()) { + top::check(m_ghostTrackSystMaker->setProperty("config", m_config), + "Failed to setProperty"); + + top::check(m_ghostTrackSystMaker->initialize(), + "Failed to initialize"); } - top::check( m_metMaker->setProperty( "config" , m_config ) , "Failed to setProperty" ); - top::check( m_metMaker->initialize() , "Failed to initialize" ); + if (m_config->useTracks()) { + top::check(m_trackSystMaker->setProperty("config", m_config), + "Failed to setProperty"); + + top::check(m_trackSystMaker->initialize(), + "Failed to initialize"); + } + + + top::check(m_metMaker->setProperty("config", m_config), "Failed to setProperty"); + top::check(m_metMaker->initialize(), "Failed to initialize"); return StatusCode::SUCCESS; } - StatusCode ObjectCollectionMaker::execute() - { + StatusCode ObjectCollectionMaker::execute(bool executeNominal) { + if (executeNominal) { + top::check(this->executeNominal(), "Failed to executeNominal()"); + } else { + top::check(this->executeSystematics(), "Failed to executeSystematics()"); + } + return StatusCode::SUCCESS; + } - if( m_config->usePhotons() ){ top::check( m_egammaMaker->executePhotons() , "Failed to executePhotons()" ); } - if( m_config->useElectrons() ){ top::check( m_egammaMaker->executeElectrons() , "Failed to executeElectrons()" ); } - if( m_config->useMuons() ){ top::check( m_muonMaker->execute() , "Failed to executeMuons()" ); } - if( m_config->useTaus() ){ top::check( m_tauMaker->execute() , "Failed to executeTaus()" ); } - if( m_config->useJets() ){ top::check( m_jetMaker->executeJets() , "Failed to executeJets()" ); } - if( m_config->useLargeRJets() ){ top::check( m_jetMaker->executeLargeRJets() , "Failed to executeLargeRJets()" ); } - if( m_config->useTrackJets() ){ top::check( m_jetMaker->executeTrackJets() , "Failed to executeTrackJets() " ); } + StatusCode ObjectCollectionMaker::executeNominal() { + if (m_config->usePhotons()) { + top::check(m_egammaMaker->executePhotons(true), "Failed to executePhotons()"); + } + if (m_config->useElectrons()) { + top::check(m_egammaMaker->executeElectrons(true), "Failed to executeElectrons()"); + } + if (m_config->useFwdElectrons()) { + top::check(m_egammaMaker->executeFwdElectrons(true), "Failed to executeFwdElectrons()"); + } + if (m_config->useMuons()) { + top::check(m_muonMaker->execute(true), "Failed to executeMuons()"); + } + if (m_config->useSoftMuons()) { + top::check(m_softmuonMaker->execute(true), "Failed to executeSoftMuons()"); + } + if (m_config->useTaus()) { + top::check(m_tauMaker->execute(true), "Failed to executeTaus()"); + } + if (m_config->useJets()) { + top::check(m_jetMaker->executeJets(true), "Failed to executeJets()"); + } + if (m_config->useLargeRJets()) { + top::check(m_jetMaker->executeLargeRJets(true), "Failed to executeLargeRJets()"); + } + if (m_config->useTrackJets()) { + top::check(m_jetMaker->executeTrackJets(true), "Failed to executeTrackJets() "); + } + if (m_config->useTracks()) { + top::check(m_trackSystMaker->execute(true), "Failed to executeTracks() "); + } // This must come _AFTER_ the jets have been calibrated! - if( m_config->useJets() && m_config->useJetGhostTrack() ){ top::check( m_ghostTrackSystMaker->execute() , "Failed to executeGhostTrackSystematics() " ); } + if (m_config->useJets() && m_config->useJetGhostTrack()) { + top::check(m_ghostTrackSystMaker->execute(true), "Failed to executeGhostTrackSystematics() "); + } + + m_config->setNominalAvailable(true); - return StatusCode::SUCCESS; } - StatusCode ObjectCollectionMaker::recalculateMET() - { - top::check( m_metMaker->recalculateMET() , "Failed to recalculateMET()" ); + StatusCode ObjectCollectionMaker::executeSystematics() { + if (m_config->isNominalAvailable() == false) { + ATH_MSG_ERROR("ObjectCollectionMaker::executeNominal has not been called before executeSystematics"); + return StatusCode::FAILURE; + } + + if (m_config->usePhotons()) { + top::check(m_egammaMaker->executePhotons(false), "Failed to executePhotons()"); + } + if (m_config->useElectrons()) { + top::check(m_egammaMaker->executeElectrons(false), "Failed to executeElectrons()"); + } + if (m_config->useFwdElectrons()) { + top::check(m_egammaMaker->executeFwdElectrons(false), "Failed to executeFwdElectrons()"); + } + if (m_config->useMuons()) { + top::check(m_muonMaker->execute(false), "Failed to executeMuons()"); + } + if (m_config->useSoftMuons()) { + top::check(m_softmuonMaker->execute(false), "Failed to executeSoftMuons()"); + } + if (m_config->useTaus()) { + top::check(m_tauMaker->execute(false), "Failed to executeTaus()"); + } + if (m_config->useJets()) { + top::check(m_jetMaker->executeJets(false), "Failed to executeJets()"); + } + if (m_config->useLargeRJets()) { + top::check(m_jetMaker->executeLargeRJets(false), "Failed to executeLargeRJets()"); + } + if (m_config->useTrackJets()) { + top::check(m_jetMaker->executeTrackJets(false), "Failed to executeTrackJets() "); + } + + // This must come _AFTER_ the jets have been calibrated! + if (m_config->useJets() && m_config->useJetGhostTrack()) { + top::check(m_ghostTrackSystMaker->execute(false), "Failed to executeGhostTrackSystematics() "); + } + + + if (m_config->useTracks()) { + top::check(m_trackSystMaker->execute(false), "Failed to executeTracks() "); + } + + return StatusCode::SUCCESS; } - StatusCode ObjectCollectionMaker::printout() - { - if( m_config->usePhotons() ){ top::check( m_egammaMaker->printoutPhotons() , "Failed to printoutPhotons()" ); } - if( m_config->useElectrons() ){ top::check( m_egammaMaker->printoutElectrons() , "Failed to printoutElectrons()" ); } - if( m_config->useMuons() ){ top::check( m_muonMaker->printout() , "Failed to printoutMuons()" ); } - if( m_config->useTaus() ){ top::check( m_tauMaker->printout() , "Failed to printoutTaus()" ); } - if( m_config->useJets() ){ top::check( m_jetMaker->printoutJets() , "Failed to printoutJets()" ); } - if( m_config->useLargeRJets() ){ top::check( m_jetMaker->printoutLargeRJets() , "Failed to printoutLargeRJets()" ); } + StatusCode ObjectCollectionMaker::recalculateMET(bool executeNominal) { + top::check(m_metMaker->recalculateMET(executeNominal), "Failed to recalculateMET()"); + return StatusCode::SUCCESS; + } + + StatusCode ObjectCollectionMaker::printout() { + if (m_config->usePhotons()) { + top::check(m_egammaMaker->printoutPhotons(), "Failed to printoutPhotons()"); + } + if (m_config->useElectrons()) { + top::check(m_egammaMaker->printoutElectrons(), "Failed to printoutElectrons()"); + } + if (m_config->useFwdElectrons()) { + top::check(m_egammaMaker->printoutFwdElectrons(), "Failed to printoutFwdElectrons()"); + } + if (m_config->useMuons()) { + top::check(m_muonMaker->printout(), "Failed to printoutMuons()"); + } + if (m_config->useSoftMuons()) { + top::check(m_softmuonMaker->printout(), "Failed to printoutSoftMuons()"); + } + if (m_config->useTaus()) { + top::check(m_tauMaker->printout(), "Failed to printoutTaus()"); + } + if (m_config->useJets()) { + top::check(m_jetMaker->printoutJets(), "Failed to printoutJets()"); + } + if (m_config->useLargeRJets()) { + top::check(m_jetMaker->printoutLargeRJets(), "Failed to printoutLargeRJets()"); + } return StatusCode::SUCCESS; } - - bool ObjectCollectionMaker::isTruthDxAOD() const - { + + bool ObjectCollectionMaker::isTruthDxAOD() const { ///-- If any of the following aren't present, then assume we're running over a truth DxAOD --/// if (m_config->usePhotons()) { - if (!evtStore()->contains<xAOD::PhotonContainer>( m_config->sgKeyPhotons() )) { + if (!evtStore()->contains<xAOD::PhotonContainer>(m_config->sgKeyPhotons())) { return true; } } - + if (m_config->useElectrons()) { - if (!evtStore()->contains<xAOD::ElectronContainer>( m_config->sgKeyElectrons() )) { + if (!evtStore()->contains<xAOD::ElectronContainer>(m_config->sgKeyElectrons())) { return true; } } - + if (m_config->useMuons()) { - if (!evtStore()->contains<xAOD::MuonContainer>( m_config->sgKeyMuons() )) { + if (!evtStore()->contains<xAOD::MuonContainer>(m_config->sgKeyMuons())) { return true; } } - + if (m_config->useTaus()) { - if (!evtStore()->contains<xAOD::TauJetContainer>( m_config->sgKeyTaus() )) { + if (!evtStore()->contains<xAOD::TauJetContainer>(m_config->sgKeyTaus())) { return true; } - } - + } + if (m_config->useJets()) { - if (!evtStore()->contains<xAOD::JetContainer>( m_config->sgKeyJets() )) { + if (!evtStore()->contains<xAOD::JetContainer>(m_config->sgKeyJets())) { return true; } - } - + } + ///-- If we have made it this far, then all reco objects are available --/// ///-- Therefore we can't be running over a truth DxAOD --/// return false; } - } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/SoftMuonObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/SoftMuonObjectCollectionMaker.cxx new file mode 100644 index 0000000000000000000000000000000000000000..c9c3ff5a70fa0fc9813c0171149955f8a63f7522 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/SoftMuonObjectCollectionMaker.cxx @@ -0,0 +1,196 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopSystematicObjectMaker/SoftMuonObjectCollectionMaker.h" +#include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" +#include "TopEvent/EventTools.h" + +#include "AthContainers/AuxElement.h" +#include "xAODEventInfo/EventInfo.h" +#include "xAODMuon/MuonContainer.h" +#include "xAODMuon/MuonAuxContainer.h" +#include "xAODCore/ShallowCopy.h" +#include "xAODBase/IParticleHelpers.h" +#include "xAODTracking/TrackParticlexAODHelpers.h" +#include "PATInterfaces/SystematicsUtil.h" + +namespace top { + SoftMuonObjectCollectionMaker::SoftMuonObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), + m_config(nullptr), + + m_specifiedSystematics(), + m_recommendedSystematics(), + + m_calibrationPeriodTool("CP::MuonCalibrationPeriodTool"), + m_muonSelectionToolVeryLooseVeto("CP::MuonSelectionToolVeryLooseVeto") { + declareProperty("config", m_config); + + declareProperty("MuonCalibrationPeriodTool", m_calibrationPeriodTool); + declareProperty("MuonSelectionToolVeryLooseVeto", m_muonSelectionToolVeryLooseVeto); + } + + StatusCode SoftMuonObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::SoftMuonObjectCollectionMaker initialize"); + + top::check(m_calibrationPeriodTool.retrieve(), "Failed to retrieve muon calibration tool"); + top::check(m_muonSelectionToolVeryLooseVeto.retrieve(), "Failed to retrieve Selection Tool"); + + ///-- Set Systematics Information --/// + const std:: string& syststr = m_config->systematics(); + std::set<std::string> syst; + + if (!m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)) { + bool ok = m_config->getSystematicsList(syststr, syst); + if (!ok) { + ATH_MSG_ERROR(" top::SoftMuonObjectCollectionMaker could not determine systematic list"); + return StatusCode::FAILURE; + } + //here the idea is that if the user specifies AllXXX, we leave syst as an empty string, so that all recommended CP + // systematics are then used + if (m_config->contains(syst, "AllMuons")) { + syst.clear(); + } + if (m_config->contains(syst, "AllSoftMuons")) { + syst.clear(); + } + } + + specifiedSystematics(syst); + + m_config->systematicsSoftMuons(specifiedSystematics()); + + ATH_MSG_INFO(" top::SoftMuonObjectCollectionMaker completed initialize"); + return StatusCode::SUCCESS; + } + + StatusCode SoftMuonObjectCollectionMaker::execute(bool executeNominal) { + const xAOD::EventInfo* eventInfo(nullptr); + + top::check(evtStore()->retrieve(eventInfo, m_config->sgKeyEventInfo()), "Failed to retrieve EventInfo"); + const float beam_pos_sigma_x = eventInfo->beamPosSigmaX(); + const float beam_pos_sigma_y = eventInfo->beamPosSigmaY(); + const float beam_pos_sigma_xy = eventInfo->beamPosSigmaXY(); + + ///-- Get base muons and tracks from xAOD --/// + const xAOD::MuonContainer* xaod(nullptr); + + top::check(evtStore()->retrieve(xaod, m_config->sgKeyMuons()), "Failed to retrieve Soft Muons"); //we use sgKeyMuons and not sgKeySoftMuons on purpose to use the same collection for muons and soft muons + + ///-- Loop over all systematics --/// + for (auto systematic : m_specifiedSystematics) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + + ///-- Tell tool which systematic to use --/// + top::check(m_calibrationPeriodTool->applySystematicVariation(systematic), "Failed to applySystematicVariation"); + + ///-- Shallow copy of the xAOD --/// + std::pair< xAOD::MuonContainer*, + xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer(*xaod); + + ///-- Loop over the xAOD Container and apply corrections--/// + for (xAOD::Muon* muon : *(shallow_xaod_copy.first)) { + + ///-- Apply momentum correction --/// + if (muon->primaryTrackParticle()) { + top::check(m_calibrationPeriodTool->applyCorrection(*muon), "Failed to applyCorrection"); + + // don't do the decorations unless the muons are at least Loose + // this is because it may fail if the muons are at just VeryLoose + if (m_muonSelectionToolVeryLooseVeto->accept(*muon)) { + double d0sig = xAOD::TrackingHelpers::d0significance(muon->primaryTrackParticle(), + beam_pos_sigma_x, + beam_pos_sigma_y, + beam_pos_sigma_xy); + muon->auxdecor<float>("d0sig") = d0sig; + + if (eventInfo->isAvailable<float>("AnalysisTop_PRIVTX_z_position")) { + float vtx_z = eventInfo->auxdata<float>("AnalysisTop_PRIVTX_z_position"); + float delta_z0 = muon->primaryTrackParticle()->z0() + muon->primaryTrackParticle()->vz() - vtx_z; + muon->auxdecor<float>("delta_z0") = delta_z0; + muon->auxdecor<float>("delta_z0_sintheta") = delta_z0 * std::sin(muon->primaryTrackParticle()->theta()); + } + } + }//end of if (muon->primaryTrackParticle()) + + }//end of loop on muons + + ///-- set links to original objects /// + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) { + ATH_MSG_ERROR(" Cannot set original object links for soft muons"); + return StatusCode::FAILURE; + } + + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeySoftMuons(systematic.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + } // Loop over all systematics + + return StatusCode::SUCCESS; + } + + StatusCode SoftMuonObjectCollectionMaker::printout() { + ///-- Loop over all systematics --/// + for (auto systematic : m_specifiedSystematics) { + const xAOD::MuonContainer* xaod(nullptr); + top::check(evtStore()->retrieve(xaod, m_config->sgKeySoftMuons( + systematic.hash())), "Failed to retrieve Soft Muons"); + + ATH_MSG_INFO(" Soft Muons with sgKey = " << m_config->sgKeySoftMuons(systematic.hash())); + for (auto muon : *xaod) { + ATH_MSG_INFO(" SOFT MU pT , eta = " << muon->pt() << " , " << muon->eta()); + } + } + + return StatusCode::SUCCESS; + } + + void SoftMuonObjectCollectionMaker::specifiedSystematics(const std::set<std::string>& specifiedSystematics) { + ///-- Get the recommended systematics from the tool, in std::vector format --/// + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_calibrationPeriodTool->recommendedSystematics()); + + for (const CP::SystematicSet& s : systList) { + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter + m_recommendedSystematics.push_back(s); + if (s.name() == "") { + m_specifiedSystematics.push_back(s); + } + + ///-- MC only --/// + if (m_config->isMC()) { + ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// + if (!m_config->isSystNominal(m_config->systematics())) { + if (specifiedSystematics.size() == 0) { + m_specifiedSystematics.push_back(s); + } + if (specifiedSystematics.size() > 0) { + for (auto i : specifiedSystematics) { + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematics.push_back(s); + } + } + } + } + } + } + m_recommendedSystematics.sort(); + m_recommendedSystematics.unique(); + m_specifiedSystematics.sort(); + m_specifiedSystematics.unique(); + } + +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TauObjectCollectionMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TauObjectCollectionMaker.cxx index f091f6a7f73b543b9587cc070c93b743aaac8b5d..d1407b95d542f0bb43e62c117ea0f691fc4acef2 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TauObjectCollectionMaker.cxx +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TauObjectCollectionMaker.cxx @@ -1,10 +1,11 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // $Id: TauObjectCollectionMaker.cxx $ #include "TopSystematicObjectMaker/TauObjectCollectionMaker.h" #include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" #include "TopEvent/EventTools.h" #include "xAODTau/TauJetContainer.h" @@ -13,144 +14,147 @@ #include "xAODBase/IParticleHelpers.h" #include "PATInterfaces/SystematicsUtil.h" -namespace top{ - - TauObjectCollectionMaker::TauObjectCollectionMaker( const std::string& name ) : - asg::AsgTool( name ), +namespace top { + TauObjectCollectionMaker::TauObjectCollectionMaker(const std::string& name) : + asg::AsgTool(name), m_config(nullptr), - + m_specifiedSystematics(), m_recommendedSystematics(), - m_calibrationTool("TauAnalysisTools::TauSmearingTool") - - { - declareProperty( "config" , m_config ); - - declareProperty( "TauSmearingTool" , m_calibrationTool ); + m_calibrationTool("TauAnalysisTools::TauSmearingTool"), + m_truthMatchingTool("TauAnalysisTools::TauTruthMatchingTool") { + declareProperty("config", m_config); + + declareProperty("TauSmearingTool", m_calibrationTool); } - StatusCode TauObjectCollectionMaker::initialize() - { - ATH_MSG_INFO(" top::TauObjectCollectionMaker initialize" ); - - top::check( m_calibrationTool.retrieve() , "Failed to retrieve tau calibration tool" ); + StatusCode TauObjectCollectionMaker::initialize() { + ATH_MSG_INFO(" top::TauObjectCollectionMaker initialize"); + + top::check(m_calibrationTool.retrieve(), "Failed to retrieve tau calibration tool"); + top::check(m_truthMatchingTool.retrieve(), "Failed to retrieve tau truth matching tool"); ///-- Set Systematics Information --/// const std:: string& syststr = m_config->systematics(); - std::set<std::string> syst; + std::set<std::string> syst; - if( !m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)){ + if (!m_config->isSystNominal(syststr) && !m_config->isSystAll(syststr)) { bool ok = m_config->getSystematicsList(syststr, syst); if (!ok) { - ATH_MSG_ERROR(" top::TauObjectCollectionMaker could not determine systematic list" ); - return StatusCode::FAILURE; + ATH_MSG_ERROR(" top::TauObjectCollectionMaker could not determine systematic list"); + return StatusCode::FAILURE; } + //here the idea is that if the user specifies AllXXX, we leave syst as an empty string, so that all recommended CP + // systematics are then used if (m_config->contains(syst, "AllTaus")) { - syst.clear(); + syst.clear(); } } - specifiedSystematics( syst ); - - m_config->systematicsTaus( specifiedSystematics() ); - + specifiedSystematics(syst); + + m_config->systematicsTaus(specifiedSystematics()); + return StatusCode::SUCCESS; } - - StatusCode TauObjectCollectionMaker::execute() - { + + StatusCode TauObjectCollectionMaker::execute(bool executeNominal) { ///-- Get base taus from xAOD --/// const xAOD::TauJetContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyTaus() ) , "Failed to retrieve Taus" ); - + + top::check(evtStore()->retrieve(xaod, m_config->sgKeyTaus()), "Failed to retrieve Taus"); + ///-- Loop over all systematics --/// - for( auto systematic : m_specifiedSystematics ){ + for (auto systematic : m_specifiedSystematics) { + ///-- if executeNominal, skip other systematics (and vice-versa) --/// + if (executeNominal && !m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; + if (!executeNominal && m_config->isSystNominal(m_config->systematicName(systematic.hash()))) continue; ///-- Tell tool which systematic to use --/// - top::check( m_calibrationTool->applySystematicVariation( systematic ) , "Failed to applySystematicVariation" ); - + top::check(m_calibrationTool->applySystematicVariation(systematic), "Failed to applySystematicVariation"); + ///-- Shallow copy of the xAOD --/// - std::pair< xAOD::TauJetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *xaod ); - + std::pair< xAOD::TauJetContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( + *xaod); + ///-- Loop over the xAOD Container and apply corrections--/// - for( auto tau : *(shallow_xaod_copy.first) ){ + for (auto tau : *(shallow_xaod_copy.first)) { + ///-- add the necessary decoration + m_truthMatchingTool->getTruth(*tau); + ///-- Apply momentum correction --/// - top::check( m_calibrationTool->applyCorrection( *tau ) , "Failed to applyCorrection" ); + top::check(m_calibrationTool->applyCorrection(*tau), "Failed to applyCorrection"); } - + ///-- set links to original objects- needed for MET calculation --/// - bool setLinks = xAOD::setOriginalObjectLink( *xaod, *shallow_xaod_copy.first ); - if (!setLinks) - ATH_MSG_ERROR(" Cannot set original object links for taus, MET recalculation may struggle" ); - + bool setLinks = xAOD::setOriginalObjectLink(*xaod, *shallow_xaod_copy.first); + if (!setLinks) ATH_MSG_ERROR(" Cannot set original object links for taus, MET recalculation may struggle"); + // Save corrected xAOD Container to StoreGate / TStore - std::string outputSGKey = m_config->sgKeyTaus( systematic.hash() ); + std::string outputSGKey = m_config->sgKeyTaus(systematic.hash()); std::string outputSGKeyAux = outputSGKey + "Aux."; - xAOD::TReturnCode save = evtStore()->tds()->record( shallow_xaod_copy.first , outputSGKey ); - xAOD::TReturnCode saveAux = evtStore()->tds()->record( shallow_xaod_copy.second , outputSGKeyAux ); - if( !save || !saveAux ){ + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + if (!save || !saveAux) { return StatusCode::FAILURE; } - - } // Loop over all systematics - + } // Loop over all systematics + return StatusCode::SUCCESS; } - - StatusCode TauObjectCollectionMaker::printout() - { + + StatusCode TauObjectCollectionMaker::printout() { ///-- Loop over all systematics --/// - for( auto s : m_specifiedSystematics ){ + for (auto s : m_specifiedSystematics) { const xAOD::TauJetContainer* xaod(nullptr); - top::check( evtStore()->retrieve( xaod , m_config->sgKeyTaus( s.hash() ) ) , "Failed to retrieve Taus" ); - - ATH_MSG_INFO(" Taus with sgKey = "<<m_config->sgKeyTaus( s.hash() ) ); - for( auto x : *xaod ){ - ATH_MSG_INFO(" TAU pT , eta = "<<x->pt()<<" , "<<x->eta() ); + top::check(evtStore()->retrieve(xaod, m_config->sgKeyTaus(s.hash())), "Failed to retrieve Taus"); + + ATH_MSG_INFO(" Taus with sgKey = " << m_config->sgKeyTaus(s.hash())); + for (auto x : *xaod) { + ATH_MSG_INFO(" TAU pT , eta = " << x->pt() << " , " << x->eta()); } } - - return StatusCode::SUCCESS; + + return StatusCode::SUCCESS; } - - - void TauObjectCollectionMaker::specifiedSystematics( const std::set<std::string>& specifiedSystematics ) - { + + void TauObjectCollectionMaker::specifiedSystematics(const std::set<std::string>& specifiedSystematics) { ///-- Get the recommended systematics from the tool, in std::vector format --/// - const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( m_calibrationTool->recommendedSystematics() ); - + const std::vector<CP::SystematicSet> systList = CP::make_systematics_vector( + m_calibrationTool->recommendedSystematics()); + for (auto s : systList) { + + if(!m_config->getTreeFilter()->filterTree(s.name())) continue; // Applying tree filter m_recommendedSystematics.push_back(s); if (s.name() == "") { m_specifiedSystematics.push_back(s); } - + ///-- MC only --/// if (m_config->isMC()) { ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// - if (!m_config->isSystNominal( m_config->systematics() )) { + if (!m_config->isSystNominal(m_config->systematics())) { if (specifiedSystematics.size() == 0) { m_specifiedSystematics.push_back(s); } - if (specifiedSystematics.size() > 0) { + if (specifiedSystematics.size() > 0) { for (auto i : specifiedSystematics) { - if ( i == s.name() ) { - m_specifiedSystematics.push_back(s); + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematics.push_back(s); } } } } } - } - m_recommendedSystematics.sort(); + } + m_recommendedSystematics.sort(); m_recommendedSystematics.unique(); m_specifiedSystematics.sort(); - m_specifiedSystematics.unique(); + m_specifiedSystematics.unique(); } - } - - diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TrackSystematicsMaker.cxx b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TrackSystematicsMaker.cxx new file mode 100644 index 0000000000000000000000000000000000000000..57f7e33281aea284d42f5cefc1f6676cc7b2f756 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/Root/TrackSystematicsMaker.cxx @@ -0,0 +1,487 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#include "TopSystematicObjectMaker/TrackSystematicsMaker.h" + +#include <limits> + +#include "PATInterfaces/SystematicsUtil.h" + +#include "xAODEventInfo/EventInfo.h" +#include "xAODBase/IParticleHelpers.h" + +#include "xAODTracking/TrackParticle.h" +#include "xAODTracking/TrackParticleContainer.h" +#include "xAODTracking/TrackParticleAuxContainer.h" + +#include "TopEvent/EventTools.h" +#include "TopConfiguration/TopConfig.h" +#include "TopConfiguration/TreeFilter.h" + +#include "InDetTrackSystematicsTools/InDetTrackSystematics.h" +#include "InDetTrackSystematicsTools/InDetTrackSmearingTool.h" +#include "InDetTrackSystematicsTools/InDetTrackBiasingTool.h" +#include "InDetTrackSystematicsTools/InDetTrackTruthFilterTool.h" +#include "InDetTrackSystematicsTools/InDetTrackTruthOriginTool.h" + +// Other includes: +#include "xAODCore/ShallowCopy.h" + +namespace top { + /* explicit */ + TrackSystematicsMaker::TrackSystematicsMaker(const std::string& name) + : ::asg::AsgTool(name), + m_config(nullptr), + m_runPeriods(), + m_specifiedSystematics(), + m_recommendedSystematics(), + m_nominalSystematicSet(), + m_smearingTool("top::TrackCPTools::InDetTrackSmearingTool"), + m_truthOriginTool("top::TrackCPTools::InDetTrackTruthOriginTool"), + m_truthFilterTool("top::TrackCPTools::InDetTrackTruthFilterTool") + { + declareProperty("config", m_config); + } + + /* virtual */ TrackSystematicsMaker::~TrackSystematicsMaker() { + } + + StatusCode TrackSystematicsMaker::initialize() { + ATH_MSG_INFO(" top::TrackSystematicsMaker initialize"); + + ATH_MSG_WARNING("Usage of tracks in AnalysisTop is experimental for now!\n"); + + m_runPeriods = m_config->runPeriodsTrack(); + + m_specifiedSystematics.push_back(CP::SystematicSet()); + + // Retrieve the systematics tools. Each individual function will cause + // program abortion upon failure. This is intended as there's no + // meaningful method of recovery. + // These tools are setup and initialised in the TopCPTools package, and we just retrieve them here. + top::check(retrieveTrackCPTool(), "Failed to retrieve the track CP tools"); + + // Setup the recommended systematics. This utilises the tools that were + // setup before. + const std:: string& syststr = m_config->systematics(); + std::set<std::string> syst; + + if (m_config->isSystNominal(syststr)) { + + specifiedSystematics({}); + + + } else if (m_config->isSystAll(syststr)) { + + specifiedSystematics({"AllTracks"}); + + } else { + + std::set<std::string> syst; + bool ok = m_config->getSystematicsList(syststr, syst); + if (!ok) { + ATH_MSG_ERROR(" top::TrackSystematicsMaker could not determine systematic list"); + return StatusCode::FAILURE; + } + + + // No need to manually handle the AllTrack case in here. + specifiedSystematics(syst); + } + + + // Pass the systematics list back to the top::TopConfig object. + m_config->systematicsTracks(specifiedSystematics()); + + ATH_MSG_INFO(" top::TrackSystematicsMaker completed initialize"); + return StatusCode::SUCCESS; + } + + + + StatusCode TrackSystematicsMaker::applyTruthFilterSystematic(InDet::InDetTrackTruthFilterTool* tool, + const CP::SystematicSet& syst) const { + + if(m_config->sgKeyTracks(syst.hash()) == "InDetTrackParticles_") + return StatusCode::SUCCESS; + + // Create a shallow copy of InDetTrackParticles: + const xAOD::TrackParticleContainer *tp(nullptr); + top::check(evtStore()->retrieve(tp, "InDetTrackParticles"), "Retrieve InDetParticles"); + + std::pair< xAOD::TrackParticleContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *tp ); + + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), + "Failed to configure tool for systematic variation"); + + + + for ( xAOD::TrackParticle* trkCpy : *(shallow_xaod_copy.first) ) { + + + if (not tool->accept(trkCpy)) trkCpy->auxdecor<char>("passTruthFilter") = 0; + else trkCpy->auxdecor<char>("passTruthFilter") = 1; + + + } + + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeyTracks(syst.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } + + + StatusCode TrackSystematicsMaker::applySmearingSystematic(InDet::InDetTrackSmearingTool* tool, + const CP::SystematicSet& syst) const { + + + if(m_config->sgKeyTracks(syst.hash()) == "InDetTrackParticles_") + return StatusCode::SUCCESS; + + // Create a shallow copy of InDetTrackParticles: + const xAOD::TrackParticleContainer *tp(nullptr); + top::check(evtStore()->retrieve(tp, "InDetTrackParticles"), "Retrieve InDetParticles"); + + std::pair< xAOD::TrackParticleContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *tp ); + + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), "Failed to configure tool for systematic variation"); + + + for ( xAOD::TrackParticle* trkCpy : *(shallow_xaod_copy.first) ) { + + top::check(tool->applyCorrection(*trkCpy), "Failure to apply track systematic"); + + } + + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeyTracks(syst.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } + + StatusCode TrackSystematicsMaker::applyBiasingSystematic(InDet::InDetTrackBiasingTool* tool, + const CP::SystematicSet& syst) const { + + if(m_config->sgKeyTracks(syst.hash()) == "InDetTrackParticles_") + return StatusCode::SUCCESS; + + + // Create a shallow copy of InDetTrackParticles: + const xAOD::TrackParticleContainer *tp(nullptr); + top::check(evtStore()->retrieve(tp, "InDetTrackParticles"), "Retrieve InDetParticles"); + + std::pair< xAOD::TrackParticleContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *tp ); + + ///-- Inform the tool --/// + top::check(tool->applySystematicVariation(syst), + "Failed to configure tool for systematic variation"); + + for ( xAOD::TrackParticle* trkCpy : *(shallow_xaod_copy.first) ) { + + top::check(tool->applyCorrection(*trkCpy), "Failure to apply track systematic"); + + } + + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeyTracks(syst.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + return StatusCode::SUCCESS; + } + + StatusCode TrackSystematicsMaker::execute(bool executeNominal) { + ATH_MSG_DEBUG(" top::TrackSystematicsMaker execute:"); + + + if (!m_config->isMC() && executeNominal) { + + // Create a shallow copy of InDetTrackParticles: + const xAOD::TrackParticleContainer *tp(nullptr); + top::check(evtStore()->retrieve(tp, "InDetTrackParticles"), "Retrieve InDetParticles"); + + std::pair< xAOD::TrackParticleContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *tp ); + + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeyTracks(m_nominalSystematicSet.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + + return StatusCode::SUCCESS; + } + if (!m_config->isMC() && !executeNominal) { + return StatusCode::SUCCESS; + } + + + ///-- Only run this on the systematic execution --/// + if (executeNominal){ + + // Create a shallow copy of InDetTrackParticles: + const xAOD::TrackParticleContainer *tp(nullptr); + top::check(evtStore()->retrieve(tp, "InDetTrackParticles"), "Retrieve InDetParticles"); + + std::pair< xAOD::TrackParticleContainer*, xAOD::ShallowAuxContainer* > shallow_xaod_copy = xAOD::shallowCopyContainer( *tp ); + + ///-- Save corrected xAOD Container to StoreGate / TStore --/// + std::string outputSGKey = m_config->sgKeyTracks(m_nominalSystematicSet.hash()); + std::string outputSGKeyAux = outputSGKey + "Aux."; + + xAOD::TReturnCode save = evtStore()->tds()->record(shallow_xaod_copy.first, outputSGKey); + xAOD::TReturnCode saveAux = evtStore()->tds()->record(shallow_xaod_copy.second, outputSGKeyAux); + + if (!save || !saveAux) { + return StatusCode::FAILURE; + } + + + return StatusCode::SUCCESS; + + } + + ///-- SMEARING --/// + for (const auto& syst : m_systs.smearing) { + top::check(applySmearingSystematic(&(*m_smearingTool), syst), + "Failure to apply TrackSystematic"); + } + + ///-- BIASING --/// + InDet::InDetTrackBiasingTool* biasingTool { + nullptr + }; + + if (m_runPeriods.size() == 1) { + biasingTool = &(*m_biasTool[0]); + + top::check(biasingTool, "Failure to selected biasing tool"); + for (const auto& syst : m_systs.bias) { + top::check(applyBiasingSystematic(biasingTool, syst), + "Failure to apply TrackSystematic"); + } + } + else { + const xAOD::EventInfo* ei { + nullptr + }; + top::check(evtStore()->retrieve(ei, "EventInfo"), + "Failure to retrieve EventInfo"); + + top::check(ei->isAvailable<unsigned int>("RandomRunNumber"), + "Require that RandomRunNumber decoration is available."); + auto randomRunNumber = ei->auxdataConst<unsigned int>("RandomRunNumber"); + + if (randomRunNumber != 0 ){ + top::check(m_runPeriods[0] <= randomRunNumber, + "RandomRunNumber is below valid range."); + top::check(randomRunNumber < m_runPeriods[m_runPeriods.size() - 1], + "RandomRunNumber is above valid range."); + + for (std::size_t i = 1; i < m_runPeriods.size(); ++i) { + if (randomRunNumber < m_runPeriods[i]) { + biasingTool = &(*m_biasTool[i - 1]); + break; + } + } + top::check(biasingTool, "Failure to selected biasing tool"); + for (const auto& syst : m_systs.bias) { + top::check(applyBiasingSystematic(biasingTool, syst), + "Failure to apply TrackSystematic"); + } + } + } + + ///-- TRUTH FILTER --/// + for (const auto& syst : m_systs.truthFilter) { + + top::check(applyTruthFilterSystematic(&(*m_truthFilterTool), syst), + "Failure to apply TrackSystematic"); + } + + ATH_MSG_DEBUG(" top::TrackSystematicsMaker completed execute"); + return StatusCode::SUCCESS; + } + + void TrackSystematicsMaker::specifiedSystematics(const std::set<std::string>& specSys) { + + // NOTE: For this function -- unlike the "proper" ObjectCollectionMakers in AnalysisTop -- an empty + // specifiedSystematics input is considered to represent "No Systematics". All Track systematics can be + // requested with the string "AllTrack". + const bool allTrackSystematics = m_config->contains(specSys, "AllTracks"); + + // Acquire the recommended systematics from the various tools and put + // into containers that store the per-tool systematics as well as a + // global container. At a later point we'll make the per-tool containers + // unique and check that the containers for various tools are + // orthogonal. + std::set<CP::SystematicSet> systs; + + // SMEARING + m_systs.smearing = CP::make_systematics_vector(m_smearingTool->recommendedSystematics()); + systs.insert(m_systs.smearing.begin(), m_systs.smearing.end()); + + // BIAS + for (const auto& tool : m_biasTool) { + m_systs.bias = + CP::make_systematics_vector(tool->recommendedSystematics()); + systs.insert(m_systs.bias.begin(), m_systs.bias.end()); + } + + // TRUTH FILTER + m_systs.truthFilter = + CP::make_systematics_vector(m_truthFilterTool->recommendedSystematics()); + systs.insert(m_systs.truthFilter.begin(), m_systs.truthFilter.end()); + + // PUT INTO RECOMMENDED AND SPECIFIED + for (const auto& s : systs) { + + // We don't want nominal. + if (s.name() == "") { + continue; + } + + m_recommendedSystematics.push_back(s); + + ///-- MC only --/// + if (m_config->isMC()) { + ///-- Are we only doing Nominal? Did the user specify specific systematics to use? --/// + if (!m_config->isSystNominal(m_config->systematics())) { + if (allTrackSystematics) { + + m_specifiedSystematics.push_back(s); + continue; + } + + for (const auto& i : specSys) { + TreeFilter filter(i); + if (!filter.filterTree(s.name())) { + m_specifiedSystematics.push_back(s); + } + } + } + } + } + + m_recommendedSystematics.sort(); + m_recommendedSystematics.unique(); + + m_specifiedSystematics.sort(); + m_specifiedSystematics.unique(); + + // Make the sublists unique and remove any elements that have not "been specified". + m_systs.makeUnique(); + m_systs.removeNonSpecified(m_specifiedSystematics); + + // Lastly, let use introduce a safeguard which ensures that the + // systematics selected for the various tools are orthogonal. This is + // done by asserting that the sum of the sizes of the individual + // systematics lists equals the size of the list of specified + // systematics. We can do this because we've made the individual + // per-tool containers unique (in makeUnique). + if(m_specifiedSystematics.size() > 1) + top::check(systs.size() == m_specifiedSystematics.size(), "Sanity check failed"); + else + top::check(m_specifiedSystematics.size() == 1, "Sanity check failed"); + + + } + + StatusCode TrackSystematicsMaker::retrieveTrackCPTool() { + ATH_MSG_INFO(" Retrieving track CPTools"); + + + top::check(m_smearingTool.retrieve(), "Failed to retrieve track smearing tool"); + + std::string biasToolPrefix {"top::TrackCPTools::InDetTrackBiasingTool"}; + top::check(not m_runPeriods.empty(), "Assertion failed"); + // Two cases are possible: + // - Either a single run number was specified to the runPeriods + // parameter in which case we'll use exactly that run number, or + // - at least two numbers have been specified, which then define + // (potentially multiple) run number ranges. + unsigned int end = 0; + if (m_runPeriods.size() == 1) { + end = 1; + m_biasTool.resize(1); + } else { + end = m_runPeriods.size() - 1; + m_biasTool.resize(m_runPeriods.size() - 1); + } + + for (unsigned int i = 0; i < end; i++) { + + + std::string biasToolName { + "" + }; + if (m_runPeriods.size() == 1) { + biasToolName = biasToolPrefix + "_" + std::to_string(m_runPeriods[0]); + } + else { + biasToolName = biasToolPrefix + "_" + std::to_string(m_runPeriods[i]) + "_" + + std::to_string(m_runPeriods[i + 1]); + } + + + if (asg::ToolStore::contains<InDet::InDetTrackBiasingTool>(biasToolName)) { + m_biasTool[i] = asg::ToolStore::get<InDet::InDetTrackBiasingTool>(biasToolName); + } else { + ATH_MSG_ERROR(" Impossible to retrieve " + biasToolName); + return StatusCode::FAILURE; + } + + + + } + + top::check(m_truthOriginTool.retrieve(), "Failed to retrieve track truth origin tool"); + top::check(m_truthFilterTool.retrieve(), "Failed to retrieve track truth filter tool"); + + + return StatusCode::SUCCESS; + } + + + inline const std::list<CP::SystematicSet>& TrackSystematicsMaker::specifiedSystematics() const { + return m_specifiedSystematics; + } + + inline const std::list<CP::SystematicSet>& TrackSystematicsMaker::recommendedSystematics() const { + return m_recommendedSystematics; + } + +} diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/EgammaObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/EgammaObjectCollectionMaker.h index ee3e1b2a6a0530ea5b1c39946d2b6a570177d521..a5eb11e2b91b9b9a3c4cdef09a1bb346ed1305bd 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/EgammaObjectCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/EgammaObjectCollectionMaker.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ -// $Id: EgammaObjectCollectionMaker.h 802735 2017-04-11 16:38:01Z tpelzer $ +// $Id: EgammaObjectCollectionMaker.h 811374 2017-10-24 13:04:52Z iconnell $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_EGAMMAOBJECTCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_EGAMMAOBJECTCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief EgammaObjectCollectionMaker - * Makes all systematic variations of photons and electrons - * - * $Revision: 802735 $ - * $Date: 2017-04-11 18:38:01 +0200 (Tue, 11 Apr 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief EgammaObjectCollectionMaker + * Makes all systematic variations of photons and electrons + * + * $Revision: 811374 $ + * $Date: 2017-10-24 14:04:52 +0100 (Tue, 24 Oct 2017) $ + * + **/ // system include(s): #include <memory> @@ -30,73 +30,108 @@ #include "PATInterfaces/SystematicSet.h" // CP Tool include(s): -#include "ElectronPhotonFourMomentumCorrection/IEgammaCalibrationAndSmearingTool.h" -#include "ElectronPhotonShowerShapeFudgeTool/IElectronPhotonShowerShapeFudgeTool.h" +#include "EgammaAnalysisInterfaces/IEgammaCalibrationAndSmearingTool.h" +#include "EgammaAnalysisInterfaces/IElectronPhotonShowerShapeFudgeTool.h" #include "IsolationSelection/IIsolationSelectionTool.h" +//#include "IsolationSelection/IIsolationLowPtPLVTool.h" #include "IsolationCorrections/IIsolationCorrectionTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class EgammaObjectCollectionMaker final : public asg::AsgTool { - public: - explicit EgammaObjectCollectionMaker( const std::string& name ); - virtual ~EgammaObjectCollectionMaker(){} - - // Delete Standard constructors - EgammaObjectCollectionMaker(const EgammaObjectCollectionMaker& rhs) = delete; - EgammaObjectCollectionMaker(EgammaObjectCollectionMaker&& rhs) = delete; - EgammaObjectCollectionMaker& operator=(const EgammaObjectCollectionMaker& rhs) = delete; - - StatusCode initialize(); - - StatusCode executePhotons(); - StatusCode executeElectrons(); - - StatusCode printoutPhotons(); - StatusCode printoutElectrons(); - - // return specific Systematic - inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsPhotons() const {return m_specifiedSystematicsPhotons;} - inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsElectrons() const {return m_specifiedSystematicsElectrons;} - - // return all recommendedSystematics - inline const std::list<CP::SystematicSet>& recommendedSystematicsPhotons() const {return m_recommendedSystematicsPhotons;} - inline const std::list<CP::SystematicSet>& recommendedSystematicsElectrons() const {return m_recommendedSystematicsElectrons;} - - protected: - // specify Systematic - virtual void specifiedSystematicsPhotons ( const std::set<std::string>& specifiedSystematics ); - virtual void specifiedSystematicsElectrons( const std::set<std::string>& specifiedSystematics ); - - private: - std::shared_ptr<top::TopConfig> m_config; - - std::list<CP::SystematicSet> m_specifiedSystematicsPhotons; - std::list<CP::SystematicSet> m_specifiedSystematicsElectrons; - - std::list<CP::SystematicSet> m_recommendedSystematicsPhotons; - std::list<CP::SystematicSet> m_recommendedSystematicsElectrons; - - ToolHandle<CP::IEgammaCalibrationAndSmearingTool> m_calibrationTool; - ToolHandle<IElectronPhotonShowerShapeFudgeTool> m_photonFudgeTool; - - ///-- Isolation --/// - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_LooseTrackOnly; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Loose; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Gradient; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_GradientLoose; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTight; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTightTrackOnly; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTightCaloOnly; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutLoose; - - ToolHandle<CP::IIsolationCorrectionTool> m_isolationCorr; - +namespace top { + class EgammaObjectCollectionMaker final: public asg::AsgTool { + public: + explicit EgammaObjectCollectionMaker(const std::string& name); + virtual ~EgammaObjectCollectionMaker() {} + + // Delete Standard constructors + EgammaObjectCollectionMaker(const EgammaObjectCollectionMaker& rhs) = delete; + EgammaObjectCollectionMaker(EgammaObjectCollectionMaker&& rhs) = delete; + EgammaObjectCollectionMaker& operator = (const EgammaObjectCollectionMaker& rhs) = delete; + + StatusCode initialize(); + + StatusCode executePhotons(bool); + StatusCode executeElectrons(bool); + StatusCode executeFwdElectrons(bool); + + StatusCode printoutPhotons(); + StatusCode printoutElectrons(); + StatusCode printoutFwdElectrons(); + + // return specific Systematic + inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsPhotons() const { + return m_specifiedSystematicsPhotons; + } + inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsElectrons() const { + return m_specifiedSystematicsElectrons; + } + inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsFwdElectrons() const { + return m_specifiedSystematicsFwdElectrons; + } + + // return all recommendedSystematics + inline const std::list<CP::SystematicSet>& recommendedSystematicsPhotons() const { + return m_recommendedSystematicsPhotons; + } + inline const std::list<CP::SystematicSet>& recommendedSystematicsElectrons() const {return m_recommendedSystematicsElectrons;} + inline const std::list<CP::SystematicSet>& recommendedSystematicsFwdElectrons() const {return m_recommendedSystematicsFwdElectrons;} + protected: + // specify Systematic + virtual void specifiedSystematicsPhotons(const std::set<std::string>& specifiedSystematics); + virtual void specifiedSystematicsElectrons(const std::set<std::string>& specifiedSystematics); + virtual void specifiedSystematicsFwdElectrons(const std::set<std::string>& specifiedSystematics); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::list<CP::SystematicSet> m_specifiedSystematicsPhotons; + std::list<CP::SystematicSet> m_specifiedSystematicsElectrons; + std::list<CP::SystematicSet> m_specifiedSystematicsFwdElectrons; + + std::list<CP::SystematicSet> m_recommendedSystematicsPhotons; + std::list<CP::SystematicSet> m_recommendedSystematicsElectrons; + std::list<CP::SystematicSet> m_recommendedSystematicsFwdElectrons; + + ToolHandle<CP::IEgammaCalibrationAndSmearingTool> m_calibrationTool; + ToolHandle<IElectronPhotonShowerShapeFudgeTool> m_photonFudgeTool; + + ///-- Isolation --/// + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_LooseTrackOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Loose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PflowLoose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Tight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PflowTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Gradient; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_GradientLoose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTightTrackOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_TightTrackOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_TightTrackOnly_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTightCaloOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_TightCaloOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutLoose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutHighPtCaloOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCHighPtCaloOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_HighPtCaloOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCLoose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PLVTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PLVLoose; + +// ToolHandle<CP::IIsolationLowPtPLVTool> m_isolationTool_LowPtPLV; + + ToolHandle<CP::IIsolationCorrectionTool> m_isolationCorr; + + // Flag for applying calibration to objects + bool calibrateElectrons; + bool calibrateFwdElectrons; + bool calibratePhotons; + + // Flag for recomputing CP vars + bool m_recomputePhotonFudge; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ElectronInJetSubtractionCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ElectronInJetSubtractionCollectionMaker.h index 0c7437f51e27bc74e4f5a68626c0185c2dd8d469..e52620624c8698de5fdeb0de521be583ac3e3398 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ElectronInJetSubtractionCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ElectronInJetSubtractionCollectionMaker.h @@ -1,30 +1,30 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: ElectronInJetSubtractionCollectionMaker.h 653798 2015-03-12 19:24:22Z morrisj $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_ELECTRONINJETSUBTRACTIONCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_ELECTRONINJETSUBTRACTIONCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief ElectronInJetSubtractionCollectionMaker - * Makes all needed collections for the Electron in jet subtraction - * Used by boosted analysis - * - * Will require a set of electron and jet collections for: - * Nominal - * All Electron systematics - * All Jet systematics - * - * This class does not do the actual subtraction algorithm - * This class prepares the collections and calls the algorithm - * - * $Revision: 653798 $ - * $Date: 2015-03-12 20:24:22 +0100 (Thu, 12 Mar 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief ElectronInJetSubtractionCollectionMaker + * Makes all needed collections for the Electron in jet subtraction + * Used by boosted analysis + * + * Will require a set of electron and jet collections for: + * Nominal + * All Electron systematics + * All Jet systematics + * + * This class does not do the actual subtraction algorithm + * This class prepares the collections and calls the algorithm + * + * $Revision: 653798 $ + * $Date: 2015-03-12 19:24:22 +0000 (Thu, 12 Mar 2015) $ + * + **/ // system include(s): #include <memory> @@ -38,30 +38,28 @@ #include "TopJetSubstructure/ElectronInJetSubtractionAlgorithm.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class ElectronInJetSubtractionCollectionMaker final : public asg::AsgTool { - public: - explicit ElectronInJetSubtractionCollectionMaker( const std::string& name ); - virtual ~ElectronInJetSubtractionCollectionMaker(){} - - // Delete Standard constructors - ElectronInJetSubtractionCollectionMaker(const ElectronInJetSubtractionCollectionMaker& rhs) = delete; - ElectronInJetSubtractionCollectionMaker(ElectronInJetSubtractionCollectionMaker&& rhs) = delete; - ElectronInJetSubtractionCollectionMaker& operator=(const ElectronInJetSubtractionCollectionMaker& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - private: - std::shared_ptr<top::TopConfig> m_config; - bool m_doLooseCuts; - // The algorithm - top::ElectronInJetSubtractionAlgorithm m_subtractionAlgorithm; +namespace top { + class ElectronInJetSubtractionCollectionMaker final: public asg::AsgTool { + public: + explicit ElectronInJetSubtractionCollectionMaker(const std::string& name); + virtual ~ElectronInJetSubtractionCollectionMaker() {} + + // Delete Standard constructors + ElectronInJetSubtractionCollectionMaker(const ElectronInJetSubtractionCollectionMaker& rhs) = delete; + ElectronInJetSubtractionCollectionMaker(ElectronInJetSubtractionCollectionMaker&& rhs) = delete; + ElectronInJetSubtractionCollectionMaker& operator = (const ElectronInJetSubtractionCollectionMaker& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(bool); + private: + std::shared_ptr<top::TopConfig> m_config; + bool m_doLooseCuts; + // The algorithm + top::ElectronInJetSubtractionAlgorithm m_subtractionAlgorithm; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/GhostTrackSystematicsMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/GhostTrackSystematicsMaker.h index e5f19550dc04a7984877f150ec15ad4d5ea61c6f..6e8052f42ba89cd478531b5dcad2a3437b4b9551 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/GhostTrackSystematicsMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/GhostTrackSystematicsMaker.h @@ -1,14 +1,12 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ // Filename: GhostTrackSystematicsMaker.h // Description: // Author: Fabian Wilk // Created: Mon Oct 24 16:54:17 2016 -// -// by Fabian Wilk <mail@fabianwilk.de> -// The ATLAS Collaboration + #ifndef _TOP_GHOSTTRACKSYSTEMATICSMAKER_H_ #define _TOP_GHOSTTRACKSYSTEMATICSMAKER_H_ @@ -30,182 +28,179 @@ // Forward Declarations. namespace InDet { - class InDetTrackSystematicsTool; - class InDetTrackSmearingTool; - class InDetTrackBiasingTool; - class InDetTrackTruthFilterTool; - class InDetTrackTruthOriginTool; - class JetTrackFilterTool; + class InDetTrackSystematicsTool; + class InDetTrackSmearingTool; + class InDetTrackBiasingTool; + class InDetTrackTruthFilterTool; + class InDetTrackTruthOriginTool; + class JetTrackFilterTool; } namespace top { - class TopConfig; + class TopConfig; } namespace top { + /* + * @brief Tool for making systematics that affect ghost-associated tracks of + * jets available. + * + * Ghost-associated tracks are available on jets through the + * getAssociatedObjects function which retrieves a + * + * std::vector<const xAOD::IParticle*> + * + * container that is decorated onto each jet object. + * + * This tool, produces one copy of this container for each of the affecting + * and requested systematics. Some systematics change only the number of + * tracks (efficiency-style systematics) while other only smear (some) of + * the track particle properties. + * + * The requested systematics are retrieved from top::TopConfig, filtered to + * only contain those affecting the ghost tracks, and propagated back to + * the top::TopConfig instance so that they become available to any tool + * which wishes to query + * + * - the affecting systematics, + * - the decoration name used for the varied ghost track container + * + * Generally, a tool should use the function + * + * top::TopConfig::systMapJetGhostTrack() + * + * to retrieve the mapping from the hash value of a systematic to the + * CP::SystematicSet of that variation for all (configured and requested) + * systematics that affect the ghost tracks (this map includes the nominal + * systematic). The decoration name can then be retrieved using + * + * top::TopConfig::decoKeyJetGhostTrack(std::size_t hash) + */ + class GhostTrackSystematicsMaker final: public asg::AsgTool { + public: + explicit GhostTrackSystematicsMaker(const std::string& name); + virtual ~GhostTrackSystematicsMaker(); + + GhostTrackSystematicsMaker(const GhostTrackSystematicsMaker& rhs) = delete; + GhostTrackSystematicsMaker(GhostTrackSystematicsMaker&& rhs) = delete; + GhostTrackSystematicsMaker& operator = (const GhostTrackSystematicsMaker& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(bool); /* - * @brief Tool for making systematics that affect ghost-associated tracks of - * jets available. - * - * Ghost-associated tracks are available on jets through the - * getAssociatedObjects function which retrieves a - * - * std::vector<const xAOD::IParticle*> - * - * container that is decorated onto each jet object. - * - * This tool, produces one copy of this container for each of the affecting - * and requested systematics. Some systematics change only the number of - * tracks (efficiency-style systematics) while other only smear (some) of - * the track particle properties. - * - * The requested systematics are retrieved from top::TopConfig, filtered to - * only contain those affecting the ghost tracks, and propagated back to - * the top::TopConfig instance so that they become available to any tool - * which wishes to query - * - * - the affecting systematics, - * - the decoration name used for the varied ghost track container + * @brief Retrieve the specified (requested) systematics list.* * - * Generally, a tool should use the function - * - * top::TopConfig::systMapJetGhostTrack() - * - * to retrieve the mapping from the hash value of a systematic to the - * CP::SystematicSet of that variation for all (configured and requested) - * systematics that affect the ghost tracks (this map includes the nominal - * systematic). The decoration name can then be retrieved using - * - * top::TopConfig::decoKeyJetGhostTrack(std::size_t hash) + * Unless systematics have been requested through the + * specifiedSystematics setter function, this will be an empty list. */ - class GhostTrackSystematicsMaker final : public asg::AsgTool { - public: - explicit GhostTrackSystematicsMaker(const std::string & name); - virtual ~GhostTrackSystematicsMaker(); - - GhostTrackSystematicsMaker(const GhostTrackSystematicsMaker & rhs) = delete; - GhostTrackSystematicsMaker(GhostTrackSystematicsMaker && rhs) = delete; - GhostTrackSystematicsMaker & operator=(const GhostTrackSystematicsMaker & rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - /* - * @brief Retrieve the specified (requested) systematics list.* - * - * Unless systematics have been requested through the - * specifiedSystematics setter function, this will be an empty list. - */ - inline virtual const std::list<CP::SystematicSet> & specifiedSystematics() const; - - /* - * @brief Retrieve the recommended systematics list. - * - * This will return a meaningless (probably empty) list unless the - * setter function specifiedSystematics has been called or the tool has - * been initialized (which call specifiedSystematics using the data - * obtained from top::TopConfig). - */ - inline const std::list<CP::SystematicSet> & recommendedSystematics() const; - - /*! - * @brief Specify the systematics to be used. - * @param specifiedSystematics Set of systematics (by name) to be used; - * an empty set will result in no systematic variation. - */ - virtual void specifiedSystematics(const std::set<std::string> & specifiedSystematics); - - protected: - StatusCode applyNoOpSystematic(xAOD::JetContainer * nominal, - const CP::SystematicSet & syst) const; - - StatusCode applyTruthFilterSystematic(xAOD::JetContainer * nominal, - InDet::InDetTrackTruthFilterTool * tool, - const CP::SystematicSet & syst) const; - - StatusCode applySmearingSystematic(xAOD::JetContainer * nominal, - InDet::InDetTrackSmearingTool * tool, - const CP::SystematicSet & syst) const; - - StatusCode applyBiasingSystematic(xAOD::JetContainer * nominal, - InDet::InDetTrackBiasingTool * tool, - const CP::SystematicSet & syst) const; - - StatusCode applyJetTrackFilterSystematic(xAOD::JetContainer * nominal, - InDet::JetTrackFilterTool * tool, - const CP::SystematicSet & syst) const; - - private: - StatusCode retrieveGhostTrackCPTool(); - - private: - std::shared_ptr<top::TopConfig> m_config; - std::vector<std::uint32_t> m_runPeriods; - - std::list<CP::SystematicSet> m_specifiedSystematics; - std::list<CP::SystematicSet> m_recommendedSystematics; - - CP::SystematicSet m_nominalSystematicSet; - - struct { - void makeUnique(){ - static auto exec = [](std::vector<CP::SystematicSet> & data){ - std::sort(data.begin(), data.end()); - data.erase(std::unique(data.begin(), data.end()), - data.end()); - }; - - exec(smearing); - exec(truthFilter); - exec(bias); - exec(jetTrackFilter); - } - - void removeNonSpecified(const std::list<CP::SystematicSet> & specified){ - auto fnCmp = [&specified](CP::SystematicSet & s){ - return std::find(specified.begin(), - specified.end(), - s) == specified.end(); - }; - - auto exec = [&specified, &fnCmp](std::vector<CP::SystematicSet> & data){ - data.erase(std::remove_if(data.begin(), data.end(), fnCmp), - data.end()); - }; - - exec(smearing); - exec(truthFilter); - exec(bias); - exec(jetTrackFilter); - } - - std::size_t numSystematics() const { - return smearing.size() + truthFilter.size() + bias.size() + jetTrackFilter.size(); - } - - std::vector<CP::SystematicSet> smearing, truthFilter, bias, jetTrackFilter; - } m_systs; - - struct { - ToolHandle<InDet::InDetTrackSmearingTool> smearing; - ToolHandle<InDet::InDetTrackTruthOriginTool> truthOrigin; - ToolHandle<InDet::InDetTrackTruthFilterTool> truthFilter; - ToolHandle<InDet::JetTrackFilterTool> jetTrackFilter; - - std::vector<ToolHandle<InDet::InDetTrackBiasingTool> > bias; - } m_tools; - }; - - /* inline virtual */ const std::list<CP::SystematicSet> & GhostTrackSystematicsMaker::specifiedSystematics() const { - return m_specifiedSystematics; - - } - /* inline */ const std::list<CP::SystematicSet> & GhostTrackSystematicsMaker::recommendedSystematics() const { - return m_recommendedSystematics; - } + inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const; + /* + * @brief Retrieve the recommended systematics list. + * + * This will return a meaningless (probably empty) list unless the + * setter function specifiedSystematics has been called or the tool has + * been initialized (which call specifiedSystematics using the data + * obtained from top::TopConfig). + */ + inline const std::list<CP::SystematicSet>& recommendedSystematics() const; + /*! + * @brief Specify the systematics to be used. + * @param specifiedSystematics Set of systematics (by name) to be used; + * an empty set will result in no systematic variation. + */ + virtual void specifiedSystematics(const std::set<std::string>& specifiedSystematics); + protected: + StatusCode applyNoOpSystematic(xAOD::JetContainer* nominal, + const CP::SystematicSet& syst) const; + + StatusCode applyTruthFilterSystematic(xAOD::JetContainer* nominal, + InDet::InDetTrackTruthFilterTool* tool, + const CP::SystematicSet& syst) const; + + StatusCode applySmearingSystematic(xAOD::JetContainer* nominal, + InDet::InDetTrackSmearingTool* tool, + const CP::SystematicSet& syst) const; + + StatusCode applyBiasingSystematic(xAOD::JetContainer* nominal, + InDet::InDetTrackBiasingTool* tool, + const CP::SystematicSet& syst) const; + + StatusCode applyJetTrackFilterSystematic(xAOD::JetContainer* nominal, + InDet::JetTrackFilterTool* tool, + const CP::SystematicSet& syst) const; + private: + StatusCode retrieveGhostTrackCPTool(); + private: + std::shared_ptr<top::TopConfig> m_config; + double m_jetPtCut, m_jetEtaCut; + std::vector<std::uint32_t> m_runPeriods; + + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_recommendedSystematics; + + CP::SystematicSet m_nominalSystematicSet; + + + + struct { + void makeUnique() { + static auto exec = [](std::vector<CP::SystematicSet>& data) { + std::sort(data.begin(), data.end()); + data.erase(std::unique(data.begin(), data.end()), + data.end()); + }; + + exec(smearing); + exec(truthFilter); + exec(bias); + exec(jetTrackFilter); + } + + void removeNonSpecified(const std::list<CP::SystematicSet>& specified) { + auto fnCmp = [&specified](CP::SystematicSet& s) { + return std::find(specified.begin(), + specified.end(), + s) == specified.end(); + }; + + auto exec = [&specified, &fnCmp](std::vector<CP::SystematicSet>& data) { + data.erase(std::remove_if(data.begin(), data.end(), fnCmp), + data.end()); + }; + + exec(smearing); + exec(truthFilter); + exec(bias); + exec(jetTrackFilter); + } + + std::size_t numSystematics() const { + return smearing.size() + truthFilter.size() + bias.size() + jetTrackFilter.size(); + } + + std::vector<CP::SystematicSet> smearing, truthFilter, bias, jetTrackFilter; + } m_systs; + + struct { + ToolHandle<InDet::InDetTrackSmearingTool> smearing; + ToolHandle<InDet::InDetTrackTruthOriginTool> truthOrigin; + ToolHandle<InDet::InDetTrackTruthFilterTool> truthFilter; + ToolHandle<InDet::JetTrackFilterTool> jetTrackFilter; + + std::vector<ToolHandle<InDet::InDetTrackBiasingTool> > bias; + } m_tools; + }; + + /* inline virtual */ const std::list<CP::SystematicSet>& GhostTrackSystematicsMaker::specifiedSystematics() const { + return m_specifiedSystematics; + } + + /* inline */ const std::list<CP::SystematicSet>& GhostTrackSystematicsMaker::recommendedSystematics() const { + return m_recommendedSystematics; + } } #endif /* _TOP_GHOSTTRACKSYSTEMATICSMAKER_H_ */ diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/JetObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/JetObjectCollectionMaker.h index 8bc19a79a6894171c37aa20fea70abf353aca70b..55ce24c27f7a5db2a57955ec5b901696c6301b14 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/JetObjectCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/JetObjectCollectionMaker.h @@ -1,28 +1,28 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration */ -// $Id: JetObjectCollectionMaker.h 794215 2017-01-27 15:12:13Z tpelzer $ +// $Id: JetObjectCollectionMaker.h 809674 2017-08-23 14:10:24Z iconnell $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_JETOBJECTCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_JETOBJECTCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief JetObjectCollectionMaker - * Makes all systematic variations of jets - * - * This is actually quite a complex tool - * The steps are as follows - * (1) Calibrate data/MC jets and save this collection to TStore - * (2) Loop over the various NP JES scenarios, using the output of (1) as an input - * (3) Loop over the various NP JER scenarios, using the output of (1) as an input - * (2.a , 3.a) Re-calculate the JVT for each jet - * - * $Revision: 794215 $ - * $Date: 2017-01-27 16:12:13 +0100 (Fri, 27 Jan 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief JetObjectCollectionMaker + * Makes all systematic variations of jets + * + * This is actually quite a complex tool + * The steps are as follows + * (1) Calibrate data/MC jets and save this collection to TStore + * (2) Loop over the various NP JES scenarios, using the output of (1) as an input + * (3) Loop over the various NP JER scenarios, using the output of (1) as an input + * (2.a , 3.a) Re-calculate the JVT for each jet + * + * $Revision: 809674 $ + * $Date: 2017-08-23 15:10:24 +0100 (Wed, 23 Aug 2017) $ + * + **/ // system include(s): #include <memory> @@ -42,119 +42,133 @@ // CP Tool include(s): #include "JetCalibTools/IJetCalibrationTool.h" #include "JetCPInterfaces/ICPJetUncertaintiesTool.h" -#include "JetResolution/IJERSmearingTool.h" #include "JetInterface/IJetUpdateJvt.h" #include "TopJetSubstructure/TopJetSubstructure.h" +#include "FTagAnalysisInterfaces/IBTaggingSelectionTool.h" +#include "JetAnalysisInterfaces/IJetSelectorTool.h" +//#include "ParticleJetTools/JetTruthLabelingTool.h" + // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class JetObjectCollectionMaker final : public asg::AsgTool { - - using systMap = std::unordered_map<CP::SystematicSet,CP::SystematicSet>; - - public: - explicit JetObjectCollectionMaker( const std::string& name ); - virtual ~JetObjectCollectionMaker(){} - - // Delete Standard constructors - JetObjectCollectionMaker(const JetObjectCollectionMaker& rhs) = delete; - JetObjectCollectionMaker(JetObjectCollectionMaker&& rhs) = delete; - JetObjectCollectionMaker& operator=(const JetObjectCollectionMaker& rhs) = delete; - - StatusCode initialize(); - - StatusCode executeJets(); - StatusCode executeLargeRJets(); - StatusCode executeTrackJets(); - - StatusCode printoutJets(); - StatusCode printoutLargeRJets(); - - // return specific Systematic - inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} - inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsLargeR() const {return m_specifiedSystematicsLargeR;} +namespace top { + class JetObjectCollectionMaker final: public asg::AsgTool { + using systMap = std::unordered_map<CP::SystematicSet, CP::SystematicSet>; + public: + explicit JetObjectCollectionMaker(const std::string& name); + virtual ~JetObjectCollectionMaker() {} + + // Delete Standard constructors + JetObjectCollectionMaker(const JetObjectCollectionMaker& rhs) = delete; + JetObjectCollectionMaker(JetObjectCollectionMaker&& rhs) = delete; + JetObjectCollectionMaker& operator = (const JetObjectCollectionMaker& rhs) = delete; + + StatusCode initialize(); + + StatusCode executeJets(bool); + StatusCode executeLargeRJets(bool); + StatusCode executeTrackJets(bool); + + StatusCode printoutJets(); + StatusCode printoutLargeRJets(); + + // return specific Systematic + inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} + inline virtual const std::list<CP::SystematicSet>& specifiedSystematicsLargeR() const { + return m_specifiedSystematicsLargeR; + } + + // return all recommendedSystematics + inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} + protected: - // return all recommendedSystematics - inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} - - protected: - // specify Systematic - virtual void specifiedSystematics( const std::set<std::string>& specifiedSystematics , const ToolHandle<ICPJetUncertaintiesTool>& tool , std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map , const std::string& modName , bool isLargeR = false); - virtual void specifiedSystematics( const std::set<std::string>& specifiedSystematics , const ToolHandle<IJERSmearingTool>& tool , std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map ); - - StatusCode execute( const bool isLargeR ); - - StatusCode calibrate( const bool isLargeR ); - virtual StatusCode applySystematic( ToolHandle<ICPJetUncertaintiesTool>& tool, const std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map , bool isLargeR = false); - virtual StatusCode applySystematic( ToolHandle<IJERSmearingTool>& tool, const std::unordered_map<CP::SystematicSet,CP::SystematicSet>& map ); - - StatusCode printout( const bool isLargeR ); - - void addCorrelation(const std::string& name, - systMap& map_one, - const std::string& syst_one_name, - systMap& map_two, - const std::string& syst_two_name); - - void addCorrelation(const std::string& name, - systMap& map_one, - const std::string& syst_one_name, - std::list<CP::SystematicSet>& jet_specified); - - - private: - std::shared_ptr<top::TopConfig> m_config; - bool m_doJER; - bool m_doFull_JER; - - bool m_do_fjvt = false; - - std::list<CP::SystematicSet> m_specifiedSystematics; - std::list<CP::SystematicSet> m_specifiedSystematicsLargeR; - std::list<CP::SystematicSet> m_specifiedSystematicsTrackJets; - std::list<CP::SystematicSet> m_recommendedSystematics; - CP::SystematicSet m_nominalSystematicSet; - - ToolHandle<IJetCalibrationTool> m_jetCalibrationTool; - ToolHandle<IJetCalibrationTool> m_jetCalibrationToolLargeR; - - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesTool; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario1; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario2; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario3; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario4; - - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR_strong; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR_medium; - ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR_weak; - - ToolHandle<IJERSmearingTool> m_jetJERSmearingTool; - ToolHandle<IJetUpdateJvt> m_jetUpdateJvtTool; - ToolHandle<IJetModifier> m_fjvtTool; - - std::string m_truthJetCollForHS; - - std::unique_ptr<top::TopJetSubstructure> m_jetSubstructure; - - systMap m_systMap_AllNP; - systMap m_systMap_ReducedNPScenario1; - systMap m_systMap_ReducedNPScenario2; - systMap m_systMap_ReducedNPScenario3; - systMap m_systMap_ReducedNPScenario4; - systMap m_systMap_LargeR_strong; - systMap m_systMap_LargeR_medium; - systMap m_systMap_LargeR_weak; - systMap m_systMap_JER; - typedef std::unordered_map<CP::SystematicSet,CP::SystematicSet>::const_iterator Itr; - - StatusCode decorateBJets(xAOD::Jet& jet); - StatusCode decorateHSJets(); + // Function will return prefix which will be added to systematic names obtained from tools + virtual std::string getLargeRModName(const std::string& NPModel) const; + // specify Systematic + virtual void addSystematics(const std::set<std::string>& specifiedSystematics, + const CP::SystematicSet& recommendedSysts, std::unordered_map<CP::SystematicSet, + CP::SystematicSet>& map, + const std::string& modName, bool isLargeR = false, + bool onlyJER = false); + + StatusCode execute(const bool isLargeR, bool executeNominal); + + StatusCode calibrate(const bool isLargeR); + virtual StatusCode applySystematic(ToolHandle<ICPJetUncertaintiesTool>& tool, + const std::unordered_map<CP::SystematicSet, CP::SystematicSet>& map, + bool isLargeR = false); + + StatusCode printout(const bool isLargeR); + + private: + std::shared_ptr<top::TopConfig> m_config; + bool m_doJER; + bool m_doFull_JER; + bool m_doFull_JER_Pseudodata; + bool m_isMC; + bool m_doMultipleJES; + bool m_do_fjvt = false; + + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_specifiedSystematicsLargeR; + std::list<CP::SystematicSet> m_specifiedSystematicsTrackJets; + std::list<CP::SystematicSet> m_recommendedSystematics; + CP::SystematicSet m_nominalSystematicSet; + + ToolHandle<IJetCalibrationTool> m_jetCalibrationTool; + ToolHandle<IJetCalibrationTool> m_jetCalibrationToolLargeR; + + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesTool; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolFrozenJMS; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario1; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario2; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario3; + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolReducedNPScenario4; + + ToolHandle<ICPJetUncertaintiesTool> m_jetUncertaintiesToolLargeR; + std::unordered_map<std::string, ToolHandle<ICPJetUncertaintiesTool> > m_tagSFuncertTool; + + // do decorate the large-R jets with the boosted-tagging flags + // and decorate jets with TAccept object containing detailed tag result informaiton + // https://twiki.cern.ch/twiki/bin/view/AtlasProtected/BoostedJetTaggingRecommendation2017#TAcceptUsageSection + std::unordered_map<std::string, ToolHandle<IJetSelectorTool> > m_boostedJetTaggers; + + ToolHandle<IJetUpdateJvt> m_jetUpdateJvtTool; + ToolHandle<IJetModifier> m_jetSelectfJvtTool; + + std::string m_truthJetCollForHS; + + std::unique_ptr<top::TopJetSubstructure> m_jetSubstructure; + + systMap m_systMap_AllNP; + systMap m_systMap_AllNP_FrozenJMS; + systMap m_systMap_ReducedNPScenario1; + systMap m_systMap_ReducedNPScenario2; + systMap m_systMap_ReducedNPScenario3; + systMap m_systMap_ReducedNPScenario4; + systMap m_systMap_LargeR; + + typedef std::unordered_map<CP::SystematicSet, CP::SystematicSet>::const_iterator Itr; + + StatusCode decorateBJets(xAOD::Jet& jet); + StatusCode decorateHSJets(); + StatusCode decorateMatchedTruth(); + StatusCode tagLargeRJet(const xAOD::Jet& jet); + StatusCode tagNominalLargeRJets(); + + ///-- Large R jet truth labeling --/// +// std::unique_ptr<JetTruthLabelingTool> m_jetTruthLabelingTool; + + // DL1 decoration + std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool> > m_btagSelToolsDL1Decor; + std::unordered_map<std::string, ToolHandle<IBTaggingSelectionTool> > m_btagSelToolsDL1Decor_trkJet; + StatusCode decorateDL1(bool trackJets = false); + + std::unordered_map<std::string, SG::AuxElement::Decorator<float>> DLx; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MissingETObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MissingETObjectCollectionMaker.h index d23a7cc679d82bcbd46e8967e1f07eb8ac178b02..a13fedc6878abdc4bc17277e331451d0df1b7b73 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MissingETObjectCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MissingETObjectCollectionMaker.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: MissingETObjectCollectionMaker.h 683191 2015-07-15 16:05:25Z morrisj $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_MISSINGETOBJECTCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_MISSINGETOBJECTCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief MissingETObjectCollectionMaker - * Makes all systematic variations of Missing ET - * - * $Revision: 683191 $ - * $Date: 2015-07-15 18:05:25 +0200 (Wed, 15 Jul 2015) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief MissingETObjectCollectionMaker + * Makes all systematic variations of Missing ET + * + * $Revision: 683191 $ + * $Date: 2015-07-15 17:05:25 +0100 (Wed, 15 Jul 2015) $ + * + **/ // system include(s): #include <memory> @@ -30,57 +30,53 @@ #include "METInterface/IMETMaker.h" #include "METInterface/IMETSystematicsTool.h" -namespace xAOD{ +namespace xAOD { class SystematicEvent; } -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class MissingETObjectCollectionMaker final : public asg::AsgTool { - public: - explicit MissingETObjectCollectionMaker( const std::string& name ); - virtual ~MissingETObjectCollectionMaker(){} - - // Delete Standard constructors - MissingETObjectCollectionMaker(const MissingETObjectCollectionMaker& rhs ) = delete; - MissingETObjectCollectionMaker(MissingETObjectCollectionMaker&& rhs ) = delete; - MissingETObjectCollectionMaker& operator=(const MissingETObjectCollectionMaker& rhs ) = delete; - - StatusCode initialize(); - StatusCode recalculateMET(); - - // return specific Systematic - inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} - - // return all recommendedSystematics - inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} - - protected: - // specify Systematic - virtual void specifiedSystematics( const std::set<std::string>& specifiedSystematics ); - - - private: - - StatusCode recalculateEventMET( xAOD::SystematicEvent* event, - const xAOD::MissingETContainer* met_core, - const xAOD::MissingETAssociationMap* met_map); - - std::shared_ptr<top::TopConfig> m_config; - - std::list<CP::SystematicSet> m_specifiedSystematics; - std::list<CP::SystematicSet> m_recommendedSystematics; - - std::string m_MET_core; - std::string m_MET_map; - - ToolHandle<IMETMaker> m_met_maker; - ToolHandle<IMETSystematicsTool> m_met_systematics; - +namespace top { + class MissingETObjectCollectionMaker final: public asg::AsgTool { + public: + explicit MissingETObjectCollectionMaker(const std::string& name); + virtual ~MissingETObjectCollectionMaker() {} + + // Delete Standard constructors + MissingETObjectCollectionMaker(const MissingETObjectCollectionMaker& rhs) = delete; + MissingETObjectCollectionMaker(MissingETObjectCollectionMaker&& rhs) = delete; + MissingETObjectCollectionMaker& operator = (const MissingETObjectCollectionMaker& rhs) = delete; + + StatusCode initialize(); + StatusCode recalculateMET(bool); + + // return specific Systematic + inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} + + // return all recommendedSystematics + inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} + protected: + // specify Systematic + virtual void specifiedSystematics(const std::set<std::string>& specifiedSystematics); + private: + StatusCode recalculateEventMET(const xAOD::SystematicEvent* event, + const xAOD::MissingETContainer* met_core, + const xAOD::MissingETAssociationMap* met_map, + bool forceUseLooseObjects=false, + std::string outputContainerSuffix=""); + + std::shared_ptr<top::TopConfig> m_config; + + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_recommendedSystematics; + + std::string m_MET_core; + std::string m_MET_map; + + ToolHandle<IMETMaker> m_met_maker; + ToolHandle<IMETSystematicsTool> m_met_systematics; }; } diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MuonObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MuonObjectCollectionMaker.h index 090e939feddc62bbe1947c5f1f5f9abfb0623937..a70c2ae7205300fb54a938f62b1e0ac007d07c8b 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MuonObjectCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/MuonObjectCollectionMaker.h @@ -1,22 +1,23 @@ /* - Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration + */ +// $Id: MuonObjectCollectionMaker.h 799839 2017-03-08 11:07:28Z grancagn $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_MUONOBJECTCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_MUONOBJECTCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief MuonObjectCollectionMaker - * Makes all systematic variations of muons. - * Momentum Corrections are applied using the calibration tool. - * Efficiency Corrections are applied using the efficiency tool. - * - * $Revision: 799839 $ - * $Date: 2017-03-08 12:07:28 +0100 (Wed, 08 Mar 2017) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief MuonObjectCollectionMaker + * Makes all systematic variations of muons. + * Momentum Corrections are applied using the calibration tool. + * Efficiency Corrections are applied using the efficiency tool. + * + * $Revision: 799839 $ + * $Date: 2017-03-08 11:07:28 +0000 (Wed, 08 Mar 2017) $ + * + **/ // system include(s): #include <memory> @@ -33,60 +34,78 @@ // CP Tool include(s): #include "MuonAnalysisInterfaces/IMuonCalibrationAndSmearingTool.h" #include "IsolationSelection/IIsolationSelectionTool.h" +//#include "IsolationSelection/IIsolationLowPtPLVTool.h" // the following is needed to make sure all muons for which d0sig is calculated are at least Loose #include "MuonAnalysisInterfaces/IMuonSelectionTool.h" - +#include "MuonMomentumCorrections/MuonCalibrationPeriodTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ - - class MuonObjectCollectionMaker final : public asg::AsgTool { - public: - explicit MuonObjectCollectionMaker( const std::string& name ); - virtual ~MuonObjectCollectionMaker(){} - - // Delete Standard constructors - MuonObjectCollectionMaker(const MuonObjectCollectionMaker& rhs) = delete; - MuonObjectCollectionMaker(MuonObjectCollectionMaker&& rhs) = delete; - MuonObjectCollectionMaker& operator=(const MuonObjectCollectionMaker& rhs) = delete; - - StatusCode initialize(); - StatusCode execute(); - - StatusCode printout(); - - // return specific Systematic - inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} - - // return all recommendedSystematics - inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} - - protected: - // specify Systematic - virtual void specifiedSystematics( const std::set<std::string>& specifiedSystematics ); - - private: - std::shared_ptr<top::TopConfig> m_config; - - std::list<CP::SystematicSet> m_specifiedSystematics; - std::list<CP::SystematicSet> m_recommendedSystematics; - - ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_calibrationTool; - - ///-- Isolation --/// - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_LooseTrackOnly; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Loose; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Gradient; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_GradientLoose; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTight; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutTightTrackOnly; - ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutLoose; - // the following is needed to make sure all muons for which d0sig is calculated are at least Loose - ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolVeryLooseVeto; - +namespace top { + class MuonObjectCollectionMaker final: public asg::AsgTool { + public: + explicit MuonObjectCollectionMaker(const std::string& name); + virtual ~MuonObjectCollectionMaker() {} + + // Delete Standard constructors + MuonObjectCollectionMaker(const MuonObjectCollectionMaker& rhs) = delete; + MuonObjectCollectionMaker(MuonObjectCollectionMaker&& rhs) = delete; + MuonObjectCollectionMaker& operator = (const MuonObjectCollectionMaker& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(bool); + + StatusCode printout(); + + // return specific Systematic + inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} + + // return all recommendedSystematics + inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} + protected: + // specify Systematic + virtual void specifiedSystematics(const std::set<std::string>& specifiedSystematics); + private: + std::shared_ptr<top::TopConfig> m_config; + + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_recommendedSystematics; + + ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_calibrationPeriodTool; + ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_calibrationTool2017; + + ///-- Isolation --/// + //until release 21.2.110 these are the used WPs + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCLoose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCTightTrackOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCTightTrackOnly_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCLoose_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FCTight_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutPflowTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_FixedCutPflowLoose; + //since release 21.2.111 these are the used WPs + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PflowTight_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PflowLoose_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PflowTight_VarRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PflowLoose_VarRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_HighPtTrackOnly; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_TightTrackOnly_VarRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_TightTrackOnly_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PLVTight; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_PLVLoose; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Tight_VarRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Tight_FixedRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Loose_VarRad; + ToolHandle<CP::IIsolationSelectionTool> m_isolationTool_Loose_FixedRad; + +// ToolHandle<CP::IIsolationLowPtPLVTool> m_isolationTool_LowPtPLV; + // the following is needed to make sure all muons for which d0sig is calculated are at least Loose + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolVeryLooseVeto; + + bool m_isFirstEvent; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ObjectCollectionMaker.h index 01d2625df73d29f75889af327635298a3f19a288..7edb717ef26a5a2042c5a6751d3585da387963fc 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ObjectCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/ObjectCollectionMaker.h @@ -1,21 +1,21 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + */ // $Id: ObjectCollectionMaker.h 790414 2016-12-19 00:49:08Z tpelzer $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_OBJECTCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_OBJECTCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief ObjectCollectionMaker - * Makes all systematic variations of all objects - * - * $Revision: 790414 $ - * $Date: 2016-12-19 01:49:08 +0100 (Mon, 19 Dec 2016) $ - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief ObjectCollectionMaker + * Makes all systematic variations of all objects + * + * $Revision: 790414 $ + * $Date: 2016-12-19 00:49:08 +0000 (Mon, 19 Dec 2016) $ + * + **/ // system include(s): #include <vector> @@ -29,45 +29,48 @@ #include "TopSystematicObjectMaker/EgammaObjectCollectionMaker.h" #include "TopSystematicObjectMaker/MuonObjectCollectionMaker.h" +#include "TopSystematicObjectMaker/SoftMuonObjectCollectionMaker.h" #include "TopSystematicObjectMaker/TauObjectCollectionMaker.h" #include "TopSystematicObjectMaker/JetObjectCollectionMaker.h" #include "TopSystematicObjectMaker/MissingETObjectCollectionMaker.h" #include "TopSystematicObjectMaker/GhostTrackSystematicsMaker.h" +#include "TopSystematicObjectMaker/TrackSystematicsMaker.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ +namespace top { + class ObjectCollectionMaker final: public asg::AsgTool { + public: + explicit ObjectCollectionMaker(const std::string& name); + virtual ~ObjectCollectionMaker() {} - class ObjectCollectionMaker final : public asg::AsgTool { - public: - explicit ObjectCollectionMaker( const std::string& name ); - virtual ~ObjectCollectionMaker() {} + ObjectCollectionMaker(const ObjectCollectionMaker& rhs) = delete; + ObjectCollectionMaker(ObjectCollectionMaker&& rhs) = delete; + ObjectCollectionMaker& operator = (const ObjectCollectionMaker& rhs) = delete; - ObjectCollectionMaker(const ObjectCollectionMaker& rhs) = delete; - ObjectCollectionMaker(ObjectCollectionMaker&& rhs) = delete; - ObjectCollectionMaker& operator=(const ObjectCollectionMaker& rhs) = delete; + StatusCode initialize(); + StatusCode execute(bool); + StatusCode executeNominal(); + StatusCode executeSystematics(); + StatusCode recalculateMET(bool); + StatusCode printout(); - StatusCode initialize(); - StatusCode execute(); - StatusCode recalculateMET(); - StatusCode printout(); - - bool isTruthDxAOD() const; + bool isTruthDxAOD() const; + private: + std::shared_ptr<top::TopConfig> m_config; + std::unique_ptr<top::EgammaObjectCollectionMaker> m_egammaMaker; + std::unique_ptr<top::MuonObjectCollectionMaker> m_muonMaker; + std::unique_ptr<top::SoftMuonObjectCollectionMaker> m_softmuonMaker; + std::unique_ptr<top::TauObjectCollectionMaker> m_tauMaker; + std::unique_ptr<top::JetObjectCollectionMaker> m_jetMaker; + std::unique_ptr<top::MissingETObjectCollectionMaker> m_metMaker; + std::unique_ptr<top::GhostTrackSystematicsMaker> m_ghostTrackSystMaker; + std::unique_ptr<top::TrackSystematicsMaker> m_trackSystMaker; - private: - - std::shared_ptr<top::TopConfig> m_config; - std::unique_ptr<top::EgammaObjectCollectionMaker> m_egammaMaker; - std::unique_ptr<top::MuonObjectCollectionMaker> m_muonMaker; - std::unique_ptr<top::TauObjectCollectionMaker> m_tauMaker; - std::unique_ptr<top::JetObjectCollectionMaker> m_jetMaker; - std::unique_ptr<top::MissingETObjectCollectionMaker> m_metMaker; - std::unique_ptr<top::GhostTrackSystematicsMaker> m_ghostTrackSystMaker; }; - } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/SoftMuonObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/SoftMuonObjectCollectionMaker.h new file mode 100644 index 0000000000000000000000000000000000000000..d1347b17b0511081f31dc9ba86f946797b605649 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/SoftMuonObjectCollectionMaker.h @@ -0,0 +1,77 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +#ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_SOFTMUONOBJECTCOLLECTIONMAKER_H +#define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_SOFTMUONOBJECTCOLLECTIONMAKER_H + +/** + * @author Marco Vanadia <marco.vanadia@cern.ch> + * + * @brief SoftMuonObjectCollectionMaker + * Makes all systematic variations of soft muons. + * Momentum Corrections are applied using the calibration tool. + * Efficiency Corrections are applied using the efficiency tool. + * + **/ + +// system include(s): +#include <memory> +#include <set> +#include <list> + +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +// Systematic include(s): +#include "PATInterfaces/SystematicSet.h" + +// CP Tool include(s): +#include "MuonAnalysisInterfaces/IMuonCalibrationAndSmearingTool.h" +//#include "IsolationSelection/IIsolationSelectionTool.h" +#include "MuonAnalysisInterfaces/IMuonSelectionTool.h" +#include "MuonMomentumCorrections/MuonCalibrationPeriodTool.h" +// Forward declaration(s): +namespace top { + class TopConfig; +} + +namespace top { + class SoftMuonObjectCollectionMaker final: public asg::AsgTool { + public: + explicit SoftMuonObjectCollectionMaker(const std::string& name); + virtual ~SoftMuonObjectCollectionMaker() {} + + // Delete Standard constructors + SoftMuonObjectCollectionMaker(const SoftMuonObjectCollectionMaker& rhs) = delete; + SoftMuonObjectCollectionMaker(SoftMuonObjectCollectionMaker&& rhs) = delete; + SoftMuonObjectCollectionMaker& operator = (const SoftMuonObjectCollectionMaker& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(bool); + + StatusCode printout(); + + // return specific Systematic + inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} + + // return all recommendedSystematics + inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} + protected: + // specify Systematic + virtual void specifiedSystematics(const std::set<std::string>& specifiedSystematics); + private: + + std::shared_ptr<top::TopConfig> m_config; + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_recommendedSystematics; + + ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_calibrationPeriodTool; + ToolHandle<CP::IMuonCalibrationAndSmearingTool> m_calibrationTool2017; + + // the following is needed to make sure all muons for which d0sig is calculated are at least Loose + ToolHandle<CP::IMuonSelectionTool> m_muonSelectionToolVeryLooseVeto; + }; +} // namespace +#endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TauObjectCollectionMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TauObjectCollectionMaker.h index 7202821469a0234f8bea4610a433a53916114efc..40f3b039d83cb10cf94ad78d104f340bb1c89611 100644 --- a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TauObjectCollectionMaker.h +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TauObjectCollectionMaker.h @@ -1,19 +1,19 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration -*/ + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ // $Id: TauObjectCollectionMaker.h $ #ifndef ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_TAUOBJECTCOLLECTIONMAKER_H #define ANALYSISTOP_TOPSYSTEMATICOBJECTMAKER_TAUOBJECTCOLLECTIONMAKER_H /** - * @author John Morris <john.morris@cern.ch> - * - * @brief TauObjectCollectionMaker - * Makes all systematic variations of taus - * - * - **/ + * @author John Morris <john.morris@cern.ch> + * + * @brief TauObjectCollectionMaker + * Makes all systematic variations of taus + * + * + **/ // system include(s): #include <memory> @@ -32,45 +32,42 @@ #include "TauAnalysisTools/ITauTruthMatchingTool.h" // Forward declaration(s): -namespace top{ +namespace top { class TopConfig; } -namespace top{ +namespace top { + class TauObjectCollectionMaker final: public asg::AsgTool { + public: + explicit TauObjectCollectionMaker(const std::string& name); + virtual ~TauObjectCollectionMaker() {} - class TauObjectCollectionMaker final : public asg::AsgTool { - public: - explicit TauObjectCollectionMaker( const std::string& name ); - virtual ~TauObjectCollectionMaker(){} + // Delete Standard constructors + TauObjectCollectionMaker(const TauObjectCollectionMaker& rhs) = delete; + TauObjectCollectionMaker(TauObjectCollectionMaker&& rhs) = delete; + TauObjectCollectionMaker& operator = (const TauObjectCollectionMaker& rhs) = delete; - // Delete Standard constructors - TauObjectCollectionMaker(const TauObjectCollectionMaker& rhs) = delete; - TauObjectCollectionMaker(TauObjectCollectionMaker&& rhs) = delete; - TauObjectCollectionMaker& operator=(const TauObjectCollectionMaker& rhs) = delete; + StatusCode initialize(); + StatusCode execute(bool); - StatusCode initialize(); - StatusCode execute(); + StatusCode printout(); - StatusCode printout(); + // return specific Systematic + inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} - // return specific Systematic - inline virtual const std::list<CP::SystematicSet>& specifiedSystematics() const {return m_specifiedSystematics;} - - // return all recommendedSystematics - inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} + // return all recommendedSystematics + inline const std::list<CP::SystematicSet>& recommendedSystematics() const {return m_recommendedSystematics;} + protected: + // specify Systematic + virtual void specifiedSystematics(const std::set<std::string>& specifiedSystematics); + private: + std::shared_ptr<top::TopConfig> m_config; - protected: - // specify Systematic - virtual void specifiedSystematics( const std::set<std::string>& specifiedSystematics ); + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_recommendedSystematics; - private: - std::shared_ptr<top::TopConfig> m_config; - - std::list<CP::SystematicSet> m_specifiedSystematics; - std::list<CP::SystematicSet> m_recommendedSystematics; - - ToolHandle<TauAnalysisTools::ITauSmearingTool> m_calibrationTool; - + ToolHandle<TauAnalysisTools::ITauSmearingTool> m_calibrationTool; + ToolHandle<TauAnalysisTools::ITauTruthMatchingTool> m_truthMatchingTool; }; } // namespace #endif diff --git a/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TrackSystematicsMaker.h b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TrackSystematicsMaker.h new file mode 100644 index 0000000000000000000000000000000000000000..910aa4c86fb52079e289bf04266536b0c18bdb88 --- /dev/null +++ b/PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker/TopSystematicObjectMaker/TrackSystematicsMaker.h @@ -0,0 +1,152 @@ +/* + Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration + */ + +// modified base on GhostTrackSystematicsMaker.h from Fabian Wilk +// Description: +// Author: Andrea Knue +// Created: June 2020 + + +#ifndef _TOP_TRACKSYSTEMATICSMAKER_H_ +#define _TOP_TRACKSYSTEMATICSMAKER_H_ + +#include <list> +#include <set> +#include <string> +#include <vector> +#include <utility> + +// Framework include(s): +#include "AsgTools/AsgTool.h" +#include "AsgTools/ToolHandle.h" + +#include "PATInterfaces/SystematicSet.h" + +#include "xAODTracking/TrackParticleContainer.h" + + +// Forward Declarations. +namespace InDet { + class InDetTrackSystematicsTool; + class InDetTrackSmearingTool; + class InDetTrackBiasingTool; + class InDetTrackTruthFilterTool; + class InDetTrackTruthOriginTool; +} + +namespace top { + class TopConfig; +} + +namespace top { + + class TrackSystematicsMaker final: public asg::AsgTool { + public: + explicit TrackSystematicsMaker(const std::string& name); + virtual ~TrackSystematicsMaker(); + + TrackSystematicsMaker(const TrackSystematicsMaker& rhs) = delete; + TrackSystematicsMaker(TrackSystematicsMaker&& rhs) = delete; + TrackSystematicsMaker& operator = (const TrackSystematicsMaker& rhs) = delete; + + StatusCode initialize(); + StatusCode execute(bool); + + /* + * @brief Retrieve the specified (requested) systematics list.* + * + * Unless systematics have been requested through the + * specifiedSystematics setter function, this will be an empty list. + */ + inline const std::list<CP::SystematicSet>& specifiedSystematics() const; + + /* + * @brief Retrieve the recommended systematics list. + * + * This will return a meaningless (probably empty) list unless the + * setter function specifiedSystematics has been called or the tool has + * been initialized (which call specifiedSystematics using the data + * obtained from top::TopConfig). + */ + inline const std::list<CP::SystematicSet>& recommendedSystematics() const; + + /*! + * @brief Specify the systematics to be used. + * @param specifiedSystematics Set of systematics (by name) to be used; + * an empty set will result in no systematic variation. + */ + virtual void specifiedSystematics(const std::set<std::string>& specifiedSystematics); + + protected: + + + StatusCode applyTruthFilterSystematic(InDet::InDetTrackTruthFilterTool* tool, + const CP::SystematicSet& syst) const; + + StatusCode applySmearingSystematic(InDet::InDetTrackSmearingTool* tool, + const CP::SystematicSet& syst) const; + + StatusCode applyBiasingSystematic(InDet::InDetTrackBiasingTool* tool, + const CP::SystematicSet& syst) const; + + private: + StatusCode retrieveTrackCPTool(); + private: + std::shared_ptr<top::TopConfig> m_config; + std::vector<std::uint32_t> m_runPeriods; + + std::list<CP::SystematicSet> m_specifiedSystematics; + std::list<CP::SystematicSet> m_recommendedSystematics; + + CP::SystematicSet m_nominalSystematicSet; + + + + struct { + void makeUnique() { + static auto exec = [](std::vector<CP::SystematicSet>& data) { + std::sort(data.begin(), data.end()); + data.erase(std::unique(data.begin(), data.end()), + data.end()); + }; + + exec(smearing); + exec(truthFilter); + exec(bias); + } + + void removeNonSpecified(const std::list<CP::SystematicSet>& specified) { + auto fnCmp = [&specified](CP::SystematicSet& s) { + return std::find(specified.begin(), + specified.end(), + s) == specified.end(); + }; + + auto exec = [&specified, &fnCmp](std::vector<CP::SystematicSet>& data) { + data.erase(std::remove_if(data.begin(), data.end(), fnCmp), + data.end()); + }; + + exec(smearing); + exec(truthFilter); + exec(bias); + } + + std::size_t numSystematics() const { + return smearing.size() + truthFilter.size() + bias.size(); + } + + std::vector<CP::SystematicSet> smearing, truthFilter, bias; + } m_systs; + + ToolHandle<InDet::InDetTrackSmearingTool> m_smearingTool; + std::vector<ToolHandle<InDet::InDetTrackBiasingTool> > m_biasTool; + ToolHandle<InDet::InDetTrackTruthOriginTool> m_truthOriginTool; + ToolHandle<InDet::InDetTrackTruthFilterTool> m_truthFilterTool; + + }; + +} + +#endif /* _TOP_TRACKSYSTEMATICSMAKER_H_ */ diff --git a/Projects/AnalysisBase/package_filters.txt b/Projects/AnalysisBase/package_filters.txt index d8cfcbe0b953d355b8aca092a621d06b7d2943fc..4e2490364b072feb664693e811b60e62428d70ee 100644 --- a/Projects/AnalysisBase/package_filters.txt +++ b/Projects/AnalysisBase/package_filters.txt @@ -126,4 +126,23 @@ + Trigger/TrigSteer/TrigCompositeUtils #+ Trigger/TrigValidation/TrigAnalysisTest +# +### AnalysisTop packages +# + ++ PhysicsAnalysis/TopPhys/TopPhysUtils/TopDataPreparation ++ PhysicsAnalysis/TopPhys/xAOD/TopAnalysis ++ PhysicsAnalysis/TopPhys/xAOD/TopCPTools ++ PhysicsAnalysis/TopPhys/xAOD/TopConfiguration ++ PhysicsAnalysis/TopPhys/xAOD/TopCorrections ++ PhysicsAnalysis/TopPhys/xAOD/TopEvent ++ PhysicsAnalysis/TopPhys/xAOD/TopEventReconstructionTools ++ PhysicsAnalysis/TopPhys/xAOD/TopEventSelectionTools ++ PhysicsAnalysis/TopPhys/xAOD/TopExamples ++ PhysicsAnalysis/TopPhys/xAOD/TopJetSubstructure ++ PhysicsAnalysis/TopPhys/xAOD/TopObjectSelectionTools ++ PhysicsAnalysis/TopPhys/xAOD/TopParticleLevel ++ PhysicsAnalysis/TopPhys/xAOD/TopPartons ++ PhysicsAnalysis/TopPhys/xAOD/TopSystematicObjectMaker + - .* diff --git a/Trigger/TrigMonitoring/TrigHLTMonitoring/python/HLTMonTriggerList.py b/Trigger/TrigMonitoring/TrigHLTMonitoring/python/HLTMonTriggerList.py index 80f5e3779c49a58095627be1b7645c1ead3e4ce0..eaa544ad286ccf93c15466c982e4c076d6a4a1f2 100644 --- a/Trigger/TrigMonitoring/TrigHLTMonitoring/python/HLTMonTriggerList.py +++ b/Trigger/TrigMonitoring/TrigHLTMonitoring/python/HLTMonTriggerList.py @@ -97,6 +97,7 @@ class HLTMonTriggerList: # Implementation of https://its.cern.ch/jira/browse/ATR-13200 def get_monitoring_mode(self): # Set monitoring mode + print ('jmasik: DQMonFlags.monManDataType(): ', DQMonFlags.monManDataType()) self.data_type = DQMonFlags.monManDataType() if self.data_type == 'monteCarlo': @@ -200,7 +201,8 @@ class HLTMonTriggerList: self.monitoring_tau = tau.monitoring_tau_pp #override if both pp and MC are true - if DQMonFlags.monManDataType()=='monteCarlo': + from AthenaCommon.GlobalFlags import globalflags + if globalflags.DataSource.get_Value() == 'geant4': self.monitoring_tau = tau.monitoring_tau_validation def set_HLTMonTrigList_HI(self): diff --git a/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDPhysValMonitoringConfig.py b/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDPhysValMonitoringConfig.py index 04390e1abae5ed835057120458a5782a5585ffc4..bd4359a1adc70cc06c47d7479d97ca24e12e99a3 100644 --- a/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDPhysValMonitoringConfig.py +++ b/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDPhysValMonitoringConfig.py @@ -200,7 +200,7 @@ def TrigIDPhysValMonitoringTool( legacy_monitoring=False ): useOffline=True if mt_chains: chainnames = [ - ":key=HLT_IDTrack_FS_FTF", + "HLT_j45_ftf_L1J15:key=HLT_IDTrack_FS_FTF:vtx=HLT_IDVertex_FS", "HLT_j.*b.*perf_split:key=HLT_IDTrack_Bjet_FTF", "HLT_j.*b.*perf_split:key=HLT_IDTrack_Bjet_IDTrig" ] diff --git a/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDtrkMonitoringConfig.py b/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDtrkMonitoringConfig.py index d72033db74a9b6f04400e0e3110200a75da3fc87..ae0bf8a1c6c75c8ac594714eec28230b4f25291e 100644 --- a/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDtrkMonitoringConfig.py +++ b/Trigger/TrigMonitoring/TrigIDtrkMonitoring/python/TrigIDtrkMonitoringConfig.py @@ -334,7 +334,7 @@ def TrigIDtrkMonitoringTool( legacy_monitoring=False ): if mt_chains: tidabjet.ntupleChainNames += [ "Offline", - ":HLT_IDTrack_FS_FTF:vtx=HLT_IDVertex_FS", + "HLT_j45_ftf_L1J15:key=HLT_IDTrack_FS_FTF:vtx=HLT_IDVertex_FS", "HLT_j.*.*boffperf.*:key=HLT_IDTrack_Bjet_FTF", "HLT_j.*.*boffperf.*:key=HLT_IDTrack_Bjet_IDTrig" ]