DL2.cxx 16.9 KB
Newer Older
1
/*
2
  Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration
3
4
5
*/

#include "FlavorTagDiscriminants/DL2.h"
6
#include "FlavorTagDiscriminants/BTagTrackIpAccessor.h"
7
8
9
#include "lwtnn/LightweightGraph.hh"
#include "lwtnn/NanReplacer.hh"

10
11
#include "xAODBTagging/BTaggingUtilities.h"

Dan Guest's avatar
Dan Guest committed
12
namespace {
13
  const std::string jetLinkName = "jetLink";
Dan Guest's avatar
Dan Guest committed
14
15
}

16
17
18

namespace FlavorTagDiscriminants {

19
20
21
22
  DL2Options::DL2Options() {
    track_prefix = "btagIp_";
    flip = FlipTagConfig::STANDARD;
    track_link_name = "BTagTrackToJetAssociator";
23
    track_link_type = TrackLinkType::TRACK_PARTICLE;
24
25
  }

26
27
28
29
30
31
  // DL2
  //
  // TODO: make this work with more input nodes
  DL2::DL2(const lwt::GraphConfig& graph_config,
           const std::vector<DL2InputConfig>& inputs,
           const std::vector<DL2TrackSequenceConfig>& track_sequences,
32
           const DL2Options& options):
33
    m_jetLink(jetLinkName),
34
    m_input_node_name(""),
35
    m_graph(new lwt::LightweightGraph(graph_config,graph_config.outputs.begin()->first)),
36
37
38
    m_variable_cleaner(nullptr)
  {
    using namespace internal;
39
    std::map<std::string, std::string> remap = options.remap_scalar;
40
41
42
43
44
45
46
47
48
49
50
    // set up inputs
    if (graph_config.inputs.size() > 1) {
      throw std::logic_error("We don't currently support graphs with "
                             "more than one input");
    } else if (graph_config.inputs.size() == 1){
      m_input_node_name = graph_config.inputs.at(0).name;
      m_variable_cleaner.reset(new lwt::NanReplacer(
                                 graph_config.inputs.at(0).defaults,
                                 lwt::rep::all));
    }
    for (const auto& input: inputs) {
51
52
53
54
55
56
57
58
59
      auto filler = get::varFromBTag(input.name, input.type,
                                     input.default_flag);
      if (input.type != EDMType::CUSTOM_GETTER) {
        m_dataDependencyNames.bTagInputs.insert(input.name);
      }
      if (input.default_flag.size() > 0) {
        m_dataDependencyNames.bTagInputs.insert(input.default_flag);
      }
      m_varsFromBTag.push_back(filler);
60
61
62
    }

    // set up sequence inputs
63
64
65
66
    for (const DL2TrackSequenceConfig& cfg: track_sequences) {
      TrackSequenceBuilder track_getter(cfg.order,
                                        cfg.selection,
                                        options);
67
      // add the tracking data dependencies
68
69
      auto track_data_deps = get::trackFilter(cfg.selection, options).second;
      track_data_deps.merge(get::flipFilter(options).second);
70

71
72
73
      track_getter.name = cfg.name;
      for (const DL2TrackInputConfig& input_cfg: cfg.inputs) {
        auto [seqGetter, deps] = get::seqFromTracks(input_cfg, options);
74
75
        track_getter.sequencesFromTracks.push_back(seqGetter);
        track_data_deps.merge(deps);
76
77
      }
      m_trackSequenceBuilders.push_back(track_getter);
78
      m_dataDependencyNames.trackInputs.merge(track_data_deps);
79
      m_dataDependencyNames.bTagInputs.insert(jetLinkName);
80
      m_dataDependencyNames.bTagInputs.insert(options.track_link_name);
81
82
83
84
85
    }

    // set up outputs
    for (const auto& out_node: graph_config.outputs) {
      std::string node_name = out_node.first;
86

87
88
89
      OutNode node;
      for (const std::string& element: out_node.second.labels) {
        std::string name = node_name + "_" + element;
90
91

        // let user rename the output
92
        if (auto h = remap.extract(name)) name = h.mapped();
93
        m_dataDependencyNames.bTagOutputs.insert(name);
94

95
96
        SG::AuxElement::Decorator<float> f(name);
        node.emplace_back(element, f);
97
98
99
      }
      m_decorators[node_name] = node;
    }
100
101

    // we want to make sure every remapping was used
102
    if (remap.size() > 0) {
103
      std::string outputs;
104
      for (const auto& item: remap) {
105
        outputs.append(item.first);
106
        if (item != *remap.rbegin()) outputs.append(", ");
107
108
109
      }
      throw std::logic_error("found unused output remapping(s): " + outputs);
    }
110
  }
111

112
  void DL2::decorate(const xAOD::BTagging& btag) const {
113
114
115
116
117
118
119
120
121
122
123
124
    auto jetLink = m_jetLink(btag);
    if (!jetLink.isValid()) {
      throw std::runtime_error("invalid jetLink");
    }
    const xAOD::Jet& jet = **jetLink;
    decorate(jet, btag);
  }
  void DL2::decorate(const xAOD::Jet& jet) const {
    decorate(jet, jet);
  }

