ATLAS Offline Software
Loading...
Searching...
No Matches
dqm_algorithms::AutoencoderExampleAlgorithm Struct Reference

#include <AutoencoderExampleAlgorithm.h>

Inheritance diagram for dqm_algorithms::AutoencoderExampleAlgorithm:
Collaboration diagram for dqm_algorithms::AutoencoderExampleAlgorithm:

Public Member Functions

 AutoencoderExampleAlgorithm ()
virtual ~AutoencoderExampleAlgorithm () override=default
virtual AutoencoderExampleAlgorithmclone () override
virtual dqm_core::Result * execute (const std::string &, const TObject &, const dqm_core::AlgorithmConfig &) override
void printDescription (std::ostream &out)

Public Attributes

Ort::Env env
Ort::SessionOptions session_options
std::unique_ptr< Ort::Session > session
std::vector< std::string > input_names
std::vector< std::string > output_names

Detailed Description

Definition at line 38 of file AutoencoderExampleAlgorithm.h.

Constructor & Destructor Documentation

◆ AutoencoderExampleAlgorithm()

dqm_algorithms::AutoencoderExampleAlgorithm::AutoencoderExampleAlgorithm ( )

Definition at line 59 of file AutoencoderExampleAlgorithm.cxx.

60: env(ORT_LOGGING_LEVEL_WARNING, "test"),
62{
63
64 dqm_core::AlgorithmManager::instance().registerAlgorithm("AutoencoderExampleAlgorithm", this);
65
66 // Demonstration Note:
67 // The following code and some code in the execute method utilize the onnx cxx api.
68 // Please refer to that documentation as you prepare cxx code for your algorithm.
69
70 // Configure session options before use.
71 session_options.SetIntraOpNumThreads(1);
72
73 // Load the model.
74 // eos does not have guaranteed availability, so we use PathResolver to find asg-calib/dev for non-production algorithms.
75 const std::string model_path = PathResolverFindCalibFile("ONNXfiles/autoencoder_model.onnx");
76 session = std::make_unique<Ort::Session>(env, model_path.c_str(), session_options);
77
78 // Prepare and, if desired, print the input node names.
79 size_t num_input_nodes = session->GetInputCount();
80 Ort::AllocatorWithDefaultOptions allocator;
81 for (size_t i = 0; i < num_input_nodes; ++i)
82 {
83 std::unique_ptr<char, Ort::detail::AllocatedFree> input_name_ptr = session->GetInputNameAllocated(i, allocator);
84 char* input_name = input_name_ptr.get();
85 input_names.push_back(input_name);
86 }
87
88 // Prepare and, if desired, print the output node names.
89 size_t num_output_nodes = session->GetOutputCount();
90 for (size_t i = 0; i < num_output_nodes; ++i)
91 {
92 std::unique_ptr<char, Ort::detail::AllocatedFree> output_name_ptr = session->GetOutputNameAllocated(i, allocator);
93 char* output_name = output_name_ptr.get();
94 output_names.push_back(output_name);
95 }
96
97}
std::string PathResolverFindCalibFile(const std::string &logical_file_name)

◆ ~AutoencoderExampleAlgorithm()

virtual dqm_algorithms::AutoencoderExampleAlgorithm::~AutoencoderExampleAlgorithm ( )
overridevirtualdefault

Member Function Documentation

◆ clone()

dqm_algorithms::AutoencoderExampleAlgorithm * dqm_algorithms::AutoencoderExampleAlgorithm::clone ( )
overridevirtual

◆ execute()

dqm_core::Result * dqm_algorithms::AutoencoderExampleAlgorithm::execute ( const std::string & name,
const TObject & object,
const dqm_core::AlgorithmConfig &  )
overridevirtual

Definition at line 115 of file AutoencoderExampleAlgorithm.cxx.

