animation via python script

There was no complete example for using python within animations (PythonAnimationCue) findable, so this may be of interest:

'''
Example of a Paraview animation via Python,
tested with Paraview 5.8.1 and Python 3.7.4.
Run "pypython example_animation.py" from the command line.
Check the enviroment from the python shell within the Paraview GUI for the use as macro.
From this python shell Paraview classes (view, scene) can be inspected,
and needed commands, e.g. load a results file, discovered from "Tools--start/stop trace
in the menubar.

The basic animation shows the change from a full to a half sphere.
The python script adds the time as text and moves a line around.
'''
from paraview.simple import *

# This cue contains the python code to be run during the animation.
# At start the text and the line are created and at
# each tick they are modified.
PythonAnimationCue1 = PythonAnimationCue()
PythonAnimationCue1.Script= """
def start_cue(self): 
    Text1 = Text()
    Text1.Text = 'SomeText'
    Show()
    Line1 = Line()
    Line1.Point1 = [-1.0, 0.0, 0.0]
    Line1.Point2 = [ 1.0, 0.0, 0.0]
    Show()
def tick(self): 
    animationScene1 = GetAnimationScene()
    animationTime = animationScene1.TimeKeeper.Time
    Text1 = FindSource("Text1")
    Text1.Text=str(animationTime)
    Line1 = FindSource("Line1")
    Line1.Point1 = [-1.0, animationTime, 0.0]
    Line1.Point2 = [ 1.0,-animationTime, 0.0]
def end_cue(self): pass
"""


# Create an animation scene with basic commands, without need for additional files
Sphere()
Show()
Render()

scene = GetAnimationScene()
cue = GetAnimationTrack("StartTheta")   # animated parameter of sphere

# animation parameter (StartTheta)
keyf0 = CompositeKeyFrame()
keyf0.Interpolation = 'Ramp'
keyf0.KeyTime = 0
keyf0.KeyValues= [0]	# DEG
keyf1 = CompositeKeyFrame()
keyf1.KeyTime = 1.0
keyf1.KeyValues= [200]	# DEG
cue.KeyFrames = [keyf0, keyf1]

# animation of text and line by python script
scene.Cues.append(PythonAnimationCue1) 

scene.StartTime=0
scene.NumberOfFrames = 100
scene.PlayMode = 'Sequence' #'Real Time'
scene.Duration = 1

scene.Play()

This works from the command line pvpython example_animation.py, but not yet as macro within python.

5 Likes