  void DL2::decorate(const xAOD::Jet& jet, const SG::AuxElement& btag) const {
125
126
    using namespace internal;
    std::vector<NamedVar> vvec;
127
    for (const auto& getter: m_varsFromBTag) {
128
      vvec.push_back(getter(btag));
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    }
    std::map<std::string, std::map<std::string, double> > nodes;
    if (m_variable_cleaner) {
      std::map<std::string, double> variables(vvec.begin(), vvec.end());
      auto cleaned = m_variable_cleaner->replace(variables);

      // Note, you can hack in more variables to `cleaned` here.

      // put the cleaned inputs into the node structure
      nodes[m_input_node_name] =  cleaned;
    }

    // add track sequences
    std::map<std::string,std::map<std::string, std::vector<double>>> seqs;
    for (const auto& builder: m_trackSequenceBuilders) {
144
      Tracks sorted_tracks = builder.tracksFromJet(jet, btag);
145
146
147
148
149
150
151
152
153
154
155
156
      Tracks flipped_tracks = builder.flipFilter(sorted_tracks, jet);
      for (const auto& seq_builder: builder.sequencesFromTracks) {
        seqs[builder.name].insert(seq_builder(jet, flipped_tracks));
      }
    }


    // save out things
    for (const auto& dec: m_decorators) {
      // the second argument to compute(...) is for sequences
      auto out_vals = m_graph->compute(nodes, seqs, dec.first);
      for (const auto& node: dec.second) {
157
        node.second(btag) = out_vals.at(node.first);
158
159
160
161
      }
    }
  }

162
163
164
165
  DL2DataDependencyNames DL2::getDataDependencyNames() const {
    return m_dataDependencyNames;
  }

166
  DL2::TrackSequenceBuilder::TrackSequenceBuilder(
167
    SortOrder sort,
168
    TrackSelection selection,
169
170
171
    const DL2Options& options):
    tracksFromJet(sort, selection, options),
    flipFilter(internal::get::flipFilter(options).first)
172
173
174
175
176
177
178
179
180
181
  {
  }



  // ________________________________________________________________________
  // Internal code
  namespace internal {

    // Track Getter Class
182
183
    TracksFromJet::TracksFromJet(SortOrder order,
                                 TrackSelection selection,
184
185
186
                                 const DL2Options& options):
      m_trackSortVar(get::trackSortVar(order, options)),
      m_trackFilter(get::trackFilter(selection, options).first)
187
    {
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
      // We have several ways to get tracks: either we retrieve an
      // IParticleContainer and cast the pointers to TrackParticle, or
      // we retrieve a TrackParticleContainer directly. Unfortunately
      // the way tracks are stored isn't consistent across the EDM, so
      // we allow configuration for both setups.
      //
      if (options.track_link_type == TrackLinkType::IPARTICLE) {
        SG::AuxElement::ConstAccessor<PartLinks> acc(options.track_link_name);
        m_associator = [acc](const SG::AuxElement& btag) -> TPV {
          TPV tracks;
          for (const ElementLink<IPC>& link: acc(btag)) {
            if (!link.isValid()) {
              throw std::logic_error("invalid particle link");
            }
            const auto* trk = dynamic_cast<const xAOD::TrackParticle*>(*link);
            if (!trk) {
              throw std::logic_error("iparticle does not cast to Track");
            }
            tracks.push_back(trk);
          }
          return tracks;
        };
      } else if (options.track_link_type == TrackLinkType::TRACK_PARTICLE){
        SG::AuxElement::ConstAccessor<TrackLinks> acc(options.track_link_name);
        m_associator = [acc](const SG::AuxElement& btag) -> TPV {
          TPV tracks;
          for (const ElementLink<TPC>& link: acc(btag)) {
            if (!link.isValid()) {
              throw std::logic_error("invalid track link");
            }
            tracks.push_back(*link);
          }
          return tracks;
        };
      } else {
        throw std::logic_error("Unknown TrackLinkType");
      }
225
    }
226
    Tracks TracksFromJet::operator()(const xAOD::Jet& jet,
227
                                     const SG::AuxElement& btagging) const {
228
      std::vector<std::pair<double, const xAOD::TrackParticle*>> tracks;
229
      for (const xAOD::TrackParticle *tp : m_associator(btagging)) {
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        if (m_trackFilter(tp)) {
          tracks.push_back({m_trackSortVar(tp, jet), tp});
        };
      }
      std::sort(tracks.begin(), tracks.end(), std::greater<>());
      std::vector<const xAOD::TrackParticle*> only_tracks;
      for (const auto& trk: tracks) only_tracks.push_back(trk.second);
      return only_tracks;
    }


    // ______________________________________________________________________
    // Internal utility functions
    //

    // The 'get' namespace is for factories that build std::function
    // objects
    namespace get {
      // factory for functions that get variables out of the b-tagging
      // object
250
      VarFromBTag varFromBTag(const std::string& name, EDMType type,
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
                            const std::string& default_flag) {
        if(default_flag.size() == 0 || name==default_flag)
        {
          switch (type) {
          case EDMType::INT: return BVarGetterNoDefault<int>(name);
          case EDMType::FLOAT: return BVarGetterNoDefault<float>(name);
          case EDMType::DOUBLE: return BVarGetterNoDefault<double>(name);
          case EDMType::UCHAR: return BVarGetterNoDefault<char>(name);
          case EDMType::CUSTOM_GETTER: return customGetterAndName(name);
          default: {
            throw std::logic_error("Unknown EDM type");
          }
          }
        }
        else{
          switch (type) {
          case EDMType::INT: return BVarGetter<int>(name, default_flag);
          case EDMType::FLOAT: return BVarGetter<float>(name, default_flag);
          case EDMType::DOUBLE: return BVarGetter<double>(name, default_flag);
          case EDMType::UCHAR: return BVarGetter<char>(name, default_flag);
          case EDMType::CUSTOM_GETTER: return customGetterAndName(name);
          default: {
            throw std::logic_error("Unknown EDM type");
          }
          }
        }
      }

      // factory for functions which return the sort variable we
      // use to order tracks
281
282
      TrackSortVar trackSortVar(SortOrder config, const DL2Options& options)
      {
283
284
        typedef xAOD::TrackParticle Tp;
        typedef xAOD::Jet Jet;
285
286
        BTagTrackIpAccessor aug(options.track_prefix);
        switch(config) {
287
288
289
290
291
292
        case SortOrder::ABS_D0_SIGNIFICANCE_DESCENDING:
          return [aug](const Tp* tp, const Jet&) {
                   return std::abs(aug.d0(*tp) / aug.d0Uncertainty(*tp));
                 };
        case SortOrder::D0_SIGNIFICANCE_DESCENDING:
          return [aug](const Tp* tp, const Jet& j) {
293
                   return aug.getSignedIp(*tp, j).ip3d_signed_d0_significance;
294
295
296
297
298
299
300
301
302
303
304
                 };
        case SortOrder::PT_DESCENDING:
          return [](const Tp* tp, const Jet&) {return tp->pt();};
        default: {
          throw std::logic_error("Unknown sort function");
        }
        }
      } // end of track sort getter

      // factory for functions that return true for tracks we want to
      // use, false for those we don't want
305
      std::pair<TrackFilter,std::set<std::string>> trackFilter(
306
        TrackSelection config, const DL2Options& options) {
307

308
309
        typedef xAOD::TrackParticle Tp;
        typedef SG::AuxElement AE;
310
        BTagTrackIpAccessor aug(options.track_prefix);
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
        auto data_deps = aug.getTrackIpDataDependencyNames();

        // make sure we record accessors as data dependencies
        auto addAccessor = [&data_deps](const std::string& n) {
                             AE::ConstAccessor<unsigned char> a(n);
                             data_deps.insert(n);
                             return a;
                           };
        auto pix_hits = addAccessor("numberOfPixelHits");
        auto pix_holes = addAccessor("numberOfPixelHoles");
        auto pix_shared = addAccessor("numberOfPixelSharedHits");
        auto pix_dead = addAccessor("numberOfPixelDeadSensors");
        auto sct_hits = addAccessor("numberOfSCTHits");
        auto sct_holes = addAccessor("numberOfSCTHoles");
        auto sct_shared = addAccessor("numberOfSCTSharedHits");
        auto sct_dead = addAccessor("numberOfSCTDeadSensors");

328
        switch (config) {
329
        case TrackSelection::ALL: return {[](const Tp*) {return true;}, {} };
330
331
332
333
334
335
336
337
          // the following numbers come from Nicole, Dec 2018:
          // pt > 1 GeV
          // abs(d0) < 1 mm
          // abs(z0 sin(theta)) < 1.5 mm
          // >= 7 si hits
          // <= 2 si holes
          // <= 1 pix holes
        case TrackSelection::IP3D_2018:
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
          return {
            [=](const Tp* tp) {
              // from the track selector tool
              if (std::abs(tp->eta()) > 2.5) return false;
              double n_module_shared = (
                pix_shared(*tp) + sct_shared(*tp) / 2);
              if (n_module_shared > 1) return false;
              if (tp->pt() <= 1e3) return false;
              if (std::abs(aug.d0(*tp)) >= 1.0) return false;
              if (std::abs(aug.z0SinTheta(*tp)) >= 1.5) return false;
              if (pix_hits(*tp) + pix_dead(*tp) + sct_hits(*tp)
                  + sct_dead(*tp) < 7) return false;
              if ((pix_holes(*tp) + sct_holes(*tp)) > 2) return false;
              if (pix_holes(*tp) > 1) return false;
              return true;
            }, data_deps
          };
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
          // Loose track selection for DIPS
          // pt > 0.5 GeV
          // abs(d0) < 3.5 mm
          // abs(z0 sin(theta)) < 5.0 mm
          // >= 7 si hits
          // <= 2 si holes
          // <= 1 pix holes
        case TrackSelection::DIPS_LOOSE_202102:
          return {
            [=](const Tp* tp) {
              // from the track selector tool
              if (std::abs(tp->eta()) > 2.5) return false;
              double n_module_shared = (
                pix_shared(*tp) + sct_shared(*tp) / 2);
              if (n_module_shared > 1) return false;
              if (tp->pt() <= 0.5e3) return false;
              if (std::abs(aug.d0(*tp)) >= 3.5) return false;
              if (std::abs(aug.z0SinTheta(*tp)) >= 5.0) return false;
              if (pix_hits(*tp) + pix_dead(*tp) + sct_hits(*tp)
                  + sct_dead(*tp) < 7) return false;
              if ((pix_holes(*tp) + sct_holes(*tp)) > 2) return false;
              if (pix_holes(*tp) > 1) return false;
              return true;
            }, data_deps
          };
380
381
382
383
384
385
386
        default:
          throw std::logic_error("unknown track selection function");
        }
      }

