From 7c36b1a09f5909d2e19ebb19a0dc934dc5bd1f83 Mon Sep 17 00:00:00 2001 From: algomez Date: Mon, 22 Jan 2024 16:11:32 -0600 Subject: [PATCH] first commit --- .gitignore | 160 ++++++ README.md | 99 +--- metadata/JMENano_HHto2B2VLNu2J_UL16.txt | 9 + metadata/bbWW.yml | 39 ++ processors/processor_bbWW.py | 648 ++++++++++++++++++++++++ 5 files changed, 872 insertions(+), 83 deletions(-) create mode 100644 .gitignore create mode 100644 metadata/JMENano_HHto2B2VLNu2J_UL16.txt create mode 100644 metadata/bbWW.yml create mode 100755 processors/processor_bbWW.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..68bc17f --- /dev/null +++ b/.gitignore @@ -0,0 +1,160 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/README.md b/README.md index fa192b1..45a73c9 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,26 @@ # bbWW +This package works on top of [coffea4bees](https://gitlab.cern.ch/cms-cmu/coffea4bees). - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +## Instructions: ``` -cd existing_repo -git remote add origin https://gitlab.cern.ch/algomez/bbWW.git -git branch -M master -git push -uf origin master +git clone ssh://git@gitlab.cern.ch:7999/cms-cmu/coffea4bees.git +cd coffea4bees/python/ +git clone ssh://git@gitlab.cern.ch:7999/algomez/bbWW.git ``` -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.cern.ch/algomez/bbWW/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +## Set Environment -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +This code has been tested at the cmslpc, and to simplify the setup, it can be used with the container needed to run on lpc condor computers. To set this container under `coffea4bees/`: +``` +curl -OL https://raw.githubusercontent.com/CoffeaTeam/lpcjobqueue/main/bootstrap.sh +bash bootstrap.sh +``` +This creates two new files in this directory: `shell` and `.bashrc`. _Additionally, this package contains a `set_shell.sh file`_ which runs the `./shell` executable with the coffea4bees container. This container is based on the `coffeateam/coffea-dask:latest` container including some additional python packages. +``` +source set_shell.sh +``` -## License -For open source projects, say how it is licensed. +Remember to run this previous command (aka set your environment) *every time you want to run something*. -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/metadata/JMENano_HHto2B2VLNu2J_UL16.txt b/metadata/JMENano_HHto2B2VLNu2J_UL16.txt new file mode 100644 index 0000000..ebae565 --- /dev/null +++ b/metadata/JMENano_HHto2B2VLNu2J_UL16.txt @@ -0,0 +1,9 @@ +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_1.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_5.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_6.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_7.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_8.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_4.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_3.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_1-1.root +/store/user/algomez/JMEnano/GluGluToHHTo2B2VLNu2J_node_cHHH1_TuneCUETP8M1_PSWeights_13TeV-powheg-pythia8/GluGluToHHTo2B2VLNu2JnodecHHH1TuneCUETP8M1PSWeights13TeV-powheg-pythia8/231113_200123/0000/JMEnano-RunIIUL16NanoAODv9-00923_2.root diff --git a/metadata/bbWW.yml b/metadata/bbWW.yml new file mode 100644 index 0000000..c0dc3c2 --- /dev/null +++ b/metadata/bbWW.yml @@ -0,0 +1,39 @@ +runner: + chunksize: 1000 + maxchunks: 20 + test_files: 2 + data_tier: nanoAOD + allowlist_sites: + - T3_US_FNALLPC + - T3_US_MIT + - T2_CH_CERN + - T2_CH_MIT + - T2_CH_Nebraska + +config: + corrections_metadata: analysis/metadata/corrections.yml + +datasets: + GluGluToHHTo2B2VLNu2J: + xs: 1. + 'UL16_preVFP': + nanoAOD: bbWW/metadata/JMENano_HHto2B2VLNu2J_UL16.txt + TTToSemiLeptonic: + xs: 1. + 'UL16_preVFP': + nanoAOD: /TTToSemiLeptonic_TuneCP5_13TeV-powheg-pythia8/RunIISummer20UL16NanoAODv9-20UL16JMENano_106X_mcRun2_asymptotic_v17-v1/NANOAODSIM + + data: + 'UL16_preVFP': + lumi: 1. + trigger: + - IsoMu22 + - IsoTkMu22 + - IsoMu22_eta2p1 + - IsoTkMu22_eta2p1 + - IsoMu24 + - IsoTkMu24 + - Ele27_WPTight_Gsf + - Ele25_eta2p1_WPTight_Gsf + - Ele27_eta2p1_WPLoose_Gsf + nanoAOD: /DoubleMuon/Run2018B-UL2018_MiniAODv2_JMENanoAODv9-v1/NANOAOD diff --git a/processors/processor_bbWW.py b/processors/processor_bbWW.py new file mode 100755 index 0000000..b9189c8 --- /dev/null +++ b/processors/processor_bbWW.py @@ -0,0 +1,648 @@ +#!/usr/bin/env python + +import sys +import os +import datetime +import numpy as np +import logging +import copy +import yaml + +import uproot +import awkward as ak +from coffea.nanoevents import NanoEventsFactory, NanoAODSchema +from coffea.jetmet_tools import CorrectedMETFactory +import cachetools +from coffea import processor +import hist +from coffea import lookup_tools +from coffea.analysis_tools import Weights +from coffea.lumi_tools import LumiMask +from coffea.processor import PackedSelection ### to move to analysis_tools +import correctionlib + +from analysis.helpers.common import mask_event_decision + +### from TAMU +from coffea.nanoevents.methods import vector +from functools import reduce + +class analysis(processor.ProcessorABC): + def __init__(self, corrections_metadata='analysis/metadata/corrections.yml'): + + self.corrections_metadata = yaml.safe_load(open(corrections_metadata, 'r')) + + # defining histograms + dataset_axis = hist.axis.StrCategory([], name="dataset", growth=True) + sel_axis = hist.axis.StrCategory([], name="selection", growth=True) + pt_axis = hist.axis.Regular(100, 0, 100, name="pt", label=r'$p_{T}$ [GeV]') + eta_axis = hist.axis.Regular(20, -5, 5, name="eta", label=r'$\eta$') + mass_axis = hist.axis.Regular(60, 0, 150, name="mass", label=r'Mass [GeV]') + + self.cutflow = {} + self.hists = { + 'numJets': hist.Hist( dataset_axis, sel_axis, + hist.axis.Regular(15, 0,15, name="numJets", label='Number of jets'), + hist.axis.Regular(15, 0,15, name="numBjets", label='Number of b jets'), + hist.axis.Regular(15, 0,15, name="numnonBjets", label='Number of non b jets'), + ), + 'jet1': hist.Hist( dataset_axis, sel_axis, pt_axis, eta_axis, storage="weight", label="Counts" ), + 'jet2': hist.Hist( dataset_axis, sel_axis, pt_axis, eta_axis, storage="weight", label="Counts" ), + } + + + @property + def accumulator(self): + return self.hists + + def process(self, events): + + year = events.metadata['year'] + + listOfCuts = PackedSelection() + isData = False if (events.run[0] == 1) else True + isMC = ~isData + logging.info( f'\nProcessing {len(events.event)} events' ) + + # adding trigger selection + trigger_selection = mask_event_decision( events, decision='OR', branch='HLT', list_to_mask=events.metadata['trigger'] ) + + # adding golden json filter (just for data) + lumimask = LumiMask(self.corrections_metadata[year]['goldenJSON']) + if isData: jsonFilter = np.array( lumimask(events.run, events.luminosityBlock) ) + else: jsonFilter = np.ones( len(events.event), dtype=bool ) + listOfCuts.add( "goldenJson", jsonFilter ) + + # adding met filters + METcleaning = mask_event_decision( events, decision='AND', branch='Flag', list_to_mask=self.corrections_metadata[year]['METFilter'], list_to_skip=['BadPFMuonDzFilter', 'hfNoisyHitsFilter'] ) + listOfCuts.add( "PassesMETFilters", METcleaning ) + + ############################################################## + # From here is a copy of the TAMU code + # basic object selection + # from https://github.com/aebid/HHbbWW_Run3/blob/main/python/object_selection.py#L8 + muons = copy.deepcopy(events.Muon) + muon_conept = ak.where( + (abs(muons.pdgId) == 13) & (muons.mediumId) & (muons.mvaTTH > 0.50), + muons.pt, + 0.9 * muons.pt * (1.0 + muons.jetRelIso) + ) + + electrons = copy.deepcopy(events.Electron) + electron_conept = ak.where( + (abs(electrons.pdgId) == 11) & (electrons.mvaTTH > 0.30), + electrons.pt, + 0.9 * electrons.pt * (1.0 + electrons.jetRelIso) + ) + + muons = ak.with_field(muons, muon_conept, "conept") ### this is stupid + electrons = ak.with_field(electrons, electron_conept, "conept") + + # from https://github.com/aebid/HHbbWW_Run3/blob/main/python/object_selection.py#L34 + ak4_jets = ak.pad_none(events.Jet, 1) + ak8_jets = events.FatJet + ak8_subjets = ak.pad_none(events.SubJet, 2) + muons = ak.with_field(muons, ak4_jets[muons.jetIdx].mask[(muons.jetIdx >= 0)], "ak4_jets") + electrons = ak.with_field(electrons, ak4_jets[electrons.jetIdx].mask[(electrons.jetIdx >= 0)], "ak4_jets") + ak8_jets = ak.with_field(ak8_jets, ak8_subjets[ak8_jets.subJetIdx1].mask[(ak8_jets.subJetIdx1 >= 0)], "subjet1") + ak8_jets = ak.with_field(ak8_jets, ak8_subjets[ak8_jets.subJetIdx2].mask[(ak8_jets.subJetIdx2 >= 0)], "subjet2") + + jetDeepJet_min_pt = 20.0; jetDeepJet_max_pt = 45.0 + + muons.jetDeepJet_Upper_x1 = ak.where( + (muons.conept - jetDeepJet_min_pt) >= 0.0, + muons.conept - jetDeepJet_min_pt, + 0.0 + ) + + muons.jetDeepJet_Upper_x2 = ak.where( + (muons.jetDeepJet_Upper_x1/(jetDeepJet_max_pt - jetDeepJet_min_pt)) <= 1.0, + (muons.jetDeepJet_Upper_x1/(jetDeepJet_max_pt - jetDeepJet_min_pt)), + 1.0 + ) + + jetDeepJet_WP_loose = 0.0613 ### this is for 2016 + jetDeepJet_WP_medium = 0.3093 ### this is for 2016 + jetDeepJet_WP_tight = 0.7221 ### this is for 2016 + muons = ak.with_field(muons, muons.jetDeepJet_Upper_x2 * jetDeepJet_WP_loose + (1 - muons.jetDeepJet_Upper_x2) * jetDeepJet_WP_medium, "jetDeepJet_Upper") + + # https://github.com/aebid/HHbbWW_Run3/blob/main/python/object_selection.py#L71 + muon_preselection_mask = ( + (abs(muons.eta) <= 2.4) & (muons.pt >= 5.0) & (abs(muons.dxy) <= 0.05) & + (abs(muons.dz) <= 0.1) & (muons.miniPFRelIso_all <= 0.4) & + (muons.sip3d <= 8) & (muons.looseId) + ) + + muon_fakeable_mask = ( + (muons.conept >= 10.0) & + ak.where( + ak.is_none(muons.ak4_jets, axis=1), + ( + (muons.mvaTTH > 0.50) + | #OR + (muons.jetRelIso < 0.80) + ), + (muons.ak4_jets.btagDeepFlavB <= jetDeepJet_WP_medium) & + ( + (muons.mvaTTH > 0.50) + | #OR + (muons.jetRelIso < 0.80) & (muons.ak4_jets.btagDeepFlavB <= muons.jetDeepJet_Upper) + ) + ) + ) + + muon_tight_mask = ((muons.mvaTTH >= 0.50) & (muons.mediumId)) + + muons = ak.with_field(muons, muon_preselection_mask, "preselected") + muons = ak.with_field(muons, muon_fakeable_mask & muon_preselection_mask, "fakeable") + muons = ak.with_field(muons, muon_tight_mask & muon_fakeable_mask & muon_preselection_mask, "tight") + + + muons = ak.with_field(muons, (getattr(muons, 'genPartFlav', False) == 1) | (getattr(muons, 'genPartFlav', False) == 15), "MC_Match") + + # https://github.com/aebid/HHbbWW_Run3/blob/main/python/object_selection.py#L116 + mvaNoIso_WPL = getattr(electrons, 'mvaIso_WP90', False) | getattr(electrons, 'mvaNoIso_WPL', False) | getattr(electrons, 'mvaFall17V2noIso_WPL', False) + mvaNoIso_WP90 = getattr(electrons, 'mvaIso_WP90', False) | getattr(electrons, 'mvaNoIso_WPL90', False) | getattr(electrons, 'mvaFall17V2noIso_WP90', False) + + electron_preselection_mask = ( + (abs(electrons.eta) <= 2.5) & (electrons.pt >= 7.0)& (abs(electrons.dxy) <= 0.05) & + (abs(electrons.dz) <= 0.1) & (electrons.miniPFRelIso_all <= 0.4) & + (electrons.sip3d <= 8) & (mvaNoIso_WPL) & (electrons.lostHits <= 1) + ) + + electron_fakeable_mask = ( + (electrons.conept >= 10.0) & (electrons.hoe <= 0.10) & (electrons.eInvMinusPInv >= -0.04) & + (electrons.lostHits == 0) & (electrons.convVeto) & + ( + (abs(electrons.eta + electrons.deltaEtaSC) > 1.479) & (electrons.sieie <= 0.030) + | #OR + (abs(electrons.eta + electrons.deltaEtaSC) <= 1.479) & (electrons.sieie <= 0.011) + ) & + ak.where( + ak.is_none(electrons.ak4_jets, axis=1), + True, + ak.where( + electrons.mvaTTH < 0.3, + electrons.ak4_jets.btagDeepFlavB <= jetDeepJet_WP_tight, + electrons.ak4_jets.btagDeepFlavB <= jetDeepJet_WP_medium + ) + ) & + ak.where( + electrons.mvaTTH < 0.30, + (electrons.jetRelIso < 0.7) & (mvaNoIso_WP90), + True + ) + ) + + electron_tight_mask = electrons.mvaTTH >= 0.30 + + electrons = ak.with_field(electrons, electron_preselection_mask, "preselected") + + electrons = electrons + mu_padded = ak.pad_none(muons, 1) + #We pad muons with 1 None to allow all electrons to have a "pair" for cleaning + + ele_mu_pair_for_cleaning = ak.cartesian( + [electrons.mask[electrons.preselected], mu_padded.mask[mu_padded.preselected]], nested=True + ) + + ele_for_cleaning, mu_for_cleaning = ak.unzip( ele_mu_pair_for_cleaning ) + + electron_cleaning_dr = ak.where( + (ak.is_none(mu_for_cleaning, axis=2) == 0) & (ak.is_none(ele_for_cleaning, axis=2) == 0), + abs(ele_for_cleaning.delta_r(mu_for_cleaning)), + electrons.preselected + ) + + electron_cleaning_mask = ak.min(electron_cleaning_dr, axis=2) > 0.30 + + electrons = ak.with_field(electrons, electron_cleaning_mask & electrons.preselected, "cleaned") + electrons = ak.with_field(electrons, electron_fakeable_mask & electron_cleaning_mask & electron_preselection_mask, "fakeable") + electrons = ak.with_field(electrons, electron_tight_mask & electron_fakeable_mask & electron_cleaning_mask & electron_preselection_mask, "tight") + + electrons = ak.with_field(electrons, (getattr(electrons, 'genPartFlav', 0) == 1) | (getattr(electrons, 'genPartFlav', 0) == 15), "MC_Match") + + # https://github.com/aebid/HHbbWW_Run3/blob/main/python/object_selection.py#L193 + ak4_jet_preselection_mask = ( + (ak4_jets.pt >= 25.0) & (abs(ak4_jets.eta) <= 2.4) & + (ak4_jets.jetId > 1) + ) + + ak4_jets_loose_btag_mask = ak4_jets.btagDeepFlavB > jetDeepJet_WP_loose + + ak4_jets_medium_btag_mask = ak4_jets.btagDeepFlavB > jetDeepJet_WP_medium + + ak4_jets = ak.with_field(ak4_jets, ak4_jet_preselection_mask, "preselected") + ak4_jets = ak4_jets + + leptons_fakeable = ak.concatenate([electrons.mask[electrons.fakeable], muons.mask[muons.fakeable]], axis=1) + #argsort fails if all values are none, fix by a all none check + #Check if variables are none, then if all in the nested list are none, then if all in the unnested list are none + if not ak.all(ak.all(ak.is_none(leptons_fakeable, axis=1), axis=1)): + leptons_fakeable = leptons_fakeable[ak.argsort(leptons_fakeable.conept, ascending=False)] + leptons_fakeable = ak.pad_none(leptons_fakeable, 1) + + ak4_jet_lep_pair_for_cleaning = ak.cartesian([ak4_jets.mask[ak4_jets.preselected], leptons_fakeable], nested=True) + ak4_jet_for_cleaning, lep_for_cleaning = ak.unzip( ak4_jet_lep_pair_for_cleaning ) + + ak4_jet_cleaning_dr_all = ak.fill_none(abs(ak4_jet_for_cleaning.delta_r(lep_for_cleaning)), True) + ak4_jet_cleaning_mask_all = ak.min(ak4_jet_cleaning_dr_all, axis=2) > 0.40 + + ak4_jet_cleaning_dr_single = ak.fill_none(abs(ak4_jet_for_cleaning.delta_r(lep_for_cleaning)), True)[:,:,0:1] + ak4_jet_cleaning_mask_single = ak.min(ak4_jet_cleaning_dr_single, axis=2) > 0.40 + + ak4_jet_cleaning_dr_double = ak.fill_none(abs(ak4_jet_for_cleaning.delta_r(lep_for_cleaning)), True)[:,:,0:2] + ak4_jet_cleaning_mask_double = ak.min(ak4_jet_cleaning_dr_double, axis=2) > 0.40 + + ak4_jets = ak.with_field(ak4_jets, ak4_jet_cleaning_mask_all & ak4_jets.preselected, "cleaned_all") + ak4_jets = ak.with_field(ak4_jets, ak4_jet_cleaning_mask_single & ak4_jets.preselected, "cleaned_single") + ak4_jets = ak.with_field(ak4_jets, ak4_jet_cleaning_mask_double & ak4_jets.preselected, "cleaned_double") + + ak4_jets = ak.with_field(ak4_jets, ak4_jets_loose_btag_mask & ak4_jets.cleaned_all, "loose_btag_all") + ak4_jets = ak.with_field(ak4_jets, ak4_jets_loose_btag_mask & ak4_jets.cleaned_single, "loose_btag_single") + ak4_jets = ak.with_field(ak4_jets, ak4_jets_loose_btag_mask & ak4_jets.cleaned_double, "loose_btag_double") + + ak4_jets = ak.with_field(ak4_jets, ak4_jets_medium_btag_mask & ak4_jets.cleaned_all, "medium_btag_all") + ak4_jets = ak.with_field(ak4_jets, ak4_jets_medium_btag_mask & ak4_jets.cleaned_single, "medium_btag_single") + ak4_jets = ak.with_field(ak4_jets, ak4_jets_medium_btag_mask & ak4_jets.cleaned_double, "medium_btag_double") + + + ak4_jets_pre = ak4_jets.mask[ak4_jets.preselected] + + ak4_jets_ptGt50 = ak4_jets_pre.mask[ak4_jets_pre.pt > 50] + + ak8_jets.tau2overtau1 = ak.where( + (ak.is_none(ak8_jets, axis=1) == 0) & (ak.is_none(ak8_jets.tau2, axis=1) == 0) & (ak.is_none(ak8_jets.tau1, axis=1) == 0), + ak8_jets.tau2 / ak8_jets.tau1, + 10.0 + ) + + ak8_jet_preselection_mask = ( + (ak.is_none(ak8_jets.subjet1) == 0) & (ak.is_none(ak8_jets.subjet2) == 0) & + (ak8_jets.subjet1.pt >= 20) & (abs(ak8_jets.subjet1.eta) <= 2.4) & + (ak8_jets.subjet2.pt >= 20) & (abs(ak8_jets.subjet2.eta) <= 2.4) & + (ak8_jets.jetId > 1) & (ak8_jets.pt >= 200) & + (abs(ak8_jets.eta) <= 2.4) & (ak8_jets.msoftdrop >= 30) & (ak8_jets.msoftdrop <= 210) & + (ak8_jets.tau2 / ak8_jets.tau1 <= 0.75) + ) + + ak8_btagDeepB_WP_medium = 0.6321 ### this is 2016 + ak8_jet_btag_mask = ( + (ak8_jets.subjet1.btagDeepB > ak8_btagDeepB_WP_medium) & (ak8_jets.subjet1.pt >= 30) + | #OR + (ak8_jets.subjet2.btagDeepB > ak8_btagDeepB_WP_medium) & (ak8_jets.subjet2.pt >= 30) + ) + + ak8_jets = ak.with_field(ak8_jets, ak8_jet_preselection_mask, "preselected") + + leptons_fakeable = ak.concatenate([electrons.mask[electrons.fakeable], muons.mask[muons.fakeable]], axis=1) + #argsort fails if all values are none, fix by a all none check + #Check if variables are none, then if all in the nested list are none, then if all in the unnested list are none + if not ak.all(ak.all(ak.is_none(leptons_fakeable, axis=1), axis=1)): + leptons_fakeable = leptons_fakeable[ak.argsort(leptons_fakeable.conept, ascending=False)] + leptons_fakeable = ak.pad_none(leptons_fakeable, 1) + + ak8_jet_lep_pair_for_cleaning = ak.cartesian([ak8_jets.mask[ak8_jets.preselected], leptons_fakeable], nested=True) + ak8_jet_for_cleaning, lep_for_cleaning = ak.unzip( ak8_jet_lep_pair_for_cleaning ) + + ak8_jet_cleaning_dr_all = ak.fill_none(abs(ak8_jet_for_cleaning.delta_r(lep_for_cleaning)), True) + ak8_jet_cleaning_mask_all = ak.min(ak8_jet_cleaning_dr_all, axis=2) > 0.80 + + ak8_jet_cleaning_dr_single = ak8_jet_cleaning_dr_all[:,:,0:1] + ak8_jet_cleaning_mask_single = ak.min(ak8_jet_cleaning_dr_single, axis=2) > 0.80 + + ak8_jet_cleaning_dr_double = ak8_jet_cleaning_dr_all[:,:,0:2] + ak8_jet_cleaning_mask_double = ak.min(ak8_jet_cleaning_dr_double, axis=2) > 0.80 + + ak8_jets = ak.with_field(ak8_jets, ak8_jet_cleaning_mask_all & ak8_jets.preselected, "cleaned_all") + ak8_jets = ak.with_field(ak8_jets, ak8_jet_cleaning_mask_single & ak8_jets.preselected, "cleaned_single") + ak8_jets = ak.with_field(ak8_jets, ak8_jet_cleaning_mask_double & ak8_jets.preselected, "cleaned_double") + + ak8_jets = ak.with_field(ak8_jets, ak8_jet_btag_mask & ak8_jets.cleaned_all, "btag_all") + ak8_jets = ak.with_field(ak8_jets, ak8_jet_btag_mask & ak8_jets.cleaned_single, "btag_single") + ak8_jets = ak.with_field(ak8_jets, ak8_jet_btag_mask & ak8_jets.cleaned_double, "btag_double") + + + events["HT"] = ak.sum(ak4_jets_ptGt50.pt, axis=1) + + ##### Event level selection + ##### https://github.com/aebid/HHbbWW_Run3/blob/main/python/event_selection.py#L14 + #Prepare leptons + leptons_preselected = ak.concatenate([electrons.mask[electrons.preselected], muons.mask[muons.preselected]], axis=1) + leptons_fakeable = ak.concatenate([electrons.mask[electrons.fakeable], muons.mask[muons.fakeable]], axis=1) + leptons_tight = ak.concatenate([electrons.mask[electrons.tight], muons.mask[muons.tight]], axis=1) + + if ak.any(leptons_preselected): #Required in case no leptons available, can happen with data + leptons_preselected = leptons_preselected[ak.argsort(leptons_preselected.conept, axis=1, ascending=False)] + if ak.any(leptons_fakeable): + leptons_fakeable = leptons_fakeable[ak.argsort(leptons_fakeable.conept, axis=1, ascending=False)] + if ak.any(leptons_tight): + leptons_tight = leptons_tight[ak.argsort(leptons_tight.conept, axis=1, ascending=False)] + + leading_leptons = ak.pad_none(leptons_fakeable, 1)[:,0] + + #We break the cuts into separate steps for the cutflow + #Step 1 -- Require at least 1 fakeable (or tight) lepton + #Step 2 -- Require MET filters + #Step 3 -- Leading lepton cone-pT for El (Mu) >= 32.0 (25.0) + #Step 4 -- Z mass and invariant mass cuts + #Step 5 -- HLT Cuts + # If El, pass El trigger + # If Mu, pass Mu trigger + #Step 6 -- MC match for leading lepton + #Step 7 -- Require no more than 1 tight lepton (must be leading) + #Step 8 -- Tau veto + #Step 9 -- 1 or more btagged ak8_jets or 1 or more btagged ak4_jets + #Step 10 -- Categories + + + events["single_cutflow"] = np.zeros_like(events.run) + + events["is_e"] = (abs(leading_leptons.pdgId) == 11) + events["is_m"] = (abs(leading_leptons.pdgId) == 13) + + #Require at least 1 fakeable (or tight) lepton + one_fakeable_lepton = ak.sum(leptons_fakeable.fakeable, axis=1) >= 1 + single_step1_mask = ak.fill_none(one_fakeable_lepton, False) + listOfCuts.add( "single_lepton", ak.to_numpy(single_step1_mask) ) + + single_step2_mask = ak.fill_none(METcleaning, False) + + #Leading lepton cone-pT for El (Mu) >= 32.0 (25.0) + cone_pt_cuts = ak.where( + abs(leading_leptons.pdgId) == 11, + leading_leptons.conept >= 32.0, + ak.where( + abs(leading_leptons.pdgId) == 13, + leading_leptons.conept >= 25.0, + False + ) + ) + single_step3_mask = ak.fill_none(cone_pt_cuts, False) + listOfCuts.add( 'LeadLeptonConePtCut', ak.to_numpy(single_step3_mask) ) + + #Z mass and invariant mass cuts + #No pair of same-flavor, opposite-sign preselcted leptons within 10 GeV of the Z mass (91.1876) + #Invariant mass of each pair of preselected leptons (electrons not cleaned) must be greater than 12 GeV + lep_pairs_for_Zmass_and_Invarmass = ak.combinations(leptons_preselected, 2) + first_leps, second_leps = ak.unzip(lep_pairs_for_Zmass_and_Invarmass) + + lep1_lorentz_vec = ak.zip( + { + "pt": ak.fill_none(first_leps.pt, 0.0), + "eta": ak.fill_none(first_leps.eta, 0.0), + "phi": ak.fill_none(first_leps.phi, 0.0), + "mass": ak.fill_none(first_leps.mass, 0.0), + }, + with_name="PtEtaPhiMLorentzVector", + behavior=vector.behavior, + ) + + lep2_lorentz_vec = ak.zip( + { + "pt": ak.fill_none(second_leps.pt, 0.0), + "eta": ak.fill_none(second_leps.eta, 0.0), + "phi": ak.fill_none(second_leps.phi, 0.0), + "mass": ak.fill_none(second_leps.mass, 0.0), + }, + with_name="PtEtaPhiMLorentzVector", + behavior=vector.behavior, + ) + + + Invariant_mass_cut = ak.all( + ( + ((lep1_lorentz_vec + lep2_lorentz_vec).mass > 12.0) | + ak.is_none(first_leps, axis = 1) | + ak.is_none(second_leps, axis = 1) + ), axis = 1 + ) + Zmass_cut = ak.any( + ( + (abs(ak.fill_none(first_leps.pdgId, 0)) == abs(ak.fill_none(second_leps.pdgId, 0))) & + (ak.fill_none(first_leps.charge, 0) != ak.fill_none(second_leps.charge, 0)) & + (abs((lep1_lorentz_vec + lep2_lorentz_vec).mass - 91.1876) < 10.0) + ), axis = 1 + ) == 0 + + single_step4_mask = ak.fill_none(Invariant_mass_cut & Zmass_cut, False) + listOfCuts.add( 'ZMassAndInvarMassCut', ak.to_numpy(single_step4_mask) ) + + + single_step5_mask = ak.fill_none(trigger_selection, False) + listOfCuts.add( 'PassesHLTCuts', ak.to_numpy(single_step5_mask) ) + + #MC match for leading and subleading leptons + leading_MC_match = leading_leptons.MC_Match | (isMC == False) + + + #No more than 1 tight leptons AND should be the same as leading lepton + n_tight_leptons = ak.sum(leptons_tight.tight, axis=1) + + tight_lep_cut = ((n_tight_leptons == 0) | ((n_tight_leptons == 1) & (leading_leptons.tight))) + + #single_step7_mask = ak.fill_none(n_tight_leptons <= 1, False) + single_step7_mask = ak.fill_none(tight_lep_cut, False) + listOfCuts.add( 'AtMostOneTightLep', ak.to_numpy(single_step7_mask) ) + + taus = copy.deepcopy(events.Tau) + #Tau veto: no tau passing pt>20, abs(eta) < 2.3, abs(dxy) <= 1000, abs(dz) <= 0.2, "decayModeFindingNewDMs", decay modes = {0, 1, 2, 10, 11}, and "byMediumDeepTau2017v2VSjet", "byVLooseDeepTau2017v2VSmu", "byVVVLooseDeepTau2017v2VSe". Taus overlapping with fakeable electrons or fakeable muons within dR < 0.3 are not considered for the tau veto + #False -> Gets Removed : True -> Passes veto + tau_veto_pairs = ak.cartesian([taus, leptons_fakeable], nested=True) + taus_for_veto, leps_for_veto = ak.unzip(tau_veto_pairs) + + tau_veto_cleaning = ak.min(abs(taus_for_veto.delta_r(leps_for_veto)), axis=2) >= 0.3 + + tau_veto_selection = ( + (taus.pt > 20) & (abs(taus.eta) < 2.3) & (abs(taus.dxy) <= 1000.0) & (abs(taus.dz) <= 0.2) & (getattr(taus, 'idDecayModeNewDMs', False) | getattr(taus, 'idDecayModeOldDMs', False)) & + ( + (taus.decayMode == 0) | (taus.decayMode == 1) | (taus.decayMode == 2) | (taus.decayMode == 10) | (taus.decayMode == 11) + ) & + (taus.idDeepTau2017v2p1VSjet >= 16) & (taus.idDeepTau2017v2p1VSmu >= 1) & (taus.idDeepTau2017v2p1VSe >= 1) + ) + + tau_veto = ak.any(tau_veto_cleaning & tau_veto_selection, axis=1) == 0 + + single_step8_mask = ak.fill_none(tau_veto, False) + listOfCuts.add( 'TauVeto', ak.to_numpy(single_step8_mask) ) + + #Jet cuts + #1 or more btagged ak8_jets or 1 or more btagged ak4_jets + one_btagged_jet = (ak.sum(ak4_jets.medium_btag_single, axis=1) >= 1) | (ak.sum(ak8_jets.btag_single, axis=1) >= 1) + + single_step9_mask = ak.fill_none(one_btagged_jet, False) + listOfCuts.add( 'AtLeastOneBJet', ak.to_numpy(single_step9_mask) ) + + #Count ak4 jets that are dR 1.2 away from btagged ak8 jets + #Require either: + # 0 ak8 btagged jets and 3 or more cleaned ak4 jets + # or + # 1 or more ak8 btagged jets and 1 or more cleaned ak4 jets 1.2dR away from an ak8 bjet + #ak8_jets_btag_single = ak8_jets.mask[ak8_jets.btag_single] + ak8_jets_btag_single = ak8_jets[ak8_jets.btag_single] + + ak8_jets_btag_single_sorted = ak8_jets_btag_single + if ak.any(ak8_jets_btag_single): #Required in case no ak8 jets available, can happen with data + ak8_jets_btag_single_sorted = ak8_jets_btag_single[ak.argsort(ak8_jets_btag_single.pt, axis=1, ascending=False)] + + ak8_jets_btag_single_sorted_padded = ak.pad_none(ak8_jets_btag_single_sorted, 1) + + ak4_jets_padded = ak.pad_none(ak4_jets, 1) + + clean_ak4_jets_btagged_ak8_jets = ak.cartesian([ak4_jets_padded.mask[ak4_jets_padded.cleaned_single], ak8_jets_btag_single_sorted_padded], nested=True) + + clean_ak4_for_veto, btag_ak8_for_veto = ak.unzip(clean_ak4_jets_btagged_ak8_jets) + + ak4_jets.jets_that_not_bb = ak.any(abs(clean_ak4_for_veto.delta_r(btag_ak8_for_veto)) > 1.2, axis=2) + n_jets_that_not_bb = ak.sum(ak4_jets.jets_that_not_bb, axis=1) + + + jet_btag_veto = ( + ( (n_jets_that_not_bb >= 1) & (ak.sum(ak8_jets.btag_single, axis=1) >= 1) ) + | + ( (ak.sum(ak8_jets.btag_single, axis=1) == 0) & (ak.sum(ak4_jets.cleaned_single, axis=1) >= 3) ) + ) + + single_step10_mask = ak.fill_none(jet_btag_veto, False) + listOfCuts.add( 'EnoughNonBJets', ak.to_numpy(single_step10_mask) ) + + + listOfCuts.add( "Single_HbbFat_WjjRes_AllReco", ak.to_numpy( ak.fill_none((ak.sum(ak8_jets.btag_single, axis=1) >= 1) & (n_jets_that_not_bb >= 2), False)) ) + + listOfCuts.add( "Single_HbbFat_WjjRes_MissJet", ak.to_numpy( ak.fill_none((ak.sum(ak8_jets.btag_single, axis=1) >= 1) & (n_jets_that_not_bb < 2), False)) ) + + listOfCuts.add( "Single_Res_allReco_2b", ak.to_numpy( ak.fill_none((ak.sum(ak8_jets.btag_single, axis=1) == 0) & (ak.sum(ak4_jets.cleaned_single, axis=1) >= 4) & (ak.sum(ak4_jets.medium_btag_single, axis=1) > 1), False)) ) + + listOfCuts.add( "Single_Res_allReco_1b", ak.to_numpy( ak.fill_none((ak.sum(ak8_jets.btag_single, axis=1) == 0) & (ak.sum(ak4_jets.cleaned_single, axis=1) >= 4) & (ak.sum(ak4_jets.medium_btag_single, axis=1) == 1), False)) ) + + listOfCuts.add( "Single_Res_MissWJet_2b", ak.to_numpy( ak.fill_none((ak.sum(ak8_jets.btag_single, axis=1) == 0) & (ak.sum(ak4_jets.cleaned_single, axis=1) < 4) & (ak.sum(ak4_jets.medium_btag_single, axis=1) > 1), False)) ) + + listOfCuts.add( "Single_Res_MissWJet_1b", ak.to_numpy( ak.fill_none((ak.sum(ak8_jets.btag_single, axis=1) == 0) & (ak.sum(ak4_jets.cleaned_single, axis=1) < 4) & (ak.sum(ak4_jets.medium_btag_single, axis=1) == 1), False)) ) + + listOfCuts.add( "Single_Signal", ak.to_numpy( ak.fill_none(((ak.sum(leptons_tight.tight, axis=1) == 1) & (leading_leptons.tight)), False)) ) + + listOfCuts.add( "Single_Fake", ak.to_numpy( ak.fill_none(((leading_leptons.tight) == 0), False)) ) + + ### Gen matching + genparts = events.GenPart + + # b-quarks from Higgs decay + bFromH = find_genpart(genparts, [5], [25]) + + # H -> WW + # light quarks W decay + qFromW = find_genpart(genparts, [1, 2 ,3, 4], [24, 25]) + + # leptons from W decay + lepFromW = find_genpart(genparts, [11, 13, 15], [24, 25]) + nuFromW = find_genpart(genparts, [12, 14, 16], [24, 25]) + + + ################################################################ + #### End of TAMU code + ################################################################ + + + # Weights + eweight = Weights(len(events),storeIndividual=True) + if not isData: + with uproot.open(events.metadata['filename']) as rfile: + Runs = rfile['Runs'] + genEventSumw = np.sum(Runs['genEventSumw']) + + lumi = events.metadata.get('lumi', 1.0) + xs = events.metadata.get('xs', 1.0) + events['weight'] = events.genWeight * (lumi * xs / genEventSumw) + eweight.add('genweight', events['genWeight']) + + pu_weight = list(correctionlib.CorrectionSet.from_file(self.corrections_metadata[year]['PU']).values())[0] + pu = pu_weight.evaluate( events.Pileup.nTrueInt.to_numpy(), 'nominal' ) + eweight.add('pileup',pu) + + def normalize(val, cut): + if cut is None: return ak.to_numpy(ak.fill_none(val, np.nan)) + else: return ak.to_numpy(ak.fill_none(val[cut], np.nan)) + + dataset = events.metadata['dataset'] + self.cutflow[dataset] = {} + sel_dict = { + 'goldenJson' : listOfCuts.require( goldenJson=True ), + 'PassesMETFilters' : listOfCuts.require( goldenJson=True, PassesMETFilters=True ), + 'single_lepton' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True ), + 'LeadLeptonConePtCut' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True ), + 'ZMassAndInvarMassCut' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True ), + 'PassesHLTCuts' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True ), + 'AtMostOneTightLep' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True, AtMostOneTightLep=True ), + 'TauVeto' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True, AtMostOneTightLep=True, TauVeto=True ), + 'AtLeastOneBJet' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True, AtMostOneTightLep=True, TauVeto=True, AtLeastOneBJet=True ), + 'EnoughNonBJets' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True, AtMostOneTightLep=True, TauVeto=True, AtLeastOneBJet=True, EnoughNonBJets=True ), + 'Single_Signal' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True, AtMostOneTightLep=True, TauVeto=True, AtLeastOneBJet=True, EnoughNonBJets=True, Single_Signal=True ), + 'Single_Res_allReco_2b' : listOfCuts.require( goldenJson=True, PassesMETFilters=True, single_lepton=True, LeadLeptonConePtCut=True, ZMassAndInvarMassCut=True, PassesHLTCuts=True, AtMostOneTightLep=True, TauVeto=True, AtLeastOneBJet=True, EnoughNonBJets=True, Single_Signal=True, Single_Res_allReco_2b=True ), + } + for isel, icut in sel_dict.items(): + iweight = eweight.weight()[icut] + self.cutflow[dataset][isel] = len(events[icut]) + + + icut = sel_dict['Single_Res_allReco_2b'] + iweight = eweight.weight()[icut] + self.hists['numJets'].fill( dataset=dataset, + selection=isel, + numJets=normalize(ak.num(ak4_jets.cleaned_single, axis=1), icut), + numBjets=normalize(ak.num(ak4_jets.medium_btag_single, axis=1), icut), + numnonBjets=normalize(ak.num(ak4_jets.jets_that_not_bb, axis=1), icut), + weight=iweight ) + self.hists['jet1'].fill( dataset=dataset, + selection=isel, + pt=normalize(ak4_jets[:,0].pt, icut), + eta=normalize(ak4_jets[:,0].eta, icut), + weight=iweight ) + + + output = { + 'hists' : self.hists, + 'cutflow': self.cutflow, + 'nEvent' : { + dataset : len(events) + } + } + + return output + + def postprocess(self, accumulator): + return accumulator + + +#### from https://github.com/aebid/HHbbWW_Run3/blob/main/python/genparticles.py#L42 +def find_genpart(genpart, pdgid, ancestors): + """ + Find gen level particles given pdgId (and ancestors ids) + + Parameters: + genpart (GenPart): NanoAOD GenPart collection. + pdgid (list): pdgIds for the target particles. + idmother (list): pdgIds for the ancestors of the target particles. + + Returns: + NanoAOD GenPart collection + """ + + def check_id(p): + return np.abs(genpart.pdgId) == p + + pid = reduce(np.logical_or, map(check_id, pdgid)) + + if ancestors: + ancs, ancs_idx = [], [] + for i, mother_id in enumerate(ancestors): + if i == 0: + mother_idx = genpart[pid].genPartIdxMother + else: + mother_idx = genpart[ancs_idx[i-1]].genPartIdxMother + ancs.append(np.abs(genpart[mother_idx].pdgId) == mother_id) + ancs_idx.append(mother_idx) + + decaymatch = reduce(np.logical_and, ancs) + return genpart[pid][decaymatch] + + return genpart[pid]