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

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현