The Python API documentation is in beta. The contents of the documentation is not finalized and could change in the future.
SimVascular provides an application programming interface (API) for accessing core SimVascular functions using the Python programming language. The API defines a number of Python modules and classes used to access, manipulate and create data for each of the path planning, segmentation, modeling, mesh generation and simulation steps in the SimVascular image-based modeling pipeline. Custom Python scripts can be written to augment the functionality provided by the SimVascular GUI and to automate modeling tasks for optimization, uncertainty quantification, and studies with large patient cohorts.
The API attempts to provide an interface conceptually similar to how data is accessed and how operations are performed using the GUI. There are, however, some differences between the GUI and API because the GUI hides SimVascular internals that must sometimes be exposed in the API. These differences are explained in the SimVascular Python Modules section.
Python is an interpreted, high-level, general-purpose programming language. It supports an object-oriented programming paradigm based on the concept of objects, which can contain data and functions (often known as methods) which operate on the data. In object-oriented programming, a class is an template for creating objects, providing initial values for data and functions or methods. The SimVascular API defines a number of classes that are used to interface to SimVascular core functions.
The Python programming environment is embedded in the SimVascular executable and includes the standard library that is distributed with Python as well as some optional components not included in Python distributions. This means that Python does not need to be installed on your computer to use Python and access the API. Embedding Python ensures the compatibility between Python and the installed module versions. However, it prevents using Python packages that may already be installed on your computer.
The Python interface can be accessed from the SimVascular Python Console or from a terminal using the Python Shell.
A Python module is used to organize related code (e.g. code used to operate on paths) and encapsulates Python classes, functions and variables under a single module name. The SimVascular sv Python package is a collection of modules that extends Python to include classes, functions and variables used to directly call SimVascular C++ functions. Classes provide a means of bundling data and functionality together into a specific object type they create. Python packages and modules are accessed using the Python import statement.
Components of a module are accessed using a dot . notation. For example, the Circle class defined in the segmentation module is accessed using sv.segmentation.Circle().
Almost everything in Python is an object. An object is an encapsulation of data members (variables) functions into a single entity. A class is an template for creating objects. A class constructor is used for instantiating an object by initializing or assigning values to its data members when an object is created. A constructor can be passed arguments just like a function and used the values of those arguments to assign values to its data members. For example, the segmentation.Circle class is used to create a circle segmentation with a given radius, center and normal arguments passed to its constructor
>>> circle_seg = sv.segmentation.Circle(radius=1.0, center=[1.0,1.0,1.0], normal=[1.0,0.0,0.0])
SimVascular uses the Visualization Toolkit (VTK), an open-source software system for image processing, 3D graphics, volume rendering and visualization, for many applications and uses its file formats to store image, model and mesh data. Many Python API functions return VTK objects that can be used in further computations or displayed in a graphics window. The VTK package is included in the SimVascular Python environment. It is accessed using the import vtk statement.
SimVascular uses the Vascular Modeling Toolkit (VMTK), a collection of libraries and tools for 3D reconstruction, geometric analysis, mesh generation and surface data analysis for image-based modeling of blood vessels, from some applications. The VMTK Python module is not included in the Python programming environment. However, some of the VMTK functionality is accessible using the SimVascular sv.vmtk module.
A Python script is a plain text file containing code written in Python. A script file containing Python code has the extension .py. Scripts are made to be directly executed. Note that a text file containing Python code can also be designed to be imported as a module. This is a useful way for a user application to organize code into reusable utilities.
The SimVascular Python Console is opened by selecting the
icon
located at the far right end on the SimVascular tool bar. The Python Console has two panels.
The right panel is used to execute commands by the Python interpreter.
The left panel lists the currently defined Python attributes (variables). Importing a module adds that module name to the list of attributes. Importing all of the sv modules by typing from sv import * in the interpreter panel adds all of the modules defined by sv to the list of attributes in the left panel.
The Python Console has two modes of operation: Console and Text Editor. The Python Console opens in Console mode that is used to interactively execute Python commands. The version of the Python interpreter embedded in the SimVascular application is printed and the Python >>> prompt is displayed meaning that the interpreter is ready for keyboard input. The Console and Text Editor buttons located at the bottom of the right panel are used to select the operational mode.
All of the built-in modules are available from the standard library that is distributed with Python. Modules can be imported and used just like any typical Python application. Commands can be interactively typed in and executed by pressing return.
Selecting the Python Console Text Editor button switches to a panel that is used to read, edit, save, and
execute Python scripts. This is the preferred method to use when developing Python scripts that need to be have access to
the SV Data Manager. A new Python script can be interactively written, tested and saved to a file. It can later be
read in and executed.
For example, the PathDemo.py script can be read in and executed by pressing the
button.
After a script is executed the variables and functions defined by it are available in the Console. Variables defined in the Console are also available in the Text Editor.
The SimVascular Python Shell provides a Python interface to SimVascular without the GUI. The Python Shell is invoked from a terminal by executing the script used to launch SimVascular interactively. The launch script is located in the SimVascular install directory and is executed for different platforms using
Linux: /usr/local/sv/simvascular/DATE/simvascular MacOS: /usr/local/sv/simvascular/DATE/simvascular Windows: C:\Program Files\SimVascular\SimVascular\DATE\sv.bat
where DATE is the SimVascular install date (e.g. 2020-04-06). In the following discussion we will use simvascular to represent the the SimVascular launch script.
The SimVascular Python interpreter, the application that executes Python programs, is invoked in interactive mode using the —python flag.
That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait.
The Python Shell behaves like the standard Python interpreter and therefore supports automatic indentation to mark blocks of code.
$ simvascular --python SimVascular Python Shell Copyright (c) Stanford University, The Regents of the University of California, and others. All Rights Reserved. Python 3.5.5 (default, Jun 14 2019, 00:18:30) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> >>> print("Hello") Hello >>>
The Python Shell is terminated using
Linux and MacOS: Ctrl-D Windows: exit() or hold the Ctrl key down while you enter a Z, then hit the “Enter” key to get back to your Windows command prompt
Python scripts are read in and executed using a double-dash — before the script name. The Python Shell passes the script to the
Python interpreter for execution and then exits.
$ simvascular --python -- path.py SimVascular Python Shell Copyright (c) Stanford University, The Regents of the University of California, and others. All Rights Reserved. New gRepository created from cv_solid_init TetGen: 1.5.1 PyModule_Create called splinePolygonContour Enabled levelSetContour Enabled polygonContour Enabled circleContour Enabled splinePolygonContour Enabled OpenCASCADE: 7.3.0 Itk: 4.13.2 TetGen Adaption Enabled pyPath initialized. Point 0, 0.000000, 0.000000, 0.000000 Point 1, 0.000000, 0.000000, 30.000000 Total number of path points created is: 100 $
The SimVascular sv Python package extends Python to include modules and classes used to access, manipulate and create data for each of the path planning, segmentation, modeling, mesh generation and simulation steps in the SimVascular image-based modeling pipeline. The sv package is imported into Python using the import sv statement. The sv package defines the following modules
Modules are accessed using sv.MODULENAME. The sv package can also be imported into Python using the
from sv import * statement. This makes all of the module names accessible without the sv prefix. A single sv
module can be imported using from sv import MODULENAME. The difference between the these statements is seen using
the dir() function which shows imported modules
$ simvascular --python >>> import sv >>> print(dir()) ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'sv'] >>> dir(sv) ['MeshSimListOption', 'MeshSimOptionTemplate', 'MutableSequence', 'OrderedDict', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'ctypes', 'dmg', 'ext', 'geometry', 'image', 'load_module', 'mesh_utils', 'meshing', 'meshsim_options', 'meshsim_plugin', 'modeling', 'parasolid_plugin', 'pathplanning', 'project', 'python_api_lib', 'repository', 'seg_lib', 'segmentation', 'solid_occt', 'sys', 'vmtk'] >>> >>> >>> from sv import * >>> dir() ['MeshSimListOption', 'MeshSimOptionTemplate', 'MutableSequence', 'OrderedDict', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'ctypes', 'dmg', 'ext', 'geometry', 'image', 'load_module', 'mesh_utils', 'meshing', 'meshsim_options', 'meshsim_plugin', 'modeling', 'parasolid_plugin', 'pathplanning', 'project', 'python_api_lib', 'repository', 'seg_lib', 'segmentation', 'solid_occt', 'sv', 'sys', 'vmtk'] >>> >>> >>> from sv import segmentation >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'segmentation']
Both of these statements show the modules defined from importing sv; dmg, meshing, etc.
The SimVascular GUI requires an active project to access the image-based modeling pipeline. A project organizes and saves data to predefined subdirectories located under the main project directory. There is a separate folder for each tool in the image-based modeling pipeline. Each tool has an XML format file with a specific extension associated with it that stores data used by the tool to represent geometry and parameters. The parameters store the tool’s state and are typically displayed in the GUI and can be modified by the user. The predefined subdirectories and XML file extension for each tool are
Tool XML files were designed to store data derived from time-varying imaging data (e.g. 4D MRI). For this reason each file
has a timestep element used to identify data with a discrete integer time step. Each sv module defines a
Series class used to read in XML files and extract data for each time step.
The Python help function is used to display the documentation of modules, functions, classes, keywords etc. Typing help(sv) prints information about the sv package.
Typing help(sv.MODLENAME) prints information about the MODULENAME module
The help() function can be used for any component (e.g. class and methods) of a module. For example,
help(sv.segmentation.Circle) prints the documentation for the segmentation module Circle class
The help documentation describes the sv package using Python docstrings format, a string literal that occurs as the first statement in a module, function, class, or method definition. A docstring is stored in the the __doc__ special attribute of an object. The docstring for a function or method summarizes its behavior and documents its arguments and return value(s).
Constructor, method and function arguments are listed under the Args: heading. Each argument is described with its name, type and description. Optional arguments are indicated using Optional preceding the argument type. The default value of optional arguments are given in the argument list. An optional argument without a default value is documented using NAME=None in the function or method definition. For example, the Circle class constructor that has center, normal and frame optional arguments that have no default value is documented using
Circle(radius, center=None, normal=None, frame=None)
Argument types are described using the following naming convention
A 3D point is represented as a list of three floats
[float, float, float]
Example: pt = [1.0, 2.0, 3.0]
A list of 3D points is represented as a list of a list of three floats
list( [float, float, float] )
Example: control_points = [ [1.0, 2.0, 3.0], [2.0, 3.0, 4.0], [3.0, 4.0, 5.0] ]
SimVascular Python object types used as function arguments and return values are designated using the class name.
For example, the Modeling union method, which takes two sv.modeling.Model arguments, is documented
using just the Model class name
union(model1, model2)
Create a solid from the Boolean union operation on two solids.
Args: model1 (Model): A solid model created by a modeler. model2 (Model): A solid model created by a modeler.
Returns (Model): The solid model of the unioned models.
The methods and functions used in the Python API are able to use Python keyword (named) arguments. This allows functions to know the names of the arguments they accept. Keyword arguments are used to clarify which values are used by what arguments. For example, creating a Circle segmentation with a given radius, centerand normal using keyword arguments makes clear the meaning of the data passed to the Circle class constructor
>>> seg = sv.segmentation.Circle(radius=1.0, center=[1.0,1.0,1.0], normal=[1.0,0.0,0.0])
All data passed to a function is checked against the type expected by the function. A type mismatch generates an error.
General type errors are detected by Python. For example, using a string for the radius argument which expects a
float generates a Python TypeError
>>> seg = sv.segmentation.Circle(radius='a', center=[1.0,1.0,1.0], normal=[1.0,0.0,0.0]) TypeError: CircleSegmentation() argument 1 must be float, not str
Errors associated with data needed by the C++ functions called from the SimVascular API are detected within the API C++
implementation. For example, passing in a list of two instead of three floats for the Circle class constructor
normal argument generates a segmentation module error
>>> seg = sv.segmentation.Circle(radius=1.0, center=[1.0,0.0,0.0], normal=[1.0]) segmentation.Error: CircleSegmentation() The 'normal' argument is not a 3D point (three float values).
All API errors are handled using exceptions. See the Error Handling section..
A Python program terminates when it encounters an error. An error can be a syntax error or an exception. A syntax error occurs when the Python parser is unable to understand a line of code. An exception is an error detected during the execution of a Python program. Both syntax errors and exceptions are fatal and cause a program to terminate.
Exceptions come in different types. The exception type is included as part of the a message printed by Python when an exception is encountered. For example, a divide by zero generates a ZeroDivisionError exception type
>>> 10 * (1/0) Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
Python has many standard exception names that are built-in identifiers (not reserved keywords). The TypeError exception is generated when an inappropriate type is passed to an API function. For example, using a string for the radius argument for the Circle constructor generates a Python TypeError
>>> seg = sv.segmentation.Circle(radius='a', center=[1.0,1.0,1.0], normal=[1.0,0.0,0.0]) TypeError: CircleSegmentation() argument 1 must be float, not str
Exceptions cause program termination unless they are explicitly caught and handled by a try/except block. Python executes code following the try statement as it would normally do. If an exception is generated in this code section then the code following the except statement is executed and the program continues.
The TypeError exception generated from using a string for the radius argument when creating a Circle segmentation is caught using a try/except block like this
>>> try: >>> seg = segmentation.Circle(radius=1.0, center=[0.0,0.0,0.0], normal=[1.0,0.0,0.0]) >>> except TypeError as err: >>> print("TypeError: ", err) >>> TypeError: CircleSegmentation() argument 1 must be float, not str
Errors associated with the C++ functions called by the SimVascular API can use exception names defined by the API in the except statement. For example, passing in a list of two elements for the normal argument generates a segmentation module error is caught using the segmentation.Error exception name and a try/except block like this
>>> try: >>> seg = segmentation.Circle(radius=1.0, center=[1.0,0.0,0.0], normal=[1.0]) >>> >>> except segmentation.Error as err: >>> print("Exception type: ", type(err)) >>> print("Error: ", err) Exception type: class 'segmentation.Error' Error: CircleSegmentation() The 'normal' argument is not a 3D point (three float values).
Any exception can be caught using the except Exception as err: statement.
>>> try: >>> seg = segmentation.Circle(radius=1.0, center=[1.0,0.0,0.0], normal=[1.0]) >>> >>> except Exception as err: >>> print("Exception type: ", type(err)) >>> print("Unexpected error: ", err) Exception type: class 'segmentation.Error' Unexpected error: CircleSegmentation() The 'normal' argument is not a 3D point (three float values).
The dmg (data manager) module provides an interface for accessing the SV Data Manager, the panel located on the left side of the main window that organizes the data defined for a SimVascular project as a hierarchical tree of data nodes. The Data Manager organizes data nodes into predefined primary data node types according to the tools that create them create them
When new data is added to the project a new data node is added under the appropriate data node type with a user-defined name.
The dmg module does not define any classes. All access to the SV Data Manager is through functions defined
for the module. For example, getting path data from the aorta data node is performed using the get_path()
function accessed directly from the dmg module
>>> path = sv.dmg.get_path('aorta')
The geometry module provides functions for performing geometric operations on vtkPolyData objects used to represents vertices, lines and polygons.
All geometric operations are performed using functions defined for the module. For example, aligning contours is performed using the align_profile() function accessed directly from the geometry module
>>> align_cont = sv.geometry.align_profile(source_cont, cont2)
The geometry module defines two classes used to set lofting parameters
The meshing module provides an interface to SimVascular meshing functionality used to generate a finite element tetrahedral mesh from a solid model.
Methods are provided for setting meshing parameters, generating meshes and extracting mesh results as VTK unstructured mesh objects. User-defined regions on model faces can be defined for local mesh refinement.
Two mesh generation software components (aka kernels) are supported
MeshSim is a commercial software package used to generate meshes from Parasolid solid models. Using MeshSim requires purchasing a license from Simmetrix, a Parasolid license from Siemens and SimVascular plugins providing an interface to the software.
TetGen is an open source software package used to generate meshes from PolyData solid models.
A mesh generation kernel name is specified using the meshing.Kernel class
The meshing module defines the following classes
The modeling module provides an interface to SimVascular modeling functionality used to generate geometric models from medical imaging data. Solid models of vessel geometry are created by lofting and capping 2D segmentations. Separate solid models are then unioned together to create a model representing a region of the vascular anatomy.
Methods are provided for querying, creating, and modifying models. This includes Boolean operations, operations on model faces, local operations acting on user-defined regions global operations acting on the entire model.
Three 3D solid modeling software components (aka kernels) are supported
A modeling kernel name is specified using the modeling.Kernel class
The PolyData modeling kernel represents models as unstructured surfaces composed of 3-sided polygons.
The OpenCASCADE modeling kernel is an open source software 3D CAD package. Models are represented as Non-Uniform Rational B-Spline (NURBS) surfaces.
The Parasolid modeling kernel is a commercial software package providing 3D solid modeling functionality. Using Parasolid requires purchasing a license from Siemens for the Parasolid libraries and a SimVascular plugin providing an interface to the libraries.
The modeling module defines the following classes
The pathplanning module provides an interface to the SimVascular path planning functionality. Paths model vessel centerlines using a small number of manually selected control points. Path geometry is represented by a set of curve points sampled from a spline passing through the control points.
The pathplanning module defines the following classes
The segmentation module provides an interface to the SimVascular image segmentation functionality.
The segmentation module defines the following classes
The vmtk module provides an interface to VMTK functions.
All VMTK operations are performed using functions defined for the module. For example, computing centerlines is performed using the centerlines() function accessed directly from the vmtk module
>>> centerlines = sv.vmtk.centerlines(model, source_ids, target_ids, use_face_ids=True)