File: component_bindings.cpp

package info (click to toggle)
camitk 6.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 389,496 kB
  • sloc: cpp: 103,476; sh: 2,448; python: 1,618; xml: 984; makefile: 128; perl: 84; sed: 20
file content (374 lines) | stat: -rw-r--r-- 17,822 bytes parent folder | download
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include "component_bindings.h"
#include "core_utils.h"
#include "qt_bindings.h"
#include "numpy_utils.h"
#include "docstrings.h"

#include <Application.h>
#include <Component.h>
#include <TransformationManager.h>
#include <ImageComponent.h>
#include <ArbitrarySingleImageComponent.h>
#include <SingleImageComponent.h>
#include <MeshComponent.h>

namespace camitk {

/// This trampoline class is required for having python Component derived class as
/// Component has a pure virtual method
class PyComponent : public camitk::Component {
    using camitk::Component::Component;  // inherit constructors

private:
    virtual void initRepresentation() override {
        // as initRepresentation is private it cannot be export to python, just do nothing.
    }
};

} // namespace camitk

void add_component_bindings(py::module_& m) {

    // --------------- Component ---------------

    // need all hierarchy so that pybind11 can ensure polymorphism
    py::class_<camitk::InterfaceProperty /* also inherits from QObject, but silenced here as not needed in python and probably extremely difficult to do! */ >(m, "InterfaceProperty", DOC(camitk_InterfaceProperty));

    py::class_<camitk::InterfaceNode>(m, "InterfaceNode", DOC(camitk_InterfaceNode));

    py::class_<camitk::InterfaceGeometry> interfaceGeometry(m, "InterfaceGeometry", DOC(camitk_InterfaceGeometry));

    py::enum_<camitk::InterfaceGeometry::RenderingMode> renderingMode(interfaceGeometry, "RenderingMode", py::arithmetic(), DOC(camitk_InterfaceGeometry_RenderingMode));
    renderingMode.value("NoRenderingMode", camitk::InterfaceGeometry::RenderingMode::None);
    renderingMode.value("Surface", camitk::InterfaceGeometry::RenderingMode::Surface);
    renderingMode.value("Wireframe", camitk::InterfaceGeometry::RenderingMode::Wireframe);
    renderingMode.value("Points", camitk::InterfaceGeometry::RenderingMode::Points);
    renderingMode.export_values();

    py::class_<camitk::InterfaceBitMap>(m, "InterfaceBitMap", DOC(camitk_InterfaceBitMap));

    py::class_<camitk::InterfaceFrame>(m, "InterfaceFrame", DOC(camitk_InterfaceFrame));

    py::class_<camitk::InterfacePersistence>(m, "InterfacePersistence", DOC(camitk_InterfacePersistence));

    py::class_<camitk::Component, camitk::PyComponent,
    camitk::InterfaceProperty, camitk::InterfaceNode, camitk::InterfaceGeometry, camitk::InterfaceBitMap, camitk::InterfaceFrame, camitk::InterfacePersistence> component(m, "Component", DOC(camitk_Component));

    component.def(py::init<const QString, const QString>(), DOC(camitk_Component_Component_1));

    // Note: use the InterfaceClass docstrings for inherited methods
    // as the doxygen parser cannot always associate the docstring
    // to the corresponding inherited method
    component.def("getName", &camitk::Component::getName,
                  DOC(camitk_InterfaceNode_getName));

    component.def("setName", [](camitk::Component & self, QString newName) {
        QString uniqueName = camitk::Application::getUniqueComponentName(newName);
        self.setName(uniqueName);
    },
    DOC(camitk_InterfaceNode_setName));

    component.def("getFileName", &camitk::Component::getFileName,
                  DOC(camitk_Component_getFileName));

    component.def("setFrameFrom", &camitk::Component::setFrameFrom,
                  DOC(camitk_InterfaceFrame_setFrameFrom));

    component.def("getFrame", &camitk::Component::getFrame,
                  py::return_value_policy::reference,
                  DOC(camitk_InterfaceFrame_getFrame));

    component.def("setFrame", [](camitk::Component & self, camitk::FrameOfReference * framePtr) {
        std::shared_ptr<camitk::FrameOfReference> frameSharedPtr = camitk::TransformationManager::getFrameOfReferenceOwnership(framePtr);
        self.setFrame(frameSharedPtr);
        // Note: the application should be refreshed to see the effect in the viewers
    },
    DOC(camitk_InterfaceFrame_setFrame));

    component.def("getPropertyValue", &camitk::Component::getPropertyValue,
                  DOC(camitk_InterfaceProperty_getPropertyValue));

    component.def("setPropertyValue", &camitk::Component::setPropertyValue,
                  DOC(camitk_InterfaceProperty_setPropertyValue));

    component.def("setModified", &camitk::Component::setModified
                  , DOC(camitk_Component_setModified));

    component.def("refresh", &camitk::Component::refresh,
                  DOC(camitk_Component_refresh));

    component.def("addChild", &camitk::Component::addChild,
                  DOC(camitk_InterfaceNode_addChild));

    component.def("getChildren", &camitk::Component::getChildren,
                    py::return_value_policy::reference,
                    DOC(camitk_InterfaceNode_getChildren));

    component.def("getParent", &camitk::Component::getParent,
                    py::return_value_policy::reference,
                    DOC(camitk_InterfaceNode_getParent));

    component.def("isTopLevel", &camitk::Component::isTopLevel,
                    DOC(camitk_Component_isTopLevel));

    component.def("isSelected", &camitk::Component::isSelected,
                    DOC(camitk_Component_isSelected));

    component.def("setSelected", &camitk::Component::setSelected,
                    py::arg("b"), 
                    py::arg("recursive") = true,
                    DOC(camitk_Component_setSelected));

    // --------------- ImageComponent ---------------

    py::class_<camitk::ImageComponent, camitk::Component> imageComponent(m, "ImageComponent", DOC(camitk_ImageComponent));

    // Note : the docstrings of this constructor was not retrieved properly
    // by the docstring generator -> it needs to be added manually here.
    imageComponent.def(py::init<const QString&, const QString&>(),
                       DOC(camitk_ImageComponent_ImageComponent_1));

    imageComponent.def("clone", [](camitk::ImageComponent & self) {
        QString cloneName = camitk::Application::getUniqueComponentName(self.getName());
        camitk::ImageComponent* clone = new camitk::ImageComponent(self.getImageData(), cloneName);
        clone->setFrameFrom(&self);
        return clone;
    },
    py::return_value_policy::reference,
    R"doc(Clone this original image. Note that the image data is not copied, only referenced from the clone, and that the frame of the clone is set to the original image component's frame.)doc");

    imageComponent.def("getImageDataAsNumpy",
    [](camitk::ImageComponent & self) {
        return camitk::vtkImageDataToNumpy(self.getImageData());
    },
    R"doc(Returns the image data as a numpy ndarray.)doc");

    imageComponent.def("getSpacing",
    [](camitk::ImageComponent & self) {
        return camitk::getVtkImageDataSpacing(self.getImageData());
    },
    R"doc(Returns the image spacing as a tuple of 3 floats (spacingX, spacingY, spacingZ).)doc");

    imageComponent.def("getDimensions",
    [](camitk::ImageComponent & self) {
        int dim[3];
        self.getImageData()->GetDimensions(dim);
        return py::make_tuple(dim[0], dim[1], dim[2]);
    },
    R"doc(Returns the image dimensions as a tuple of 3 integers (dimX, dimY, dimZ).)doc");

    imageComponent.def("replaceImageData",
    [](camitk::ImageComponent * self, const py::array & numpyArray) {
        vtkSmartPointer<vtkImageData> imgData = camitk::numpyToVTKImageData(numpyArray);
        self->replaceImageData(imgData, true);
        // FIXME CamiTK Core: 3D viewer actor is not updated properly, copy is always required
        self->refresh();
    },
    R"doc(Replaces the image data with the given numpy ndarray.)doc");

    imageComponent.def("getDataFrame", &camitk::ImageComponent::getDataFrame,
                       py::return_value_policy::reference,
                       DOC(camitk_ImageComponent_getDataFrame));

    // TODO should this helper method be added in ImageComponent as well?
    imageComponent.def("getArbitrarySliceFrame", [](camitk::ImageComponent & self) {
        return self.getArbitrarySlices()->getArbitraryFrame();
    },
    py::return_value_policy::reference,
    R"doc(Returns the FrameOfReference used for the arbitrary slice.)doc");

    imageComponent.def("getLastPixelPicked", [](camitk::ImageComponent & self) {
        int i, j, k;
        self.getLastPixelPicked(&i, &j, &k);
        return py::make_tuple(i, j, k);
    },
    DOC(camitk_ImageComponent_getLastPixelPicked));

    imageComponent.def("getLastPointPickedDataFrame", [](camitk::ImageComponent & self) {
        double x, y, z;
        self.getLastPointPickedDataFrame(&x, &y, &z);
        return py::make_tuple(x, y, z);
    },
    DOC(camitk_ImageComponent_getLastPointPickedDataFrame));

    imageComponent.def("getLastPointPickedWorldFrame", [](camitk::ImageComponent & self) {
        double x, y, z;
        self.getLastPointPickedWorldFrame(&x, &y, &z);
        return py::make_tuple(x, y, z);
    },
    DOC(camitk_ImageComponent_getLastPointPickedWorldFrame));

    // --------------- MeshComponent ---------------

    py::class_<camitk::MeshComponent, camitk::Component> meshComponent(m, "MeshComponent", DOC(camitk_MeshComponent));

    meshComponent.def("setRenderingModes", [](camitk::MeshComponent & self, int modes) {
        self.setRenderingModes(camitk::InterfaceGeometry::RenderingModes(modes));
    },
    DOC(camitk_InterfaceGeometry_setRenderingModes));

    meshComponent.def("clone", [](camitk::MeshComponent & self) {
        QString cloneName = camitk::Application::getUniqueComponentName(self.getName());
        camitk::MeshComponent* clone = new camitk::MeshComponent(self.getPointSet(), cloneName);
        clone->setFrameFrom(&self);
        return clone;
    },
    py::return_value_policy::reference,
    R"doc(Clone this original mesh. Note that the point set is not copied, only referenced from the clone, and that the frame of the clone is set to the original mesh component's frame.)doc");

    meshComponent.def("getPointSetAsNumpy",
    [](camitk::MeshComponent & self) {
        return camitk::vtkPointSetToNumpy(self.getPointSet());
    },
    R"doc(Returns the point set as a numpy ndarray of shape (N, 3) where N is the number of points.)doc");

    meshComponent.def("replacePointSet",
    [](camitk::MeshComponent & self, const py::array & numpyArray) {
        vtkSmartPointer<vtkPoints> points = camitk::numpyToVtkPoints(numpyArray);
        self.getPointSet()->SetPoints(points);

        // check if this is a point cloud
        vtkSmartPointer<vtkPolyData> polyData = vtkPolyData::SafeDownCast(self.getPointSet());
        if (polyData != nullptr && self.getPointSet()->GetNumberOfCells() == 1) {
            // this is a point cloud, update the verts
            vtkNew<vtkCellArray> verts;
            verts->InsertNextCell(points->GetNumberOfPoints());
            for (vtkIdType i = 0; i < points->GetNumberOfPoints(); ++i) {
                verts->InsertCellPoint(i);
            }
            polyData->SetVerts(verts);
        }

        self.getPointSet()->Modified();
        self.refresh();
    },
    R"doc(Replaces the point set with the given numpy ndarray of shape (N, 3) where N is the number of points. If there is no Cell/polygons, this will be interpreted as a point cloud (it will create one cell containing all the points).)doc");

    meshComponent.def("setColor", [](camitk::MeshComponent & self, const QColor & newColor) {
        double actorColor[4];
        actorColor[0] = newColor.redF();
        actorColor[1] = newColor.greenF();
        actorColor[2] = newColor.blueF();
        actorColor[3] = newColor.alphaF();
        self.setActorColor(self.getRenderingModes(), actorColor);
    },
    DOC(camitk_InterfaceGeometry_setActorColor_1));

    meshComponent.def("getColor", [](camitk::MeshComponent & self) {
        double actorColor[4];
        self.getActorColor(self.getRenderingModes(), actorColor);
        QColor currentColor;
        currentColor.setRgbF(actorColor[0], actorColor[1], actorColor[2], actorColor[3]);
        return currentColor;
    },
    DOC(camitk_InterfaceGeometry_getActorColor));

    meshComponent.def("setLinesAsTubes", &camitk::MeshComponent::setLinesAsTubes,
                      py::arg("isTubes") = true,
                      py::arg("radiusFromLength") = true,
                      py::arg("radiusFactor") = 1.0 / 40.0,
                      py::arg("numberOfSides") = 5,
                      DOC(camitk_InterfaceGeometry_setLinesAsTubes));

    // enum
    // TODO change to enum_native when updating binding to pybind3
    // see https://pybind11.readthedocs.io/en/stable/classes.html#enumerations-and-internal-types
    py::enum_<camitk::MeshComponent::FieldType> fieldType(meshComponent, "FieldType",
            DOC(camitk_MeshComponent_FieldType));
    fieldType.value("POINTS", camitk::MeshComponent::POINTS);
    fieldType.value("CELLS", camitk::MeshComponent::CELLS);
    fieldType.value("MESH", camitk::MeshComponent::MESH);
    fieldType.export_values();

    meshComponent.def("getNumberOfDataArray", &camitk::MeshComponent::getNumberOfDataArray,
                      DOC(camitk_MeshComponent_getNumberOfDataArray));

    meshComponent.def("getDataArray", [](camitk::MeshComponent & self, camitk::MeshComponent::FieldType field, int index) {
        vtkSmartPointer<vtkDataArray> dataArray = self.getDataArray(field, index);
        return camitk::vtkDataArrayToNumpy(dataArray);
    },
    R"doc(Get the data array of specified field type and index as a numpy ndarray.)doc");

    meshComponent.def("addDataArray", [](camitk::MeshComponent & self, camitk::MeshComponent::FieldType field, const QString & name, const py::array & numpyArray) {
        self.addDataArray(field, name, camitk::numpyToVtkDataArray(numpyArray));
    },
    R"doc(Add a data array using the given a numpy ndarray.)doc");

    meshComponent.def("removeDataArray", &camitk::MeshComponent::removeDataArray,
                      DOC(camitk_MeshComponent_removeDataArray));

    meshComponent.def("addPointData", [](camitk::MeshComponent & self, const QString & name, const py::array & numpyArray) {
        self.addPointData(name, camitk::numpyToVtkDataArray(numpyArray));
    },
    R"doc(Adds a point data array using the given numpy ndarray.)doc");

    meshComponent.def("addCellData", [](camitk::MeshComponent & self, const QString & name, const py::array & numpyArray) {
        self.addCellData(name, camitk::numpyToVtkDataArray(numpyArray));
    },
    R"doc(Adds a cell data array using the given numpy ndarray.)doc");

    meshComponent.def("setDataRepresentationOff", &camitk::MeshComponent::setDataRepresentationOff,
                      py::arg("dataType") = camitk::MeshComponent::SCALARS | camitk::MeshComponent::VECTORS | camitk::MeshComponent::TENSORS,
                      py::arg("blockRefresh") = false,
                      DOC(camitk_MeshComponent_setDataRepresentationOff));

    meshComponent.def("getPickedPointId", &camitk::MeshComponent::getPickedPointId,
                      DOC(camitk_MeshComponent_getPickedPointId));

    meshComponent.def("getPickedPointPosition", [](camitk::MeshComponent & self) {
        double position[3] { 0.0, 0.0, 0.0 };
        if (self.getPickedPointId() >= 0 && self.getPickedPointId() < self.getPointSet()->GetNumberOfPoints()) {
            self.getPointSet()->GetPoint(self.getPickedPointId(), position);
        }
        return py::make_tuple(position[0], position[1], position[2]);
    },
    R"doc(Returns the position of the picked point as a tuple of 3 floats (x, y, z) in this mesh component frame. If no point is picked, returns (0.0, 0.0, 0.0).)doc");

    meshComponent.def("getPickedCellId", &camitk::MeshComponent::getPickedCellId,
                      DOC(camitk_MeshComponent_getPickedCellId));

    // --------------- Utils ---------------

    m.def("newImageComponentFromNumpy",
          &camitk::newImageComponentFromNumpy,
          py::arg("array"),  // extract the array part of the dict
          py::arg("name") = "image",
          py::arg("spacing") = py::none(), // by default no spacing have to be given
          py::return_value_policy::reference,
          R"doc(Create an Image Component by creating a new vtkImageData from the given array of voxel and spacing, if provided))doc");

    m.def("newMeshComponentFromNumpy",
          &camitk::newMeshComponentFromNumpy,
          py::arg("name") = "mesh",
          py::arg("points_array"),
          py::arg("polys_array") = py::array(),
          py::return_value_policy::reference,
          R"doc(Creates a Mesh Component by creating a new vtkPointSet made of the given point array and poly array(only vtkPolyData and point clouds are supported for now))doc");

}