Search code examples
pythonanimationoctavemontecarloscatter

Creating animation in python from Octave code


I am new to coding and have been trying to create an animation in python from a previously generated code in Octave (below). So far I have not had any success, besides plotting an unanimated scatter plot. Any tips or help would be greatly appreciated.

    clear;

    N = 100;  
    NT = 200;

    for i=1:N  
        x(i) = 0;  
        y(i) = 0;  
    end

    plot(x,y,'o');  
    axis([0 20 -10 10]);

    for k = 1 : NT 
        x = x + normrnd(0.1,0.1,1,N);  
        y = y + normrnd(0,0.1,1,N);  
        temp = mod(k,1);  
        if temp == 0  

          plot(x,y,'s');
          axis([0 20 -10 10]);
          drawnow

       end
    end

Here is one of the many attempts that did not work (below).

    import numpy as np
    import matplotlib as plt
    from pylab import *
    from matplotlib import animation
    import random

    n=100
    nt=2000
    m=20
    mu=0
    sigma=0.1
    p=100

    fig = plt.figure()
    ax = plt.axes(xlim=(-10, 10), ylim=(-10, 10))
    scat, = ax.plot([], [])

    # initialization function: plot the background of each frame
    def init():
          x = 0
          y = 0
          return scat,

    # animation function.  This is called sequentially
    def animate(i):
        for k in range (1,nt):
            x =  x+ np.random.normal(mu, sigma, n)
            return scat,

        for i in range (1,nt):
            y =  y+ np.random.normal(mu, sigma, n)
            return scat,

    anim = animation.FuncAnimation(fig, animate, 
    init_func=init,frames=200, interval=20, blit=True)

    plt.show()

Solution

  • you could do the animation using Octave of Python.

    For the python script I think that one of the problems was to set a return within a loop, therefore several times for one function def animate. Looking at the animation doc https://matplotlib.org/api/animation_api.html I edited your example and got this which I think might be usefull:

    import numpy as np
    import matplotlib.pyplot as plt
    from pylab import *
    from matplotlib.animation import FuncAnimation
    import random
    
    n=100
    sigma=0.1
    nt=2000
    
    fig, ax = plt.subplots()
    xdata, ydata = [0.0], [0.0]
    ln, = plt.plot([], [], 'ro', animated=True)
    
    def init():
        ax.set_xlim(  0, 20)
        ax.set_ylim(-10, 10)
        return ln,
    
    def update(frame):
        global xdata
        global ydata
        xdata = xdata + np.random.normal(0.1, sigma, n)
        ydata = ydata + np.random.normal(0.0, sigma, n)
        ln.set_data(xdata, ydata)
        return ln,
    
    ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                        init_func=init, blit=True)
    plt.show()
    

    You could also do the animation using octaves print command to generate several pngs and use gimp to produce a gif or embbed in LaTeX the pngs using animate.

    Best, Jorge