• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..30-Jan-2019-

vtkmodules/H30-Jan-2019-13,3879,997

README.mdH A D30-Jan-201917.3 KiB532366

dummy.cxxH A D30-Jan-201933 54

vtk.pyH A D30-Jan-20191.5 KiB4723

vtkParaPythonAppInit.cxxH A D30-Jan-2019656 172

vtkPythonAppInit.cxxH A D30-Jan-20192.6 KiB9961

vtkpython.rcH A D30-Jan-201934 11

README.md

1Notes on the Python Wrappers for VTK
2====================================
3
4First version by David Gobbi: Dec 19, 2002
5
6Last update was on Feb 12, 2016
7
8Abstract:
9=========
10
11This document provides a detailed description of how VTK objects are
12accessed and modified through Python.
13
14
15Overview:
16=========
17
18Nearly all the power of VTK objects are available through Python
19    (with a few exceptions as noted below).  The C++ semantics are
20translated as directly as possible to Python semantics.  Currently,
21full support is provided for Python 2.6, 2.7, and 3.2 through 3.5.
22
23
24The Basics:
25===========
26
27If VTK has been properly built and installed with the python wrappers,
28then VTK can be accessed by importing the 'vtk' module:
29
30    import vtk
31
32or
33
34    from vtk import *
35
36For the most part, using VTK from Python is very similar to using VTK
37from C++ except for changes in syntax, e.g.
38
39    vtkObject *o = vtkObject::New()
40
41becomes
42
43    o = vtkObject()
44
45and
46
47    o->Method()
48
49becomes
50
51    o.Method()
52
53Some other important differences are that you can pass a Python tuple,
54list or array to a method that requires a C++ array e.g.:
55
56    >>> a = vtkActor()
57    >>> p = (100.0, 200.0, 100.0)
58    >>> a.SetPosition(p)
59
60If the C++ array parameter is used to return information, you must
61pass a Python list or array that has the correct number of slots to
62accept the returned values:
63
64    >>> z = [0.0, 0.0, 0.0]
65    >>> vtkMath.Cross((1,0,0),(0,1,0),z)
66    >>> print z
67    [0.0, 0.0, 1.0]
68
69For multi-dimensional arrays, it is your choice whether to use
70a nested list, or whether to use a numpy array with the correct
71size and number of dimensions.
72
73If the C++ method returns a pointer to an array, then that method is
74only wrapped if there is a hint (usually in VTK/Wrapping/hints)
75that gives the size of the array.  Hinted pointers are returned as
76tuples:
77
78    >>> a = vtkActor()
79    >>> print a.GetPosition()
80    (0.0, 0.0, 0.0)
81
82Finally, the python 'None' is treated the same as C++ 'NULL':
83
84    >>> a = vtkActor()
85    >>> a.SetMapper(None)
86    >>> print a.GetMapper()
87    None
88
89And perhaps one of the most pleasant features of Python is that all
90type-checking is performed at run time, so the type casts that are
91often necessary in VTK-C++ are never needed in VTK-Python.
92
93
94Strings (Python 3 vs. Python 2)
95---------------------
96
97The mapping of Python string types to C++ string types is different
98in Python 3 as compared to Python 2.  In Python 2, the basic 'str()'
99type was for 8-bit strings, and a separate 'unicode()' type was used
100for unicode strings.
101
102For Python 3, the basic 'str()' type is unicode, and when you pass a
103str() as a VTK 'std::string' or 'const char \*' parameter, VTK will
104receive the string in utf-8 encoding.  To use a different encoding,
105you must encode the string yourself and pass it to VTK as a bytes()
106object, e.g. writer.SetFileName('myfile'.encode('latin1')).
107
108When VTK returns a 'const char \*' or 'std::string' in Python 3, the
109wrappers will test to see of the string is utf-8 (or ascii), and if
110so they will pass the string to python as a unicode str() object.
111If the VTK string is not valid utf-8, then the wrappers will pass
112the string to python as a bytes() object.
113
114This means that using encodings other than utf-8 with VTK is risky.
115In rare cases, these other encodings might produce 8-bit data that
116the wrappers will detect as utf-8, causing them to produce a string
117with incorrect characters.
118
119
120STL Containers
121-----------
122
123VTK provides conversion between 'std::vector' and Python sequences
124such as 'tuple' and 'list'.  If the C++ method returns a vector,
125the Python method will return a tuple:
126
127    C++: const std::vector<std::string>& GetPaths()
128    C++: std::vector<std::string> GetPaths()
129    Python: GetPaths() -> Tuple[str]
130
131If the C++ method accepts a vector, then the Python method can be
132passed any sequence with compatible values:
133
134    C++: void SetPaths(const std::vector<std::string>& paths)
135    C++: void SetPaths(std::vector<std::string> paths)
136    Python: SetPaths(paths: Sequence[str]) -> None
137
138Furthermore, if the C++ method accepts a non-const vector reference,
139then the Python method can be passed a mutable sequence (e.g. list):
140
141    C++: void GetPaths(std::vector<std::string>& paths)
142    Python: GetPaths(paths: MutableSequence[str]) -> None
143
144The value type of the std::vector must be std::string or a
145fundamental numeric type such as 'double' or 'int' (including
146'signed char' and 'unsigned char' but excluding 'char').
147
148
149Constants
150---------
151
152Most VTK constants are available in Python, usually in the 'vtk'
153module but sometimes as class attributes:
154
155    >>> vtk.VTK_DOUBLE_MAX
156    1.0000000000000001e+299
157    >>> vtk.vtkCommand.ErrorEvent
158    39
159
160Each named enum type is wrapped as a new Python type, and members
161of the enum are instances of that type.  This allows type checking
162for enum types:
163
164    >>> # works if given a constant of the correct enum type
165    >>> o.SetIntegrationMode(o.Continuous)
166    >>> # does not work, because 'int' is not of the correct type
167    >>> o.SetIntegrationMode(10)
168    TypeError: SetIntegrationMode arg 1: expected enum EnumType, got int
169
170Note that members of anonymous enums do not have a special type, and
171are simply wrapped as python ints.
172
173
174Namespaces
175----------
176
177Namespaces are currently wrapped in a very limited manner: the only
178namespace members that are wrapped are constants and enum types.
179There is no wrapping of namespaced classes or functions, or of nested
180namespaces.  This is likely to be expanded upon when (or if) VTK begins
181to make greater use of namespaces.
182
183
184Unavailable methods
185-------------------
186
187A method is not wrapped if:
188
1891. its parameter list contains a pointer to anything other than
190   a vtkObjectBase-derived object or a fundamental C++ type (void,
191   char, int, unsigned short, double, etc.)
1922. it returns a pointer to anything other than a vtkObjectBase-derived
193   object, unless the method returns a pointer to a fundamental C++
194   type and has an entry in the wrapping hints file, or the method is
195   a vtkDataArray Get() method, or the returned type is 'char \*' or 'void \*'
1963. it is an operator method (though many exceptions exist)
197
198
199Unavailable classes
200-------------------
201
202Some classes are meant to be used only by other VTK classes and are
203not wrapped.  These are labelled as WRAP\_EXCLUDE\_PYTHON in the
204CMakeLists.txt files.
205
206
207Printing VTK objects
208====================
209
210Printing a vtk object will provide the same information as provided
211by the vtkObject::Print() method (i.e. the values of all instance variables)
212The same information is provided by calling str(obj).  A more compact
213representation of the object is available by calling repr(obj)
214
215    repr(obj)  ->  '(vtkFloatArray)0x100c8d48'
216
217
218Built-in documentation
219======================
220
221All of the documentation that is available in the VTK header files and
222in the html man pages is also available through python.
223
224If you want to see what methods are available for a class, use e.g.
225
226    >>> dir(vtk.vtkActor)
227
228or, equivalently,
229
230    >>> a = vtk.vtkActor()
231    >>> dir(a)
232
233
234You can also retrieve documentation about VTK classes and methods
235from the built-in 'docstrings':
236
237    >>> help(vtk.vtkActor)
238    >>> help(vtk.vtkActor.SetUserTransform)
239    [ lots of info printed, try it yourself ]
240
241For the method documentation, all the different 'signatures' for the
242method are given in Python format and the original C++ format:
243
244    >>> help(vtkActor.SetPosition)
245    SetPosition(...)
246    V.SetPosition(float, float, float)
247    C++: virtual void SetPosition(double _arg1, double _arg2, double _arg3)
248    V.SetPosition([float, float, float])
249    C++: virtual void SetPosition(double _arg[3])
250
251    Set/Get/Add the position of the Prop3D in world coordinates.
252
253
254Peculiarities and special features
255==================================
256
257Deleting a vtkObject
258---------------------
259
260There is no direct equivalent of VTK's Delete() since Python provides a
261mechanism for automatic garbage collection.  The object will be
262deleted once there are no remaining references to it either from
263inside Python or from other VTK objects.  It is possible to get rid of
264the local reference to the object by using the python 'del' command,
265i.e. 'del o', and this will result in a call to Delete() if the
266local reference to the object was the last remaining reference to the
267object from within Python.
268
269
270Templated classes
271-----------------
272
273Templated classes are rare in VTK.  Where they occur, they can be
274instantiated much like they can be in C++, except that \[ \] brackets
275are used for the template arguments instead of < > brackets:
276
277    >>> v = vtkVector['float64',3]([1.0, 2.0, 3.0])
278    >>> a = vtkDenseArray[str]()
279
280Only a limited range of template args can be used, usually dictated by
281by which args are used by typedefs and by other classes in the C++ code.
282A list of the allowed argument combinations available for a particular
283template can be found by calling help() on the template:
284
285    >>> help(vtkVector)
286
287The types are usually given as strings, in the form 'int32', 'uint16',
288'float32', 'float64', 'bool', 'char', 'str', 'vtkVariant'.
289Python type objects are acceptable, too, if the name of the type is
290the same as one of the accepted type strings:
291
292    >>> a = vtkDenseArray[int]()
293
294Note that python 'int' is the same size as a C++ 'long', and python
295'float' is the same size as C++ 'double'.  For compatibility with the
296python array module, single-character typecodes are allowed, taken from
297this list: '?', 'c', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q',
298'f', 'd'.  The python array documentation explains what these mean.
299
300
301Operator methods
302----------------
303
304Some useful operators are wrapped in python: the \[ \] operator is
305wrapped for indexing and item assignment, but because it relies on
306hints to guess which indices are out-of-bounds, it is only wrapped
307for vtkVector and a few other classes.
308
309The comparison operators '<' '<=' '==' '>=' '>' are wrapped for all
310classes that have these operators in C++.
311
312The '<<' operator for printing is wrapped and is used by the python
313'print()' and 'str()' commands.
314
315
316Pass-by-reference
317-----------------
318
319Pass-by-reference of values that are mutable in C++ but not in
320Python (such as string, int, and float) is only possible by
321using vtk.reference(), which is in the vtkCommonCore Python module:
322
323    >>> plane = vtk.vtkPlane()
324    >>> t = vtk.reference(0.0)
325    >>> x = [0.0, 0.0, 0.0]
326    >>> plane.InsersectWithLine([0, 0, -1], [0, 0, 1], t, x)
327    >>> print t
328    0.5
329
330
331Observer, Event and CallData
332----------------------------
333
334*Simple callback*
335
336Similarly to what can be done in C++, a python function can be called
337each time a VTK event is invoked on a given object:
338
339    >>> def onObjectModified(object, event):
340    >>>     print('object: %s - event: %s' % (object.GetClassName(), event))
341    >>>
342    >>> o = vtkObject()
343    >>> o.AddObserver(vtkCommand.ModifiedEvent, onObjectModified)
344    1
345    >>> o.Modified()
346    object: vtkObject - event: ModifiedEvent
347
348
349*Callback with CallData*
350
351In case there is a 'CallData' value associated with an event, in C++, you
352have to cast it from void\* to the expected type using reinterpret\_cast.
353For example, see http://www.vtk.org/Wiki/VTK/Examples/Cxx/Interaction/CallData
354
355The equivalent in python is to set a CallDataType attribute on the
356associated python callback. The supported CallDataType are vtk.VTK\_STRING,
357vtk.VTK\_OBJECT, vtk.VTK\_INT, vtk.VTK\_LONG, vtk.VTK\_DOUBLE, vtk.VTK\_FLOAT
358
359For example:
360
361    >>> def onError(object, event, calldata):
362    >>>     print('object: %s - event: %s - msg: %s' % (object.GetClassName(),
363                                                        event, calldata))
364    >>>
365    >>> onError.CallDataType = vtk.VTK_INT
366    >>>
367    >>> lt = vtkLookupTable()
368    >>> lt.AddObserver(vtkCommand.ErrorEvent, onError)
369    1
370    >>> lt.SetTableRange(2,1)
371    object: vtkLookupTable - event: ErrorEvent - msg: ERROR:
372    In /home/jchris/Projects/VTK6/Common/Core/vtkLookupTable.cxx, line 122
373    vtkLookupTable (0x6b40b30): Bad table range: [2, 1]
374
375
376For convenience, the CallDataType can also be specified where the function
377is first declared with the help of the 'calldata\_type' decorator:
378
379    >>> @calldata_type(vtk.VTK_INT)
380    >>> def onError(object, event, calldata):
381    >>>     print('object: %s - event: %s - msg: %s' % (object.GetClassName(),
382                                                        event, calldata))
383
384
385Subclassing a VTK class
386-----------------------
387
388It is possible to subclass a VTK class from within Python, but it
389is NOT possible to properly override the virtual methods of the class.
390The python-level code will be invisible to the VTK C++ code, so when
391the virtual method is called from C++, the method that you defined from
392within Python will not be called.  The method will only be executed if
393you call it from within Python.
394
395It is therefore not reasonable, for instance, to subclass the
396vtkInteractorStyle to provide custom python interaction.  Instead,
397you have to do this by adding Observers to the vtkInteractor object.
398
399
400Class methods
401-------------
402
403In C++, if you want to call a method from a superclass you can do the
404following:
405
406    vtkActor *a = vtkActor::New();
407    a->vtkProp3D::SetPosition(10,20,50);
408
409The equivalent in python is
410
411    >>> a = vtkActor()
412    >>> vtkProp3D.SetPosition(a,10,20,50)
413
414
415Void pointers
416-------------
417
418As a special feature, a C++ method that requires a 'void \*' can
419be passed any python object that supports the 'buffer' protocol,
420which include string objects, numpy arrays and even VTK arrays.
421Extreme caution should be applied when using this feature.
422
423Methods that return a 'void \*' in C++ will, in Python, return a
424string with a hexadecimal number that gives the memory address.
425
426
427Transmitting data from Python to VTK
428------------------------------------
429
430If you have a large block of data in Python (for example a Numeric
431array) that you want to access from VTK, then you can do so using
432the vtkDataArray.SetVoidArray() method.
433
434
435Creating a Python object from just the address of a VTK object
436--------------------------------------------------------------
437
438When you instantiate a class, you can provide a hexadecimal string
439containing the address of an existing vtk object, e.g.
440
441    t = vtkTransform('_1010e068_vtkTransform_p')
442
443The string follows SWIG mangling conventions.  If a wrapper for the
444specified object already exists, then that wrapper will be used rather
445than a new wrapper being created.  If you want to use this feature
446of vtkpython, please think twice.
447
448
449VTK C++ methods with 'pythonic' equivalents
450-------------------------------------------
451
452    SafeDownCast(): Unnecessary, Python already knows the real type
453    IsA():          Python provides a built-in isinstance() method.
454    IsTypeOf():     Python provides a built-in issubclass() method.
455    GetClassName(): This info is given by o.__class__.__name__
456
457
458Special VTK types
459===================
460
461In addition to VTK objects that are derived from vtkObjectBase, there
462are many lightweight types in VTK such as vtkTimeStamp or vtkVariant.
463These can usually be distinguished from vtkObjects because they do
464not have a C++ '::New()' method for construction.
465
466These types are wrapped in a slightly different way from vtkObject-derived
467classes.  The details of memory management are different because Python
468actually keeps a copy of the object within its 'wrapper', whereas for
469vtkObjects it just keeps a pointer.
470
471An incomplete list of these types is as follows:
472vtkVariant, vtkTimeStamp, vtkArrayCoordinates, vtkArrayExtents,
473vtkArrayExtentsList, vtkArrayRange
474
475
476Automatic conversion
477--------------------
478
479These special types can have several constructors, and the constructors
480can be used for automatic type conversion for VTK methods.  For
481example, vtkVariantArray has a method InsertNextItem(vtkVariant v), and
482vtkVariant has a constructor vtkVariant(int x).  So, you can do this:
483
484    >>> variantArray.InsertNextItem(1)
485
486The wrappers will automatically construct a vtkVariant from '1', and
487will then pass it as a parameter to InsertNextItem.
488
489
490Comparison and mapping
491----------------------
492
493Some special types can be sorted by value, and some can be used as
494dict keys.  Sorting requires the existence of comparison operators
495such as '<' '<=' '==' '>=' '>' and these are not automatically wrapped.
496The use of an object as a dict key requires the computation of a
497hash.  Comparison and hashing are supported by vtkVariant and
498vtkTimeStamp, and will be supported by other types on a case-by-case
499basis.
500
501The reason that all vtkObjects can be easily hashed, while vtk
502special types are hard to hash, is that vtkObjects are hashed
503by memory address.  This cannot be done for special types, since
504they must be hashed by value, not by address.  I.e. vtkVariant(1)
505must hash equal to every other vtkVariant(1), even though the
506various instances will lie and different memory addresses.
507
508
509Special attributes available from VTK-Python
510============================================
511
512Special vtk object attributes:
513-----------------------------
514
515    o.__class__   the class that this object is an instance of
516    o.__doc__     a description of the class (obtained from C++ header file)
517    o.__this__    a string containing the address of the VTK object
518
519
520Special method attributes:
521--------------------------
522
523    m.__doc__     a description of the method (obtained from C++ header file)
524
525
526Special vtk class attributes:
527----------------------------
528
529    c.__bases__   a tuple of base classes for this class (empty for vtkObject)
530    c.__doc__     a description of the class (obtained from C++ header file)
531    c.__name__    the name of the class, same as returned by GetClassName()
532