Commit 810993d9 authored by David Gobbi's avatar David Gobbi Committed by Kitware Robot
Browse files

Merge topic 'readme-wrap-markdown'

bb8fe552 Python uses WRAP_EXCLUDE_PYTHON, not WRAP_EXCLUDE.
bc23917e Small clarification to pointer wrapping for Python.
5188ddd5

 Convert README_WRAP into markdown format.
Acked-by: Kitware Robot's avatarKitware Robot <kwrobot@kitware.com>
Reviewed-by: default avatarDavid E DeMarle <dave.demarle@kitware.com>
Merge-request: !1214
parents 9fbc01f6 bb8fe552
Pipeline #6998 failed with stage
Notes on the Python Wrappers for VTK
====================================
First version by David Gobbi: Dec 19, 2002
Last update was on Feb 10, 2016
Last update was on Feb 12, 2016
Abstract:
=========
This document provides a detailed description of how VTK objects are
accessed and modified through Python. The installation of VTK-Python
is covered in README.txt.
accessed and modified through Python.
Overview:
=========
Nearly all the power of VTK objects are available through Python
(with a few exceptions as noted below). The C++ semantics are
(with a few exceptions as noted below). The C++ semantics are
translated as directly as possible to Python semantics. Currently,
full support is provided for Python 2.6, 2.7, 3.2, 3.3, and 3.4.
full support is provided for Python 2.6, 2.7, and 3.2 through 3.5.
The Basics:
===========
If VTK has been properly built and installed with the python wrappers,
then VTK can be accessed by importing the "vtk" module:
then VTK can be accessed by importing the 'vtk' module:
import vtk
or
from vtk import *
For the most part, using VTK from Python is very similar to using VTK
from C++ except for changes in syntax, e.g.
vtkObject *o = vtkObject::New()
becomes
o = vtkObject()
and
o->Method()
becomes
o.Method()
Some other important differences are that you can pass a Python tuple,
list or array to a method that requires a C++ array e.g.:
>>> a = vtkActor()
>>> p = (100.0, 200.0, 100.0)
>>> a.SetPosition(p)
>>> a = vtkActor()
>>> p = (100.0, 200.0, 100.0)
>>> a.SetPosition(p)
If the C++ array parameter is used to return information, you must
pass a Python list or array that has the correct number of slots to
accept the returned values:
>>> z = [0.0, 0.0, 0.0]
>>> vtkMath.Cross((1,0,0),(0,1,0),z)
>>> print z
[0.0, 0.0, 1.0]
>>> z = [0.0, 0.0, 0.0]
>>> vtkMath.Cross((1,0,0),(0,1,0),z)
>>> print z
[0.0, 0.0, 1.0]
For multi-dimensional arrays, it is your choice whether to use
a nested list, or whether to use a numpy array with the correct
......@@ -65,16 +75,16 @@ only wrapped if there is a hint (usually in VTK/Wrapping/hints)
that gives the size of the array. Hinted pointers are returned as
tuples:
>>> a = vtkActor()
>>> print a.GetPosition()
(0.0, 0.0, 0.0)
>>> a = vtkActor()
>>> print a.GetPosition()
(0.0, 0.0, 0.0)
Finally, the python 'None' is treated the same as C++ NULL:
Finally, the python 'None' is treated the same as C++ 'NULL':
>>> a = vtkActor()
>>> a.SetMapper(None)
>>> print a.GetMapper()
None
>>> a = vtkActor()
>>> a.SetMapper(None)
>>> print a.GetMapper()
None
And perhaps one of the most pleasant features of Python is that all
type-checking is performed at run time, so the type casts that are
......@@ -85,17 +95,17 @@ Strings (Python 3 vs. Python 2)
---------------------
The mapping of Python string types to C++ string types is different
in Python 3 as compared to Python 2. In Python 2, the basic str()
type was for 8-bit strings, and a separate unicode() type was used
in Python 3 as compared to Python 2. In Python 2, the basic 'str()'
type was for 8-bit strings, and a separate 'unicode()' type was used
for unicode strings.
For Python 3, the basic str() type is unicode, and when you pass a
str() as a VTK "std::string" or "const char *" parameter, VTK will
For Python 3, the basic 'str()' type is unicode, and when you pass a
str() as a VTK 'std::string' or 'const char \*' parameter, VTK will
receive the string in utf-8 encoding. To use a different encoding,
you must encode the string yourself and pass it to VTK as a bytes()
object, e.g. writer.SetFileName("myfile".encode('latin1')).
object, e.g. writer.SetFileName('myfile'.encode('latin1')).
When VTK returns a "const char *" or "std::string" in Python 3, the
When VTK returns a 'const char \*' or 'std::string' in Python 3, the
wrappers will test to see of the string is utf-8 (or ascii), and if
so they will pass the string to python as a unicode str() object.
If the VTK string is not valid utf-8, then the wrappers will pass
......@@ -110,23 +120,23 @@ with incorrect characters.
Constants
---------
Most VTK constants are available in Python, usually in the "vtk"
Most VTK constants are available in Python, usually in the 'vtk'
module but sometimes as class attributes:
>>> vtk.VTK_DOUBLE_MAX
1.0000000000000001e+299
>>> vtk.vtkCommand.ErrorEvent
39
>>> vtk.VTK_DOUBLE_MAX
1.0000000000000001e+299
>>> vtk.vtkCommand.ErrorEvent
39
Each named enum type is wrapped as a new Python type, and members
of the enum are instances of that type. This allows type checking
for enum types:
>>> # works if given a constant of the correct enum type
>>> o.SetIntegrationMode(o.Continuous)
>>> # does not work, because "int" is not of the correct type
>>> o.SetIntegrationMode(10)
TypeError: SetIntegrationMode arg 1: expected enum EnumType, got int
>>> # works if given a constant of the correct enum type
>>> o.SetIntegrationMode(o.Continuous)
>>> # does not work, because 'int' is not of the correct type
>>> o.SetIntegrationMode(10)
TypeError: SetIntegrationMode arg 1: expected enum EnumType, got int
Note that members of anonymous enums do not have a special type, and
are simply wrapped as python ints.
......@@ -145,22 +155,24 @@ to make greater use of namespaces.
Unavailable methods
-------------------
A method is not wrapped if
1) its parameter list contains a pointer that isn't a vtkObject
pointer, char pointer, or void pointer -- though the vtkDataArray
"Tuple" methods are an exception, they are wrapped
2) it returns a pointer that is not a vtkObject pointer, char pointer,
or void pointer, unless the method has an entry in the wrapping
hints file -- again, vtkDataArray methods are an exception
3) it is an operator method (though many exceptions exist)
A method is not wrapped if:
1. its parameter list contains a pointer to anything other than
a vtkObjectBase-derived object or a fundamental C++ type (void,
char, int, unsigned short, double, etc.)
2. it returns a pointer to anything other than a vtkObjectBase-derived
object, unless the method returns a pointer to a fundamental C++
type and has an entry in the wrapping hints file, or the method is
a vtkDataArray Get() method, or the returned type is 'char \*' or 'void \*'
3. it is an operator method (though many exceptions exist)
Unavailable classes
-------------------
Some classes are meant to be used only by other VTK classes and are
not wrapped. These are labelled as WRAP_EXCLUDE in the CMakeLists.txt
files.
not wrapped. These are labelled as WRAP\_EXCLUDE\_PYTHON in the
CMakeLists.txt files.
Printing VTK objects
......@@ -171,7 +183,7 @@ by the vtkObject::Print() method (i.e. the values of all instance variables)
The same information is provided by calling str(obj). A more compact
representation of the object is available by calling repr(obj)
repr(obj) -> '(vtkFloatArray)0x100c8d48'
repr(obj) -> '(vtkFloatArray)0x100c8d48'
Built-in documentation
......@@ -182,26 +194,26 @@ in the html man pages is also available through python.
If you want to see what methods are available for a class, use e.g.
>>> dir(vtk.vtkActor)
>>> dir(vtk.vtkActor)
or, equivalently,
>>> a = vtk.vtkActor()
>>> dir(a)
>>> a = vtk.vtkActor()
>>> dir(a)
You can also retrieve documentation about VTK classes and methods
from the built-in "docstrings":
from the built-in 'docstrings':
>>> help(vtk.vtkActor)
>>> help(vtk.vtkActor.SetUserTransform)
[ lots of info printed, try it yourself ]
>>> help(vtk.vtkActor)
>>> help(vtk.vtkActor.SetUserTransform)
[ lots of info printed, try it yourself ]
For the method documentation, all the different 'signatures' for the
method are given in Python format and the original C++ format:
>>> help(vtkActor.SetPosition)
SetPosition(...)
>>> help(vtkActor.SetPosition)
SetPosition(...)
V.SetPosition(float, float, float)
C++: virtual void SetPosition(double _arg1, double _arg2, double _arg3)
V.SetPosition([float, float, float])
......@@ -216,12 +228,12 @@ Peculiarities and special features
Deleting a vtkObject
---------------------
There is no direct equivalent of o->Delete() since Python provides a
There is no direct equivalent of VTK's Delete() since Python provides a
mechanism for automatic garbage collection. The object will be
deleted once there are no remaining references to it either from
inside Python or from other VTK objects. It is possible to get rid of
the local reference to the object by using the python 'del' command,
i.e. "del o", and this will result in a call to o->Delete() if the
i.e. 'del o', and this will result in a call to Delete() if the
local reference to the object was the last remaining reference to the
object from within Python.
......@@ -230,25 +242,25 @@ Templated classes
-----------------
Templated classes are rare in VTK. Where they occur, they can be
instantiated much like they can be in C++, except that [ ] brackets
instantiated much like they can be in C++, except that \[ \] brackets
are used for the template arguments instead of < > brackets:
>>> v = vtkVector['float64',3]([1.0, 2.0, 3.0])
>>> a = vtkDenseArray[str]()
>>> v = vtkVector['float64',3]([1.0, 2.0, 3.0])
>>> a = vtkDenseArray[str]()
Only a limited range of template args can be used, usually dictated by
by which args are used by typedefs and by other classes in the C++ code.
A list of the allowed argument combinations available for a particular
template can be found by calling help() on the template:
>>> help(vtkVector)
>>> help(vtkVector)
The types are usually given as strings, in the form 'int32', 'uint16',
'float32', 'float64', 'bool', 'char', 'str', 'vtkVariant'.
Python type objects are acceptable, too, if the name of the type is
the same as one of the accepted type strings:
>>> a = vtkDenseArray[int]()
>>> a = vtkDenseArray[int]()
Note that python 'int' is the same size as a C++ 'long', and python
'float' is the same size as C++ 'double'. For compatibility with the
......@@ -260,7 +272,7 @@ this list: '?', 'c', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q',
Operator methods
----------------
Some useful operators are wrapped in python: the [ ] operator is
Some useful operators are wrapped in python: the \[ \] operator is
wrapped for indexing and item assignment, but because it relies on
hints to guess which indices are out-of-bounds, it is only wrapped
for vtkVector and a few other classes.
......@@ -279,66 +291,66 @@ Pass-by-reference of values that are mutable in C++ but not in
Python (such as string, int, and float) is only possible by
using vtk.mutable(), which is in the vtk module:
>>> plane = vtkPlane()
>>> t = mutable(0.0)
>>> x = [0.0, 0.0, 0.0]
>>> plane.InsersectWithLine([0, 0, -1], [0, 0, 1], t, x)
>>> print t
0.5
>>> plane = vtkPlane()
>>> t = mutable(0.0)
>>> x = [0.0, 0.0, 0.0]
>>> plane.InsersectWithLine([0, 0, -1], [0, 0, 1], t, x)
>>> print t
0.5
Observer, Event and CallData
----------------------------
* Simple callback
*Simple callback*
Similarly to what can be done in C++, a python function can be called
each time a VTK event is invoked on a given object:
>>> def onObjectModified(object, event):
>>> print("object: %s - event: %s" % (object.GetClassName(), event))
>>>
>>> o = vtkObject()
>>> o.AddObserver(vtkCommand.ModifiedEvent, onObjectModified)
1
>>> o.Modified()
object: vtkObject - event: ModifiedEvent
>>> def onObjectModified(object, event):
>>> print('object: %s - event: %s' % (object.GetClassName(), event))
>>>
>>> o = vtkObject()
>>> o.AddObserver(vtkCommand.ModifiedEvent, onObjectModified)
1
>>> o.Modified()
object: vtkObject - event: ModifiedEvent
* Callback with CallData
*Callback with CallData*
In case there is a "CallData" value associated with an event, in C++, you
have to cast it from void* to the expected type using reinterpret_cast.
In case there is a 'CallData' value associated with an event, in C++, you
have to cast it from void\* to the expected type using reinterpret\_cast.
For example, see http://www.vtk.org/Wiki/VTK/Examples/Cxx/Interaction/CallData
The equivalent in python is to set a CallDataType attribute on the
associated python callback. The supported CallDataType are vtk.VTK_STRING,
vtk.VTK_OBJECT, vtk.VTK_INT, vtk.VTK_LONG, vtk.VTK_DOUBLE, vtk.VTK_FLOAT
associated python callback. The supported CallDataType are vtk.VTK\_STRING,
vtk.VTK\_OBJECT, vtk.VTK\_INT, vtk.VTK\_LONG, vtk.VTK\_DOUBLE, vtk.VTK\_FLOAT
For example:
>>> def onError(object, event, calldata):
>>> print("object: %s - event: %s - msg: %s" % (object.GetClassName(),
event, calldata))
>>>
>>> onError.CallDataType = vtk.VTK_INT
>>>
>>> lt = vtkLookupTable()
>>> lt.AddObserver(vtkCommand.ErrorEvent, onError)
1
>>> lt.SetTableRange(2,1)
object: vtkLookupTable - event: ErrorEvent - msg: ERROR:
In /home/jchris/Projects/VTK6/Common/Core/vtkLookupTable.cxx, line 122
vtkLookupTable (0x6b40b30): Bad table range: [2, 1]
>>> def onError(object, event, calldata):
>>> print('object: %s - event: %s - msg: %s' % (object.GetClassName(),
event, calldata))
>>>
>>> onError.CallDataType = vtk.VTK_INT
>>>
>>> lt = vtkLookupTable()
>>> lt.AddObserver(vtkCommand.ErrorEvent, onError)
1
>>> lt.SetTableRange(2,1)
object: vtkLookupTable - event: ErrorEvent - msg: ERROR:
In /home/jchris/Projects/VTK6/Common/Core/vtkLookupTable.cxx, line 122
vtkLookupTable (0x6b40b30): Bad table range: [2, 1]
For convenience, the CallDataType can also be specified where the function
is first declared with the help of the "calldata_type" decorator:
is first declared with the help of the 'calldata\_type' decorator:
>>> @calldata_type(vtk.VTK_INT)
>>> def onError(object, event, calldata):
>>> print("object: %s - event: %s - msg: %s" % (object.GetClassName(),
event, calldata))
>>> @calldata_type(vtk.VTK_INT)
>>> def onError(object, event, calldata):
>>> print('object: %s - event: %s - msg: %s' % (object.GetClassName(),
event, calldata))
Subclassing a VTK class
......@@ -362,24 +374,24 @@ Class methods
In C++, if you want to call a method from a superclass you can do the
following:
vtkActor *a = vtkActor::New();
a->vtkProp3D::SetPosition(10,20,50);
vtkActor *a = vtkActor::New();
a->vtkProp3D::SetPosition(10,20,50);
The equivalent in python is
>>> a = vtkActor()
>>> vtkProp3D.SetPosition(a,10,20,50)
>>> a = vtkActor()
>>> vtkProp3D.SetPosition(a,10,20,50)
Void pointers
-------------
As a special feature, a C++ method that requires a void * can
be passed any python object that supports the "buffer" protocol,
As a special feature, a C++ method that requires a 'void \*' can
be passed any python object that supports the 'buffer' protocol,
which include string objects, numpy arrays and even VTK arrays.
Extreme caution should be applied when using this feature.
Methods that return a void * in C++ will, in Python, return a
Methods that return a 'void \*' in C++ will, in Python, return a
string with a hexidecimal number that gives the memory address.
......@@ -396,24 +408,22 @@ Creating a Python object from just the address of a VTK object
When you instantiate a class, you can provide a hexidecimal string
containing the address of an existing vtk object, e.g.
t = vtkTransform('_1010e068_vtkTransform_p')
t = vtkTransform('_1010e068_vtkTransform_p')
The string follows SWIG mangling conventions. If a wrapper for the
specified object already exists, then that wrapper will be used rather
than a new wrapper being created. If you want to use this feature
of vtkpython, please think twice.
VTK C++ methods with "pythonic" equivalents
VTK C++ methods with 'pythonic' equivalents
-------------------------------------------
SafeDownCast(): Python knows the real type of any VTK object,
so casts don't do anything.
IsA(): Python provides a built-in isinstance() method.
IsTypeOf(): Python provides a built-in issubclass() method.
GetClassName(): This info is given by o.__class__.__name__
SafeDownCast(): Unnecessary, Python already knows the real type
IsA(): Python provides a built-in isinstance() method.
IsTypeOf(): Python provides a built-in issubclass() method.
GetClassName(): This info is given by o.__class__.__name__
Special VTK types
......@@ -422,13 +432,12 @@ Special VTK types
In addition to VTK objects that are derived from vtkObjectBase, there
are many lightweight types in VTK such as vtkTimeStamp or vtkVariant.
These can usually be distinguished from vtkObjects because they do
not have a C++ "::New()" method for construction.
not have a C++ '::New()' method for construction.
These types are wrapped in different way from vtkObject-derived classes.
In Python they look like "types" instead of looking like python "classes".
They cannot be subclassed, and the details of memory management are
different because Python actually keeps a copy of the object within
its "wrapper", whereas for vtkObjects it just keeps a pointer.
These types are wrapped in a slightly different way from vtkObject-derived
classes. The details of memory management are different because Python
actually keeps a copy of the object within its 'wrapper', whereas for
vtkObjects it just keeps a pointer.
An incomplete list of these types is as follows:
vtkVariant, vtkTimeStamp, vtkArrayCoordinates, vtkArrayExtents,
......@@ -443,9 +452,9 @@ can be used for automatic type conversion for VTK methods. For
example, vtkVariantArray has a method InsertNextItem(vtkVariant v), and
vtkVariant has a constructor vtkVariant(int x). So, you can do this:
>>> variantArray.InsertNextItem(1)
>>> variantArray.InsertNextItem(1)
The wrappers will automatically construct a vtkVariant from "1", and
The wrappers will automatically construct a vtkVariant from '1', and
will then pass it as a parameter to InsertNextItem.
......@@ -454,7 +463,7 @@ Comparison and mapping
Some special types can be sorted by value, and some can be used as
dict keys. Sorting requires the existence of comparison operators
such as "< <= == != > >=" and these are not automatically wrapped.
such as '<' '<=' '==' '>=' '>' and these are not automatically wrapped.
The use of an object as a dict key requires the computation of a
hash. Comparison and hashing are supported by vtkVariant and
vtkTimeStamp, and will be supported by other types on a case-by-case
......@@ -471,27 +480,23 @@ various instances will lie and different memory addresses.
Special attributes available from VTK-Python
============================================
Special vtkobject attributes:
Special vtk object attributes:
-----------------------------
o.__class__ the vtkclass that this object is an instance of
o.__doc__ a description of the class (obtained from C++ header file)
o.__this__ a string containing the address of the VTK object
o.__class__ the class that this object is an instance of
o.__doc__ a description of the class (obtained from C++ header file)
o.__this__ a string containing the address of the VTK object
Special method attributes:
--------------------------
m.__doc__ a description of the method (obtained from C++ header file)
m.__doc__ a description of the method (obtained from C++ header file)
Special vtkclass attributes:
Special vtk class attributes:
----------------------------
c.__bases__ a tuple of base classes for this class (empty for vtkObject)
c.__doc__ a description of the class (obtained from C++ header file)
c.__name__ the name of the class, same as returned by GetClassName()
END OF FILE
c.__bases__ a tuple of base classes for this class (empty for vtkObject)
c.__doc__ a description of the class (obtained from C++ header file)
c.__name__ the name of the class, same as returned by GetClassName()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment