Matlab's “OutputFcn” implementation in Python for ODE solvingodeint returns wrong results for an ODE including descrete functionCalling an external command in PythonWhat are metaclasses in Python?Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Does Python have a string 'contains' substring method?

What is this unknown executable on my boot volume? Is it Malicious?

Why is the T-1000 humanoid?

Why did it become so much more expensive to start a university?

What's the biggest organic molecule that could have a smell?

Is there any way to land a rover on the Moon without using any thrusters?

Can the UK veto its own extension request?

What exactly is a marshrutka (маршрутка)?

In Germany, how can I maximize the impact of my charitable donations?

What are uses of the byte after BRK instruction on 6502?

Type leftwards arrow on macOS

Are scroll bars dead in 2019?

Is it appropriate for a professor to require students to sign a non-disclosure agreement before being taught?

Relocation error, error code (127) after last updates

Linear Programming with additional "if-then"/"Default to zero" constraints?

How to say "quirky" in German without sounding derogatory?

Could a Scotland-NI bridge break Brexit impasse?

Is there a reliable way to hide/convey a message in vocal expressions (speech, song,...)

What jurisdiction do Scottish courts have over the Westminster parliament?

Is "you will become a subject matter expert" code for "you'll be working on your own 100% of the time"?

Why do sellers care about down payments?

Were Roman public roads build by private companies?

Uncovering the Accelerated Dragon opening

Do they still use tiger roars in the 2019 "Lion King" movie?

Why isn't `typename` required for a base class that is a nested type?



Matlab's “OutputFcn” implementation in Python for ODE solving


odeint returns wrong results for an ODE including descrete functionCalling an external command in PythonWhat are metaclasses in Python?Is there a way to run Python on Android?Finding the index of an item given a list containing it in PythonWhat is the difference between Python's list methods append and extend?How can I safely create a nested directory?Does Python have a ternary conditional operator?How to get the current time in PythonHow can I make a time delay in Python?Does Python have a string 'contains' substring method?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to solve an ODE using Python's solve_ivp. However, I want to change the right hand side of my ODE dynamically based on a comparison between the current solution and previous solution. The idea behind this is that my right hand side is a vector field, and I want to ensure directionality of the vector field by reversing the right hand side based on the direction of the previous solution.



The implementation for this is as follows: I want to check the dot product in the right hand side function definition between the previous solution and the vector field. If the dot product is negative the right hand side is multiplied by -1.



I therefore need to access the previous state of the ODE solver and use it in comparison with the current iteration. In MATLAB there is the possibility of using "OutputFcn" while solving an ODE. This function is called after every iteration of the integrator. In the function it is therefore possible to simply extract the state as a variable and use it in the next iteration. I have not been able to find something similar for Python.



def RHS(timesnotused,x):
out = solve_ivp(doubleGyreVar, [0,T/2, T], [x[0], x[1], 1, 0, 0, 1], rtol = 1e-10, atol=1e-10)
output = out.y
J = output[2:,-1].reshape(2,2)
CG = np.matmul(J.T , J)
lambdas, xis = np.linalg.eig(CG)
xi_1 = xis[np.argmin(lambdas)]
xi_2 = xis[np.argmax(lambdas)]
lambda_1 = np.min(lambdas)
lambda_2 = np.max(lambdas)

alpha = ((lambda_2-lambda_1) / (lambda_2+lambda_1))**2

sign = 1
if np.dot(xlast,xi_1) < 0:
sign = -1

return(sign*alpha*xi_1)


As can be seen I want "xlast" to be the previous solution, and check it with xi_1 of the current iteration. Somehow xlast needs to be updated every iteration.










share|improve this question


























  • This is not a very well defined mathematical problem. How likely do you think that your computation is different to the case where you take the current point in the computation of the dot product?

    – LutzL
    Mar 28 at 10:11











  • I am not sure how likely it is, but the method I am trying to use has been executed earlier in Matlab using the "outputfcn" method,

    – Aalok Parkash
    Mar 28 at 10:16











  • I'm just saying that this sounds like an XY problem, where you look for a solution to the Y programming problem where it would be better to first gain clarity on the X mathematical modeling problem. Note that the times that outputfcn are called are non-predictable, and not guaranteed to be uniform. They are somewhat related to the curvature of the solution, and of course depending on the tolerances given. In any case what you are doing in the Y implementation is rather unrelated to the X problem and thus the exact solution.

    – LutzL
    Mar 28 at 11:42


















0















I am trying to solve an ODE using Python's solve_ivp. However, I want to change the right hand side of my ODE dynamically based on a comparison between the current solution and previous solution. The idea behind this is that my right hand side is a vector field, and I want to ensure directionality of the vector field by reversing the right hand side based on the direction of the previous solution.



The implementation for this is as follows: I want to check the dot product in the right hand side function definition between the previous solution and the vector field. If the dot product is negative the right hand side is multiplied by -1.



I therefore need to access the previous state of the ODE solver and use it in comparison with the current iteration. In MATLAB there is the possibility of using "OutputFcn" while solving an ODE. This function is called after every iteration of the integrator. In the function it is therefore possible to simply extract the state as a variable and use it in the next iteration. I have not been able to find something similar for Python.



def RHS(timesnotused,x):
out = solve_ivp(doubleGyreVar, [0,T/2, T], [x[0], x[1], 1, 0, 0, 1], rtol = 1e-10, atol=1e-10)
output = out.y
J = output[2:,-1].reshape(2,2)
CG = np.matmul(J.T , J)
lambdas, xis = np.linalg.eig(CG)
xi_1 = xis[np.argmin(lambdas)]
xi_2 = xis[np.argmax(lambdas)]
lambda_1 = np.min(lambdas)
lambda_2 = np.max(lambdas)

alpha = ((lambda_2-lambda_1) / (lambda_2+lambda_1))**2

sign = 1
if np.dot(xlast,xi_1) < 0:
sign = -1

return(sign*alpha*xi_1)


As can be seen I want "xlast" to be the previous solution, and check it with xi_1 of the current iteration. Somehow xlast needs to be updated every iteration.










share|improve this question


























  • This is not a very well defined mathematical problem. How likely do you think that your computation is different to the case where you take the current point in the computation of the dot product?

    – LutzL
    Mar 28 at 10:11











  • I am not sure how likely it is, but the method I am trying to use has been executed earlier in Matlab using the "outputfcn" method,

    – Aalok Parkash
    Mar 28 at 10:16











  • I'm just saying that this sounds like an XY problem, where you look for a solution to the Y programming problem where it would be better to first gain clarity on the X mathematical modeling problem. Note that the times that outputfcn are called are non-predictable, and not guaranteed to be uniform. They are somewhat related to the curvature of the solution, and of course depending on the tolerances given. In any case what you are doing in the Y implementation is rather unrelated to the X problem and thus the exact solution.

    – LutzL
    Mar 28 at 11:42














0












0








0








I am trying to solve an ODE using Python's solve_ivp. However, I want to change the right hand side of my ODE dynamically based on a comparison between the current solution and previous solution. The idea behind this is that my right hand side is a vector field, and I want to ensure directionality of the vector field by reversing the right hand side based on the direction of the previous solution.



The implementation for this is as follows: I want to check the dot product in the right hand side function definition between the previous solution and the vector field. If the dot product is negative the right hand side is multiplied by -1.



I therefore need to access the previous state of the ODE solver and use it in comparison with the current iteration. In MATLAB there is the possibility of using "OutputFcn" while solving an ODE. This function is called after every iteration of the integrator. In the function it is therefore possible to simply extract the state as a variable and use it in the next iteration. I have not been able to find something similar for Python.



def RHS(timesnotused,x):
out = solve_ivp(doubleGyreVar, [0,T/2, T], [x[0], x[1], 1, 0, 0, 1], rtol = 1e-10, atol=1e-10)
output = out.y
J = output[2:,-1].reshape(2,2)
CG = np.matmul(J.T , J)
lambdas, xis = np.linalg.eig(CG)
xi_1 = xis[np.argmin(lambdas)]
xi_2 = xis[np.argmax(lambdas)]
lambda_1 = np.min(lambdas)
lambda_2 = np.max(lambdas)

alpha = ((lambda_2-lambda_1) / (lambda_2+lambda_1))**2

sign = 1
if np.dot(xlast,xi_1) < 0:
sign = -1

return(sign*alpha*xi_1)


As can be seen I want "xlast" to be the previous solution, and check it with xi_1 of the current iteration. Somehow xlast needs to be updated every iteration.










