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<>

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
 
bool hasAbilityToProduceInLumis () const final
 
bool hasAbilityToProduceInRuns () const final
 

Static Public Member Functions

static void fillDescriptions (edm::ConfigurationDescriptions &descriptions)
 
static edm::ParameterSetDescription getDescription ()
 

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
 

Detailed Description

template<typename T>
class BaseMVAValueMapProducer< T >

Description: [one line class summary]

Implementation: [Notes on implementation]

Definition at line 59 of file BaseMVAValueMapProducer.h.

Constructor & Destructor Documentation

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

Definition at line 61 of file BaseMVAValueMapProducer.h.

61  :
62  src_(consumes<edm::View<T>>(iConfig.getParameter<edm::InputTag>("src"))),
63  variablesOrder_(iConfig.getParameter<std::vector<std::string>>("variablesOrder")),
64  name_(iConfig.getParameter<std::string>("name")),
65  backend_(iConfig.getParameter<std::string>("backend")),
66  weightfilename_(iConfig.getParameter<edm::FileInPath>("weightFile").fullPath()),
67  isClassifier_(iConfig.getParameter<bool>("isClassifier")),
68  tmva_(backend_=="TMVA"),tf_(backend_=="TF")
69  {
70  if(tmva_) reader_=new TMVA::Reader();
71  edm::ParameterSet const & varsPSet = iConfig.getParameter<edm::ParameterSet>("variables");
72  for (const std::string & vname : varsPSet.getParameterNamesForType<std::string>()) {
73  funcs_.emplace_back(std::pair<std::string,StringObjectFunction<T,true>>(vname,varsPSet.getParameter<std::string>(vname)));
74  }
75 
76  values_.resize(variablesOrder_.size());
77  size_t i=0;
78  for(const auto & v : variablesOrder_){
79  positions_[v]=i;
80  if(tmva_) reader_->AddVariable(v,(&values_.front())+i);
81  i++;
82  }
83 // reader_.BookMVA(name_,iConfig.getParameter<edm::FileInPath>("weightFile").fullPath() );
84  if(tmva_)
85  {
87  }else if(tf_) {
90  inputTensorName_=iConfig.getParameter<std::string>("inputTensorName");
91  outputTensorName_=iConfig.getParameter<std::string>("outputTensorName");
92  output_names_=iConfig.getParameter<std::vector<std::string>>("outputNames");
93  for(const auto & s : iConfig.getParameter<std::vector<std::string>>("outputFormulas")) { output_formulas_.push_back(StringObjectFunction<std::vector<float>>(s));}
94  size_t nThreads = iConfig.getParameter<unsigned int>("nThreads");
95  std::string singleThreadPool = iConfig.getParameter<std::string>("singleThreadPool");
96  tensorflow::SessionOptions sessionOptions;
97  tensorflow::setThreading(sessionOptions, nThreads, singleThreadPool);
98  session_ = tensorflow::createSession(graph_, sessionOptions);
99 
100  } else {
101  throw cms::Exception("ConfigError") << "Only 'TF' and 'TMVA' backends are supported\n";
102  }
103  if(tmva_) produces<edm::ValueMap<float>>();
104  else {
105  for(const auto & n : output_names_){
106  produces<edm::ValueMap<float>>(n);
107  }
108  }
109 
110  }
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_
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:317
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:197
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 111 of file BaseMVAValueMapProducer.h.

111 {}

Member Function Documentation

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

Definition at line 122 of file BaseMVAValueMapProducer.h.

122 {};
template<typename T>
void BaseMVAValueMapProducer< T >::endStream ( )
inlineoverrideprivate

Definition at line 124 of file BaseMVAValueMapProducer.h.

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

Reimplemented in BJetEnergyRegressionMVA.

Definition at line 128 of file BaseMVAValueMapProducer.h.

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

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

Definition at line 229 of file BaseMVAValueMapProducer.h.

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

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

229  {
231  std::string modname;
232  if (typeid(T) == typeid(pat::Jet)) modname+="Jet";
233  else if (typeid(T) == typeid(pat::Muon)) modname+="Muon";
234  else if (typeid(T) == typeid(pat::Electron)) modname+="Ele";
235  modname+="BaseMVAValueMapProducer";
236  descriptions.add(modname,desc);
237 }
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 205 of file BaseMVAValueMapProducer.h.

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

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

205  {
207  desc.add<edm::InputTag>("src")->setComment("input physics object collection");
208  desc.add<std::vector<std::string>>("variablesOrder")->setComment("ordered list of MVA input variable names");
209  desc.add<std::string>("name")->setComment("output score variable name");
210  desc.add<bool>("isClassifier")->setComment("is a classifier discriminator");
212  variables.setAllowAnything();
213  desc.add<edm::ParameterSetDescription>("variables", variables)->setComment("list of input variable definitions");
214  desc.add<edm::FileInPath>("weightFile")->setComment("xml weight file");
215  desc.add<std::string>("backend","TMVA")->setComment("TMVA or TF");
216  desc.add<std::string>("inputTensorName","")->setComment("Name of tensorflow input tensor in the model");
217  desc.add<std::string>("outputTensorName","")->setComment("Name of tensorflow output tensor in the model");
218  desc.add<std::vector<std::string>>("outputNames",std::vector<std::string>())->setComment("Names of the output values to be used in the output valuemap");
219  desc.add<std::vector<std::string>>("outputFormulas",std::vector<std::string>())->setComment("Formulas to be used to post process the output");
220  desc.add<unsigned int>("nThreads",1)->setComment("number of threads");
221  desc.add<std::string>("singleThreadPool", "no_threads");
222 
223 
224  return desc;
225 }
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 155 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_, 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().

156 {
158  iEvent.getByToken(src_, src);
159  readAdditionalCollections(iEvent,iSetup);
160  std::vector<std::vector<float>> mvaOut((tmva_)?1:output_names_.size());
161  for( auto & v : mvaOut) v.reserve(src->size());
162 
163  for(auto const & o: *src) {
164  for(auto const & p : funcs_ ){
165  setValue(p.first,p.second(o));
166  }
168  if(tmva_){
169  mvaOut[0].push_back(isClassifier_ ? reader_->EvaluateMVA(name_) : reader_->EvaluateRegression(name_)[0]);
170  }
171  if(tf_){
172  //currently support only one input sensor to reuse the TMVA like config
173  tensorflow::TensorShape input_size {1,(long long int)positions_.size()} ;
174  tensorflow::NamedTensorList input_tensors;
175  input_tensors.resize(1);
176  input_tensors[0] = tensorflow::NamedTensor(inputTensorName_, tensorflow::Tensor(tensorflow::DT_FLOAT, input_size));
177  for(size_t j =0; j < values_.size();j++) {
178  input_tensors[0].second.matrix<float>()(0,j) = values_[j];
179  }
180  std::vector<tensorflow::Tensor> outputs;
181  std::vector<std::string> names; names.push_back(outputTensorName_);
182  tensorflow::run(session_, input_tensors, names, &outputs);
183  std::vector<float> tmpOut;
184  for(int k=0;k<outputs.at(0).matrix<float>().dimension(1);k++) tmpOut.push_back(outputs.at(0).matrix<float>()(0, k));
185  for(size_t k=0;k<output_names_.size();k++) mvaOut[k].push_back(output_formulas_[k](tmpOut));
186 
187  }
188 
189 
190  }
191  size_t k=0;
192  for( auto & m : mvaOut) {
193  std::unique_ptr<edm::ValueMap<float>> mvaV(new edm::ValueMap<float>());
195  filler.insert(src,m.begin(),m.end());
196  filler.fill();
197  iEvent.put(std::move(mvaV),(tmva_)?"":output_names_[k]);
198  k++;
199  }
200 
201 }
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:137
std::vector< StringObjectFunction< std::vector< float > > > output_formulas_
bool getByToken(EDGetToken token, Handle< PROD > &result) const
Definition: Event.h:579
const std::string names[nVars_]
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 127 of file BaseMVAValueMapProducer.h.

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

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

Definition at line 113 of file BaseMVAValueMapProducer.h.

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

113  {
114  if(positions_.find(var)!=positions_.end())
116  }
std::map< std::string, size_t > positions_

Member Data Documentation

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

Definition at line 141 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 143 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 131 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