c++ live animation using matplotlib

Viewed 751

I have a c++ program which outputs position versus time (trajectory), and I am going to generate animation from it. Till now I generated images then produced animation from it. But I am going to do real time animation, i.e. running c++ code and generating animation at the same time. I know the basic python/c++ linking like the bellow code,

#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <python2.7/Python.h>
int main()
{
        char filename[] = "pyemb.py";
        FILE* fp;
        Py_Initialize();
        for (int istep = 0; istep < 20; istep++)
             {
                PyObject* PyFileObject = PyFile_FromString(filename, "r");
                PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), filename, 1);
             }
        Py_Finalize();
        return 0;}

and I wrote a basic code by mpl.animation to produce live animation in python,

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

np.random.seed(0)
N = 10
L = 4.0
init_state = np.random.random((N, 2))

fig = plt.figure()
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(0., L), ylim=(0., L))

particles, = ax.plot([], [], 'bo', ms=6)
particles.set_data([], [])

def animate(i):
    """perform animation step"""
    ran_angle = np.random.random((N,))
    ran_cos = np.cos(ran_angle*2.*np.pi)
    ran_sin = np.sin(ran_angle*2.*np.pi)
    init_state[:, 0] += ran_cos
    init_state[:, 1] += ran_sin

    for ind in range(N):
        for ii in range(2):
            if (init_state[ind,ii] > L):
                init_state[ind,ii] -= L
            if (init_state[ind,ii] <= 0):
                init_state[ind,ii] += L

    particles.set_data(init_state[:, 0], init_state[:, 1])
    return particles
ani = animation.FuncAnimation(fig, animate, frames=20, interval=1, blit=False, repeat = False)
ani.save('particle_box.mp4', fps=3, extra_args=['-vcodec', 'libx264'])

but I don't know how to link them dynamically. I googled a lot, but with no success, partly because I didn't know what to exactly search for.

0 Answers
Related