dolfin

FEniCS/Dolfin support submodule.

Basic example:

import dolfin
from vedo.dolfin import dataurl, download, plot
fname = download(dataurl+"dolfin_fine.xml")
mesh = dolfin.Mesh(fname)
plot(mesh)

dolfinmesh

Find many more examples in vedo/examples/dolfin

Latex

class vedo.dolfin.Latex(formula, pos=(0, 0, 0), c='k', s=1, bg=None, alpha=1, res=30, usetex=False)[source]

Bases: vedo.picture.Picture

Render Latex formulas.

Parameters
  • formula (str) – latex text string

  • pos (list) – position coordinates in space

  • c – face color

  • bg – background color box

  • res (int) – dpi resolution

  • usetex (bool) – use latex compiler of matplotlib

You can access the latex formula in Latex.formula’.

latex.py latex.py

Plotter

class vedo.dolfin.Plotter(shape=(1, 1), N=None, pos=(0, 0), size='auto', screensize='auto', title='vedo', bg='white', bg2=None, axes=None, sharecam=True, resetcam=True, interactive=None, offscreen=False, qtWidget=None, wxWidget=None)[source]

Bases: object

Main class to manage actors.

Parameters
  • shape (list) – shape of the grid of renderers in format (rows, columns). Ignored if N is specified.

  • N (int) – number of desired renderers arranged in a grid automatically.

  • pos (list) – (x,y) position in pixels of top-left corner of the rendering window on the screen

  • size – size of the rendering window. If ‘auto’, guess it based on screensize.

  • screensize – physical size of the monitor screen

  • bg – background color or specify jpg image file name with path

  • bg2 – background color of a gradient towards the top

  • axes (int) –

    • 0, no axes

    • 1, draw three gray grid walls

    • 2, show cartesian axes from (0,0,0)

    • 3, show positive range of cartesian axes from (0,0,0)

    • 4, show a triad at bottom left

    • 5, show a cube at bottom left

    • 6, mark the corners of the bounding box

    • 7, draw a 3D ruler at each side of the cartesian axes

    • 8, show the VTK CubeAxesActor object

    • 9, show the bounding box outLine,

    • 10, show three circles representing the maximum bounding box,

    • 11, show a large grid on the x-y plane (use with zoom=8)

    • 12, show polar axes.

    • 13, draw a simple ruler at the bottom of the window

Axis type-1 can be fully customized by passing a dictionary axes=dict(). Check Axes() for the available options.

Parameters
  • sharecam (bool) – if False each renderer will have an independent vtkCamera

  • interactive (bool) – if True will stop after show() to allow interaction w/ window

  • offscreen (bool) – if True will not show the rendering window

  • qtWidget (QVTKRenderWindowInteractor) – render in a Qt-Widget using an QVTKRenderWindowInteractor. Overrides offscreen to True Overrides interactive to False See Also: examples qt_windows1.py and qt_windows2.py

multiwindows

add(actors, at=None, render=True, resetcam=False)[source]

Append input object to the internal list of actors to be shown.

Parameters
  • at (int) – add the object at the specified renderer

  • render (bool) – render the scene after adding the object

addButton(fnc, states=('On', 'Off'), c=('w', 'w'), bc=('dg', 'dr'), pos=(0.7, 0.05), size=24, font='Normografo', bold=False, italic=False, alpha=1, angle=0)[source]

Add a button to the renderer window.

Parameters
  • states (list) – a list of possible states, e.g. [‘On’, ‘Off’]

  • c – a list of colors for each state

  • bc – a list of background colors for each state

  • pos – 2D position in pixels from left-bottom corner

  • size – size of button font

  • font (str) – font type (arial, courier, times)

  • bold (bool) – bold face (False)

  • italic (bool) – italic face (False)

  • alpha (float) – opacity level

  • angle (float) – anticlockwise rotation in degrees

buttons.py buttons.py

addCallback(eventName, func, priority=0.0, verbose=False)[source]

Add a function to be executed while show() is active. Information about the event can be acquired with method getEvent().

Return a unique id for the callback.

The callback function (see example below) exposes a dictionary with the following information:

  • name: event name,

  • id: event unique identifier,

  • priority: event priority (float),

  • interactor: the interactor object,

  • at: renderer nr. where the event occured

  • actor: object picked by the mouse

  • picked3d: point picked in world coordinates

  • keyPressed: key pressed as string

  • picked2d: screen coords of the mouse pointer

  • delta2d: shift wrt previous position (to calculate speed, direction)

  • delta3d: …same but in 3D world coords

  • angle2d: angle of mouse movement on screen

  • speed2d: speed of mouse movement on screen

  • speed3d: speed of picked point in world coordinates

  • isPoints: True if of class

  • isMesh: True if of class

  • isAssembly: True if of class

  • isVolume: True if of class Volume

  • isPicture: True if of class

Frequently used events are:

  • KeyPress, KeyRelease: listen to keyboard events

  • LeftButtonPress, LeftButtonRelease: listen to mouse clicks

  • MiddleButtonPress, MiddleButtonRelease

  • RightButtonPress, RightButtonRelease

  • MouseMove: listen to mouse pointer changing position

  • MouseWheelForward, MouseWheelBackward

  • Enter, Leave: listen to mouse entering or leaving the window

  • Pick, StartPick, EndPick: listen to object picking

  • ResetCamera, ResetCameraClippingRange

  • Error, Warning

  • Char

  • Timer

Check the complete list of events here:

https://vtk.org/doc/nightly/html/classvtkCommand.html

Example
from vedo import *

def func(evt): # called every time the mouse moves
    # evt is a dotted dictionary
    if not evt.actor:
        return  # no hit, return
    print("point coords =", evt.picked3d)
    # print("full event dump:", evt)

elli = Ellipsoid()
plt = show(elli, axes=1, interactive=False)
plt.addCallback('MouseMove', func)
interactive()
addCutterTool(obj=None, mode='box', invert=False)[source]

Create an interactive tool to cut away parts of a mesh or volume.

Parameters
  • mode (str) – either “box”, “plane” or “sphere”

  • invert (bool) – invert selection (inside-out)

cutter.py cutter.py

addGlobalAxes(axtype=None, c=None)[source]

Draw axes on scene. Available axes types:

Parameters

axtype (int) –

  • 0, no axes,

  • 1, draw three gray grid walls

  • 2, show cartesian axes from (0,0,0)

  • 3, show positive range of cartesian axes from (0,0,0)

  • 4, show a triad at bottom left

  • 5, show a cube at bottom left

  • 6, mark the corners of the bounding box

  • 7, draw a 3D ruler at each side of the cartesian axes

  • 8, show the vtkCubeAxesActor object

  • 9, show the bounding box outLine

  • 10, show three circles representing the maximum bounding box

  • 11, show a large grid on the x-y plane

  • 12, show polar axes

  • 13, draw a simple ruler at the bottom of the window

Axis type-1 can be fully customized by passing a dictionary axes=dict().

Example
from vedo import Box, show
b = Box(pos=(0,0,0), length=80, width=90, height=70).alpha(0)

show(b, axes={ 'xtitle':'Some long variable [a.u.]',
               'numberOfDivisions':4,
               # ...
             }
)

customAxes1.py customAxes1.py customAxes2.py customAxes3.py

customIndividualAxes.py customIndividualAxes.py

addHoverLegend(at=0, c=None, pos='bottom-left', font='Calco', s=0.75, bg='auto', alpha=0.1, precision=2, maxlength=24, useInfo=False)[source]

Add a legend with 2D text which is triggered by hovering the mouse on an object.

The created text object are stored in plotter.hoverLegends.

Parameters
  • c – text color. If None then black or white is chosen automatically

  • pos (str) – text positioning

  • font (str) – text font

  • s (float) – text size factor

  • bg – background color of the 2D box containing the text

  • alpha (float) – box transparency

  • precision (int) – number of significant digits

  • maxlength (int) – maximum number of characters per line

  • useInfo (bool) – visualize the content of the obj.info attribute

addIcon(icon, pos=3, size=0.08)[source]

Add an inset icon mesh into the same renderer.

Parameters
  • pos – icon position in the range [1-4] indicating one of the 4 corners, or it can be a tuple (x,y) as a fraction of the renderer size.

  • size (float) – size of the square inset.

icon icon.py

addInset(*actors, **options)[source]

Add a draggable inset space into a renderer.

Parameters
  • at (int) – specify the renderer number

  • pos – icon position in the range [1-4] indicating one of the 4 corners, or it can be a tuple (x,y) as a fraction of the renderer size.

  • size (float) – size of the square inset.

  • draggable (bool) – if True the subrenderer space can be dragged around.

  • c – color of the inset frame when dragged

inset.py inset.py

addLegendBox(**kwargs)[source]

Add a legend to the top right

addRendererFrame(c=None, alpha=None, lw=None, pad=None)[source]

Add a frame to the renderer subwindow

Parameters
  • c (str, optional) – color name or index. The default is None.

  • alpha (float, optional) – opacity. The default is None.

  • lw (int, optional) – line width in pixels. The default is None.

  • pad (float, optional) – padding space. The default is None.

addSlider2D(sliderfunc, xmin, xmax, value=None, pos=4, title='', font='', titleSize=1, c=None, showValue=True, delayed=False)[source]

Add a slider widget which can call an external custom function.

Parameters
  • sliderfunc – external function to be called by the widget

  • xmin (float) – lower value

  • xmax (float) – upper value

  • value (float) – current value

  • pos (list) – position corner number: horizontal [1-5] or vertical [11-15] it can also be specified by corners coordinates [(x1,y1), (x2,y2)]

  • title (str) – title text

  • titleSize (float) – title text scale [1.0]

  • font (str) – title font [arial, courier]

  • showValue (bool) – if true current value is shown

  • delayed (bool) – if True the callback is delayed to when the mouse is released

sliders1.py sliders1.py sliders2.py

addSlider3D(sliderfunc, pos1, pos2, xmin, xmax, value=None, s=0.03, t=1, title='', rotation=0, c=None, showValue=True)[source]

Add a 3D slider widget which can call an external custom function.

Parameters
  • sliderfunc – external function to be called by the widget

  • pos1 (list) – first position coordinates

  • pos2 (list) – second position coordinates

  • xmin (float) – lower value

  • xmax (float) – upper value

  • value (float) – initial value

  • s (float) – label scaling factor

  • t (float) – tube scaling factor

  • title (str) – title text

  • c – slider color

  • rotation (float) – title rotation around slider axis

  • showValue (bool) – if True current value is shown

sliders3d.py sliders3d.py

addSplineTool(points, pc='k', ps=8, lc='r4', ac='g5', lw=2, closed=False, interactive=True)[source]

Add a spline tool to the current plotter. Nodes of the spline can be dragged in space with the mouse. Clicking on the line itself adds an extra point. Selecting a point and pressing del removes it.

Parameters
  • points (Mesh, Points, array) – the set of vertices forming the spline nodes.

  • pc (str, optional) – point color. The default is ‘k’.

  • ps (str, optional) – point size. The default is 8.

  • lc (str, optional) – line color. The default is ‘r4’.

  • ac (str, optional) – active point marker color. The default is ‘g5’.

  • lw (int, optional) – line width. The default is 2.

  • closed (bool, optional) – spline is meant to be closed. The default is False.

Returns

Return type

SplineTool object.

allowInteraction()[source]

Call this method from inside a loop to allow mouse and keyboard interaction.

background(c1=None, c2=None, at=None)[source]

Set the color of the background for the current renderer. A different renderer index can be specified by keyword at.

Parameters
  • c1 (list, optional) – background main color. The default is None.

  • c2 (list, optional) – background color for the upper part of the window. The default is None.

  • at (int, optional) – renderer index. The default is 0.

clear(actors=None, at=None)[source]

Delete specified list of actors, by default delete all.

close()[source]

Close the Plotter instance and release resources.

closeWindow()[source]

Close the current or the input rendering window.

computeWorldPosition(pos2d, at=0, objs=(), bounds=(), offset=None, pixeltol=None, worldtol=None)[source]

Transform a 2D point on the screen into a 3D point inside the rendering scene.

Parameters
  • pos2d (list) – 2D screen coordinates point.

  • at (int, optional) – renderer number. The default is 0.

  • objs (list, optional) – list of Mesh objects to project the point onto. The default is ().

  • bounds (list, optional) – specify a bounding box as [xmin,xmax, ymin,ymax, zmin,zmax]. The default is ().

  • offset (float, optional) – specify an offset value. The default is None (will use system defaults).

  • pixeltol (int, optional) – screen tolerance in pixels. The default is None (will use system defaults).

  • worldtol (float, optional) – world coordinates tolerance. The default is None (will use system defaults).

Returns

the point in 3D world coordinates.

Return type

numpy array

export(filename='scene.npz')[source]

Export scene to file to HTML, X3D or Numpy file.

flyTo(point, at=0)[source]

Fly camera to the specified point.

Parameters
  • point (list) – point in space to place camera.

  • at (int, optional) – Renderer number. The default is 0.

  • Example

    from vedo import Cone
    Cone().show(axes=1).flyTo([1,0,0]).show()
    

getMeshes(at=None, includeNonPickables=False)[source]

Return a list of Meshes from the specified renderer.

Parameters
  • at (int) – specify which renderer to look into.

  • includeNonPickables (bool) – include non-pickable objects

getVolumes(at=None, includeNonPickables=False)[source]

Return a list of Volumes from the specified renderer.

Parameters
  • at (int) – specify which renderer to look into.

  • includeNonPickables (bool) – include non-pickable objects

load(filename, unpack=True, force=False)[source]

Load objects from file. The output will depend on the file extension. See examples below.

Parameters
  • unpack (bool) – only for multiblock data, if True returns a flat list of objects.

  • force (bool) – when downloading a file ignore any previous cached downloads and force a new one.

Example
from vedo import *
# Return a list of 2 Mesh
g = load([dataurl+'250.vtk', dataurl+'290.vtk'])
show(g)
# Return a list of meshes by reading all files in a directory
# (if directory contains DICOM files then a Volume is returned)
g = load('mydicomdir/')
show(g)
# Return a Volume. Color/Opacity transfer function can be specified too.
g = load(dataurl+'embryo.slc')
g.c(['y','lb','w']).alpha((0.0, 0.4, 0.9, 1)).show()
moveCamera(camstart, camstop, fraction)[source]

Takes as input two vtkCamera objects and set camera at an intermediate position:

fraction=0 -> camstart, fraction=1 -> camstop.

camstart and camstop can also be dictionaries of format:

camstart = dict(pos=…, focalPoint=…, viewup=…, distance=…, clippingRange=…)

Press shift-C key in interactive mode to dump a python snipplet of parameters for the current camera view.

parallelProjection(value=True, at=0)[source]

Use parallel projection at a specified renderer. Object is seen from “infinite” distance, e.i. remove any perspective effects.

play(events='.vedo_recorded_events.log', repeats=0)[source]

Play camera, mouse, keystrokes and all other events.

Parameters
  • events (str, optional) – file o string of events. The default is ‘.vedo_recorded_events.log’.

  • repeats (int, optional) – number of extra repeats of the same events. The default is 0.

pop(at=0)[source]

Remove the last added object from the rendering window

record(filename='.vedo_recorded_events.log')[source]

Record camera, mouse, keystrokes and all other events. Recording can be toggled on/off by pressing key “R”.

Parameters

filename (str, optional) – ascii file to store events. The default is ‘.vedo_recorded_events.log’.

Returns

events – a string descriptor of events.

Return type

str

remove(actors, at=None, render=False, resetcam=False)[source]

Remove input object to the internal list of actors to be shown.

Parameters
  • at (int) – remove the object at the specified renderer

  • render (bool) – render the scene after removing the object

removeCallback(cid)[source]

Remove a callback function by its id or a whole category of callbacks by their name.

Parameters

cid (int,str) – unique id of the callback. If an event name is passed all callbacks of that type are removed

render(resetcam=False)[source]

Render the scene.

resetCamera()[source]

Reset the camera position and zooming.

screenshot(filename='screenshot.png', scale=None, returnNumpy=False)[source]

Take a screenshot of the Plotter window.

Parameters
  • scale (int) – set image magnification

  • returnNumpy (bool) – return a numpy array of the image

show(*actors, at=None, axes=None, resetcam=None, zoom=False, interactive=None, viewup='', azimuth=0, elevation=0, roll=0, camera=None, interactorStyle=0, mode=None, rate=None, bg=None, bg2=None, size=None, title=None, q=False)[source]

Render a list of actors.

If filename is given, its type is guessed based on its extension. Supported formats are: vtu, vts, vtp, ply, obj, stl, 3ds, xml, neutral, gmsh, pcd, xyz, txt, byu, tif, slc, vti, mhd, png, jpg. Otherwise it will be interpreted as a comment to appear on the top-left of the window.

Parameters
  • at (int) – number of the renderer to plot to, if more than one exists

  • shape (list) –

    Number of sub-render windows inside of the main window. Specify two across with shape=(2, 1) and a two by two grid with shape=(2, 2). By default there is only one renderer. Can also accept a shape as string descriptor. E.g.

    • shape=”3|1” means 3 plots on the left and 1 on the right,

    • shape=”4/2” means 4 plots on top of 2 at bottom.

  • axes (int) –

    set the type of axes to be shown

    • 0, no axes

    • 1, draw three customizable gray grid walls

    • 2, show cartesian axes from (0,0,0)

    • 3, show positive range of cartesian axes from (0,0,0)

    • 4, show a triad at bottom left

    • 5, show a cube at bottom left

    • 6, mark the corners of the bounding box

    • 7, draw a 3D ruler at each side of the cartesian axes

    • 8, show the vtkCubeAxesActor object

    • 9, show the bounding box outLine

    • 10, show three circles representing the maximum bounding box

    • 11, show a large grid on the x-y plane (use with zoom=8)

    • 12, show polar axes

    • 13, draw a simple ruler at the bottom of the window

  • azimuth/elevation/roll (float) – move camera accordingly

  • viewup (str) – either [‘x’, ‘y’, ‘z’] to set vertical direction

  • resetcam (bool) – re-adjust camera position to fit objects

  • camera (dict) –

    Camera parameters can further be specified with a dictionary assigned to the camera keyword (E.g. show(camera={‘pos’:(1,2,3), ‘thickness’:1000,}))

    • pos, (list), the position of the camera in world coordinates

    • focalPoint (list), the focal point of the camera in world coordinates

    • viewup (list), the view up direction vector for the camera

    • distance (float), set the focal point to the specified distance from the camera position.

    • clippingRange (float), distance of the near and far clipping planes along

      the direction of projection.

    • parallelScale (float),

      scaling used for a parallel projection, i.e. the height of the viewport in world-coordinate distances. The default is 1. Note that the “scale” parameter works as an “inverse scale”, larger numbers produce smaller images. This method has no effect in perspective projection mode.

    • thickness (float),

      set the distance between clipping planes. This method adjusts the far clipping plane to be set a distance ‘thickness’ beyond the near clipping plane.

    • viewAngle (float),

      the camera view angle, which is the angular height of the camera view measured in degrees. The default angle is 30 degrees. This method has no effect in parallel projection mode. The formula for setting the angle up for perfect perspective viewing is: angle = 2*atan((h/2)/d) where h is the height of the RenderWindow (measured by holding a ruler up to your screen) and d is the distance from your eyes to the screen.

  • interactive (bool) – pause and interact with window (True) or continue execution (False)

  • rate (float) – maximum rate of show() in Hertz

  • mode (int,str) – set the type of interaction - 0 = TrackballCamera [default] - 1 = TrackballActor - 2 = JoystickCamera - 3 = JoystickActor - 4 = Flight - 5 = RubberBand2D - 6 = RubberBand3D - 7 = RubberBandZoom - 8 = Context - 9 = 3D - 10 = Terrain - 11 = Unicam - 12 = Image

  • q (bool) – force program to quit after show() command returns.

timerCallback(action, timerId=None, dt=10, oneShot=False)[source]

Activate or destroy an existing Timer Event callback.

Parameters
  • action (str) – Either “create” or “destroy”.

  • timerId (int) – When destroying the timer, the ID of the timer as returned when created.

  • dt (int) – time in milliseconds between each repeated call

  • oneShot (bool) – create a one shot timer of prescribed duration instead of a repeating one.

topicture(scale=None)[source]

Generate a Picture object from the current rendering window.

Parameters

scale (int) – set image magnification

ProgressBar

class vedo.dolfin.ProgressBar(start, stop, step=1, c=None, bold=True, italic=False, title='', ETA=True, width=25, char='━', char_back='─')[source]

Bases: object

Class to print a progress bar with optional text message.

Example
import time
pb = ProgressBar(0,400, c='red')
for i in pb.range():
    time.sleep(.1)
    pb.print('some message')

progressbar

len()[source]

Return the number of steps.

print(txt='', counts=None, c=None)[source]

Print the progress bar and optional message.

range()[source]

Return the range iterator.

Text2D

class vedo.dolfin.Text2D(txt='', pos='top-left', s=1, c=None, alpha=0.1, bg=None, font='', justify='', bold=False, italic=False)[source]

Bases: vtkmodules.vtkRenderingCore.vtkActor2D, vedo.shapes.TextBase

Returns a 2D text object. All properties of the text, and the text itself, can be changed after creation (which is expecially useful in loops).

Parameters
  • pos

    text is placed in one of the 8 positions:

    bottom-left bottom-right top-left top-right bottom-middle middle-right middle-left top-middle

    If a pair (x,y) is passed as input the 2D text is place at that position in the coordinate system of the 2D screen (with the origin sitting at the bottom left).

  • s (float) – size of text.

  • bg – background color

  • alpha (float) – background opacity

  • justify (str) – text justification

  • font (str) –

    predefined available fonts are

    • Arial

    • Bongas

    • Calco

    • Comae

    • Courier

    • Glasgo

    • Kanopus

    • LionelOfParis

    • LogoType

    • Normografo

    • Quikhand

    • SmartCouric

    • Theemim

    • Times

    • VictorMono

    • More fonts at: https://vedo.embl.es/fonts/

    A path to a .otf or .ttf font-file can also be supplied as input.

pos(pos='top-left', justify='')[source]

Set position of the text to draw. Keyword pos can be a string or 2D coordinates in the range [0,1], being (0,0) the bottom left corner.

size(s)[source]
text(txt=None)[source]

Set/get the input text string

Text3D

class vedo.dolfin.Text3D(txt, pos=(0, 0, 0), s=1, font='', hspacing=1.15, vspacing=2.15, depth=0, italic=False, justify='bottom-left', c=None, alpha=1, literal=False)[source]

Bases: vedo.mesh.Mesh

Generate a 3D polygonal Mesh representing a text string.

Can render strings like 3.7 10^9 or H_2 O with subscripts and superscripts. Most Latex symbols are also supported (e.g. mu_lambda). Symbols ~ ^ _ are reserved modifiers:

use ~ to add a short space, 1/4 of the default empty space, use ^ and _ to start up/sub scripting, a space terminates their effect.

Monospaced fonts are: Calco, Glasgo, SmartCouric, VictorMono, Justino. More fonts at: https://vedo.embl.es/fonts/

Parameters
  • pos (list) – position coordinates in 3D space

  • s (float) – size of text.

  • depth (float) – text thickness.

  • italic (bool,float) – italic font type (can be a signed float too).

  • justify (str) – text justification as centering of the bounding box (bottom-left, bottom-right, top-left, top-right, centered).

  • font (str) – available 3D-polygonized fonts are Bongas, Calco, Comae, Kanopus, Glasgo, LionelOfParis, LogoType, Normografo, Quikhand, SmartCouric, Theemim, VictorMono, VTK, Capsmall, Cartoons123, PlanetBenson, Vega, Justino, Spears, Meson. Default is Normografo, which can be changed using settings.defaultFont

  • hspacing (float) – horizontal spacing of the font.

  • vspacing (float) – vertical spacing of the font for multiple lines text.

  • literal (bool) – if set to True will ignore modifiers like _ or ^

markpoint.py markpoint.py fonts.py captions.py

fontlist fonts3d caption.py

Video

class vedo.dolfin.Video(name='movie.mp4', duration=None, fps=24, backend='ffmpeg')[source]

Bases: object

Class to generate a video from the specified rendering window. Program ffmpeg is used to create video from each generated frame. :param str name: name of the output file. :param int fps: set the number of frames per second. :param float duration: set the total duration of the video and recalculates fps accordingly. :param str ffmpeg: set path to ffmpeg program. Default value assumes ffmpeg command is in the path.

makeVideo.py makeVideo.py

action(elevation_range=(0, 80), azimuth_range=(0, 359), zoom=None, cam1=None, cam2=None, resetcam=False)[source]

Automatic shooting of a static scene by specifying rotation and elevation ranges.

Parameters
  • elevation_range (list) – initial and final elevation angles

  • azimuth_range (list) – initial and final azimuth angles

  • zoom (float) – initial zooming

  • cam2 (cam1) – initial and final camera position, can be dictionary or a vtkCamera

addFrame()[source]

Add frame to current video.

close()[source]

Render the video and write to file. Return the current Plotter instance.

pause(pause=0)[source]

Insert a pause, in seconds.

clear

vedo.dolfin.clear(actor=None, at=None)[source]

Clear specific actor or list of actors from the current rendering window. Keyword at specify the reneder to be cleared.

download

vedo.dolfin.download(url, force=False, verbose=True)[source]

Retrieve a file from a url, save it locally and return its path.

embedWindow

vedo.dolfin.embedWindow(backend='ipyvtk', verbose=True)[source]

Use this function to control whether the rendering window is inside the jupyter notebook or as an independent external window

exportWindow

vedo.dolfin.exportWindow(fileoutput, binary=False)[source]

Exporter which writes out the renderered scene into an HTML, X3D or Numpy file.

export_x3d.py export_x3d.py

generated webpage

See also: FEniCS test webpage.

Note

the rendering window can also be exported to numpy file scene.npz by pressing E keyboard at any moment during visualization.

histogram

vedo.dolfin.histogram(*args, **kwargs)[source]

Histogramming for 1D and 2D data arrays.

For 1D arrays:

Parameters
  • bins (int) – number of bins.

  • vrange (list) – restrict the range of the histogram.

  • density (bool) – normalize the area to 1 by dividing by the nr of entries and bin size.

  • logscale (bool) – use logscale on y-axis.

  • fill (bool) – fill bars woth solid color c.

  • gap (float) – leave a small space btw bars.

  • outline (bool) – show outline of the bins.

  • errors (bool) – show error bars.

histo_1D.py histo_1D.py

If mode='polar' assume input is polar coordinate system (rho, theta):

Parameters
  • weights (list) – array of weights, of the same shape as the input. Each value only contributes its associated weight towards the bin count (instead of 1).

  • title (str) – histogram title

  • tsize (float) – title size

  • bins (int) – number of bins in phi

  • r1 (float) – inner radius

  • r2 (float) – outer radius

  • phigap (float) – gap angle btw 2 radial bars, in degrees

  • rgap (float) – gap factor along radius of numeric angle labels

  • lpos (float) – label gap factor along radius

  • lsize (float) – label size

  • c – color of the histogram bars, can be a list of length bins.

  • bc – color of the frame and labels

  • alpha – alpha of the frame

  • cmap (str) – color map name

  • deg (bool) – input array is in degrees

  • vmin (float) – minimum value of the radial axis

  • vmax (float) – maximum value of the radial axis

  • labels (list) – list of labels, must be of length bins

  • showDisc (bool) – show the outer ring axis

  • nrays (int) – draw this number of axis rays (continuous and dashed)

  • showLines (bool) – show lines to the origin

  • showAngles (bool) – show angular values

  • showErrors (bool) – show error bars

histo_polar.py histo_polar.py

For 2D arrays:

Input data formats [(x1,x2,..), (y1,y2,..)] or [(x1,y1), (x2,y2),..] are both valid.

Parameters
  • xtitle (str) – x axis title

  • ytitle (str) – y axis title

  • bins (list) – binning as (nx, ny)

  • vrange (list) – range in x and y in format [(xmin,xmax), (ymin,ymax)]

  • cmap (str) – color map name

  • lw (float) – line width of the binning

  • scalarbar (bool) – add a scalarbar

histo_2D.py histo_2D.py

If mode='hexbin', build a hexagonal histogram from a list of x and y values.

Parameters
  • xtitle (str) – x axis title

  • ytitle (str) – y axis title

  • bins (bool) – nr of bins for the smaller range in x or y.

  • vrange (list) – range in x and y in format [(xmin,xmax), (ymin,ymax)]

  • norm (float) – sets a scaling factor for the z axis (freq. axis).

  • fill (bool) – draw solid hexagons.

  • cmap (str) – color map name for elevation.

histo_hexagonal.py histo_hexagonal.py

If mode='spheric', build a histogram from list of theta and phi values.

Parameters
  • rmax (float) – maximum radial elevation of bin

  • res (int) – sphere resolution

  • cmap – color map name

  • lw (float) – line width of the bin edges

  • scalarbar (bool) – add a scalarbar to plot

histo_spheric.py histo_spheric.py

interactive

vedo.dolfin.interactive()[source]

Start the rendering window interaction mode.

load

vedo.dolfin.load(inputobj, unpack=True, force=False)[source]

Load Mesh, Volume and Picture objects from file or from the web.

The output will depend on the file extension. See examples below. Unzip on the fly, if it ends with .gz. Can load an object directly from a URL address.

Parameters
  • unpack (bool) – unpack MultiBlockData into a flat list of objects.

  • force (bool) – when downloading a file ignore any previous cached downloads and force a new one.

Examples
from vedo import dataurl, load, show

# Return a Mesh object
g = load(dataurl+'250.vtk')
show(g)

# Return a list of 2 meshes
g = load([dataurl+'250.vtk', dataurl+'270.vtk'])
show(g)

# Return a list of meshes by reading all files in a directory
# (if directory contains DICOM files then a Volume is returned)
g = load('mydicomdir/')
show(g)

# Return a Volume. Color/Opacity transfer functions can be specified later.
g = load(dataurl+'embryo.slc')
g.c(['y','lb','w']).alpha((0.0, 0.4, 0.9, 1)).show()

# Download a file from a URL address and unzip it on the fly
g = load('https://vedo.embl.es/examples/panther.stl.gz')
show(g)

plot

vedo.dolfin.plot(*inputobj, **options)[source]

Plot the object(s) provided.

Input can be any combination of: Mesh, Volume, dolfin.Mesh, dolfin.MeshFunction, dolfin.Expression or dolfin.Function.

Returns

the current Plotter class instance.

Parameters
  • mode (str) –

    one or more of the following can be combined in any order

    • mesh/color, will plot the mesh, by default colored with a scalar if available

    • displacement show displaced mesh by solution

    • arrows, mesh displacements are plotted as scaled arrows.

    • lines, mesh displacements are plotted as scaled lines.

    • tensors, to be implemented

  • add (bool) – add the input objects without clearing the already plotted ones

  • density (float) – show only a subset of lines or arrows [0-1]

  • wire[frame] (bool) – visualize mesh as wireframe [False]

  • c[olor] – set mesh color [None]

  • exterior (bool) – only show the outer surface of the mesh [False]

  • alpha (float) – set object’s transparency [1]

  • lw (float) – line width of the mesh (set to zero to hide mesh) [0.5]

  • ps (float) – set point size of mesh vertices [None]

  • z (float) – add a constant to z-coordinate (useful to show 2D slices as function of time)

  • legend (str) – add a legend to the top-right of window [None]

  • scalarbar (bool) – add a scalarbar to the window [‘vertical’]

  • vmin (float) – set the minimum for the range of the scalar [None]

  • vmax (float) – set the maximum for the range of the scalar [None]

  • scale (float) – add a scaling factor to arrows and lines sizes [1]

  • cmap (str) – choose a color map for scalars

  • shading (str) – mesh shading [‘flat’, ‘phong’, ‘gouraud’]

  • text (str) – add a gray text comment to the top-left of the window [None]

  • isolines (dict) –

    dictionary of isolines properties

    • n, (int) - add this number of isolines to the mesh

    • c, - isoline color

    • lw, (float) - isoline width

    • z, (float) - add to the isoline z coordinate to make them more visible

  • streamlines (dict) –

    dictionary of streamlines properties

    • probes, (list, None) - custom list of points to use as seeds

    • tol, (float) - tolerance to reduce the number of seed points used in mesh

    • lw, (float) - line width of the streamline

    • direction, (str) - direction of integration (‘forward’, ‘backward’ or ‘both’)

    • maxPropagation, (float) - max propagation of the streamline

    • scalarRange, (list) - scalar range of coloring

  • warpZfactor (float) – elevate z-axis by scalar value (useful for 2D geometries)

  • warpYfactor (float) – elevate z-axis by scalar value (useful for 1D geometries)

  • scaleMeshFactors (list) – rescale mesh by these factors [1,1,1]

  • new (bool) – spawn a new instance of Plotter class, pops up a new window

  • at (int) – renderer number to plot to

  • shape (list) – subdvide window in (n,m) rows and columns

  • N (int) – automatically subdvide window in N renderers

  • pos (list) – (x,y) coordinates of the window position on screen

  • size – window size (x,y)

  • title (str) – window title

  • bg – background color name of window

  • bg2 – second background color name to create a color gradient

  • style (int) –

    choose a predefined style [0-4]

    • 0, vedo, style (blackboard background, rainbow color map)

    • 1, matplotlib, style (white background, viridis color map)

    • 2, paraview, style

    • 3, meshlab, style

    • 4, bw, black and white style.

  • axes (int) –

    axes type number

    • 0, no axes,

    • 1, draw customizable grid axes (see below).

    • 2, show cartesian axes from (0,0,0)

    • 3, show positive range of cartesian axes from (0,0,0)

    • 4, show a triad at bottom left

    • 5, show a cube at bottom left

    • 6, mark the corners of the bounding box

    • 7, draw a simple ruler at the bottom of the window

    • 8, show the vtkCubeAxesActor object,

    • 9, show the bounding box outLine,

    • 10, show three circles representing the maximum bounding box,

    • 11, show a large grid on the x-y plane (use with zoom=8)

    • 12, show polar axes.

Axes type-1 can be fully customized by passing a dictionary axes=dict().

Parameters
  • infinity (bool) – if True fugue point is set at infinity (no perspective effects)

  • sharecam (bool) – if False each renderer will have an independent vtkCamera

  • interactive (bool) – if True will stop after show() to allow interaction w/ window

  • offscreen (bool) – if True will not show the rendering window

  • zoom (float) – camera zooming factor

  • viewup – camera view-up direction [‘x’,’y’,’z’, or a vector direction]

  • azimuth (float) – add azimuth rotation of the scene, in degrees

  • elevation (float) – add elevation rotation of the scene, in degrees

  • roll (float) – add roll-type rotation of the scene, in degrees

  • camera (dict) –

    Camera parameters can further be specified with a dictionary assigned to the camera keyword: (E.g. show(camera={‘pos’:(1,2,3), ‘thickness’:1000,}))

    • pos, (list),

      the position of the camera in world coordinates

    • focalPoint, (list),

      the focal point of the camera in world coordinates

    • viewup, (list),

      the view up direction for the camera

    • distance, (float),

      set the focal point to the specified distance from the camera position.

    • clippingRange, (float),

      distance of the near and far clipping planes along the direction of projection.

    • parallelScale, (float),

      scaling used for a parallel projection, i.e. the height of the viewport in world-coordinate distances. The default is 1. Note that the “scale” parameter works as an “inverse scale”, larger numbers produce smaller images. This method has no effect in perspective projection mode.

    • thickness, (float),

      set the distance between clipping planes. This method adjusts the far clipping plane to be set a distance ‘thickness’ beyond the near clipping plane.

    • viewAngle, (float),

      the camera view angle, which is the angular height of the camera view measured in degrees. The default angle is 30 degrees. This method has no effect in parallel projection mode. The formula for setting the angle up for perfect perspective viewing is: angle = 2*atan((h/2)/d) where h is the height of the RenderWindow (measured by holding a ruler up to your screen) and d is the distance from your eyes to the screen.

  • interactorStyle (int) – change the style of muose interaction of the scene

  • q (bool) – exit python session after returning.

printHistogram

vedo.dolfin.printHistogram(data, bins=10, height=10, logscale=False, minbin=0, horizontal=False, char='▉', c=None, bold=True, title='Histogram')[source]

Ascii histogram printing. Input can also be Volume or Mesh. Returns the raw data before binning (useful when passing vtk objects).

Parameters
  • bins (int) – number of histogram bins

  • height (int) – height of the histogram in character units

  • logscale (bool) – use logscale for frequencies

  • minbin (int) – ignore bins before minbin

  • horizontal (bool) – show histogram horizontally

  • char (bool) – character to be used

  • c (str,int) – ascii color

  • char – use boldface

  • title (str) – histogram title

Example
from vedo import printHistogram
import np as np
d = np.random.normal(size=1000)
data = printHistogram(d, c='blue', logscale=True, title='my scalars')
data = printHistogram(d, c=1, horizontal=1)
print(np.mean(data)) # data here is same as d

printhisto

printc

vedo.dolfin.printc(*strings, c=None, bc=None, bold=True, italic=False, blink=False, underline=False, strike=False, dim=False, invert=False, box='', end='\n', flush=True)[source]

Print to terminal in color (any color!).

Parameters
  • c – foreground color name or (r,g,b)

  • bc – background color name or (r,g,b)

  • bold (bool) – boldface [True]

  • italic (bool) – italic [False]

  • blink (bool) – blinking text [False]

  • underline (bool) – underline text [False]

  • strike (bool) – strike through text [False]

  • dim (bool) – make text look dimmer [False]

  • invert (bool) – invert background and forward colors [False]

  • box – print a box with specified text character [‘’]

  • flush (bool) – flush buffer after printing [True]

  • end (str) – the end character to be printed [newline]

Example
from vedo.colors import printc
printc('anything', c='tomato', bold=False, end=' ')
printc('anything', 455.5, c='lightblue')
printc(299792.48, c=4)

colorprint.py printc.py

screenshot

vedo.dolfin.screenshot(filename='screenshot.png', scale=None, returnNumpy=False)[source]

Save a screenshot of the current rendering window.

Parameters
  • scale (int) – set image magnification

  • returnNumpy (bool) – return a numpy array of the image

show

vedo.dolfin.show(*actors, at=None, shape=(1, 1), N=None, pos=(0, 0), size='auto', screensize='auto', title='vedo', bg='white', bg2=None, axes=None, interactive=None, offscreen=False, sharecam=True, resetcam=True, zoom=None, viewup='', azimuth=0, elevation=0, roll=0, camera=None, interactorStyle=0, mode=None, q=False, new=False)[source]

Create on the fly an instance of class Plotter and show the object(s) provided.

Allowed input objects types are: str, Mesh, Volume, Picture, Assembly vtkPolyData, vtkActor, vtkActor2D, vtkImageActor, vtkAssembly or vtkVolume.

If filename is given, its type is guessed based on its extension. Supported formats are: vtu, vts, vtp, ply, obj, stl, 3ds, xml, neutral, gmsh, pcd, xyz, txt, byu, tif, slc, vti, mhd, png, jpg.

Parameters
  • at (int) – number of the renderer to plot to, if more than one exists

  • shape (list) –

    Number of sub-render windows inside of the main window. Specify two across with shape=(2, 1) and a two by two grid with shape=(2, 2). By default there is only one renderer. Can also accept a shape as string descriptor. E.g.:

    • shape=”3|1” means 3 plots on the left and 1 on the right,

    • shape=”4/2” means 4 plots on top of 2 at bottom.

  • axes (int) –

    set the type of axes to be shown

    • 0, no axes

    • 1, draw three gray grid walls

    • 2, show cartesian axes from (0,0,0)

    • 3, show positive range of cartesian axes from (0,0,0)

    • 4, show a triad at bottom left

    • 5, show a cube at bottom left

    • 6, mark the corners of the bounding box

    • 7, draw a 3D ruler at each side of the cartesian axes

    • 8, show the vtkCubeAxesActor object

    • 9, show the bounding box outLine

    • 10, show three circles representing the maximum bounding box

    • 11, show a large grid on the x-y plane

    • 12, show polar axes

    • 13, draw a simple ruler at the bottom of the window

    Axis type-1 can be fully customized by passing a dictionary axes=dict() where: Check addons.Axes() for the full list of options.

  • azimuth/elevation/roll (float) – move camera accordingly

  • viewup (str) – either [‘x’, ‘y’, ‘z’] or a vector to set vertical direction

  • resetcam (bool) – re-adjust camera position to fit objects

  • camera (dict) –

    Camera parameters can further be specified with a dictionary assigned to the camera keyword (E.g. show(camera={‘pos’:(1,2,3), ‘thickness’:1000,}))

    • pos, (list), the position of the camera in world coordinates

    • focalPoint (list), the focal point of the camera in world coordinates

    • viewup (list), the view up direction for the camera

    • distance (float), set the focal point to the specified distance from the camera position.

    • clippingRange (float), distance of the near and far clipping planes along the direction

      of projection.

    • parallelScale (float),

      scaling used for a parallel projection, i.e. the height of the viewport in world-coordinate distances. The default is 1. Note that the “scale” parameter works as an “inverse scale”, larger numbers produce smaller images. This method has no effect in perspective projection mode.

    • thickness (float),

      set the distance between clipping planes. This method adjusts the far clipping plane to be set a distance ‘thickness’ beyond the near clipping plane.

    • viewAngle (float),

      the camera view angle, which is the angular height of the camera view measured in degrees. The default angle is 30 degrees. This method has no effect in parallel projection mode. The formula for setting the angle up for perfect perspective viewing is: angle = 2*atan((h/2)/d) where h is the height of the RenderWindow (measured by holding a ruler up to your screen) and d is the distance from your eyes to the screen.

  • interactive (bool) – pause and interact with window (True) or continue execution (False)

  • rate (float) – maximum rate of show() in Hertz

  • mode (int) –

    set the type of interaction

    • 0 = TrackballCamera [default]

    • 1 = TrackballActor

    • 2 = JoystickCamera

    • 3 = JoystickActor

    • 4 = Flight

    • 5 = RubberBand2D

    • 6 = RubberBand3D

    • 7 = RubberBandZoom

    • 8 = Context

    • 9 = 3D

    • 10 = Terrain

    • 11 = Unicam

  • q (bool) – force program to quit after show() command returns.

  • new (bool) – if set to True, a call to show will instantiate a new Plotter object (a new window) instead of reusing the first created.

Returns

the current Plotter class instance.

Note

With multiple renderers, keyword at can become a list, e.g.

from vedo import *
s = Sphere()
c = Cube()
p = Paraboloid()
show(s, c, at=[0, 1], shape=(3,1))
show(p, at=2, interactive=True)
#
# is equivalent to:
plt = Plotter(shape=(3,1))
s = Sphere()
c = Cube()
p = Paraboloid()
plt.show(s, at=0)
plt.show(p, at=1)
plt.show(c, at=2, interactive=True)