Imported Upstream version 1.25.0
[platform/core/ml/nnfw.git] / compiler / circle-mpqsolver / src / bisection / VISQErrorApproximator.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "VISQErrorApproximator.h"
18
19 #include <fstream>
20 #include <json.h>
21
22 using namespace mpqsolver::bisection;
23
24 void VISQErrorApproximator::init(const std::string &visq_data_path)
25 {
26   // read file
27   std::ifstream file(visq_data_path);
28   init(file);
29 }
30
31 void VISQErrorApproximator::init(std::istream &visq_data)
32 {
33   Json::Reader reader;
34   Json::Value completeJsonData;
35   if (!reader.parse(visq_data, completeJsonData))
36   {
37     throw std::runtime_error("Invalid visq stream");
38   }
39
40   if (!completeJsonData.isMember("error"))
41   {
42     throw std::runtime_error("No 'error' section in visq stream");
43   }
44
45   auto layers = completeJsonData["error"][0];
46   auto names = layers.getMemberNames();
47   for (auto name : names)
48   {
49     auto value = layers[name].asFloat();
50     _layer_errors[name] = value;
51   }
52 }
53
54 float VISQErrorApproximator::approximate(const std::string &node_name) const
55 {
56   auto iter = _layer_errors.find(node_name);
57   if (iter == _layer_errors.end())
58   {
59     return 0.f;
60   }
61
62   return iter->second;
63 }