share|improve this question
















I am trying to solve an ODE using Python's solve_ivp. However, I want to change the right hand side of my ODE dynamically based on a comparison between the current solution and previous solution. The idea behind this is that my right hand side is a vector field, and I want to ensure directionality of the vector field by reversing the right hand side based on the direction of the previous solution.



The implementation for this is as follows: I want to check the dot product in the right hand side function definition between the previous solution and the vector field. If the dot product is negative the right hand side is multiplied by -1.



I therefore need to access the previous state of the ODE solver and use it in comparison with the current iteration. In MATLAB there is the possibility of using "OutputFcn" while solving an ODE. This function is called after every iteration of the integrator. In the function it is therefore possible to simply extract the state as a variable and use it in the next iteration. I have not been able to find something similar for Python.



def RHS(timesnotused,x):
out = solve_ivp(doubleGyreVar, [0,T/2, T], [x[0], x[1], 1, 0, 0, 1], rtol = 1e-10, atol=1e-10)
output = out.y
J = output[2:,-1].reshape(2,2)
CG = np.matmul(J.T , J)
lambdas, xis = np.linalg.eig(CG)
xi_1 = xis[np.argmin(lambdas)]
xi_2 = xis[np.argmax(lambdas)]
lambda_1 = np.min(lambdas)
lambda_2 = np.max(lambdas)

alpha = ((lambda_2-lambda_1) / (lambda_2+lambda_1))**2

sign = 1
if np.dot(xlast,xi_1) < 0:
sign = -1

return(sign*alpha*xi_1)


As can be seen I want "xlast" to be the previous solution, and check it with xi_1 of the current iteration. Somehow xlast needs to be updated every iteration.







python matlab ode






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 9:59







Aalok Parkash

















asked Mar 28 at 9:54









Aalok ParkashAalok Parkash

212 bronze badges




212 bronze badges















  • This is not a very well defined mathematical problem. How likely do you think that your computation is different to the case where you take the current point in the computation of the dot product?

    – LutzL
    Mar 28 at 10:11











  • I am not sure how likely it is, but the method I am trying to use has been executed earlier in Matlab using the "outputfcn" method,

    – Aalok Parkash
    Mar 28 at 10:16











  • I'm just saying that this sounds like an XY problem, where you look for a solution to the Y programming problem where it would be better to first gain clarity on the X mathematical modeling problem. Note that the times that outputfcn are called are non-predictable, and not guaranteed to be uniform. They are somewhat related to the curvature of the solution, and of course depending on the tolerances given. In any case what you are doing in the Y implementation is rather unrelated to the X problem and thus the exact solution.

    – LutzL
    Mar 28 at 11:42


















  • This is not a very well defined mathematical problem. How likely do you think that your computation is different to the case where you take the current point in the computation of the dot product?

    – LutzL
    Mar 28 at 10:11











  • I am not sure how likely it is, but the method I am trying to use has been executed earlier in Matlab using the "outputfcn" method,

    – Aalok Parkash
    Mar 28 at 10:16











  • I'm just saying that this sounds like an XY problem, where you look for a solution to the Y programming problem where it would be better to first gain clarity on the X mathematical modeling problem. Note that the times that outputfcn are called are non-predictable, and not guaranteed to be uniform. They are somewhat related to the curvature of the solution, and of course depending on the tolerances given. In any case what you are doing in the Y implementation is rather unrelated to the X problem and thus the exact solution.

    – LutzL
    Mar 28 at 11:42

















This is not a very well defined mathematical problem. How likely do you think that your computation is different to the case where you take the current point in the computation of the dot product?

– LutzL
Mar 28 at 10:11





This is not a very well defined mathematical problem. How likely do you think that your computation is different to the case where you take the current point in the computation of the dot product?

– LutzL
Mar 28 at 10:11













I am not sure how likely it is, but the method I am trying to use has been executed earlier in Matlab using the "outputfcn" method,

– Aalok Parkash
Mar 28 at 10:16





I am not sure how likely it is, but the method I am trying to use has been executed earlier in Matlab using the "outputfcn" method,

– Aalok Parkash
Mar 28 at 10:16













I'm just saying that this sounds like an XY problem, where you look for a solution to the Y programming problem where it would be better to first gain clarity on the X mathematical modeling problem. Note that the times that outputfcn are called are non-predictable, and not guaranteed to be uniform. They are somewhat related to the curvature of the solution, and of course depending on the tolerances given. In any case what you are doing in the Y implementation is rather unrelated to the X problem and thus the exact solution.

– LutzL
Mar 28 at 11:42






I'm just saying that this sounds like an XY problem, where you look for a solution to the Y programming problem where it would be better to first gain clarity on the X mathematical modeling problem. Note that the times that outputfcn are called are non-predictable, and not guaranteed to be uniform. They are somewhat related to the curvature of the solution, and of course depending on the tolerances given. In any case what you are doing in the Y implementation is rather unrelated to the X problem and thus the exact solution.

– LutzL
Mar 28 at 11:42













1 Answer
1






active

oldest

votes


















0
















If the differential equation you want to solve is



dx/dt = sign(g(x)) * F(x)


for some sufficiently smooth functions g, F, then you have a discontinuous right side where all advanced numerical solvers will produce nonsense as soon as they approach this jump singularity.



The clearest method to solve such a multi-phase system is to present only continuous right sides to the numerical solver and to handle the phase change via the event mechanism that is also present in scipy.integrate.solve_ivp.



I explored a mechanism to do that with the tools of scipy in a similar problem with a sign function producing a discontinuity in odeint returns wrong results for an ODE including descrete function






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',
    autoActivateHeartbeat: false,
    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/4.0/"u003ecc by-sa 4.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%2f55394633%2fmatlabs-outputfcn-implementation-in-python-for-ode-solving%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









    0
















    If the differential equation you want to solve is



    dx/dt = sign(g(x)) * F(x)


    for some sufficiently smooth functions g, F, then you have a discontinuous right side where all advanced numerical solvers will produce nonsense as soon as they approach this jump singularity.



    The clearest method to solve such a multi-phase system is to present only continuous right sides to the numerical solver and to handle the phase change via the event mechanism that is also present in scipy.integrate.solve_ivp.



    I explored a mechanism to do that with the tools of scipy in a similar problem with a sign function producing a discontinuity in odeint returns wrong results for an ODE including descrete function






    share|improve this answer































      0
















      If the differential equation you want to solve is



      dx/dt = sign(g(x)) * F(x)


      for some sufficiently smooth functions g, F, then you have a discontinuous right side where all advanced numerical solvers will produce nonsense as soon as they approach this jump singularity.



      The clearest method to solve such a multi-phase system is to present only continuous right sides to the numerical solver and to handle the phase change via the event mechanism that is also present in scipy.integrate.solve_ivp.



      I explored a mechanism to do that with the tools of scipy in a similar problem with a sign function producing a discontinuity in odeint returns wrong results for an ODE including descrete function






      share|improve this answer





























        0














        0










        0









        If the differential equation you want to solve is



        dx/dt = sign(g(x)) * F(x)


        for some sufficiently smooth functions g, F, then you have a discontinuous right side where all advanced numerical solvers will produce nonsense as soon as they approach this jump singularity.



        The clearest method to solve such a multi-phase system is to present only continuous right sides to the numerical solver and to handle the phase change via the event mechanism that is also present in scipy.integrate.solve_ivp.



        I explored a mechanism to do that with the tools of scipy in a similar problem with a sign function producing a discontinuity in odeint returns wrong results for an ODE including descrete function






        share|improve this answer















        If the differential equation you want to solve is



        dx/dt = sign(g(x)) * F(x)


        for some sufficiently smooth functions g, F, then you have a discontinuous right side where all advanced numerical solvers will produce nonsense as soon as they approach this jump singularity.



        The clearest method to solve such a multi-phase system is to present only continuous right sides to the numerical solver and to handle the phase change via the event mechanism that is also present in scipy.integrate.solve_ivp.



        I explored a mechanism to do that with the tools of scipy in a similar problem with a sign function producing a discontinuity in odeint returns wrong results for an ODE including descrete function







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 28 at 13:59

























        answered Mar 28 at 12:07









        LutzLLutzL

        14.9k2 gold badges14 silver badges27 bronze badges




        14.9k2 gold badges14 silver badges27 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.




















            draft saved

            draft discarded















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394633%2fmatlabs-outputfcn-implementation-in-python-for-ode-solving%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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript