CMS 3D CMS Logo

List of all members | Public Member Functions | Static Public Member Functions | Private Member Functions | Private Attributes
BaseMVAValueMapProducer< T > Class Template Reference

#include <PhysicsTools/PatAlgos/plugins/BaseMVAValueMapProducer.cc>

Inheritance diagram for BaseMVAValueMapProducer< T >:
edm::stream::EDProducer<> edm::stream::EDProducerBase edm::ProducerBase edm::EDConsumerBase edm::ProductRegistryHelper

Public Member Functions

 BaseMVAValueMapProducer (const edm::ParameterSet &iConfig)
 
void setValue (const std::string var, float val)
 
 ~BaseMVAValueMapProducer () override
 
- Public Member Functions inherited from edm::stream::EDProducer<>
 EDProducer ()=default
 
- Public Member Functions inherited from edm::stream::EDProducerBase
 EDProducerBase ()
 
ModuleDescription const & moduleDescription () const
 
 ~EDProducerBase () override
 
- Public Member Functions inherited from edm::ProducerBase
void callWhenNewProductsRegistered (std::function< void(BranchDescription const &)> const &func)
 
std::vector< edm::ProductResolverIndex > const & indiciesForPutProducts (BranchType iBranchType) const
 
 ProducerBase ()
 
std::vector< edm::ProductResolverIndex > const & putTokenIndexToProductResolverIndex () const
 
void registerProducts (ProducerBase *, ProductRegistry *, ModuleDescription const &)
 
std::function< void(BranchDescription const &)> registrationCallback () const
 used by the fwk to register list of products More...
 
void resolvePutIndicies (BranchType iBranchType, ModuleToResolverIndicies const &iIndicies, std::string const &moduleLabel)
 
virtual ~ProducerBase () noexcept(false)
 
- Public Member Functions inherited from edm::EDConsumerBase
std::vector< ConsumesInfoconsumesInfo () const
 
void convertCurrentProcessAlias (std::string const &processName)
 Convert "@currentProcess" in InputTag process names to the actual current process name. More...
 
 EDConsumerBase ()
 
 EDConsumerBase (EDConsumerBase const &)=delete
 
 EDConsumerBase (EDConsumerBase &&)=default
 
ProductResolverIndexAndSkipBit indexFrom (EDGetToken, BranchType, TypeID const &) const
 
void itemsMayGet (BranchType, std::vector< ProductResolverIndexAndSkipBit > &) const
 
void itemsToGet (BranchType, std::vector< ProductResolverIndexAndSkipBit > &) const
 
std::vector< ProductResolverIndexAndSkipBit > const & itemsToGetFrom (BranchType iType) const
 
void labelsForToken (EDGetToken iToken, Labels &oLabels) const
 
void modulesWhoseProductsAreConsumed (std::vector< ModuleDescription const * > &modules, ProductRegistry const &preg, std::map< std::string, ModuleDescription const * > const &labelsToDesc, std::string const &processName) const
 
EDConsumerBase const & operator= (EDConsumerBase const &)=delete
 
EDConsumerBaseoperator= (EDConsumerBase &&)=default
 
bool registeredToConsume (ProductResolverIndex, bool, BranchType) const
 
bool registeredToConsumeMany (TypeID const &, BranchType) const
 
void updateLookup (BranchType iBranchType, ProductResolverIndexHelper const &, bool iPrefetchMayGet)
 
virtual ~EDConsumerBase () noexcept(false)
 

Static Public Member Functions

static void fillDescriptions (edm::ConfigurationDescriptions &descriptions)
 
static edm::ParameterSetDescription getDescription ()
 
- Static Public Member Functions inherited from edm::stream::EDProducerBase
static const std::string & baseType ()
 
static void fillDescriptions (ConfigurationDescriptions &descriptions)
 
static void prevalidate (ConfigurationDescriptions &descriptions)
 

Private Member Functions

void beginStream (edm::StreamID) override
 
void endStream () override
 
virtual void fillAdditionalVariables (const T &)
 
void produce (edm::Event &, const edm::EventSetup &) override
 
virtual void readAdditionalCollections (edm::Event &, const edm::EventSetup &)
 to be implemented in derived classes, filling values for additional variables More...
 

Private Attributes

std::string backend_
 
std::vector< std::pair< std::string, StringObjectFunction< T, true > > > funcs_
 
tensorflow::GraphDef * graph_
 
std::string inputTensorName_
 
bool isClassifier_
 
std::string name_
 
std::vector< StringObjectFunction< std::vector< float > > > output_formulas_
 
std::vector< std::string > output_names_
 
std::string outputTensorName_
 
std::map< std::string, size_t > positions_
 
TMVA::Reader * reader_
 
tensorflow::Session * session_
 
edm::EDGetTokenT< edm::View< T > > src_
 
bool tf_
 
bool tmva_
 
std::vector< float > values_
 
std::vector< std::string > variablesOrder_
 
std::string weightfilename_
 

Additional Inherited Members

- Public Types inherited from edm::stream::EDProducer<>
typedef CacheContexts< T... > CacheTypes
 
typedef CacheTypes::GlobalCache GlobalCache
 
typedef AbilityChecker< T... > HasAbility
 
typedef CacheTypes::LuminosityBlockCache LuminosityBlockCache
 
typedef LuminosityBlockContextT< LuminosityBlockCache, RunCache, GlobalCacheLuminosityBlockContext
 
typedef CacheTypes::LuminosityBlockSummaryCache LuminosityBlockSummaryCache
 
typedef CacheTypes::RunCache RunCache
 
typedef RunContextT< RunCache, GlobalCacheRunContext
 
typedef CacheTypes::RunSummaryCache RunSummaryCache
 
- Public Types inherited from edm::stream::EDProducerBase
typedef EDProducerAdaptorBase ModuleType
 
- Public Types inherited from edm::ProducerBase
using ModuleToResolverIndicies = std::unordered_multimap< std::string, std::tuple< edm::TypeID const *, const char *, edm::ProductResolverIndex >>
 
typedef ProductRegistryHelper::TypeLabelList TypeLabelList
 
- Public Types inherited from edm::EDConsumerBase
typedef ProductLabels Labels
 
- Protected Member Functions inherited from edm::EDConsumerBase
template<typename ProductType , BranchType B = InEvent>
EDGetTokenT< ProductType > consumes (edm::InputTag const &tag)
 
EDGetToken consumes (const TypeToGet &id, edm::InputTag const &tag)
 
template<BranchType B>
EDGetToken consumes (TypeToGet const &id, edm::InputTag const &tag)
 
ConsumesCollector consumesCollector ()
 Use a ConsumesCollector to gather consumes information from helper functions. More...
 
template<typename ProductType , BranchType B = InEvent>
void consumesMany ()
 
void consumesMany (const TypeToGet &id)
 
template<BranchType B>
void consumesMany (const TypeToGet &id)
 
template<typename ProductType , BranchType B = InEvent>
EDGetTokenT< ProductType > mayConsume (edm::InputTag const &tag)
 
EDGetToken mayConsume (const TypeToGet &id, edm::InputTag const &tag)
 
template<BranchType B>
EDGetToken mayConsume (const TypeToGet &id, edm::InputTag const &tag)
 

Detailed Description

template<typename T>
class BaseMVAValueMapProducer< T >

Description: [one line class summary]

Implementation: [Notes on implementation]

Definition at line 52 of file BaseMVAValueMapProducer.h.

Constructor & Destructor Documentation

template<typename T>
BaseMVAValueMapProducer< T >::BaseMVAValueMapProducer ( const edm::ParameterSet iConfig)
inlineexplicit

Definition at line 54 of file BaseMVAValueMapProducer.h.

54  :
56  variablesOrder_(iConfig.getParameter<std::vector<std::string>>("variablesOrder")),
57  name_(iConfig.getParameter<std::string>("name")),
58  backend_(iConfig.getParameter<std::string>("backend")),
59  weightfilename_(iConfig.getParameter<edm::FileInPath>("weightFile").fullPath()),
60  isClassifier_(iConfig.getParameter<bool>("isClassifier")),
61  tmva_(backend_=="TMVA"),tf_(backend_=="TF")
62  {
63  if(tmva_) reader_=new TMVA::Reader();
64  edm::ParameterSet const & varsPSet = iConfig.getParameter<edm::ParameterSet>("variables");
65  for (const std::string & vname : varsPSet.getParameterNamesForType<std::string>()) {
66  funcs_.emplace_back(std::pair<std::string,StringObjectFunction<T,true>>(vname,varsPSet.getParameter<std::string>(vname)));
67  }
68 
69  values_.resize(variablesOrder_.size());
70  size_t i=0;
71  for(const auto & v : variablesOrder_){
72  positions_[v]=i;
73  if(tmva_) reader_->AddVariable(v,(&values_.front())+i);
74  i++;
75  }
76 // reader_.BookMVA(name_,iConfig.getParameter<edm::FileInPath>("weightFile").fullPath() );
77  if(tmva_)
78  {
80  }else if(tf_) {
83  inputTensorName_=iConfig.getParameter<std::string>("inputTensorName");
84  outputTensorName_=iConfig.getParameter<std::string>("outputTensorName");
85  output_names_=iConfig.getParameter<std::vector<std::string>>("outputNames");
86  for(const auto & s : iConfig.getParameter<std::vector<std::string>>("outputFormulas")) { output_formulas_.push_back(StringObjectFunction<std::vector<float>>(s));}
87  size_t nThreads = iConfig.getParameter<unsigned int>("nThreads");
88  std::string singleThreadPool = iConfig.getParameter<std::string>("singleThreadPool");
89  tensorflow::SessionOptions sessionOptions;
90  tensorflow::setThreading(sessionOptions, nThreads, singleThreadPool);
91  session_ = tensorflow::createSession(graph_, sessionOptions);
92 
93  } else {
94  throw cms::Exception("ConfigError") << "Only 'TF' and 'TMVA' backends are supported\n";
95  }
96  if(tmva_) produces<edm::ValueMap<float>>();
97  else {
98  for(const auto & n : output_names_){
99  produces<edm::ValueMap<float>>(n);
100  }
101  }
102 
103  }
Session * createSession(SessionOptions &sessionOptions)
Definition: TensorFlow.cc:87
T getParameter(std::string const &) const
std::vector< StringObjectFunction< std::vector< float > > > output_formulas_
GraphDef * loadGraphDef(const std::string &pbFile)
Definition: TensorFlow.cc:68
tensorflow::GraphDef * graph_
EDGetTokenT< ProductType > consumes(edm::InputTag const &tag)
std::vector< std::string > getParameterNamesForType(bool trackiness=true) const
Definition: ParameterSet.h:194
std::map< std::string, size_t > positions_
std::vector< std::string > variablesOrder_
singleThreadPool
Definition: jets_cff.py:291
edm::EDGetTokenT< edm::View< T > > src_
void setThreading(SessionOptions &sessionOptions, int nThreads, const std::string &singleThreadPool="no_threads")
Definition: TensorFlow.cc:19
void setLogging(const std::string &level="3")
Definition: TensorFlow.cc:14
tensorflow::Session * session_
TMVA::IMethod * loadTMVAWeights(TMVA::Reader *reader, const std::string &method, const std::string &weightFile, bool verbose=false)
std::string fullPath() const
Definition: FileInPath.cc:184
std::vector< std::pair< std::string, StringObjectFunction< T, true > > > funcs_
std::vector< std::string > output_names_
template<typename T>
BaseMVAValueMapProducer< T >::~BaseMVAValueMapProducer ( )
inlineoverride

Definition at line 104 of file BaseMVAValueMapProducer.h.

104 {}

Member Function Documentation

template<typename T>
void BaseMVAValueMapProducer< T >::beginStream ( edm::StreamID  )
inlineoverrideprivatevirtual

Reimplemented from edm::stream::EDProducerBase.

Definition at line 115 of file BaseMVAValueMapProducer.h.

115 {};
template<typename T>
void BaseMVAValueMapProducer< T >::endStream ( )
inlineoverrideprivatevirtual

Reimplemented from edm::stream::EDProducerBase.

Definition at line 117 of file BaseMVAValueMapProducer.h.

117 {};
template<typename T>
virtual void BaseMVAValueMapProducer< T >::fillAdditionalVariables ( const T )
inlineprivatevirtual

Reimplemented in BJetEnergyRegressionMVA.

Definition at line 121 of file BaseMVAValueMapProducer.h.

Referenced by BaseMVAValueMapProducer< T >::produce().

121 {}
template<typename T >
void BaseMVAValueMapProducer< T >::fillDescriptions ( edm::ConfigurationDescriptions descriptions)
static

Definition at line 222 of file BaseMVAValueMapProducer.h.

References edm::ConfigurationDescriptions::add(), BaseMVAValueMapProducer< T >::getDescription(), and AlCaHLTBitMon_QueryRunRegistry::string.

Referenced by BaseMVAValueMapProducer< pat::Jet >::setValue().

222  {
224  std::string modname;
225  if (typeid(T) == typeid(pat::Jet)) modname+="Jet";
226  else if (typeid(T) == typeid(pat::Muon)) modname+="Muon";
227  else if (typeid(T) == typeid(pat::Electron)) modname+="Ele";
228  modname+="BaseMVAValueMapProducer";
229  descriptions.add(modname,desc);
230 }
static edm::ParameterSetDescription getDescription()
Analysis-level electron class.
Definition: Electron.h:52
Analysis-level calorimeter jet class.
Definition: Jet.h:80
void add(std::string const &label, ParameterSetDescription const &psetDescription)
long double T
Analysis-level muon class.
Definition: Muon.h:50
template<typename T >
edm::ParameterSetDescription BaseMVAValueMapProducer< T >::getDescription ( )
static

Definition at line 198 of file BaseMVAValueMapProducer.h.

References edm::ParameterSetDescription::add(), edm::ParameterSetDescription::setAllowAnything(), edm::ParameterDescriptionNode::setComment(), AlCaHLTBitMon_QueryRunRegistry::string, and objects.autophobj::variables.

Referenced by BaseMVAValueMapProducer< T >::fillDescriptions(), BJetEnergyRegressionMVA::fillDescriptions(), and BaseMVAValueMapProducer< pat::Jet >::setValue().

198  {
200  desc.add<edm::InputTag>("src")->setComment("input physics object collection");
201  desc.add<std::vector<std::string>>("variablesOrder")->setComment("ordered list of MVA input variable names");
202  desc.add<std::string>("name")->setComment("output score variable name");
203  desc.add<bool>("isClassifier")->setComment("is a classifier discriminator");
205  variables.setAllowAnything();
206  desc.add<edm::ParameterSetDescription>("variables", variables)->setComment("list of input variable definitions");
207  desc.add<edm::FileInPath>("weightFile")->setComment("xml weight file");
208  desc.add<std::string>("backend","TMVA")->setComment("TMVA or TF");
209  desc.add<std::string>("inputTensorName","")->setComment("Name of tensorflow input tensor in the model");
210  desc.add<std::string>("outputTensorName","")->setComment("Name of tensorflow output tensor in the model");
211  desc.add<std::vector<std::string>>("outputNames",std::vector<std::string>())->setComment("Names of the output values to be used in the output valuemap");
212  desc.add<std::vector<std::string>>("outputFormulas",std::vector<std::string>())->setComment("Formulas to be used to post process the output");
213  desc.add<unsigned int>("nThreads",1)->setComment("number of threads");
214  desc.add<std::string>("singleThreadPool", "no_threads");
215 
216 
217  return desc;
218 }
void setComment(std::string const &value)
void setAllowAnything()
allow any parameter label/value pairs
ParameterDescriptionBase * add(U const &iLabel, T const &value)
template<typename T >
void BaseMVAValueMapProducer< T >::produce ( edm::Event iEvent,
const edm::EventSetup iSetup 
)
overrideprivate

Definition at line 148 of file BaseMVAValueMapProducer.h.

References pat::helper::ParametrizationHelper::dimension(), edm::helper::Filler< Map >::fill(), BaseMVAValueMapProducer< T >::fillAdditionalVariables(), objects.autophobj::filler, BaseMVAValueMapProducer< T >::funcs_, edm::Event::getByToken(), BaseMVAValueMapProducer< T >::inputTensorName_, edm::helper::Filler< Map >::insert(), createfilelist::int, BaseMVAValueMapProducer< T >::isClassifier_, gen::k, funct::m, eostools::move(), BaseMVAValueMapProducer< T >::name_, cscdqm::h::names, connectstrParser::o, BaseMVAValueMapProducer< T >::output_formulas_, BaseMVAValueMapProducer< T >::output_names_, PatBasicFWLiteJetAnalyzer_Selector_cfg::outputs, BaseMVAValueMapProducer< T >::outputTensorName_, AlCaHLTBitMon_ParallelJobs::p, BaseMVAValueMapProducer< T >::positions_, edm::Event::put(), BaseMVAValueMapProducer< T >::readAdditionalCollections(), BaseMVAValueMapProducer< T >::reader_, tensorflow::run(), BaseMVAValueMapProducer< T >::session_, BaseMVAValueMapProducer< T >::setValue(), TrackRefitter_38T_cff::src, BaseMVAValueMapProducer< T >::src_, BaseMVAValueMapProducer< T >::tf_, BaseMVAValueMapProducer< T >::tmva_, findQualityFiles::v, and BaseMVAValueMapProducer< T >::values_.

Referenced by BaseMVAValueMapProducer< pat::Jet >::beginStream().

149 {
151  iEvent.getByToken(src_, src);
152  readAdditionalCollections(iEvent,iSetup);
153  std::vector<std::vector<float>> mvaOut((tmva_)?1:output_names_.size());
154  for( auto & v : mvaOut) v.reserve(src->size());
155 
156  for(auto const & o: *src) {
157  for(auto const & p : funcs_ ){
158  setValue(p.first,p.second(o));
159  }
161  if(tmva_){
162  mvaOut[0].push_back(isClassifier_ ? reader_->EvaluateMVA(name_) : reader_->EvaluateRegression(name_)[0]);
163  }
164  if(tf_){
165  //currently support only one input sensor to reuse the TMVA like config
166  tensorflow::TensorShape input_size {1,(long long int)positions_.size()} ;
167  tensorflow::NamedTensorList input_tensors;
168  input_tensors.resize(1);
169  input_tensors[0] = tensorflow::NamedTensor(inputTensorName_, tensorflow::Tensor(tensorflow::DT_FLOAT, input_size));
170  for(size_t j =0; j < values_.size();j++) {
171  input_tensors[0].second.matrix<float>()(0,j) = values_[j];
172  }
173  std::vector<tensorflow::Tensor> outputs;
174  std::vector<std::string> names; names.push_back(outputTensorName_);
175  tensorflow::run(session_, input_tensors, names, &outputs);
176  std::vector<float> tmpOut;
177  for(int k=0;k<outputs.at(0).matrix<float>().dimension(1);k++) tmpOut.push_back(outputs.at(0).matrix<float>()(0, k));
178  for(size_t k=0;k<output_names_.size();k++) mvaOut[k].push_back(output_formulas_[k](tmpOut));
179 
180  }
181 
182 
183  }
184  size_t k=0;
185  for( auto & m : mvaOut) {
186  std::unique_ptr<edm::ValueMap<float>> mvaV(new edm::ValueMap<float>());
188  filler.insert(src,m.begin(),m.end());
189  filler.fill();
190  iEvent.put(std::move(mvaV),(tmva_)?"":output_names_[k]);
191  k++;
192  }
193 
194 }
virtual void fillAdditionalVariables(const T &)
std::vector< NamedTensor > NamedTensorList
Definition: TensorFlow.h:26
OrphanHandle< PROD > put(std::unique_ptr< PROD > product)
Put a new product.
Definition: Event.h:127
std::vector< StringObjectFunction< std::vector< float > > > output_formulas_
static const HistoName names[]
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:508
void setValue(const std::string var, float val)
std::pair< std::string, Tensor > NamedTensor
Definition: TensorFlow.h:25
std::map< std::string, size_t > positions_
int k[5][pyjets_maxn]
edm::EDGetTokenT< edm::View< T > > src_
tensorflow::Session * session_
void run(Session *session, const NamedTensorList &inputs, const std::vector< std::string > &outputNames, const std::vector< std::string > &targetNodes, std::vector< Tensor > *outputs)
Definition: TensorFlow.cc:210
uint32_t dimension(pat::CandKinResolution::Parametrization parametrization)
Returns the number of free parameters in a parametrization (3 or 4)
std::vector< std::pair< std::string, StringObjectFunction< T, true > > > funcs_
def move(src, dest)
Definition: eostools.py:510
std::vector< std::string > output_names_
virtual void readAdditionalCollections(edm::Event &, const edm::EventSetup &)
to be implemented in derived classes, filling values for additional variables
template<typename T>
virtual void BaseMVAValueMapProducer< T >::readAdditionalCollections ( edm::Event ,
const edm::EventSetup  
)
inlineprivatevirtual

to be implemented in derived classes, filling values for additional variables

Reimplemented in BJetEnergyRegressionMVA.

Definition at line 120 of file BaseMVAValueMapProducer.h.

Referenced by BaseMVAValueMapProducer< T >::produce().

120 {}
template<typename T>
void BaseMVAValueMapProducer< T >::setValue ( const std::string  var,
float  val 
)
inline

Definition at line 106 of file BaseMVAValueMapProducer.h.

Referenced by BaseMVAValueMapProducer< T >::produce().

106  {
107  if(positions_.find(var)!=positions_.end())
109  }
std::map< std::string, size_t > positions_

Member Data Documentation

template<typename T>
std::string BaseMVAValueMapProducer< T >::backend_
private

Definition at line 134 of file BaseMVAValueMapProducer.h.

template<typename T>
std::vector<std::pair<std::string,StringObjectFunction<T,true> > > BaseMVAValueMapProducer< T >::funcs_
private
template<typename T>
tensorflow::GraphDef* BaseMVAValueMapProducer< T >::graph_
private
template<typename T>
std::string BaseMVAValueMapProducer< T >::inputTensorName_
private
template<typename T>
bool BaseMVAValueMapProducer< T >::isClassifier_
private

Definition at line 136 of file BaseMVAValueMapProducer.h.

Referenced by BaseMVAValueMapProducer< T >::produce().

template<typename T>
std::string BaseMVAValueMapProducer< T >::name_
private
template<typename T>
std::vector<StringObjectFunction<std::vector<float> > > BaseMVAValueMapProducer< T >::output_formulas_
private
template<typename T>
std::vector<std::string> BaseMVAValueMapProducer< T >::output_names_
private
template<typename T>
std::string BaseMVAValueMapProducer< T >::outputTensorName_
private
template<typename T>
std::map<std::string,size_t> BaseMVAValueMapProducer< T >::positions_
private
template<typename T>
TMVA::Reader* BaseMVAValueMapProducer< T >::reader_
private
template<typename T>
tensorflow::Session* BaseMVAValueMapProducer< T >::session_
private
template<typename T>
edm::EDGetTokenT<edm::View<T> > BaseMVAValueMapProducer< T >::src_
private

Definition at line 124 of file BaseMVAValueMapProducer.h.

Referenced by BaseMVAValueMapProducer< T >::produce().

template<typename T>
bool BaseMVAValueMapProducer< T >::tf_
private
template<typename T>
bool BaseMVAValueMapProducer< T >::tmva_
private
template<typename T>
std::vector<float> BaseMVAValueMapProducer< T >::values_
private
template<typename T>
std::vector<std::string> BaseMVAValueMapProducer< T >::variablesOrder_
private
template<typename T>
std::string BaseMVAValueMapProducer< T >::weightfilename_
private