Using solve_ivp instead of odeint to solve initial problem value











up vote
0
down vote

favorite












Currently, I solve the following ODE system of equations using odeint



dx/dt = (-x + u)/2.0



dy/dt = (-y + x)/5.0



initial conditions: x = 0, y = 0



However, I would like to use solve_ivp which seems to be the recommended option for this type of problems, but honestly I don't know how to adapt the code...



Here is the code I'm using with odeint:



import numpy as np
from scipy.integrate import odeint, solve_ivp
import matplotlib.pyplot as plt

def model(z, t, u):
x = z[0]
y = z[1]
dxdt = (-x + u)/2.0
dydt = (-y + x)/5.0
dzdt = [dxdt, dydt]
return dzdt

def main():
# initial condition
z0 = [0, 0]

# number of time points
n = 401

# time points
t = np.linspace(0, 40, n)

# step input
u = np.zeros(n)
# change to 2.0 at time = 5.0
u[51:] = 2.0

# store solution
x = np.empty_like(t)
y = np.empty_like(t)
# record initial conditions
x[0] = z0[0]
y[0] = z0[1]

# solve ODE
for i in range(1, n):
# span for next time step
tspan = [t[i-1], t[i]]
# solve for next step
z = odeint(model, z0, tspan, args=(u[i],))
# store solution for plotting
x[i] = z[1][0]
y[i] = z[1][1]
# next initial condition
z0 = z[1]

# plot results
plt.plot(t,u,'g:',label='u(t)')
plt.plot(t,x,'b-',label='x(t)')
plt.plot(t,y,'r--',label='y(t)')
plt.ylabel('values')
plt.xlabel('time')
plt.legend(loc='best')
plt.show()

main()









share|improve this question


























    up vote
    0
    down vote

    favorite












    Currently, I solve the following ODE system of equations using odeint



    dx/dt = (-x + u)/2.0



    dy/dt = (-y + x)/5.0



    initial conditions: x = 0, y = 0



    However, I would like to use solve_ivp which seems to be the recommended option for this type of problems, but honestly I don't know how to adapt the code...



    Here is the code I'm using with odeint:



    import numpy as np
    from scipy.integrate import odeint, solve_ivp
    import matplotlib.pyplot as plt

    def model(z, t, u):
    x = z[0]
    y = z[1]
    dxdt = (-x + u)/2.0
    dydt = (-y + x)/5.0
    dzdt = [dxdt, dydt]
    return dzdt

    def main():
    # initial condition
    z0 = [0, 0]

    # number of time points
    n = 401

    # time points
    t = np.linspace(0, 40, n)

    # step input
    u = np.zeros(n)
    # change to 2.0 at time = 5.0
    u[51:] = 2.0

    # store solution
    x = np.empty_like(t)
    y = np.empty_like(t)
    # record initial conditions
    x[0] = z0[0]
    y[0] = z0[1]

    # solve ODE
    for i in range(1, n):
    # span for next time step
    tspan = [t[i-1], t[i]]
    # solve for next step
    z = odeint(model, z0, tspan, args=(u[i],))
    # store solution for plotting
    x[i] = z[1][0]
    y[i] = z[1][1]
    # next initial condition
    z0 = z[1]

    # plot results
    plt.plot(t,u,'g:',label='u(t)')
    plt.plot(t,x,'b-',label='x(t)')
    plt.plot(t,y,'r--',label='y(t)')
    plt.ylabel('values')
    plt.xlabel('time')
    plt.legend(loc='best')
    plt.show()

    main()









    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Currently, I solve the following ODE system of equations using odeint



      dx/dt = (-x + u)/2.0



      dy/dt = (-y + x)/5.0



      initial conditions: x = 0, y = 0



      However, I would like to use solve_ivp which seems to be the recommended option for this type of problems, but honestly I don't know how to adapt the code...



      Here is the code I'm using with odeint:



      import numpy as np
      from scipy.integrate import odeint, solve_ivp
      import matplotlib.pyplot as plt

      def model(z, t, u):
      x = z[0]
      y = z[1]
      dxdt = (-x + u)/2.0
      dydt = (-y + x)/5.0
      dzdt = [dxdt, dydt]
      return dzdt

      def main():
      # initial condition
      z0 = [0, 0]

      # number of time points
      n = 401

      # time points
      t = np.linspace(0, 40, n)

      # step input
      u = np.zeros(n)
      # change to 2.0 at time = 5.0
      u[51:] = 2.0

      # store solution
      x = np.empty_like(t)
      y = np.empty_like(t)
      # record initial conditions
      x[0] = z0[0]
      y[0] = z0[1]

      # solve ODE
      for i in range(1, n):
      # span for next time step
      tspan = [t[i-1], t[i]]
      # solve for next step
      z = odeint(model, z0, tspan, args=(u[i],))
      # store solution for plotting
      x[i] = z[1][0]
      y[i] = z[1][1]
      # next initial condition
      z0 = z[1]

      # plot results
      plt.plot(t,u,'g:',label='u(t)')
      plt.plot(t,x,'b-',label='x(t)')
      plt.plot(t,y,'r--',label='y(t)')
      plt.ylabel('values')
      plt.xlabel('time')
      plt.legend(loc='best')
      plt.show()

      main()









      share|improve this question













      Currently, I solve the following ODE system of equations using odeint



      dx/dt = (-x + u)/2.0



      dy/dt = (-y + x)/5.0



      initial conditions: x = 0, y = 0



      However, I would like to use solve_ivp which seems to be the recommended option for this type of problems, but honestly I don't know how to adapt the code...



      Here is the code I'm using with odeint:



      import numpy as np
      from scipy.integrate import odeint, solve_ivp
      import matplotlib.pyplot as plt

      def model(z, t, u):
      x = z[0]
      y = z[1]
      dxdt = (-x + u)/2.0
      dydt = (-y + x)/5.0
      dzdt = [dxdt, dydt]
      return dzdt

      def main():
      # initial condition
      z0 = [0, 0]

      # number of time points
      n = 401

      # time points
      t = np.linspace(0, 40, n)

      # step input
      u = np.zeros(n)
      # change to 2.0 at time = 5.0
      u[51:] = 2.0

      # store solution
      x = np.empty_like(t)
      y = np.empty_like(t)
      # record initial conditions
      x[0] = z0[0]
      y[0] = z0[1]

      # solve ODE
      for i in range(1, n):
      # span for next time step
      tspan = [t[i-1], t[i]]
      # solve for next step
      z = odeint(model, z0, tspan, args=(u[i],))
      # store solution for plotting
      x[i] = z[1][0]
      y[i] = z[1][1]
      # next initial condition
      z0 = z[1]

      # plot results
      plt.plot(t,u,'g:',label='u(t)')
      plt.plot(t,x,'b-',label='x(t)')
      plt.plot(t,y,'r--',label='y(t)')
      plt.ylabel('values')
      plt.xlabel('time')
      plt.legend(loc='best')
      plt.show()

      main()






      python scipy ode differential-equations






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 at 15:26









      Sergio Manchado

      484




      484
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          It's important that solve_ivp expects f(t, z) as right-hand side of the ODE. If you don't want to change your ode function and also want to pass your parameter u, I recommend to define a wrapper function:



          def model(z, t, u):
          x = z[0]
          y = z[1]
          dxdt = (-x + u)/2.0
          dydt = (-y + x)/5.0
          dzdt = [dxdt, dydt]
          return dzdt

          def odefun(t, z):
          if t < 5:
          return model(z, t, 0)
          else:
          return model(z, t, 2)


          Now it's easy to call solve_ivp:



          def main():
          # initial condition
          z0 = [0, 0]

          # number of time points
          n = 401

          # time points
          t = np.linspace(0, 40, n)

          # step input
          u = np.zeros(n)
          # change to 2.0 at time = 5.0
          u[51:] = 2.0

          res = solve_ivp(fun=odefun, t_span=[0, 40], y0=z0, t_eval=t)
          x = res.y[0, :]
          y = res.y[1, :]

          # plot results
          plt.plot(t,u,'g:',label='u(t)')
          plt.plot(t,x,'b-',label='x(t)')
          plt.plot(t,y,'r--',label='y(t)')
          plt.ylabel('values')
          plt.xlabel('time')
          plt.legend(loc='best')
          plt.show()

          main()


          Note that without passing t_eval=t, the solver will automatically choose the time points inside tspan at which the solution will be stored.






          share|improve this answer





















            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%2f53415322%2fusing-solve-ivp-instead-of-odeint-to-solve-initial-problem-value%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            It's important that solve_ivp expects f(t, z) as right-hand side of the ODE. If you don't want to change your ode function and also want to pass your parameter u, I recommend to define a wrapper function:



            def model(z, t, u):
            x = z[0]
            y = z[1]
            dxdt = (-x + u)/2.0
            dydt = (-y + x)/5.0
            dzdt = [dxdt, dydt]
            return dzdt

            def odefun(t, z):
            if t < 5:
            return model(z, t, 0)
            else:
            return model(z, t, 2)


            Now it's easy to call solve_ivp:



            def main():
            # initial condition
            z0 = [0, 0]

            # number of time points
            n = 401

            # time points
            t = np.linspace(0, 40, n)

            # step input
            u = np.zeros(n)
            # change to 2.0 at time = 5.0
            u[51:] = 2.0

            res = solve_ivp(fun=odefun, t_span=[0, 40], y0=z0, t_eval=t)
            x = res.y[0, :]
            y = res.y[1, :]

            # plot results
            plt.plot(t,u,'g:',label='u(t)')
            plt.plot(t,x,'b-',label='x(t)')
            plt.plot(t,y,'r--',label='y(t)')
            plt.ylabel('values')
            plt.xlabel('time')
            plt.legend(loc='best')
            plt.show()

            main()


            Note that without passing t_eval=t, the solver will automatically choose the time points inside tspan at which the solution will be stored.






            share|improve this answer

























              up vote
              0
              down vote



              accepted










              It's important that solve_ivp expects f(t, z) as right-hand side of the ODE. If you don't want to change your ode function and also want to pass your parameter u, I recommend to define a wrapper function:



              def model(z, t, u):
              x = z[0]
              y = z[1]
              dxdt = (-x + u)/2.0
              dydt = (-y + x)/5.0
              dzdt = [dxdt, dydt]
              return dzdt

              def odefun(t, z):
              if t < 5:
              return model(z, t, 0)
              else:
              return model(z, t, 2)


              Now it's easy to call solve_ivp:



              def main():
              # initial condition
              z0 = [0, 0]

              # number of time points
              n = 401

              # time points
              t = np.linspace(0, 40, n)

              # step input
              u = np.zeros(n)
              # change to 2.0 at time = 5.0
              u[51:] = 2.0

              res = solve_ivp(fun=odefun, t_span=[0, 40], y0=z0, t_eval=t)
              x = res.y[0, :]
              y = res.y[1, :]

              # plot results
              plt.plot(t,u,'g:',label='u(t)')
              plt.plot(t,x,'b-',label='x(t)')
              plt.plot(t,y,'r--',label='y(t)')
              plt.ylabel('values')
              plt.xlabel('time')
              plt.legend(loc='best')
              plt.show()

              main()


              Note that without passing t_eval=t, the solver will automatically choose the time points inside tspan at which the solution will be stored.






              share|improve this answer























                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                It's important that solve_ivp expects f(t, z) as right-hand side of the ODE. If you don't want to change your ode function and also want to pass your parameter u, I recommend to define a wrapper function:



                def model(z, t, u):
                x = z[0]
                y = z[1]
                dxdt = (-x + u)/2.0
                dydt = (-y + x)/5.0
                dzdt = [dxdt, dydt]
                return dzdt

                def odefun(t, z):
                if t < 5:
                return model(z, t, 0)
                else:
                return model(z, t, 2)


                Now it's easy to call solve_ivp:



                def main():
                # initial condition
                z0 = [0, 0]

                # number of time points
                n = 401

                # time points
                t = np.linspace(0, 40, n)

                # step input
                u = np.zeros(n)
                # change to 2.0 at time = 5.0
                u[51:] = 2.0

                res = solve_ivp(fun=odefun, t_span=[0, 40], y0=z0, t_eval=t)
                x = res.y[0, :]
                y = res.y[1, :]

                # plot results
                plt.plot(t,u,'g:',label='u(t)')
                plt.plot(t,x,'b-',label='x(t)')
                plt.plot(t,y,'r--',label='y(t)')
                plt.ylabel('values')
                plt.xlabel('time')
                plt.legend(loc='best')
                plt.show()

                main()


                Note that without passing t_eval=t, the solver will automatically choose the time points inside tspan at which the solution will be stored.






                share|improve this answer












                It's important that solve_ivp expects f(t, z) as right-hand side of the ODE. If you don't want to change your ode function and also want to pass your parameter u, I recommend to define a wrapper function:



                def model(z, t, u):
                x = z[0]
                y = z[1]
                dxdt = (-x + u)/2.0
                dydt = (-y + x)/5.0
                dzdt = [dxdt, dydt]
                return dzdt

                def odefun(t, z):
                if t < 5:
                return model(z, t, 0)
                else:
                return model(z, t, 2)


                Now it's easy to call solve_ivp:



                def main():
                # initial condition
                z0 = [0, 0]

                # number of time points
                n = 401

                # time points
                t = np.linspace(0, 40, n)

                # step input
                u = np.zeros(n)
                # change to 2.0 at time = 5.0
                u[51:] = 2.0

                res = solve_ivp(fun=odefun, t_span=[0, 40], y0=z0, t_eval=t)
                x = res.y[0, :]
                y = res.y[1, :]

                # plot results
                plt.plot(t,u,'g:',label='u(t)')
                plt.plot(t,x,'b-',label='x(t)')
                plt.plot(t,y,'r--',label='y(t)')
                plt.ylabel('values')
                plt.xlabel('time')
                plt.legend(loc='best')
                plt.show()

                main()


                Note that without passing t_eval=t, the solver will automatically choose the time points inside tspan at which the solution will be stored.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 at 18:53









                joni

                678157




                678157






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53415322%2fusing-solve-ivp-instead-of-odeint-to-solve-initial-problem-value%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







                    Popular posts from this blog

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks