Matplotlib won't animate a function









up vote
1
down vote

favorite












I'm trying to make an animation of the following wavefunction:



Wavefunction



For some reason my code works for n=0 but then it doesn't for any other n. I checked the values of the function for various n, x and t and it seems to work fine but for some reason matplotlib isn't animating. Here's the code:



%matplotlib qt

import numpy as np
from sympy import hermite
from scipy.special import gamma
import matplotlib.pyplot as plt
from matplotlib import animation


def psi(n, x, t):
A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
E = n + 0.5
f = A * hermite(n, x) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
return f


def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
nf = int((xf - x0) / dx + 1)
nt = int((tf - t0) / dt + 1)
x = np.linspace(x0, xf, nf)
t = np.linspace(t0, tf, nt)

fig, ax = plt.subplots()

ax.set_xlim((x0, xf))
ax.set_ylim((ym, yM))

line, = ax.plot(, , lw=2)

def init():
line.set_data(, )
return line,

def animate(i):
y = f(x, i)
line.set_data(x, y)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=5 * t, interval=20, blit=True)
plt.show()
return anim


F = lambda x,t: psi(1, x, t)
anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)









share|improve this question























  • Your function also works when you take x out and define it as hermite(n, 1), etc.
    – l'L'l
    Nov 11 at 0:32














up vote
1
down vote

favorite












I'm trying to make an animation of the following wavefunction:



Wavefunction



For some reason my code works for n=0 but then it doesn't for any other n. I checked the values of the function for various n, x and t and it seems to work fine but for some reason matplotlib isn't animating. Here's the code:



%matplotlib qt

import numpy as np
from sympy import hermite
from scipy.special import gamma
import matplotlib.pyplot as plt
from matplotlib import animation


def psi(n, x, t):
A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
E = n + 0.5
f = A * hermite(n, x) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
return f


def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
nf = int((xf - x0) / dx + 1)
nt = int((tf - t0) / dt + 1)
x = np.linspace(x0, xf, nf)
t = np.linspace(t0, tf, nt)

fig, ax = plt.subplots()

ax.set_xlim((x0, xf))
ax.set_ylim((ym, yM))

line, = ax.plot(, , lw=2)

def init():
line.set_data(, )
return line,

def animate(i):
y = f(x, i)
line.set_data(x, y)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=5 * t, interval=20, blit=True)
plt.show()
return anim


F = lambda x,t: psi(1, x, t)
anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)









share|improve this question























  • Your function also works when you take x out and define it as hermite(n, 1), etc.
    – l'L'l
    Nov 11 at 0:32












up vote
1
down vote

favorite









up vote
1
down vote

favorite











I'm trying to make an animation of the following wavefunction:



Wavefunction



For some reason my code works for n=0 but then it doesn't for any other n. I checked the values of the function for various n, x and t and it seems to work fine but for some reason matplotlib isn't animating. Here's the code:



%matplotlib qt

import numpy as np
from sympy import hermite
from scipy.special import gamma
import matplotlib.pyplot as plt
from matplotlib import animation


def psi(n, x, t):
A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
E = n + 0.5
f = A * hermite(n, x) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
return f


def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
nf = int((xf - x0) / dx + 1)
nt = int((tf - t0) / dt + 1)
x = np.linspace(x0, xf, nf)
t = np.linspace(t0, tf, nt)

fig, ax = plt.subplots()

ax.set_xlim((x0, xf))
ax.set_ylim((ym, yM))

line, = ax.plot(, , lw=2)

def init():
line.set_data(, )
return line,

def animate(i):
y = f(x, i)
line.set_data(x, y)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=5 * t, interval=20, blit=True)
plt.show()
return anim


F = lambda x,t: psi(1, x, t)
anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)









share|improve this question















I'm trying to make an animation of the following wavefunction:



Wavefunction



For some reason my code works for n=0 but then it doesn't for any other n. I checked the values of the function for various n, x and t and it seems to work fine but for some reason matplotlib isn't animating. Here's the code:



%matplotlib qt

import numpy as np
from sympy import hermite
from scipy.special import gamma
import matplotlib.pyplot as plt
from matplotlib import animation


def psi(n, x, t):
A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
E = n + 0.5
f = A * hermite(n, x) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
return f


def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
nf = int((xf - x0) / dx + 1)
nt = int((tf - t0) / dt + 1)
x = np.linspace(x0, xf, nf)
t = np.linspace(t0, tf, nt)

