treelite
qnode_template.h
Go to the documentation of this file.
1 
8 #ifndef TREELITE_COMPILER_NATIVE_QNODE_TEMPLATE_H_
9 #define TREELITE_COMPILER_NATIVE_QNODE_TEMPLATE_H_
10 
11 namespace treelite {
12 namespace compiler {
13 namespace native {
14 
15 const char* qnode_template =
16 R"TREELITETEMPLATE(
17 static const double threshold[] = {{
18 {array_threshold}
19 }};
20 static const int th_begin[] = {{
21 {array_th_begin}
22 }};
23 static const int th_len[] = {{
24 {array_th_len}
25 }};
26 
27 #include <stdlib.h>
28 
29 /*
30  * \brief function to convert a feature value into bin index.
31  * \param val feature value, in floating-point
32  * \param fid feature identifier
33  * \return bin index corresponding to given feature value
34  */
35 static inline int quantize(float val, unsigned fid) {{
36  const size_t offset = th_begin[fid];
37  const double* array = &threshold[offset];
38  int len = th_len[fid];
39  int low = 0;
40  int high = len;
41  int mid;
42  double mval;
43  // It is possible th_begin[i] == [total_num_threshold]. This means that
44  // all features i, (i+1), ... are not used for any of the splits in the model.
45  // So in this case, just return something
46  if (offset == {total_num_threshold} || val < array[0]) {{
47  return -10;
48  }}
49  while (low + 1 < high) {{
50  mid = (low + high) / 2;
51  mval = array[mid];
52  if (val == mval) {{
53  return mid * 2;
54  }} else if (val < mval) {{
55  high = mid;
56  }} else {{
57  low = mid;
58  }}
59  }}
60  if (array[low] == val) {{
61  return low * 2;
62  }} else if (high == len) {{
63  return len * 2;
64  }} else {{
65  return low * 2 + 1;
66  }}
67 }}
68 )TREELITETEMPLATE";
69 
70 const char* quantize_loop_template =
71 R"TREELITETEMPLATE(
72 for (int i = 0; i < {num_feature}; ++i) {{
73  if (data[i].missing != -1 && !is_categorical[i]) {{
74  data[i].qvalue = quantize(data[i].fvalue, i);
75  }}
76 }}
77 )TREELITETEMPLATE";
78 
79 } // namespace native
80 } // namespace compiler
81 } // namespace treelite
82 #endif // TREELITE_COMPILER_NATIVE_QNODE_TEMPLATE_H_