lavavu module

LavaVu python interface: viewer utils & wrapper

This module provides an interface to the LavaVu library allowing loading of data, rendering of static images, animation and interactive visualisation

To create an instance of the LavaVu rendering engine, use the Viewer() class, e.g.

>>> import lavavu
>>> lv = lavavu.Viewer()

See the lavavu.Viewer class documentation for more information.

Module Summary

functions:

lavavu.download

Download a file from an internet URL

lavavu.grid2d

Generate a 2d grid of vertices

lavavu.grid3d

Generate a 2d grid of vertices in 3d space

lavavu.cubehelix

Create CubeHelix spectrum colourmap with monotonically increasing/descreasing intensity

lavavu.loadCPT

Create a colourmap from a CPT colour table file

lavavu.matplotlib_colourmap

Import a colourmap from a matplotlib

lavavu.printH5

Print info about HDF5 data set (requires h5py)

lavavu.lerp

Linear Interpolation between values of two lists

lavavu.player

Shows a video inline within an ipython notebook.

lavavu.inject

Inject HTML into a notebook cell

lavavu.hidecode

Allow toggle of code cells

lavavu.style

Inject stylesheet

lavavu.cellstyle

Override the notebook cell styles

lavavu.cellwidth

Override the notebook cell width

lavavu.is_ipython

Detects if running within IPython environment

lavavu.is_notebook

Detects if running within an interactive IPython notebook environment

lavavu.getname

Attempt to find the name of a variable from the main module namespace

classes:

lavavu.Viewer

The Viewer class provides an interface to a LavaVu session

lavavu.Object

The Object class provides an interface to a LavaVu drawing object Object instances are created internally in the Viewer class and can be retrieved from the object list

lavavu.Properties

The Properties class provides an interface to a collection of properties with a control factory, allowing controls to be created to manipulate their values interactively Properties can be passed in when created or set by using as a dictionary:

lavavu.ColourMap

The ColourMap class provides an interface to a LavaVu ColourMap ColourMap instances are created internally in the Viewer class and can be retrieved from the colourmaps list

lavavu.DrawData

The DrawData class provides an interface to a single object data element DrawData instances are created internally from the Geometry class

lavavu.Figure

The Figure class wraps a set of visualisation state data, providing a way of managing a collection of preset visualisations or "figures" of a single model

lavavu.Geometry

The Geometry class provides an interface to a drawing object's internal data Geometry instances are created internally in the Object class with the data property

lavavu.Image

The Image class provides an interface to a raw image

lavavu.Video

The Video class provides an interface to record animations

Module Details

functions:

download(url, filename=None, overwrite=False, quiet=False)[source]

Download a file from an internet URL

Parameters:
  • url (str) – URL to request the file from

  • filename (str) – Filename to save, default is to keep the same name in current directory

  • overwrite (boolean) – Always overwrite file if it exists, default is to never overwrite

Returns:

filename – Actual filename written to local filesystem

Return type:

str

grid2d(corners=((0.0, 1.0), (1.0, 0.0)), dims=[2, 2])[source]

Generate a 2d grid of vertices

Parameters:
  • corners (tuple or list) – top left and bottom right corner vertices (2d)

  • dims (tuple or list) – dimensions of grid nodes, number of vertices to generate in each direction

Returns:

vertices – The 2d vertices of the generated grid

Return type:

array

grid3d(corners=((0.0, 1.0, 0.0), (1.0, 1.0, 0.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0)), dims=[2, 2])[source]

Generate a 2d grid of vertices in 3d space

Parameters:
  • corners (tuple or list) – 3 or 4 corner vertices (3d)

  • dims (tuple or list) – dimensions of grid nodes, number of vertices to generate in each direction

Returns:

vertices – The 3d vertices of the generated 2d grid

Return type:

array

cubehelix(samples=16, start=0.5, rot=-0.9, sat=1.0, gamma=1.0, alpha=None)[source]

Create CubeHelix spectrum colourmap with monotonically increasing/descreasing intensity

Implemented from FORTRAN 77 code from D.A. Green, 2011, BASI, 39, 289. “A colour scheme for the display of astronomical intensity images” http://adsabs.harvard.edu/abs/2011arXiv1108.5083G

Parameters:
  • samples (int) – Number of colour samples to produce

  • start (float) – Start colour [0,3] 1=red,2=green,3=blue

  • rot (float) – Rotations through spectrum, negative to reverse direction

  • sat (float) – Colour saturation grayscale to full [0,1], >1 to oversaturate

  • gamma (float) – Gamma correction [0,1]

  • alpha (list or tuple) – Alpha [min,max] for transparency ramp

Returns:

List of colours ready to be loaded by colourmap()

Return type:

list

loadCPT(fn, positions=True)[source]

Create a colourmap from a CPT colour table file

Parameters:

positions (boolean) – Set this to false to ignore any positional data and load only the colours from the file

Returns:

colours – Colour string ready to be loaded by colourmap()

Return type:

string

matplotlib_colourmap(name, samples=16)[source]

Import a colourmap from a matplotlib

Parameters:
  • name (str) – Name of the matplotlib colourmap preset to import

  • samples (int) – Number of samples to take for LinearSegmentedColormap type

Returns:

List of colours ready to be loaded by colourmap()

Return type:

list

printH5(h5)[source]

Print info about HDF5 data set (requires h5py)

Parameters:

h5 – HDF5 Dataset loaded with h5py

lerp(first, second, mu)[source]

Linear Interpolation between values of two lists

Parameters:
  • first (tuple or list) – first list of values

  • second (tuple or list) – second list of values

  • mu (float) – Interpolation factor [0,1]

Returns:

A list of the interpolated values

Return type:

list

player(filename, width=None, height=None, params='', nocache=True)[source]

Shows a video inline within an ipython notebook. If IPython is not running, just returns

Parameters:
  • filename (str) – Path and name of the file to play

  • width (int) – Fixed width of player window, otherwise will use video resolution

  • height (int) – Fixed height of player window, otherwise will use video resolution

  • params (str) – Any other parameters to add to the <video> tag, eg: “autoplay”

  • nocache (bool) – Add a timestamp to the filename url to prevent caching

inject(html)[source]

Inject HTML into a notebook cell

hidecode()[source]

Allow toggle of code cells

style(css)[source]

Inject stylesheet

cellstyle(css)[source]

Override the notebook cell styles

cellwidth(width='99%')[source]

Override the notebook cell width

is_ipython()[source]

Detects if running within IPython environment

Returns:

True if IPython detected Does not necessarrily indicate running within a browser / notebook context

Return type:

boolean

is_notebook()[source]

Detects if running within an interactive IPython notebook environment

Returns:

True if IPython detected and browser/notebook display capability detected

Return type:

boolean

getname(var)[source]

Attempt to find the name of a variable from the main module namespace

Parameters:

var – The variable in question

Returns:

name – Name of the variable

Return type:

str

classes:

class Viewer(*args, resolution=None, binpath=None, context='default', port=8080, threads=False, **kwargs)[source]

Bases: dict

The Viewer class provides an interface to a LavaVu session

Parameters:
  • arglist (list) – list of additional init arguments to pass

  • database (str) – initial database (or model) file to load

  • figure (int) – initial figure id to display

  • timestep (int) – initial timestep to display

  • verbose (boolean) – verbose output to command line for debugging

  • interactive (boolean) – begin in interactive mode, opens gui window and passes control to event loop immediately

  • hidden (boolean) – begin hidden, for offscreen rendering or web browser control

  • cache (boolean) – cache all model timesteps in loaded database, everything loaded into memory on startup (assumes enough memory is available)

  • quality (int) – Render sampling quality, render 2^N times larger image and downsample output For anti-aliasing image rendering where GPU multisample anti-aliasing is not available

  • writeimage (boolean) – Write images and quit, create images for all figures/timesteps in loaded database then exit

  • script (list) – List of script commands to run after initialising

  • initscript (boolean) – Set to False to disable loading any “init.script” file found in current directory

  • usequeue (boolean) – Set to True to add all commands to a background queue for processing rather than immediate execution

  • **kwargs – Remaining keyword args will be passed to the created viewer and parsed into the initial set of global properties

Example

Create a viewer, setting the initial background colour to white

>>> import lavavu
>>> lv = lavavu.Viewer(background="white")

Objects can be added by loading files: #>>> lavavu.download(source + ‘Mandible.obj’) # doctest: +ELLIPSIS

>>> import lavavu
>>> obj = lv.file('model.obj') 

Or creating empty objects and loading data:

>>> obj = lv.points('mypoints')
>>> obj.vertices([[0,0,0], [1,1,1]])

Viewer commands can be called as methods on the viewer object:

>>> lv.rotate('x', 45)

Viewer properties can be set by using it like a dictionary:

>>> lv["background"] = "grey50"

A list of available commands and properties can be found in the docs

or by using the online help:

>>> lv.help('rotate') 
>>> lv.help('opacity') 
(...)
ColourMap(identifier=None, **kwargs)[source]

Get or create a colourmap

Parameters:
  • identifier (str or int or Object, optional) – If a string, lookup an object by name If a number, lookup object by index If an object reference, lookup the Object by reference If omitted, return the last object in the list If no matching object found and string identifier provided, creates an empty object

  • **kwargs – Set of properties passed to the object

Returns:

obj – The object located

Return type:

Object

Figure(name, objects=None, **kwargs)[source]

Create a figure

Parameters:
  • name (str) – Name of the figure

  • objects (list) – List of objects or object names to include in the figure, others will be hidden

Returns:

figure – Figure object

Return type:

Figure

Object(identifier=None, **kwargs)[source]

Get or create a visualisation object

Parameters:
  • identifier (str or int or Object, optional) – If a string, lookup an object by name If a number, lookup object by index If an object reference, lookup the Object by reference If omitted, return the last object in the list If no matching object found and string identifier provided, creates an empty object

  • **kwargs – Set of properties passed to the object

Returns:

obj – The object located/created

Return type:

Object

Properties(callback=None, **kwargs)[source]

Create a property collection, essentially a dict() but with a control factory that allows creation of interactive controls to edit the properties

Parameters:
  • callback (function) – Optional function to call whenever a property in this collection is changed by an interactive control The function should take one argument, the collection of type lavavu.Properties() and will be called, with the new values whenever the control value is updated.

  • **kwargs – Set of initial properties to store in the collection

Returns:

props – The collection created

Return type:

Properties

__call__(cmds)[source]

Run a LavaVu script

Parameters:

cmds (str) – String containing commands to run, separate commands with semi-colons”

Example

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> lv.test()
>>> lv('reset; translate -2')
>>> print(lv['translate'])
[-2.0, 0.0, -6.928203105926514]
__init__(*args, resolution=None, binpath=None, context='default', port=8080, threads=False, **kwargs)[source]

Create and init viewer instance

Parameters:
  • args) ((see Viewer class docs for setup) –

  • resolution (list, tuple) – Window/image resolution in pixels [x,y] For off-screen/windowless rendering this sets the default image output and viewer widget size For interactive windows this sets the window size.

  • binpath (str) – Override the executable path

  • context (str) – OpenGL context type, “default” will create a context and window based on available configurations. “provided” specifies a user provided context, set this if you have already created and activated the context. “moderngl” creates a context in python using the moderngl module (experimental). “moderngl.” creates a context and a window in python using the moderngl module (experimental) specify class after separator, eg: moderngl.headless, moderngl.pyglet, moderngl.pyqt5.

  • port (int) – Web server port, open server on specific port for control/interaction Viewer will be run in a separate thread, all rendering will be done in this thread When disabled (None) creates the viewer in the current(main) thread and disables the server

  • threads (bool) – Use threads instead of asyncio

add(name=None, **kwargs)[source]

Add a visualisation object

Parameters:

name (str) – Name to apply to the created object If an object of this name exists, it will be returned instead of created

Returns:

obj – The object created

Return type:

Object

addstep(step=-1, **kwargs)[source]

Add a new time step

Parameters:
  • step (int, optional) – Time step number, default is current + 1

  • **kwargs – Timestep specific properties passed to the created object

args(*args, arglist=None, database=None, figure=None, timestep=None, verbose=False, interactive=False, hidden=True, cache=False, quality=3, writeimage=False, resolution=None, script=None, initscript=False, usequeue=False, **kwargs)[source]

Execute the viewer, initialising with provided arguments and entering event loop if requested

Parameters: see __init__ docs

args : passed directly to viewer, eg: filenames or initial script commands kwargs: parsed as below to specific switches

browser(resolution=None, inline=True)[source]

Open web server browser interface

camera(data=None)[source]

Get/set the current camera viewpoint

Displays and returns camera in python form that can be pasted and executed to restore the same camera view

Parameters:

data (dict) – Camera view to apply if any

Returns:

result – Current camera view or previous if applying a new view

Return type:

dict

clear(objects=True, colourmaps=True)[source]

Clears all data from the visualisation Including objects and colourmaps by default

Parameters:
  • objects (boolean) – including all objects, if set to False will clear the objects but not delete them

  • colourmaps (boolean) – including all colourmaps

colourbar(obj=None, **kwargs)[source]

Create a new colourbar

Parameters:

obj (Object, optional) – Vis object the colour bar applies to

Returns:

colourbar – The colourbar object created

Return type:

Object

colourmap(data=None, name='', reverse=False, monochrome=False, **kwargs)[source]

Load or create a colour map

Parameters:
  • name (str) – Name of the colourmap, if this colourmap name is found the data will replace the existing colourmap, otherwise a new colourmap will be created

  • data (list or str) – Provided colourmap data can be - a string, - list of colour strings, - list of position,value tuples - or a built in colourmap name If none provided, a default colourmap will be loaded from lavavu.cubehelix()

  • reverse (boolean) – Reverse the order of the colours after loading

  • monochrome (boolean) – Convert to greyscale

Returns:

The wrapper object of the colourmap loaded/created

Return type:

ColourMap(dict)

property colourmaps

Returns the list of active colourmaps

Returns:

colourmaps – A dictionary containing the available colourmaps as ColourMap() wrapper objects

Return type:

dict

commands(cmds, queue=False)[source]

Execute viewer commands https://lavavu.github.io/Documentation/Scripting-Commands-Reference These commands can also be executed individually by calling them as methods of the viewer object

Parameters:

cmds (list or str) – Command(s) to execute

connect()[source]

Provides the link to open an external interactive window

defaultcolourmap(name)[source]

Get content of a default colour map

Parameters:

name (str) – Name of the built in colourmap to return

Returns:

Colourmap data formatted as a string

Return type:

str

defaultcolourmaps()[source]

Get the list of default colour map names

Returns:

colourmaps – Names of all predefined colour maps

Return type:

list of str

display(resolution=(0, 0), transparent=False, filename='*')[source]

Show the current display as inline image within an ipython notebook.

If IPython is installed, displays the result image content inline

If IPython is not installed, will save the result with a default filename in the current directory

Parameters:
  • resolution (list or tuple) – Image resolution in pixels [x,y]

  • transparent (boolean) – Creates a PNG image with a transparent background

  • filename (str) – Name of the file to save when not running in IPython (should be .jpg or .png) Defaults to an autogenerated filename in current directory.

events()[source]

Process input events allows running interactive event loop while animating from python e.g.

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> def event_loop():
...     while lv.events():
...         #...build next frame here...
...         lv.render()
... event_loop() 
Returns:

False if user quit program, True otherwise

Return type:

boolean

exec_webgl(code, ID=None)[source]

Runs code to act on the active (last) webgl viewer object

The viewer will be available in the variable ‘viewer’ by inserting code before the provided JavaScript, allowing execution of viewer functions in the following script

Parameters:
  • code (str) – A JavaScript string to execute after getting the viewer object

  • ID (int) – A specific webgl ID number, if multiple are active this allows specifying which to execute code with, the first being ID=0

export(filepath='exported.gldb', objects=None, compress=None)[source]

Export model and state to a database snapshot

Parameters:
  • filepath (str) – Filename to export, defaults to exported.gldb

  • objects (list[str]) – List of object names to export

  • compress (int) – Set flag override default zlib compression of database (0=None, 1=fast, 6=standard, 9=best compression)

export_mesh(filepath, objects=None, rgba=True)[source]

Use trimesh to export mesh objects to a supported format, eg: GLTF (.glb)

See: https://trimsh.org/trimesh.exchange.html Requires “trimesh” module Supports triangle mesh object data

Parameters:
  • filepath (str) – Output file to write

  • objects (list) – Objects to export, defaults to all

  • rgba (bool) – If set, convert colourmap/value data to rgba before export

property figures

Retrieve the saved figures from loaded model Dict returned contains Figure objects which can be used to modify the figure

Returns:

figures – A dictionary of all available figures by name

Return type:

dict

file(filename, obj=None, **kwargs)[source]

Load a database or model file

Parameters:
  • filename (str) – Name of the file to load

  • obj (Object) – Vis object to load the file data into, if not provided a default will be created

files(files, obj=None, **kwargs)[source]

Load data from a series of files (using wildcards or a list)

Parameters:
  • files (str) – Specification of the files to load, either a list of full paths or a file spec string such as *.gldb

  • obj (Object) – Vis object to load the data into, if not provided a default will be created

frame(resolution=None, quality=90)[source]

Get an image frame, returns current display as base64 encoded jpeg data url

Parameters:
  • resolution (list or tuple) – Image resolution in pixels [x,y]

  • quality (int) – Quality for JPEG image compression, default 90%

Returns:

image – encoded image as string data

Return type:

str

get_all_vertices(objectlist=None, values=None)[source]

Extract all vertex data from a list of objects

Parameters:
  • objectlist (list) – List of objects, defaults to all

  • values (str) – Optional label of a value data set to collect alongside the vertices

Returns:

  • pverts (array) – the vertices, numpy array

  • bb_all (tuple) – the bounding box of the combined data

  • pvals (array) – the values, numpy array (only returned if values != None)

getcolourmap(mapid, string=True)[source]

Return colour map data as a string or list Either return format can be used to create/modify a colourmap with colourmap()

Parameters:
  • mapid (str or int) – Name or index of the colourmap to retrieve

  • string (boolean) – The default is to return the data as a string of colours separated by semi-colons To instead return a list of (position,[R,G,B,A]) tuples for easier automated processing in python, set this to False

Returns:

mapdata – The formatted colourmap data

Return type:

str or list

getview()[source]

Get current view settings

Returns:

view – json string containing saved view settings

Return type:

str

property gl

Return GL version string

help(cmd='', obj=None)[source]

Get help on a command or property

Parameters:

cmd (str) – Command to get help with, if ommitted displays general introductory help If cmd is a property or is preceded with ‘@’ will display property help

image(filename='', resolution=None, transparent=False, quality=95)[source]

Save or get an image of current display

Parameters:
  • filename (str) – Name of the file to save (should be .jpg or .png), if not provided the image will be returned as a base64 encoded data url

  • resolution (list or tuple) – Image resolution in pixels [x,y]

  • transparent (boolean) – Creates a PNG image with a transparent background

  • quality (int) – Quality for JPEG image compression, default 95%

Returns:

image – filename of saved image or encoded image as string data

Return type:

str

init()[source]

Re-initialise the viewer window

interact(local=False, loop=False)[source]

Opens an external interactive window in a separate web browser tab/window

Parameters:
  • local (boolean) – If local is True will use the webbrowser module to open a browser window. If False, attempts to open a popup window and provides a link for the user to open the window

  • loop (boolean) – If loop is True and run from a python script instead of a notebook, this starts an event handling loop which blocks python execution until the window is closed

interactive(args=None)[source]

Open an interactive native window

WARNING: On MacOS this function will never return until the window closes

jpeg(resolution=None, quality=90)[source]

Get an image frame, returns current display as JPEG data in a bytearray

Parameters:
  • resolution (list or tuple) – Image resolution in pixels [x,y]

  • quality (int) – Quality for JPEG image compression, default 90%

Returns:

image – encoded image as byte array

Return type:

bytearray

loadimage(filename)[source]

Return raw image data from file

Parameters:

filename (str) – Source image file (jpeg/png, tiff if libtiff supported)

Returns:

image – Numpy array of the image data loaded

Return type:

array

property objects

Returns the active objects

Returns:

objects – A dictionary wrapper containing the list of available visualisation objects Can be printed, iterated or accessed as a dictionary by object name

Return type:

_Objects(dict)

property output_path

str Returns image output path

Type:

output_path

parse_colour(colour)[source]

Parse a colour string and return a numpy RGBA array

Parameters:

colour (str) – Colour string, accepts html formats and X11 colour names or JSON string RGBA array

Returns:

rgba – the colour data as RGBA float array

Return type:

array

Example

Parse a colour string

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> lv.parse_colour('rgba(255,24,128,1.0)')
array([1.  , 0.09, 0.5 , 1.  ], dtype=float32)
png(resolution=None)[source]

Get an image frame, returns current display as PNG data in a bytearray

Parameters:

resolution (list or tuple) – Image resolution in pixels [x,y]

Returns:

image – encoded image as byte array

Return type:

bytearray

property port

HTTP server interface port

Returns:

port – Port the HTTP server is running on Will return 0 if server is not running

Return type:

int

rawimage(resolution=(640, 480), channels=3)[source]

Return raw image data

Parameters:
  • resolution (tuple(int,int)) – Image width and height in pixels

  • channels (int) – colour channels/depth in bytes (1=luminance, 3=RGB(default), 4=RGBA)

Returns:

image – Numpy array of the image data requested

Return type:

array

redisplay()[source]

Update the display of any interactive viewer

This is required after changing vis properties from python so the changes are reflected in the viewer

render()[source]

Render a new frame, explicit display update

restore(filename='state.json')[source]

Restore visualisation state from a json file (Includes all properties, colourmaps and defined objects but not their geometry data)

Parameters:

filename (str) – Name of the file to load

serve(*args, **kwargs)[source]

Run a web server in python This uses server.py to launch a simple web server

Parameters:
  • port (int) – port to run on

  • ipv6 (boolean) – use ipv6 if True, ipv4 if False

  • retries (int) – Number of attempts to open a port, incrementing the port number each time

setview(view)[source]

Set current view settings

Parameters:

view (str) – json string containing saved view settings

property step

int Returns current timestep

Type:

step

property steps

Retrieve the time step data from loaded model

Returns:

timesteps – A list of all available time steps

Return type:

list

store(filename='state.json')[source]

Store current visualisation state as a json file (Includes all properties, colourmaps and defined objects but not their geometry data)

Parameters:

filename (str) – Name of the file to save

testimage(expfile, outfile, tolerance=0.0001, clear=False)[source]

Compare two images

Parameters:
  • expfile (str) – Expected result image

  • outfile (str) – Test output image

  • tolerance (float) – Tolerance level of difference before a comparison fails, default 0.0001

Returns:

result – True if test passes, difference <= tolerance False if test fails, difference > tolerance

Return type:

boolean

testimages(imagelist=None, tolerance=0.0001, expectedPath='expected/', outputPath='./', clear=True)[source]

Compare a list of images to expected images for testing

Parameters:
  • imagelist (list) – List of test images to compare with expected results If not provided, will process all jpg and png images in working directory

  • tolerance (float) – Tolerance level of difference before a comparison fails, default 0.0001

  • expectedPath (str) – Where to find the expected result images (should have the same filenames as output images)

  • outputPath (str) – Where to find the output images

  • clear (boolean) – If the test passes the output images will be deleted, set to False to disable deletion

timesteps()[source]

Retrieve the time step data from loaded model

Returns:

timesteps – A list of all available time steps

Return type:

list

update(filter=None)[source]

Write visualisation data back to the database

Parameters:

filter (str) – Optional filter to type of geometry to be updated, if omitted all will be written (labels, points, grid, triangles, vectors, tracers, lines, shapes, volume)

video(filename='', fps=30, quality=1, resolution=(0, 0), **kwargs)[source]

Record and show the generated video inline within an ipython notebook.

If IPython is installed, displays the result video content inline

If IPython is not installed, will save the result in the current directory

This function is best used with the “with” statement as it returns a context manager. Alternatively recording can be manually started, stopped and the video displayed

See also: Video (class)

Parameters:
  • filename (str) – Name of the file to save, if not provided a default will be used

  • fps (int) – Frames to output per second of video

  • quality (int) – Encoding quality, 1=low(default), 2=medium, 3=high, higher quality reduces encoding artifacts at cost of larger file size

  • resolution (list or tuple) – Video resolution in pixels [x,y]

  • **kwargs – Any additional keyword args will be passed to lavavu.player()

Returns:

recorder – Context manager object that controls the video recording

Return type:

Video(object)

video_steps(filename='', start=0, end=0, fps=10, quality=1, resolution=(0, 0), **kwargs)[source]

Record a video of the model by looping through all time steps

Shows the generated video inline within an ipython notebook.

If IPython is installed, displays the result video content inline

If IPython is not installed, will save the result in the current directory

Parameters:
  • filename (str) – Name of the file to save, if not provided a default will be used

  • start (int) – First timestep to record, if not specified will use first available

  • end (int) – Last timestep to record, if not specified will use last available

  • fps (int) – Frames to output per second of video

  • quality (int) – Encoding quality, 1=low(default), 2=medium, 3=high, higher quality reduces encoding artifacts at cost of larger file size

  • resolution (list or tuple) – Video resolution in pixels [x,y]

  • **kwargs – Any additional keyword args will be passed to lavavu.player()

viewport(x=0.0, y=0.0, width=1.0, height=1.0, replace=False, **kwargs)[source]

Add a viewport object

Parameters:
  • x (float) – x offset as fraction of window size [0,1]

  • y (float) – y offset as fraction of window size [0,1]

  • width (float) – width as fraction of window size [0,1]

  • height (float) – height as fraction of window size [0,1]

  • replace (bool) – Set to True to replace the active viewport instead of adding a new viewport

  • dict (Subsequent kwargs are passed as properties) –

webgl(filename=None, resolution=(640, 480), browser=False, menu=True, **kwargs)[source]

Create a WebGL page with a 3D interactive view of the active model (will only contain a snapshot of the current timestep for 4D data)

Result can be saved with a provided filename as a HTML file in the current directory

If running from IPython, displays the result WebGL content inline in the cell by default

Parameters:
  • filename (str) – Filename to save generated HTML page. If running in IPython the default behaviour is to display the result inline and no file will be written Otherwise, content will be written to “webgl.html” if not provided.

  • resolution (list or tuple) – Display window resolution in pixels [x,y] for inline viewer

  • browser (boolean) – Open generated page in a new full browser window

  • menu (boolean) – Include and interactive menu for controlling visualisation appearance, on by default

  • kwargs – Additional named arguments passed will be added to the global WebGL viewer settings, defaults are: interactive=True, immediatesort=False, sortenabled=True

webview(resolution=(640, 480))[source]

Create a full WebGL2 view of the model

If running from IPython, displays the result WebGL2 content inline in the cell in an iframe

Parameters:

resolution (list or tuple) – Display window resolution in pixels [x,y] for inline viewer

window(resolution=None, menu=True)[source]

Create and display an interactive viewer instance

This shows an active viewer window to the visualisation that can be controlled with the mouse or html widgets

Parameters:
  • resolution (tuple(int,int)) – Frame size in pixels: width, height. Defaults to the viewer default output resolution, usually (640,480)

  • menu (boolean) – Adds a menu to the top right allowing control of vis parameters, defaults to on

class Object(parent, *args, **kwargs)[source]

Bases: dict

The Object class provides an interface to a LavaVu drawing object Object instances are created internally in the Viewer class and can be retrieved from the object list

New objects are also created using viewer methods

Parameters:

**kwargs – Initial set of properties passed to the created object

Example

Create a viewer, load some test data, get objects

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> lv.test()
>>> print(lv.objects)
dict_keys(['particles', 'particles_colourbar', 'line-segments', 'Z-cross-section', 'Y-cross-section', 'X-cross-section'])

Object properties can be passed in when created or set by using as a dictionary:

>>> obj = lv.points(pointtype="sphere")
>>> obj["pointsize"] = 5

A list of available properties can be found here: https://lavavu.github.io/Documentation/Property-Reference or by using the online help:

>>> obj.help('opacity') 
append()[source]

Append a new data element to the object

Object data is sometimes dependant on individual elements to determine where one part ends and another starts, e.g. line segments, grids

This allows manually closing the active element so all new data is loaded into a new element

clear()[source]

Clear all visualisation data from this object

cleardata(typename='')[source]

Clear specific visualisation data/values from this object

Parameters:

typename (str) – Optional filter naming type of data to be cleared, Either a built in type: (vertices/normals/vectors/indices/colours/texcoords/luminance/rgb/values) or a user defined data label

colourbar(**kwargs)[source]

Create a new colourbar using this object’s colourmap

Returns:

colourbar – The colourbar object created

Return type:

Object

colourmap(data=None, name=None, reverse=False, monochrome=False, **kwargs)[source]

Load colour map data for object

Parameters:
  • data (list or str or ColourMap) – If not provided, just returns the colourmap (A default is created if none exists) Provided colourmap data can be - a string, - list of colour strings, - list of position,value tuples - a built in colourmap name - An existing ColourMap object Creates a colourmap named objectname_colourmap if object doesn’t already have a colourmap

  • name (str) – Name of colourmap, when creating a new one

  • reverse (boolean) – Reverse the order of the colours after loading

  • monochrome (boolean) – Convert to greyscale

Returns:

The wrapper object of the colourmap loaded/created

Return type:

ColourMap(dict)

colours(data)[source]

Load colour data for object

Parameters:

data (str or list or array) – Pass a list or numpy uint32 array of colours if a string or list of strings is provided, colours are parsed as html colour string values if a numpy array is passed, colours are loaded as 4 byte ARGB unsigned integer values

commands(cmds, queue=False)[source]

Execute viewer commands with this object as the target https://lavavu.github.io/Documentation/Scripting-Commands-Reference

Parameters:

cmds (list or str) – Command(s) to execute

contours(isovalues=None, name=None, labels=True, convert=False, updatedb=False, **kwargs)[source]

Generate a contours from a surface/grid data set using the marching squares algorithm

Parameters:
  • isovalues (number,list) – Isovalues to draw contour lines on, number or list

  • name (str) – Name of the created object, automatically assigned if not provided

  • labels (bool) – Label one of the contour lines for each of the interval values, positioning of these is automatic but not always ideal

  • convert (bool) – Setting this flag to True will replace the existing surface grid object with the newly created contours by deleting the grid data and loading the line data into the preexisting object

  • updatedb (bool) – Setting this flag to True will write the newly created/modified data to the database when done

  • **kwargs – Initial set of properties passed to the created object

Returns:

obj – The contour object created/converted

Return type:

Object

property data

Return internal geometry data at current timestep Returns a Geometry() object that can be iterated through containing all data elements Elements contain vertex/normal/value etc. data as numpy arrays

Returns:

An object holding the data elements retrieved

Return type:

Geometry

Example

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> obj = lv.points(vertices=[[0,1], [1,0]])
>>> for el in obj.data:
...     print(el)
DrawData("points") ==> {'vertices': (2, 3)}
property datasets

Retrieve available labelled data sets on this object

Returns:

A dictionary containing the data objects available by label

Return type:

dict

exclude(*args, **kwargs)[source]

Filter data by excluding a range of values shortcut for: filter(… , out=True)

Parameters:
  • label (str) – Data label to filter on

  • values (number or list or tuple) – value range single value, list or tuple if a single value the filter applies to only this value: x == value if a list e.g. [0,1] range is inclusive 0 <= x <= 1 if a tuple e.g. (0,1) range is exclusive 0 < x < 1

Returns:

The filter id created

Return type:

int

excludemap(*args, **kwargs)[source]

Filter data by excluding a range of mapped values shortcut for: filter(… , out=True, map=True)

Parameters:
  • label (str) – Data label to filter on

  • values (number or list or tuple) – value range single value, list or tuple if a single value the filter applies to only this value: x == value if a list e.g. [0,1] range is inclusive 0 <= x <= 1 if a tuple e.g. (0,1) range is exclusive 0 < x < 1

Returns:

The filter id created

Return type:

int

export(filepath=None, compress=None)[source]

Export model and state to a database snapshot

Parameters:
  • filepath (str) – Filename to export, defaults to [object name].gldb

  • compress (int) – Set flag override default zlib compression of database (0=None, 1=fast, 6=standard, 9=best compression)

export_mesh(filepath, rgba=True)[source]

Use trimesh to export mesh object to a supported format, eg: GLTF (.glb)

See: https://trimsh.org/trimesh.exchange.html Requires “trimesh” module Supports triangle mesh object data

Parameters:
  • filepath (str) – Output file to write

  • rgba (bool) – If set, convert colourmap/value data to rgba before export

file(*args, **kwargs)[source]

Load data from a file into this object

Parameters:

filename (str) – Name of the file to load

files(*args, **kwargs)[source]

Load data from a series of files into this object (using wildcards or a list)

Parameters:

files (str) – Specification of the files to load

filter(label, values=None, out=False, map=False)[source]

Filter data by including a range of values

Parameters:
  • label (str) – Data label to filter on

  • values (number or list or tuple) – value range single value, list or tuple if a single value the filter applies to only this value: x == value if a list e.g. [0,1] range is inclusive 0 <= x <= 1 if a tuple e.g. (0,1) range is exclusive 0 < x < 1

  • out (boolean) – Set this flag to filter out values instead of including them

  • map (boolean) – Set this flag to filter by normalised values mapped to [0,1] instead of actual min/max of the data range

Returns:

The filter id created

Return type:

int

getcolourmap(string=True)[source]

Return the colour map data from the object as a string or list Either return format can be used to create/modify a colourmap with colourmap()

Parameters:

string (boolean) – The default is to return the data as a string of colours separated by semi-colons To instead return a list of (position,[R,G,B,A]) tuples for easier automated processing in python, set this to False

Returns:

mapdata – The formatted colourmap data

Return type:

str/list

help(cmd='')[source]

Get help on an object method or property

Parameters:

cmd (str) – Command to get help with, if ommitted displays general introductory help If cmd is a property or is preceded with ‘@’ will display property help

include(*args, **kwargs)[source]

Filter data by including a range of values shortcut for: filter(… , out=False)

Parameters:
  • label (str) – Data label to filter on

  • values (number or list or tuple) – value range single value, list or tuple if a single value the filter applies to only this value: x == value if a list e.g. [0,1] range is inclusive 0 <= x <= 1 if a tuple e.g. (0,1) range is exclusive 0 < x < 1

Returns:

The filter id created

Return type:

int

includemap(*args, **kwargs)[source]

Filter data by including a range of mapped values shortcut for: filter(… , out=False, map=True)

Parameters:
  • label (str) – Data label to filter on

  • values (number or list or tuple) – value range single value, list or tuple if a single value the filter applies to only this value: x == value if a list e.g. [0,1] range is inclusive 0 <= x <= 1 if a tuple e.g. (0,1) range is exclusive 0 < x < 1

Returns:

The filter id created

Return type:

int

indices(data, offset=0)[source]

Load index data for object

Parameters:
  • data (list or array) – Pass a list or numpy uint32 array of indices indices are loaded as 32 bit unsigned integer values

  • offset (int) – Specify an initial index offset, for 1-based indices pass offset=1 Default is zero-based

isosurface(isovalues=None, name=None, convert=False, updatedb=False, **kwargs)[source]

Generate an isosurface from a volume data set using the marching cubes algorithm

Parameters:
  • isovalues (number,list) – Isovalues to create surfaces for, number or list

  • name (str) – Name of the created object, automatically assigned if not provided

  • convert (bool) – Setting this flag to True will replace the existing volume object with the newly created isosurface by deleting the volume data and loading the mesh data into the preexisting object

  • updatedb (bool) – Setting this flag to True will write the newly created/modified data to the database when done

  • **kwargs – Initial set of properties passed to the created object

Returns:

obj – The isosurface object created/converted

Return type:

Object

labels(data)[source]

Load label data for object

Parameters:

data (list or str) – Pass a label or list of labels to be applied, one per vertex

luminance(data)[source]

Load luminance data for object

Parameters:

data (list or array) – Pass a list or numpy uint8 array of luminance values values are loaded as 8 bit unsigned integers

magnitude(data, label='magnitude')[source]

Load magnitude of a vector array as value data for an object

Parameters:
  • data (list or array) – Pass a list or numpy float32 3d array of vertices

  • label (str) – Label for this data set, default=”magnitude”

property name

Get the object’s name property

Returns:

name – The name of the object

Return type:

str

normals(data)[source]

Load 3d normal data for object

Parameters:

data (list or array) – Pass a list or numpy float32 3d array of normals

opacitymap(data=None, **kwargs)[source]

Load opacity map data for object

Parameters:

data (list or str) – If not provided, just returns the opacity map (A default is created if none exists) Provided opacity map data can be - list of opacity values, - list of position,opacity tuples Creates an opacity map named objectname_opacitymap if object doesn’t already have an opacity map

Returns:

The wrapper object of the opacity map loaded/created

Return type:

ColourMap(dict)

reload()[source]

Fully reload the object’s data, recalculating all parameters such as colours that may be cached on the GPU, required after changing some properties so the changes are reflected in the visualisation

rgb(data)[source]

Load rgb data for object

Parameters:

data (list or array) – Pass a list or numpy uint8 array of rgb values values are loaded as 8 bit unsigned integer values

rgba(data)[source]

Load rgba data for object

Parameters:

data (list or array) – Pass a list or numpy uint8 array of rgba values values are loaded as 8 bit unsigned integer values

select()[source]

Set this object as the selected object

swapv(a, b)[source]

Swap coordinates of 3d data (vertices, normals, vectors) This replaces the swapyz property/feature that only applied to OBJ import

swapxy()[source]

Swap X and Y coordinates of 3d data (vertices, normals, vectors)

swapxz()[source]

Swap X and Z coordinates of 3d data (vertices, normals, vectors)

swapyz()[source]

Swap Y and Z coordinates of 3d data (vertices, normals, vectors)

texcoords(data)[source]

Load 2d texture coordinate data for object

Parameters:

data (list or array) – Pass a list or numpy float32 2d array of coordinates

texture(data=None, flip=True, filter=2, bgr=False)[source]

Load or clear texture data for object

Parameters:
  • data (list or array or string) – (If data is not provided, the object’s texture data will be cleared) Pass a list or numpy uint32 or uint8 array texture data is loaded as raw image data shape of array must be 2d or 3d, either (height, width, channels) for RGB(A) image or (height, width) for single channel grayscale image Pass a string to load a texture from given filename

  • flip (boolean) – flip the texture vertically after loading (default is enabled as usually required for OpenGL but can be disabled)

  • filter (int) – type of filtering, 0=None/nearest, 1=linear, 2=mipmap linear

  • bgr (boolean) – rgb data is in BGR/BGRA format instead of RGB/RGBA

triangles(data, split=0)[source]

Load triangle data,

This is the same as loading vertices into a triangle mesh object but allows decomposing the mesh into smaller triangles with the split option

Parameters:

split (int) – Split triangles this many times on loading

update(filter=None)[source]

Write the objects’s visualisation data back to the database

Parameters:

filter (str) – Optional filter to type of geometry to be updated, if omitted all will be written (eg: labels, points, grid, triangles, vectors, tracers, lines, shapes, volume)

values(data, label='default')[source]

Load value data for object

Parameters:
  • data (list or array) – Pass a list or numpy float32 array of values

  • label (str) – Label for this data set

vectors(data)[source]

Load 3d vector data for object

Parameters:

data (list or array) – Pass a list or numpy float32 3d array of vectors

vertices(data)[source]

Load 3d vertex data for object

Parameters:

data (list or array) – Pass a list or numpy float32 3d array of vertices

class Properties(parent, callback=None, **kwargs)[source]

Bases: dict

The Properties class provides an interface to a collection of properties with a control factory, allowing controls to be created to manipulate their values interactively Properties can be passed in when created or set by using as a dictionary:

Parameters:
  • callback (function) – Optional function to call whenever a property in this collection is changed by an interactive control The function should take one argument, the collection of type lavavu.Properties() and will be called, with the new values whenever the control value is updated.

  • **kwargs – Set of initial properties to store in the collection

Example

Create a property set, load some test data

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> props = lv.Properties(floatprop=1.0)
>>> props["boolprop"] = True
>>> print(props)
{'floatprop': 1.0, 'boolprop': True}

Now create some controls to manipulate them

>>> f = props.control.Range('floatprop', range=(0,1))
>>> b = props.control.Checkbox('boolprop')
class ColourMap(ref, parent, *args, **kwargs)[source]

Bases: dict

The ColourMap class provides an interface to a LavaVu ColourMap ColourMap instances are created internally in the Viewer class and can be retrieved from the colourmaps list

New colourmaps are also created using viewer methods

Parameters:

**kwargs – Initial set of properties passed to the created colourmap

property colours

Returns the list of colours

Returns:

colours – A list of colours

Return type:

list

property name

Get the colourmap name property

Returns:

name – The name of the colourmap

Return type:

str

property positions

Returns the list of colour positions

Returns:

positions – A list of colour positions [0,1]

Return type:

list

tohexstr()[source]

Get the colourmap colour data as a string with hex rgb:a representation, NOTE: ignores position data

Returns:

The colour data which can be used to re-create the colourmap

Return type:

str

tolist()[source]

Get the colourmap data as a python list

Returns:

The colour and position data which can be used to re-create the colourmap

Return type:

list

update(data=None, reverse=False, monochrome=False, **kwargs)[source]

Update the colour map data

Parameters:
  • data (list,str) – Provided colourmap data can be - a string, - list of colour strings, - list of position,value tuples - or a built in colourmap name

  • reverse (boolean) – Reverse the order of the colours after loading

  • monochrome (boolean) – Convert to greyscale

class DrawData(data, obj)[source]

Bases: object

The DrawData class provides an interface to a single object data element DrawData instances are created internally from the Geometry class

copy(), get() and set() methods provide access to the data types

Example

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> obj = lv.points(vertices=[[0,1], [1,0]], colours="red blue")
>>> obj.values([2, 3], "myvals")

Get the data elements

>>> print(obj.data)
[DrawData("points") ==> {'vertices': (2, 3), 'colours': (2,), 'myvals': (2,)}]

Get a copy of the colours (if any)

>>> colours = obj.data.colours_copy
>>> print(colours)
[array([4278190335, 4294901760], dtype=uint32)]

Get a view of the vertex data

>>> verts = obj.data.vertices
>>> print(verts)
[array([[0., 1., 0.],
       [1., 0., 0.]], dtype=float32)]

WARNING: this reference may be deleted by other calls, use _copy if you are not processing the data immediately and relying on it continuing to exist later

Get a some value data by label “myvals” >>> vals = obj.data.myvals >>> print(vals) [array([2., 3.], dtype=float32)]

Load some new values for this data, provided list must match first dimension of existing data list

>>> print(obj.data.myvals)
[array([2., 3.], dtype=float32)]
>>> obj.data.myvals = [[4,5]]
>>> print(obj.data.myvals)
[array([4., 5.], dtype=float32)]
copy(typename)[source]

Get a copy of a data element from geometry data

This is a safe version of get() that copies the data before returning so can be assured it will remain valid

Parameters:

typename (str) – Type of data to be retrieved (vertices/normals/vectors/indices/colours/texcoords/luminance/rgb/values)

Returns:

data – Numpy array containing a copy of the data set requested

Return type:

array

get(typename)[source]

Get a data element from geometry data

Warning… other than for internal use, should always immediately make copies of the data there is no guarantee memory will not be released!

Parameters:

typename (str) – Type of data to be retrieved (vertices/normals/vectors/indices/colours/texcoords/luminance/rgb/values)

Returns:

data – Numpy array view of the data set requested

Return type:

array

set(typename, array)[source]

Set a data element in geometry data

Parameters:
  • typename (str) – Type of data to set (vertices/normals/vectors/indices/colours/texcoords/luminance/rgb/values)

  • array (array) – Numpy array holding the data to be written

class Figure(parent, name)[source]

Bases: dict

The Figure class wraps a set of visualisation state data, providing a way of managing a collection of preset visualisations or “figures” of a single model

  • Figures represent a full set of visualisation settings, including visibility of chosen objects

  • A single model can contain many objects and multiple figures, all of which work on the same set of objects, but may not use them all (ie: some are hidden)

  • A figure object encapsulates the same data that can be stored on disk in a JSON file with Viewer.store(filename) and restored with Viewer.restore(filename)

image(*args, **kwargs)[source]

Render this figure to an image file:

  • Load the figure state into the Viewer,

  • Call Viewer.image(args, kwargs) to render an image to file

load()[source]

Load this figure’s state into the Viewer

save()[source]

Save the Viewer state to this figure

show(*args, **kwargs)[source]

Render this figure

  • Load the figure state into the Viewer,

  • Call Viewer.display(args, kwargs) to render

class Geometry(obj, timestep=-2, filter=None)[source]

Bases: list

The Geometry class provides an interface to a drawing object’s internal data Geometry instances are created internally in the Object class with the data property

Example

Get all object data

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> obj = lv.points()
>>> #Fixed points, always plotted regardless of timestep
>>> obj.vertices([[-1,-1], [0,0], [1,1]])
>>> #Add triangles to same object, switch the geometry type:
>>> obj["renderer"] = "triangles"
>>> lv.addstep()
>>> print(lv.steps)
[0]
>>> obj.vertices([[0,1], [1,1], [1,0]])
>>> obj.append()
>>> obj.vertices([[2,2], [2,3], [3,2]])
>>> lv.addstep()
>>> print(lv.steps)
[0, 1]
>>> obj.vertices([[0.5,1], [1.5,1], [1.5,0]])

Loop through all elements of an object (at current timestep)

>>> for i,el in enumerate(obj):
...     print(i,el)
...     print(el.vertices)
0 DrawData("points") ==> {'vertices': (3, 3)}
[[-1. -1.  0.]
 [ 0.  0.  0.]
 [ 1.  1.  0.]]
1 DrawData("triangles") ==> {'vertices': (3, 3)}
[[0.5 1.  0. ]
 [1.5 1.  0. ]
 [1.5 0.  0. ]]

Get only triangle data

>>> data = obj.data["triangles"]
>>> print(data)
[DrawData("triangles") ==> {'vertices': (3, 3)}]
>>> print(data.vertices)
[array([[0.5, 1. , 0. ],
       [1.5, 1. , 0. ],
       [1.5, 0. , 0. ]], dtype=float32)]

Get data at specific timestep only (default is current step including fixed data)

>>> data = obj.data["0"]
>>> print(data)
[DrawData("triangles") ==> {'vertices': (3, 3)}, DrawData("triangles") ==> {'vertices': (3, 3)}]
>>> print(data.vertices)
[array([[0., 1., 0.],
       [1., 1., 0.],
       [1., 0., 0.]], dtype=float32), array([[2., 2., 0.],
       [2., 3., 0.],
       [3., 2., 0.]], dtype=float32)]

Loop through data elements

>>> for el in data:
...     print(el)
DrawData("triangles") ==> {'vertices': (3, 3)}
DrawData("triangles") ==> {'vertices': (3, 3)}

Show the fixed data (timestep -1)

>>> print(obj.data["-1"])
[DrawData("points") ==> {'vertices': (3, 3)}]
class Image(resolution=(640, 480), channels=4, value=[255, 255, 255, 0], data=None)[source]

Bases: object

The Image class provides an interface to a raw image

Example

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> lv.test()
>>> img = lv.rawimage() 
>>> img.save('out.png') 

TODO: control blend equations

blend(source, resolution=None, position=(0, 0))[source]

Render another image to a specified position with this image with alpha blending

Parameters:
  • source (array or lavavu.Viewer) – Numpy array containing raw image data to paste or a Viewer instance to source the frame from

  • resolution (tuple(int,int)) – Sub-image width and height in pixels, if not provided source must be a numpy array of the correct dimensions

  • position (tuple(int,int)) – Sub-image x,y offset in pixels

convert(source)[source]

Attempts to convert an image to the same pixel format as this image

Parameters:

source (array) – Numpy array containing raw image data to convert

Returns:

result – Numpy array containing converted raw image data if successful, or original data otherwise

Return type:

array

crop(width, height, x=0, y=0)[source]

Crop image to specified width and height, with optional x,y offset

Parameters:
  • width (int) – Crop width

  • height (int) – Crop height

  • x (int) – Crop x offset

  • y (int) – Crop y offset

display()[source]

Show the image as inline image within an ipython notebook.

paste(source, resolution=None, position=(0, 0))[source]

Render another image to a specified position with this image

Parameters:
  • source (array or lavavu.Viewer) – Numpy array containing raw image data to paste or a Viewer instance to source the frame from

  • resolution (tuple(int,int)) – Sub-image width and height in pixels, if not provided and source is a numpy array will get dimensions from shape, otherwise will use default viewer dimensions

  • position (tuple(int,int)) – Sub-image x,y offset in pixels

save(filename)[source]

Save a raw image data to provided filename

Parameters:

filename (str) – Output filename (png/jpg supported, default is png if no extension)

Returns:

path – Path to the output image

Return type:

str

class Video(viewer=None, filename='', resolution=(0, 0), framerate=30, quality=1, **kwargs)[source]

Bases: object

The Video class provides an interface to record animations

Example

>>> import lavavu
>>> lv = lavavu.Viewer()
>>> lv.test()
>>> with lv.video():           
...     for i in range(0,5):   
...         lv.rotate('y', 10) 
...         lv.render()        
__init__(viewer=None, filename='', resolution=(0, 0), framerate=30, quality=1, **kwargs)[source]

Record and show the generated video inline within an ipython notebook.

If IPython is installed, displays the result video content inline

If IPython is not installed, will save the result in the current directory

This function is best used with the “with” statement as the object is a context manager. Alternatively recording can be manually started, stopped and the video displayed

Parameters:
  • viewer (lavavu.Viewer()) – Viewer object

  • filename (str) – Name of the file to save, if not provided a default will be used

  • fps (int) – Frames to output per second of video

  • quality (int) – Encoding quality, 1=low(default), 2=medium, 3=high, higher quality reduces encoding artifacts at cost of larger file size

  • resolution (list or tuple) – Video resolution in pixels [x,y]

  • **kwargs – Any additional keyword args will be passed to lavavu.player()

play()[source]

Show the video in an inline player if in an interative notebook

start()[source]

Start recording, all rendered frames will be added to the video

stop()[source]

Stop recording, final frames will be written and file closed, ready to play. No further frames will be added to the video

write(image)[source]

Add a frame to the video (when writing custom video frames rather than rendering them within lavavu)

Parameters:

image (list or array or Image) – Pass a list or numpy uint8 array of rgba values or an Image object values are loaded as 8 bit unsigned integer values