fig, ax = plt.subplots()

ax.set_xlim((x0, xf))
ax.set_ylim((ym, yM))

line, = ax.plot(, , lw=2)

def init():
line.set_data(, )
return line,

def animate(i):
y = f(x, i)
line.set_data(x, y)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=5 * t, interval=20, blit=True)
plt.show()
return anim


F = lambda x,t: psi(1, x, t)
anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)






numpy animation matplotlib scipy physics






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 0:55









ImportanceOfBeingErnest

119k10119192




119k10119192










asked Nov 10 at 23:59









Kirtpole

84




84











  • Your function also works when you take x out and define it as hermite(n, 1), etc.
    – l'L'l
    Nov 11 at 0:32
















  • Your function also works when you take x out and define it as hermite(n, 1), etc.
    – l'L'l
    Nov 11 at 0:32















Your function also works when you take x out and define it as hermite(n, 1), etc.
– l'L'l
Nov 11 at 0:32




Your function also works when you take x out and define it as hermite(n, 1), etc.
– l'L'l
Nov 11 at 0:32












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










I don't think you want to evaluate the hermite polynomials symbolically. Instead, why not use numpy.polynomial.hermite.hermval? Also maybe use scipy.special.factorial to calculate the factorial.



import numpy as np
from numpy.polynomial.hermite import hermval
from scipy.special import factorial
import matplotlib.pyplot as plt
from matplotlib import animation


def psi(n, x, t):
A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * factorial(n)))
E = n + 0.5
nar = np.zeros(n+1)
nar[-1] = 1
f = A * hermval(x,nar) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
return f


def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
nf = int((xf - x0) / dx + 1)
nt = int((tf - t0) / dt + 1)
x = np.linspace(x0, xf, nf)
t = np.linspace(t0, tf, nt)

fig, ax = plt.subplots()

ax.set_xlim((x0, xf))
ax.set_ylim((ym, yM))

line, = ax.plot(, , lw=2)

def init():
line.set_data(, )
return line,

def animate(i):
y = f(x, i)
line.set_data(x, y)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=5 * t, interval=20, blit=True)
plt.show()
return anim


F = lambda x,t: psi(3, x, t)
anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)





share|improve this answer



























    up vote
    0
    down vote













    Here's a fix. Redefine your psi function to be:



    def psi(n, x, t):
    A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
    E = n + 0.5
    herms = np.array([hermite(n, xelem) for xelem in x])
    f = A * herms * np.exp(-(x ** 2) / 2) * np.cos(E * t)
    return f


    Basically, hermite seems to be a little weird/buggy. If x if a numpy array, then hermite(n=0, x) works just fine. However, if n>0 then hermite will complain bitterly if x is anything other than a single value. So we work around that by feeding in the values from x to hermite one at a time, then make the herms array from those results.



    Quantum mechanics was many years ago now, so I can't tell you if there is a justifiable reason for the inconsistency of hermite vis-a-vis array inputs. My guess is that it's just down to a slightly buggy implementation in sympy. In any case, once you fix up those two lines in psi the animations seem to work fine.






    share|improve this answer






















    • Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
      – Kirtpole
      Nov 11 at 1:33










    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244610%2fmatplotlib-wont-animate-a-function%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    I don't think you want to evaluate the hermite polynomials symbolically. Instead, why not use numpy.polynomial.hermite.hermval? Also maybe use scipy.special.factorial to calculate the factorial.



    import numpy as np
    from numpy.polynomial.hermite import hermval
    from scipy.special import factorial
    import matplotlib.pyplot as plt
    from matplotlib import animation


    def psi(n, x, t):
    A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * factorial(n)))
    E = n + 0.5
    nar = np.zeros(n+1)
    nar[-1] = 1
    f = A * hermval(x,nar) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
    return f


    def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
    nf = int((xf - x0) / dx + 1)
    nt = int((tf - t0) / dt + 1)
    x = np.linspace(x0, xf, nf)
    t = np.linspace(t0, tf, nt)

    fig, ax = plt.subplots()

    ax.set_xlim((x0, xf))
    ax.set_ylim((ym, yM))

    line, = ax.plot(, , lw=2)

    def init():
    line.set_data(, )
    return line,

    def animate(i):
    y = f(x, i)
    line.set_data(x, y)
    return line,

    anim = animation.FuncAnimation(fig, animate, init_func=init,
    frames=5 * t, interval=20, blit=True)
    plt.show()
    return anim


    F = lambda x,t: psi(3, x, t)
    anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)





    share|improve this answer
























      up vote
      0
      down vote



      accepted










      I don't think you want to evaluate the hermite polynomials symbolically. Instead, why not use numpy.polynomial.hermite.hermval? Also maybe use scipy.special.factorial to calculate the factorial.



      import numpy as np
      from numpy.polynomial.hermite import hermval
      from scipy.special import factorial
      import matplotlib.pyplot as plt
      from matplotlib import animation


      def psi(n, x, t):
      A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * factorial(n)))
      E = n + 0.5
      nar = np.zeros(n+1)
      nar[-1] = 1
      f = A * hermval(x,nar) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
      return f


      def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
      nf = int((xf - x0) / dx + 1)
      nt = int((tf - t0) / dt + 1)
      x = np.linspace(x0, xf, nf)
      t = np.linspace(t0, tf, nt)

      fig, ax = plt.subplots()

      ax.set_xlim((x0, xf))
      ax.set_ylim((ym, yM))

      line, = ax.plot(, , lw=2)

      def init():
      line.set_data(, )
      return line,

      def animate(i):
      y = f(x, i)
      line.set_data(x, y)
      return line,

      anim = animation.FuncAnimation(fig, animate, init_func=init,
      frames=5 * t, interval=20, blit=True)
      plt.show()
      return anim


      F = lambda x,t: psi(3, x, t)
      anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)





      share|improve this answer






















        up vote
        0
        down vote



        accepted







        up vote
        0
        down vote



        accepted






        I don't think you want to evaluate the hermite polynomials symbolically. Instead, why not use numpy.polynomial.hermite.hermval? Also maybe use scipy.special.factorial to calculate the factorial.



        import numpy as np
        from numpy.polynomial.hermite import hermval
        from scipy.special import factorial
        import matplotlib.pyplot as plt
        from matplotlib import animation


        def psi(n, x, t):
        A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * factorial(n)))
        E = n + 0.5
        nar = np.zeros(n+1)
        nar[-1] = 1
        f = A * hermval(x,nar) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
        return f


        def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
        nf = int((xf - x0) / dx + 1)
        nt = int((tf - t0) / dt + 1)
        x = np.linspace(x0, xf, nf)
        t = np.linspace(t0, tf, nt)

        fig, ax = plt.subplots()

        ax.set_xlim((x0, xf))
        ax.set_ylim((ym, yM))

        line, = ax.plot(, , lw=2)

        def init():
        line.set_data(, )
        return line,

        def animate(i):
        y = f(x, i)
        line.set_data(x, y)
        return line,

        anim = animation.FuncAnimation(fig, animate, init_func=init,
        frames=5 * t, interval=20, blit=True)
        plt.show()
        return anim


        F = lambda x,t: psi(3, x, t)
        anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)





        share|improve this answer












        I don't think you want to evaluate the hermite polynomials symbolically. Instead, why not use numpy.polynomial.hermite.hermval? Also maybe use scipy.special.factorial to calculate the factorial.



        import numpy as np
        from numpy.polynomial.hermite import hermval
        from scipy.special import factorial
        import matplotlib.pyplot as plt
        from matplotlib import animation


        def psi(n, x, t):
        A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * factorial(n)))
        E = n + 0.5
        nar = np.zeros(n+1)
        nar[-1] = 1
        f = A * hermval(x,nar) * np.exp(-(x ** 2) / 2) * np.cos(E * t)
        return f


        def animar(f, x0=0, xf=1, dx=0.01, t0=0, tf=1, dt=0.01, ym=-2, yM=2):
        nf = int((xf - x0) / dx + 1)
        nt = int((tf - t0) / dt + 1)
        x = np.linspace(x0, xf, nf)
        t = np.linspace(t0, tf, nt)

        fig, ax = plt.subplots()

        ax.set_xlim((x0, xf))
        ax.set_ylim((ym, yM))

        line, = ax.plot(, , lw=2)

        def init():
        line.set_data(, )
        return line,

        def animate(i):
        y = f(x, i)
        line.set_data(x, y)
        return line,

        anim = animation.FuncAnimation(fig, animate, init_func=init,
        frames=5 * t, interval=20, blit=True)
        plt.show()
        return anim


        F = lambda x,t: psi(3, x, t)
        anim = animar(F, x0=-3, xf=3, tf=3, ym=-1, yM=1)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 1:23









        ImportanceOfBeingErnest

        119k10119192




        119k10119192






















            up vote
            0
            down vote













            Here's a fix. Redefine your psi function to be:



            def psi(n, x, t):
            A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
            E = n + 0.5
            herms = np.array([hermite(n, xelem) for xelem in x])
            f = A * herms * np.exp(-(x ** 2) / 2) * np.cos(E * t)
            return f


            Basically, hermite seems to be a little weird/buggy. If x if a numpy array, then hermite(n=0, x) works just fine. However, if n>0 then hermite will complain bitterly if x is anything other than a single value. So we work around that by feeding in the values from x to hermite one at a time, then make the herms array from those results.



            Quantum mechanics was many years ago now, so I can't tell you if there is a justifiable reason for the inconsistency of hermite vis-a-vis array inputs. My guess is that it's just down to a slightly buggy implementation in sympy. In any case, once you fix up those two lines in psi the animations seem to work fine.






            share|improve this answer






















            • Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
              – Kirtpole
              Nov 11 at 1:33














            up vote
            0
            down vote













            Here's a fix. Redefine your psi function to be:



            def psi(n, x, t):
            A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
            E = n + 0.5
            herms = np.array([hermite(n, xelem) for xelem in x])
            f = A * herms * np.exp(-(x ** 2) / 2) * np.cos(E * t)
            return f


            Basically, hermite seems to be a little weird/buggy. If x if a numpy array, then hermite(n=0, x) works just fine. However, if n>0 then hermite will complain bitterly if x is anything other than a single value. So we work around that by feeding in the values from x to hermite one at a time, then make the herms array from those results.



            Quantum mechanics was many years ago now, so I can't tell you if there is a justifiable reason for the inconsistency of hermite vis-a-vis array inputs. My guess is that it's just down to a slightly buggy implementation in sympy. In any case, once you fix up those two lines in psi the animations seem to work fine.






            share|improve this answer






















            • Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
              – Kirtpole
              Nov 11 at 1:33












            up vote
            0
            down vote










            up vote
            0
            down vote









            Here's a fix. Redefine your psi function to be:



            def psi(n, x, t):
            A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
            E = n + 0.5
            herms = np.array([hermite(n, xelem) for xelem in x])
            f = A * herms * np.exp(-(x ** 2) / 2) * np.cos(E * t)
            return f


            Basically, hermite seems to be a little weird/buggy. If x if a numpy array, then hermite(n=0, x) works just fine. However, if n>0 then hermite will complain bitterly if x is anything other than a single value. So we work around that by feeding in the values from x to hermite one at a time, then make the herms array from those results.



            Quantum mechanics was many years ago now, so I can't tell you if there is a justifiable reason for the inconsistency of hermite vis-a-vis array inputs. My guess is that it's just down to a slightly buggy implementation in sympy. In any case, once you fix up those two lines in psi the animations seem to work fine.






            share|improve this answer














            Here's a fix. Redefine your psi function to be:



            def psi(n, x, t):
            A = (np.pi ** -0.25) * (1 / np.sqrt((2 ** n) * gamma(n + 1)))
            E = n + 0.5
            herms = np.array([hermite(n, xelem) for xelem in x])
            f = A * herms * np.exp(-(x ** 2) / 2) * np.cos(E * t)
            return f


            Basically, hermite seems to be a little weird/buggy. If x if a numpy array, then hermite(n=0, x) works just fine. However, if n>0 then hermite will complain bitterly if x is anything other than a single value. So we work around that by feeding in the values from x to hermite one at a time, then make the herms array from those results.



            Quantum mechanics was many years ago now, so I can't tell you if there is a justifiable reason for the inconsistency of hermite vis-a-vis array inputs. My guess is that it's just down to a slightly buggy implementation in sympy. In any case, once you fix up those two lines in psi the animations seem to work fine.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 11 at 1:25

























            answered Nov 11 at 1:19









            tel

            2,9431426




            2,9431426











            • Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
              – Kirtpole
              Nov 11 at 1:33
















            • Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
              – Kirtpole
              Nov 11 at 1:33















            Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
            – Kirtpole
            Nov 11 at 1:33




            Thanks! This worked perfectly. It's weird because I could get hermite to work when making a regular plot in x and manually change the value of t, but not on the animation. But welp, thanks for the help.
            – Kirtpole
            Nov 11 at 1:33

















             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244610%2fmatplotlib-wont-animate-a-function%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto