forked from PDAL/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibpdalpython.cpp
More file actions
353 lines (280 loc) · 12.3 KB
/
libpdalpython.cpp
File metadata and controls
353 lines (280 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/functional.h>
#include <pybind11/stl/filesystem.h>
#include <iostream>
#include <pdal/pdal_config.hpp>
#include <pdal/StageFactory.hpp>
#define NPY_TARGET_VERSION NPY_1_22_API_VERSION
#define NPY_NO_DEPRECATED_API NPY_1_22_API_VERSION
#define PY_ARRAY_UNIQUE_SYMBOL PDAL_ARRAY_API
#include <numpy/arrayobject.h>
#include "PyArray.hpp"
#include "PyDimension.hpp"
#include "PyPipeline.hpp"
#include "StreamableExecutor.hpp"
namespace py = pybind11;
namespace pdal {
using namespace py::literals;
py::object getInfo() {
return py::module_::import("types").attr("SimpleNamespace")(
"version"_a = pdal::Config::versionString(),
"major"_a = pdal::Config::versionMajor(),
"minor"_a = pdal::Config::versionMinor(),
"patch"_a = pdal::Config::versionPatch(),
"debug"_a = pdal::Config::debugInformation(),
"sha1"_a = pdal::Config::sha1(),
"plugin"_a = pdal::Config::pluginInstallPath()
);
};
std::vector<py::dict> getDrivers() {
std::vector<py::dict> drivers;
pdal::StageFactory f(false);
pdal::PluginManager<pdal::Stage>::loadAll();
pdal::StringList stages = pdal::PluginManager<pdal::Stage>::names();
pdal::StageExtensions& extensions = pdal::PluginManager<pdal::Stage>::extensions();
for (auto name : stages)
{
pdal::Stage *s = f.createStage(name);
std::string description = pdal::PluginManager<Stage>::description(name);
std::string link = pdal::PluginManager<Stage>::link(name);
std::vector<std::string> extension_names = extensions.extensions(name);
py::dict d(
"name"_a=name,
"description"_a=description,
"streamable"_a=s->pipelineStreamable(),
"extensions"_a=extension_names
);
f.destroyStage(s);
drivers.push_back(std::move(d));
}
return drivers;
};
py::object getOptions() {
py::object json = py::module_::import("json");
py::dict stageOptions;
pdal::StageFactory f;
pdal::PluginManager<pdal::Stage>::loadAll();
pdal::StringList stages = pdal::PluginManager<pdal::Stage>::names();
for (auto name : stages)
{
pdal::Stage *s = f.createStage(name);
pdal::ProgramArgs args;
s->addAllArgs(args);
std::ostringstream ostr;
args.dump3(ostr);
py::str pystring(ostr.str());
pystring.attr("strip");
py::object j;
try {
j = json.attr("loads")(pystring);
} catch (py::error_already_set &e) {
std::cerr << "failed:" << name << "'" << ostr.str() << "'" <<std::endl;
continue; // skip this one because we can't parse it
}
f.destroyStage(s);
stageOptions[pybind11::cast(name)] = std::move(j);
}
return stageOptions;
};
std::vector<py::dict> getDimensions() {
py::object np = py::module_::import("numpy");
py::object dtype = np.attr("dtype");
std::vector<py::dict> dims;
for (const auto& dim: getValidDimensions())
{
py::dict d(
"name"_a=dim.name,
"description"_a=dim.description,
"dtype"_a=dtype(dim.type + std::to_string(dim.size))
);
dims.push_back(std::move(d));
}
return dims;
};
std::string getReaderDriver(std::filesystem::path const& p)
{
return StageFactory::inferReaderDriver(p.string());
}
std::string getWriterDriver(std::filesystem::path const& p)
{
return StageFactory::inferWriterDriver(p.string());
}
using pdal::python::PipelineExecutor;
using pdal::python::StreamableExecutor;
class PipelineIterator : public StreamableExecutor {
public:
using StreamableExecutor::StreamableExecutor;
py::object getSchema() {
return py::module_::import("json").attr("loads")(StreamableExecutor::getSchema());
}
py::array executeNext() {
PyArrayObject* arr(StreamableExecutor::executeNext());
if (!arr)
throw py::stop_iteration();
return py::reinterpret_steal<py::array>((PyObject*)arr);
}
py::object getMetadata() {
py::object json = py::module_::import("json");
std::stringstream strm;
MetadataNode root = (StreamableExecutor::getMetadata()).clone("metadata");
pdal::Utils::toJSON(root, strm);
py::bytes pybytes(strm.str());
py::str pystring ( pybytes.attr("decode")("utf-8", "ignore"));
py::object j;
j = json.attr("loads")(pystring);
return j;
}
};
class Pipeline {
public:
point_count_t execute(pdal::StringList allowedDims) {
point_count_t response(0);
{
py::gil_scoped_release release;
response = getExecutor()->execute(allowedDims);
}
return response;
}
point_count_t executeStream(point_count_t streamLimit, pdal::StringList allowedDims) {
point_count_t response(0);
{
py::gil_scoped_release release;
response = getExecutor()->executeStream(streamLimit, allowedDims);
}
return response;
}
std::unique_ptr<PipelineIterator> iterator(int chunk_size, int prefetch, pdal::StringList allowedDims) {
return std::unique_ptr<PipelineIterator>(new PipelineIterator(
getJson(), _inputs, _loglevel, chunk_size, prefetch, allowedDims
));
}
void setInputs(const std::vector<py::object>& inputs) {
_inputs.clear();
for (const auto& input_obj: inputs) {
if (py::isinstance<py::array>(input_obj)) {
// Backward compatibility for accepting list of numpy arrays
auto ndarray = input_obj.cast<py::array>();
_inputs.push_back(std::make_shared<pdal::python::Array>((PyArrayObject*)ndarray.ptr()));
} else {
// Now expected to be a list of pairs: (numpy array, <optional> stream handler)
auto input = input_obj.cast<std::pair<py::array, pdal::python::ArrayStreamHandler>>();
_inputs.push_back(std::make_shared<pdal::python::Array>(
(PyArrayObject*)input.first.ptr(),
input.second ?
std::make_shared<pdal::python::ArrayStreamHandler>(input.second)
: nullptr));
}
}
delExecutor();
}
int getLoglevel() { return _loglevel; }
void setLogLevel(int level) { _loglevel = level; delExecutor(); }
std::string getLog() { return getExecutor()->getLog(); }
std::string getPipeline() { return getExecutor()->getPipeline(); }
std::string getSrsWKT2() { return getExecutor()->getSrsWKT2(); }
py::object getQuickInfo() {
py::object json = py::module_::import("json");
std::string response;
{
py::gil_scoped_release release;
response = getExecutor()->getQuickInfo();
}
py::bytes pybytes(response);
py::str pystring ( pybytes.attr("decode")("utf-8", "ignore"));
pystring.attr("strip");
py::object j;
j = json.attr("loads")(pystring);
return j;
}
py::object getMetadata() {
py::object json = py::module_::import("json");
py::bytes pybytes(getExecutor()->getMetadata());
py::str pystring ( pybytes.attr("decode")("utf-8", "ignore"));
py::object j;
j = json.attr("loads")(pystring);
return j;
}
py::object getSchema() {
return py::module_::import("json").attr("loads")(getExecutor()->getSchema());
}
std::vector<py::array> getArrays() {
std::vector<py::array> output;
for (const auto &view: getExecutor()->views()) {
PyArrayObject* arr(pdal::python::viewToNumpyArray(view));
output.push_back(py::reinterpret_steal<py::array>((PyObject*)arr));
}
return output;
}
std::vector<py::array> getMeshes() {
std::vector<py::array> output;
for (const auto &view: getExecutor()->views()) {
PyArrayObject* arr(pdal::python::meshToNumpyArray(view->mesh()));
output.push_back(py::reinterpret_steal<py::array>((PyObject*)arr));
}
return output;
}
std::string getJson() const {
PYBIND11_OVERRIDE_PURE_NAME(std::string, Pipeline, "toJSON", getJson);
}
bool hasInputs() { return !_inputs.empty(); }
void copyInputs(const Pipeline& other) { _inputs = other._inputs; }
void delExecutor() { _executor.reset(); }
PipelineExecutor* getExecutor() {
// We need to acquire the GIL before we create the executor
// because this method does Python init stuff but pybind11 doesn't
// automatically encapsulate it with a gil_scoped_acquire like it
// does for all of the other methods it knows about
py::gil_scoped_acquire acquire;
if (!_executor)
_executor.reset(new PipelineExecutor(getJson(), _inputs, _loglevel));
return _executor.get();
}
private:
std::unique_ptr<PipelineExecutor> _executor;
std::vector<std::shared_ptr<pdal::python::Array>> _inputs;
int _loglevel;
};
PYBIND11_MODULE(libpdalpython, m)
{
_import_array();
py::class_<PipelineIterator>(m, "PipelineIterator")
.def("__iter__", [](PipelineIterator &it) -> PipelineIterator& { return it; })
.def("__next__", &PipelineIterator::executeNext)
.def_property_readonly("log", &PipelineIterator::getLog)
.def_property_readonly("schema", &PipelineIterator::getSchema)
.def_property_readonly("srswkt2", &PipelineIterator::getSrsWKT2)
.def_property_readonly("pipeline", &PipelineIterator::getPipeline)
.def_property_readonly("metadata", &PipelineIterator::getMetadata);
py::class_<Pipeline>(m, "Pipeline")
.def(py::init<>())
.def("execute", &Pipeline::execute, py::arg("allowed_dims") =py::list())
.def("execute_streaming", &Pipeline::executeStream, "chunk_size"_a=10000, py::arg("allowed_dims") =py::list())
.def("iterator", &Pipeline::iterator, "chunk_size"_a=10000, "prefetch"_a=0, py::arg("allowed_dims") =py::list())
.def_property("inputs", nullptr, &Pipeline::setInputs)
.def_property("loglevel", &Pipeline::getLoglevel, &Pipeline::setLogLevel)
.def_property_readonly("log", &Pipeline::getLog)
.def_property_readonly("schema", &Pipeline::getSchema)
.def_property_readonly("srswkt2", &Pipeline::getSrsWKT2)
.def_property_readonly("pipeline", &Pipeline::getPipeline)
.def_property_readonly("quickinfo", &Pipeline::getQuickInfo)
.def_property_readonly("metadata", &Pipeline::getMetadata)
.def_property_readonly("arrays", &Pipeline::getArrays)
.def_property_readonly("meshes", &Pipeline::getMeshes)
.def_property_readonly("_has_inputs", &Pipeline::hasInputs)
.def("_copy_inputs", &Pipeline::copyInputs)
.def("toJSON", &Pipeline::getJson)
.def("_del_executor", &Pipeline::delExecutor);
m.def("getInfo", &getInfo);
m.def("getDrivers", &getDrivers);
m.def("getOptions", &getOptions);
m.def("getDimensions", &getDimensions);
m.def("infer_reader_driver", &getReaderDriver);
m.def("infer_writer_driver", &getWriterDriver);
if (pdal::Config::versionMajor() < 2)
throw pybind11::import_error("PDAL version must be >= 2.7");
if (pdal::Config::versionMajor() == 2 && pdal::Config::versionMinor() < 7)
throw pybind11::import_error("PDAL version must be >= 2.7");
};
}; // namespace pdal