      // factory for functions that build std::vector objects from
      // track sequences
387
      std::pair<SeqFromTracks,std::set<std::string>> seqFromTracks(
388
        const DL2TrackInputConfig& cfg, const DL2Options& options)
389
      {
390
        const std::string prefix = options.track_prefix;
391
        switch (cfg.type) {
392
393
394
395
396
397
        case EDMType::FLOAT: return {
            SequenceGetter<float>(cfg.name), {cfg.name}
          };
        case EDMType::UCHAR: return {
            SequenceGetter<unsigned char>(cfg.name), {cfg.name}
          };
398
399
400
401
        case EDMType::CUSTOM_GETTER: {
          return customNamedSeqGetterWithDeps(
            cfg.name, options.track_prefix);
        }
402
403
404
405
406
407
408
409
410
411
412
        default: {
          throw std::logic_error("Unknown EDM type");
        }
        }
      }

      // here we define filters for the "flip" taggers
      //
      // start by defining the raw functions, there's a factory
      // function below to convert the configuration enums to a
      // std::function
413
      Tracks negativeIpOnly(BTagTrackIpAccessor& aug,
414
415
416
417
418
419
420
                            const Tracks& tracks,
                            const xAOD::Jet& j) {
        Tracks filtered;
        // we want to reverse the order of the tracks as part of the
        // flipping
        for (auto ti = tracks.crbegin(); ti != tracks.crend(); ti++) {
          const xAOD::TrackParticle* tp = *ti;
421
          double sip = aug.getSignedIp(*tp, j).ip3d_signed_d0_significance;
422
423
424
425
426
427
          if (sip < 0) filtered.push_back(tp);
        }
        return filtered;
      }

      // factory function
428
      std::pair<TrackSequenceFilter,std::set<std::string>> flipFilter(
429
        const DL2Options& options)
430
      {
431
        namespace ph = std::placeholders;  // for _1, _2, _3
432
433
        BTagTrackIpAccessor aug(options.track_prefix);
        switch(options.flip) {
434
435
        case FlipTagConfig::NEGATIVE_IP_ONLY:
          // flips order and removes tracks with negative IP
436
437
438
439
          return {
            std::bind(&negativeIpOnly, aug, ph::_1, ph::_2),
            aug.getTrackIpDataDependencyNames()
          };
440
441
        case FlipTagConfig::FLIP_SIGN:
          // Just flips the order
442
443
444
445
446
          return {
            [](const Tracks& tr, const xAOD::Jet& ) {
              return Tracks(tr.crbegin(), tr.crend());},
            {}
          };
447
        case FlipTagConfig::STANDARD:
448
          return {[](const Tracks& tr, const xAOD::Jet& ) { return tr; }, {}};
449
450
451
452
453
454
455
456
457
        default: {
          throw std::logic_error("Unknown flip config");
        }
        }
      }
    } // end of get namespace
  } // end of internal namespace

}