10#include "trg/cdc/modules/neurotrigger/CDCTriggerNeuroDataModule.h"
13#include <framework/datastore/StoreArray.h>
14#include <mdst/dataobjects/MCParticle.h>
15#include <tracking/dataobjects/RecoTrack.h>
16#include <trg/cdc/dataobjects/CDCTriggerSegmentHit.h>
17#include <trg/cdc/dataobjects/CDCTriggerTrack.h>
18#include <framework/datastore/StoreObjPtr.h>
19#include <framework/dataobjects/EventMetaData.h>
20#include <framework/core/ModuleParam.templateDetails.h>
22#include <cdc/geometry/CDCGeometryPar.h>
23#include <framework/gearbox/Unit.h>
24#include <framework/geometry/B2Vector3.h>
29#include "boost/iostreams/filter/gzip.hpp"
30#include "boost/iostreams/filtering_streambuf.hpp"
31#include "boost/iostreams/filtering_stream.hpp"
32#include "boost/multi_array.hpp"
33#define BOOST_MULTI_ARRAY_NO_GENERATORS
45 "This module takes 2dtracks, track segments, and targettracks (either recotracks or mcparticles) as input and generates training data for the neurotrigger in a tab separated, gzip compressed file."
49 "Name of the input StoreArray of CDCTriggerSegmentHits. The Axials need to have a relation to inputtracks",
52 "Name of the StoreArray holding the 2D input tracks.",
53 std::string(
"CDCTriggerNNInput2DTracks"));
55 "Name of the MCParticle/RecoTrack collection used as target values.",
56 std::string(
"RecoTracks"));
58 "If true, use RecoTracks as targets instead of MCParticles.",
61 "Name of the event time object.",
62 std::string(
"CDCTriggerNeuroETFT0"));
64 "When using real tracks, use neurotracks instead of 2dtracks as input to the neurotrigger. this is important to get the relations right.",
67 "Only use a track for a single expert",
true);
69 "Name of the configuration file. This File should be created by the CDCTriggerIDHistModule and will be extended in this module",
72 "Name of the configuration file, which will be written. If left blank, the same file as the input configuration file is used and it will be overwritten.",
75 "Name of the gzip file, where the training samples will be saved.",
76 std::string(
"out.gz"));
102 B2ERROR(
"The Neurotrigger needs to be initialized by a configuration file! Make sure to give the configuration file as a parameter.");
113 for (
int iSL = 0; iSL < 9; ++iSL) {
114 m_trainSet[iMLP].addCounters(cdc.nWiresInLayer(layerId));
115 layerId += (iSL > 0 ? 6 : 7);
122 B2ERROR(
"Number of ID sets (" <<
m_trainSet.size() <<
") should match " <<
126 std::ofstream gzipfile4(
m_filename, std::ios_base::trunc | std::ios_base::binary);
127 boost::iostreams::filtering_ostream outStream;
128 outStream.push(boost::iostreams::gzip_compressor());
129 outStream.push(gzipfile4);
131 outStream << sample.headline << std::endl;
142 float thetaTarget = 0;
148 B2DEBUG(150,
"Skipping CDCTriggerTrack without relation to RecoTrack.");
154 bool foundValidRep =
false;
155 for (
unsigned irep = 0; irep < reps.size() && !foundValidRep; ++irep) {
163 genfit::MeasuredStateOnPlane state =
165 reps[irep]->extrapolateToLine(state, TVector3(0, 0, -1000), TVector3(0, 0, 2000));
169 state.setPosMom(state.getPos(), -state.getMom());
170 state.setChargeSign(-state.getCharge());
175 thetaTarget = state.getMom().Theta();
176 zTarget = state.getPos().Z();
181 foundValidRep =
true;
183 if (!foundValidRep) {
184 B2DEBUG(150,
"No valid representation found for RecoTrack, skipping.");
191 B2DEBUG(150,
"Skipping CDCTriggerTrack without relation to MCParticle.");
202 float phi0 =
m_tracks[itrack]->getPhi0();
203 float invpt =
m_tracks[itrack]->getKappa(1.5);
204 float theta = atan2(1.,
m_tracks[itrack]->getCotTheta());
206 if (sectors.size() == 0)
continue;
209 std::vector<float> targetRaw = {};
211 targetRaw.push_back(zTarget);
213 targetRaw.push_back(thetaTarget);
214 for (
unsigned i = 0; i < sectors.size(); ++i) {
215 int isector = sectors[i];
216 std::vector<float> target =
m_NeuroTrigger[isector].scaleTarget(targetRaw);
218 bool outOfRange =
false;
219 for (
unsigned itarget = 0; itarget < target.size(); ++itarget) {
220 if (fabs(target[itarget]) > 1.) {
222 target[itarget] /= fabs(target[itarget]);
234 unsigned long sectorPattern =
m_NeuroTrigger[isector].getSLpattern();
236 unsigned long sectorPatternMask =
m_NeuroTrigger[isector].getSLpatternMask();
237 B2DEBUG(250,
"hitPattern " << hitPattern <<
" sectorPattern " << sectorPattern);
239 if (!
m_singleUse && sectorPattern > 0 && (sectorPattern & hitPattern) != sectorPattern) {
240 B2DEBUG(250,
"hitPattern not matching " << (sectorPattern & hitPattern));
243 }
else if (
m_singleUse && sectorPattern > 0 && (sectorPattern) != (hitPattern & sectorPatternMask)) {
245 B2DEBUG(250,
"hitPattern not matching " << (sectorPatternMask & hitPattern));
251 if ((hitPattern & 341) != 341 &&
252 (hitPattern & 341) != 340 &&
253 (hitPattern & 341) != 337 &&
254 (hitPattern & 341) != 325 &&
255 (hitPattern & 341) != 277 &&
256 (hitPattern & 341) != 85) {
257 B2DEBUG(250,
"Not enough axial hits (<4), skipping!");
261 std::vector<unsigned> hitIds;
269 evtmetadata->getExperiment(), evtmetadata->getRun(), evtmetadata->getSubrun(), evtmetadata->getEvent(), itrack, i,
273 if ((
m_trainSet)[isector].nSamples() % 1000 == 0) {
274 B2DEBUG(50,
m_trainSet[isector].nSamples() <<
" samples for training collected for sector " << isector);
276 std::ofstream gzipfile4(
m_filename, std::ios_base::app | std::ios_base::binary);
277 boost::iostreams::filtering_ostream outStream;
278 outStream.push(boost::iostreams::gzip_compressor());
279 outStream.push(gzipfile4);
280 outStream << sample << std::endl;
289 std::stringstream ss;
290 for (
unsigned int i = 0; i <
m_trainSet.size(); ++i) {
291 ss <<
"expert " << i <<
" : " <<
m_trainSet[i].nSamples() <<
", ";
309 B2DEBUG(10,
"Collected events: " << ss.str());
Struct for training data of a single MLP for the neuro trigger.
std::string m_EventTimeName
name of the event time StoreObjPtr
std::vector< CDCTriggerMLPData > m_trainSet
Sets of training data for all sectors.
bool m_trainOnRecoTracks
Switch between MCParticles or RecoTracks as targets.
NeuroTriggerParameters m_neuroParameters
Parameters for the NeuroTrigger.
NeuroTrigger m_NeuroTrigger
Instance of the NeuroTrigger.
std::string m_targetCollectionName
Name of the MCParticles/RecoTracks collection used as target values.
bool m_neuroTrackInputMode
Switch to rescale out of range target values or ignore them.
std::string m_inputCollectionName
Name of the StoreArray containing the input 2D tracks.
StoreArray< CDCTriggerTrack > m_tracks
List of input tracks.
std::string m_filename
Name of gzip file where the training data are saved.
bool m_singleUse
use a track only once and not for every expert
std::string m_writeconfigFileName
Name of the configuration file used in the module to write the neuroparamters.
int m_trackcounter
counter for tracks
std::string m_hitCollectionName
Name of the StoreArray containing the input track segment hits.
std::string m_configFileName
Name of the configuration file used in the module to load the neuroparamters.
The Class for CDC Geometry Parameters.
static CDCGeometryPar & Instance(const CDCGeometry *=nullptr)
Static method to get a reference to the CDCGeometryPar instance.
A Class to store the Monte Carlo particle information.
ROOT::Math::XYZVector getProductionVertex() const
Return production vertex position.
ROOT::Math::XYZVector getMomentum() const
Return momentum.
void setDescription(const std::string &description)
Sets the description of the module.
void lock()
lock the variable, to make it read only
std::vector< NNTParam< unsigned short > > maxHitsPerSL
Maximum number of hits in a single super layer for all networks.
NNTParam< bool > rescaleTarget
flag to allow for target tracks lying out of the output range to be rescaled during training.
NNTParam< bool > targetTheta
train theta as output
NNTParam< unsigned > ETOption
Determine, how the event time should be obtained.
NNTParam< bool > targetZ
train z as output
const std::string et_option() const
return the string variant ov the et option
void loadconfigtxt(const std::string &filename)
load the configuration from a file
void saveconfigtxt(const std::string &filename)
save the configuration to a file
void initialize(const Parameters &p)
Set parameters and get some network independent parameters.
void updateTrack(const CDCTriggerTrack &track)
Calculate 2D phi position and arclength for the given track and store them.
std::vector< unsigned > selectHits(unsigned isector, const CDCTriggerTrack &track, bool returnAllRelevant=false)
Select best hits for each super layer.
void initializeCollections(std::string hitCollectionName, std::string eventTimeName, const std::string &et_option)
set the hit collection and event time to required and store the hit collection name
std::vector< float > getInputVector(unsigned isector, const std::vector< unsigned > &hitIds)
Calculate input values for MLP.
std::vector< unsigned > selectHitsHWSim(unsigned isector, const CDCTriggerTrack &track)
Select hits for each super layer from the ones related to input track.
std::vector< int > selectMLPsTrain(float phi0, float invpt, float theta)
Select all matching expert MLPs based on the given track parameters.
unsigned long getCompleteHitPattern(unsigned isector, const CDCTriggerTrack &track, const bool neurotrackinputmode)
Get complete hit pattern of neurotrack.
void getEventTime(unsigned isector, const CDCTriggerTrack &track, std::string et_option, const bool)
Read out the event time and store it.
unsigned nSectors() const
return number of neural networks
This is the Reconstruction Event-Data Model Track.
const std::vector< genfit::AbsTrackRep * > & getRepresentations() const
Return a list of track representations. You are not allowed to modify or delete them!
bool wasFitSuccessful(const genfit::AbsTrackRep *representation=nullptr) const
Returns true if the last fit with the given representation was successful.
const genfit::MeasuredStateOnPlane & getMeasuredStateOnPlaneClosestTo(const ROOT::Math::XYZVector &closestPoint, const genfit::AbsTrackRep *representation=nullptr)
Return genfit's MasuredStateOnPlane, that is closest to the given point useful for extrapolation of m...
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
Accessor to arrays stored in the data store.
int getEntries() const
Get the number of objects in the array.
Type-safe access to single objects in the data store.
void addParam(const std::string &name, T ¶mVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
virtual void initialize() override
Initialize the module.
virtual void event() override
Called once for each event.
virtual void terminate() override
Do the training for all sectors.
CDCTriggerNeuroDataModule()
Constructor, for setting module description and parameters.
Abstract base class for different kinds of events.
Struct to keep one set of training data for either training, validation or testing.