Skip to content

Commit 3d93a23

Browse files
committed
implement py_Predictor py_Classifier pickle
1 parent 3061c98 commit 3d93a23

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

bindings/py/cpp_src/bindings/algorithms/py_SDRClassifier.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,35 @@ This may also be a list for when the input has multiple categories.)",
109109

110110
// TODO: Pickle support
111111

112+
// pickle
113+
// https://github.com/pybind/pybind11/issues/1061
114+
py_Classifier.def(py::pickle(
115+
[](const Classifier& self)
116+
{
117+
// __getstate__
118+
std::ostringstream os;
119+
120+
self.save(os);
121+
122+
return py::bytes(os.str());
123+
},
124+
[](const py::bytes &str)
125+
{
126+
// __setstate__
127+
if (py::len(str) == 0)
128+
{
129+
throw std::runtime_error("Empty state");
130+
}
131+
132+
std::stringstream is( str.cast<std::string>() );
133+
134+
std::unique_ptr<Classifier> clsr(new Classifier());
135+
clsr->load(is);
136+
137+
return clsr;
138+
}
139+
));
140+
112141

113142
py::class_<Predictor> py_Predictor(m, "Predictor",
114143
R"(The Predictor class does N-Step ahead predictions.
@@ -189,5 +218,34 @@ This may also be a list for when the input has multiple categories.)",
189218
py::arg("classification"));
190219

191220
// TODO: Pickle support
221+
222+
// pickle
223+
// https://github.com/pybind/pybind11/issues/1061
224+
py_Predictor.def(py::pickle(
225+
[](const Predictor& self)
226+
{
227+
// __getstate__
228+
std::ostringstream os;
229+
230+
self.save(os);
231+
232+
return py::bytes(os.str());
233+
},
234+
[](const py::bytes &str)
235+
{
236+
// __setstate__
237+
if (py::len(str) == 0)
238+
{
239+
throw std::runtime_error("Empty state");
240+
}
241+
242+
std::stringstream is( str.cast<std::string>() );
243+
244+
std::unique_ptr<Predictor> pred(new Predictor());
245+
pred->load(is);
246+
247+
return pred;
248+
}
249+
));
192250
}
193251
} // namespace htm_ext

0 commit comments

Comments
 (0)