118{
119 // Using the TObject object, check if it is of TH2 type, throw error if not the right type.
120 // Demonstration Note:
121 // The TObject object can vary depending on what kind of TObject you wish to utilize for your algorithm.
122 // The remainder of the execute method assumes the goals of this particular new algorithm. Modify as needed.
123 const TH2* histogram;
124 if (object.IsA()->InheritsFrom("TH2"))
125 {
126 histogram = dynamic_cast<const TH2*>(&object);
127 if (histogram->GetDimension() < 2)
128 {
129 throw dqm_core::BadConfig( ERS_HERE, name, "dimension of histogram < 2");
130 }
131 }
132 else
133 {
134 throw dqm_core::BadConfig( ERS_HERE, name, "does not inherit from TH2" );
135 }
136
137 // Extract data from histogram.
138 std::vector<std::vector<float>> hist_data = extract_histogram_data(histogram);
139
140 // Run inference for the data using the model.
141 std::vector<std::vector<float>> output_data;
142 std::vector<int64_t> input_dims = {1, 3}; // Input here is as a single data point with 3 features
143
144 Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
145 const char* input_names_cstr[] = { input_names[0].c_str() };
146 const char* output_names_cstr[] = { output_names[0].c_str() };
147 for (auto& input_data : hist_data) {
148 // Create the input tensor.
149 Ort::Value input_tensor = Ort::Value::CreateTensor<float>(memory_info, input_data.data(), input_data.size(), input_dims.data(), input_dims.size());
150
151 // Run the inference.
152 auto output_tensors = session->Run(Ort::RunOptions{nullptr}, input_names_cstr, &input_tensor, 1, output_names_cstr, 1);
153
154 // Check if the std::vector or its output_tensors do or do not have valid values for existence.
155 if (output_tensors.empty() || output_tensors[0].HasValue())
156 {
157 throw dqm_core::BadConfig(ERS_HERE, name, "Output tensor does not have values or does not exist");
158 }
159
160 // Check Tensor Size.
161 const size_t tensor_size = output_tensors[0].GetTensorTypeAndShapeInfo().GetElementCount();
162
163 if (tensor_size < 3)
164 {
165 throw dqm_core::BadConfig(ERS_HERE, name, "Output tensor < 3 elements");
166 }
167
168 // Prepare the output_data.
169 float* raw_output = output_tensors[0].GetTensorMutableData<float>();
170 std::vector<float> output_point(raw_output, raw_output + 3);
171 output_data.push_back(output_point);
172 }
173
174 // Compute the reconstruction error.
175 // (Algorithm specific logic, post inference)
176 std::vector<float> reconstruction_errors;
177 for (size_t i = 0; i < hist_data.size(); ++i) {
178 float error = 0.0;
179 for (size_t j = 0; j < 3; ++j) {
180 error += std::pow(hist_data[i][j] - output_data[i][j], 2);
181 }
182 reconstruction_errors.push_back(std::sqrt(error));
183 }
184
185 // Calculate threshold based on the 99th percentile of reconstruction errors
186 // (Algorithm specific logic, post inference)
187 std::nth_element(reconstruction_errors.begin(), reconstruction_errors.begin() + std::roundl(reconstruction_errors.size() * (99. / 100.)), reconstruction_errors.end());
188 float threshold = reconstruction_errors[reconstruction_errors.size() * 99 / 100];
189
190 // Identify anomalies based on threshold vs reconstruction_error.
191 // (Algorithm specific logic, post inference)
192 std::vector<bool> anomalies;
193 for (const auto& error : reconstruction_errors) {
194 anomalies.push_back(error > threshold);
195 }
196
197 // Demonstration Note:
198 // There are a lot of variations on how the result of the dqm_algorithm including how it interacts with the test display.
199 // I suggest looking at least at other algorithms for inspiration.
200 // The documentation and examples of that is outside of scope of this template.
201 // However, this template demonstrates at least the minimum required to setup the new algorithm and on the test display
202 // with perhaps some information of interest to this particular new algorithm.
203
204 // Prepare the resulthisto
205 TH2* resulthisto;
206 if (histogram->InheritsFrom("TH2"))
207 {
208 resulthisto=static_cast<TH2*>(histogram->Clone());
209 }
210 else
211 {
212 throw dqm_core::BadConfig( ERS_HERE, name, "does not inherit from TH2" );
213 }
214 resulthisto->Reset();
215
216 // Loop through anomalies to set result, print, etc.
217 for (size_t i = 0; i < anomalies.size(); ++i) {
218 if (anomalies[i])
219 {
220 // Set the resulting histogram to the bin content
221 resulthisto->SetBinContent(hist_data[i][0], hist_data[i][1], hist_data[i][2]);
222 }
223 }
224
225 // Prepare the result of the main/execute method
226 dqm_core::Result* result = new dqm_core::Result();
227
228 // For the result, set NBins to the number of anomalies
229 result->tags_["NBins"] = anomalies.size();
230
231 // For the result, set the resulting histogram to the bin content we SetBinContent above with
232 result->object_ = boost::shared_ptr<TObject>(resulthisto);
233
234 // Set the thresholds
235 double gthreshold = 5000;
236 double rthreshold = 10000;
237
238 // Determine if the overall histogram is green, yellow, or red and send that to the result
239 if (anomalies.size() <= gthreshold)
240 {
241 result->status_ = dqm_core::Result::Green;
242 }
243 else if (anomalies.size() < rthreshold)
244 {
245 result->status_ = dqm_core::Result::Yellow;
246 }
247 else
248 {
249 result->status_ = dqm_core::Result::Red;
250 }
251
252 // For debugging, remove when done
253 //dqm_core::Result *result = new dqm_core::Result(dqm_core::Result::Undefined);
254 return result;
255}
std::string histogram
Definition chains.cxx:52
float j(const xAOD::IParticle &, const xAOD::TrackMeasurementValidation &hit, const Eigen::Matrix3d &jab_inv)
std::vector< std::vector< float > > extract_histogram_data(const TH2 *hist)
#define IsA
Declare the TObject style functions.

◆ printDescription()

void dqm_algorithms::AutoencoderExampleAlgorithm::printDescription ( std::ostream & out)

Definition at line 266 of file AutoencoderExampleAlgorithm.cxx.

267{
268 out<<"AutoencoderExampleAlgorithm: Load and process an onnx autoencoder model given the AutoencoderExampleAlgorithm.cxx "<<std::endl;
269}

Member Data Documentation

◆ env

Ort::Env dqm_algorithms::AutoencoderExampleAlgorithm::env

Definition at line 52 of file AutoencoderExampleAlgorithm.h.

◆ input_names

std::vector<std::string> dqm_algorithms::AutoencoderExampleAlgorithm::input_names

Definition at line 55 of file AutoencoderExampleAlgorithm.h.

◆ output_names

std::vector<std::string> dqm_algorithms::AutoencoderExampleAlgorithm::output_names

Definition at line 56 of file AutoencoderExampleAlgorithm.h.

◆ session

std::unique_ptr<Ort::Session> dqm_algorithms::AutoencoderExampleAlgorithm::session

Definition at line 54 of file AutoencoderExampleAlgorithm.h.

◆ session_options

Ort::SessionOptions dqm_algorithms::AutoencoderExampleAlgorithm::session_options

Definition at line 53 of file AutoencoderExampleAlgorithm.h.


The documentation for this struct was generated from the following files: