Running an ODEProblem until given a signal - callback

Is it possible for the timespan of an ODEProblem to be open-ended, i.e. for the problem to run until given an external signal (possibly via a discrete callback with an appropriate condition)? Intuitively, this would mean giving something like tspan = (0.0, Inf), although I'm not sure if that is allowed and can't seem to find anything in the documentation. TIA.

Yes, you can use tspan = (0.0, Inf). Of course, if you do this, you'll want to make sure you setup a terminating event like in this example so that it doesn't run forever, or you can use the integrator interface to control the steps and stop whenever you want.

Related

Ending fminsearch on a whim

Id like to be able to cancel fminsearch (eg using ctrl+c) and retaining the best solution so far. Is there a way to do this? I dont know exactly what sort of tolerance I want to set, I'd much rather "play by ear" and ctrl+c when I'm satisfied with the solution. Matlab keeps going onnn and on and on for what seems to be no gain.
fminsearch can be terminated early by both output functions and plot functions. To get an interactive demand from the user, use of graphical interfaces that don't wait until code is finished executing to update is basically essential, so using a plot function would be the most straightforward way of achieving this. The default plot function figure has "Stop" and "Pause" buttons built in, as seen in the documentation's example for calling:
fminsearch(funfcn,x,optimset('PlotFcns',#optimplotfval))
If the Stop button is clicked, fminsearch returns the result of its latest iteration and by default displays the information:
Optimization terminated prematurely by user.

Matlab Simulink: while loop with subtraction

I am hoping somebody here will be able to help me out with my small issue with one of the Simulink/Matlab code. It is quite similar to the problem that I’ve discussed earlier, but a little bit more complicated and now it is more a Simulink issue, rather than a Matlab one.
So I have a turbine which speed is controlled by the gate’s opening, hence the control voltage. By controlling the gate opening I am accelerating the turbine and at some point in time, I need to introduce a saturation effect (since I am testing the code now, it will be done an external signal). This effect won’t change the control voltage, but it affects other components of the system, hence at the same control voltage, the turbine’s speed will go up. But at the same time, I need to keep the speed at the same value as it was before the saturation effect (let’s say it was 320 rpm). To do so I need to decrease the control voltage and should keep doing it until I reach the speed as it was before. There is no need to do it instantly (this approach will be later introduced in hardware), but it will be a nice thing to check the algorithm in these synthetic tests.
In terms of the model, I was planning to use a while loop with the speed requirement “if speed > 320” again, now just to simplify things. To decrease the control voltage I was planning to subtract from the original 50 (% opening) - 0.25 (u2) at first and after that increasing this value by 0.25 until I decrease the speed below 320. I can’t know the exact opening when this requirement will be satisfied, hence I need some kind of algorithm to “track” this voltage.
So it should be something like this:
u2 = 0;
While speed > 320
u2 = u2+0.25
End
u2 is initially zero since we have a predefined initial control voltage. And obviously, when we reach the motor’s speed below 320, I need to keep the latest value of the u2 (and control voltage).
Overall, it is a small code and should be done in Simulink (don’t want to introduce any other Fcn function into the model). I’ve never used while and if blocks in Simulink, but so far I came up with this system. It’s a simplified version of my model, but the control principle is the same.
We are getting the motor speed of 350, compared with 320 (the speed before “saturation), and if our speed after saturation is higher, we need to reduce the control voltage. To trigger the while loop block I’ve decided to use a simple switch. The while block meanwhile is:
Definitely not the best implementation but I was trying a lot of different combinations and without any real success. I am always getting the same error:
Was trying to use a step signal instead of the constant “7” – to model acceleration of the motor, and was getting the same error at the moment of acceleration above 320 threshold. So looks like the approach is almost right but mathematically it fails to find the most suitable solution. I’ve tried to implement a transport delay in the memory part of the while subsystem but was getting errors during compilation all the time.
Are there any obvious (and not so) mistakes? Or maybe from the beginning, I should have chosen another approach… I really hope that somebody will be able to help. Thank you in advance and have a great day.
I do not think that you have used While block correctly.
This is what I have done, I used a "Matlab function" block instead of "While" block as follows,
The function in Matlab function is
function u2=fcn(speed,u2d)
if speed>320
u2=u2d+0.25;
else
u2=u2d;
end
And the results I have got, Scope 1
Scope
Edit
As you prefer a function free model, the following may do the same.

Searching for max-min in MATLAB

I am writing a matlab code where i calculate the max-min.
I am using matlab's "fminimax" to solve the following problem:
ki=G(i,:);
ki(i)=0;
fs(i)=-((G(i,i)*pt(i)+sum(ki.*pt)+C1)-(C2*(sum(ki.*pt)+C1)));
G: is a system matrix. pt: is the optimization variable.
When the actual system matrix is used, the "fminimax" stops after one iteration and returns the initial value of "pt", no matter what the initial value for "pt", i.e. no solution is found. (the initial value is defined as X0 in the documentation). The system has the following parameters: G is in the order of e-11, pt is in the order of e-1, and c1 is in the order of e-14.
when i try a randomly generated test matrix and different parameters, the "fminimax" finds a solution for the problem, and everything works fine. G in order of e-2, pt in order of e-2, c1 is in the order of e-7.
I tried to scale the actual system: "fminimax" lasted more than one iteration, however, it still returned the initial value of pt, i.e. it couldn't find a solution.
I tried to change the tolerance of the "fminmax", using "options" [StepTolerance, OptimalityTolerance, ConstraintTolerance, and functiontolerance]. There were no impact at all. still no solution.
I thought that the problem might be that the precision of "fminimax" is not that high, or it is not suitable to solve the problem. i think it is also slow.
i downloaded CPLX, and i wanted to transform the max-min problem into linear programing, using a method i found in a book. However, when i tried my code on a simple minimax it didn't give the same solution.
I thought of using CVX for example, but the problem is not convex.
What might be the problem?
P.S. the system matrix, G, has different realizations, i tried some of them. However, the "fminimax" responds in the same way for all of them, i.e. it wasn't able to find an adequate solution.
I am not convinced that the optimization solvers are broken. If the problem is nonconvex, then there can be multiple local minimizers. Given the information you have provided, we have no way of knowing whether you started at an initial condition.
The first place you need to start is by getting more information from the optimization exit condition... Did it finish because it hit the iteration limit? (I hope not since it isn't doing many iterations)... Did it finish because a tolerance was hit (e.g. the function did not change by more than xxxx)? Or perhaps it could not find a feasible solution? (I don't know if you have any constraints that need to be met).
More than likely, I wold guess that you are starting at a local minimizer without realizing it. So you need to determine whether you are indeed at a local minimizer by looking at the jacobian of the function evaluated at your initial guess. Either calculate it analytically or use a finite step approximation....

Change simulink parameters at runtime from the code/block flow

My initial problem is that I have a continuous transfer function which coefficients change with time.
Currently the TF's coefficients are expressed in function of the block mask parameters. These parameters are tunable, and if I change the value in the mask parameters dialog during a simulation the response seems to react appropriately.
However how can I do just that in the code/block flow? Basically, I
have the block parameter 'maskParam' which is set using the mask
parameters dialog, and in the mask initialization commands:
'param=maskParam'. 'param' is used in the transfer function and I
would like to change it in real time (as param=maskParam*f(t)).
I have already looked around and found relevant solutions but either it's unbelievably complicated; or the only transfer function which we are allowed to modify at runtime is discrete and 1) I would like to avoid z-transforming my quite complex TF (I don't have the control toolbox) 2) The sampling time seems to be fixed.. None uses this "dirty" technique of updating parameters, maybe that's the way around?
To illustrate:
I am assuming that you want to change your sim parameters whilst the simulation is running?
A solution is that you run your simulation for inf period and use/change a workspace variable during the simulation period to make the changes take effect.
for Example:
If you look at the w block, you can set it's value in runtime, by doing this:
set_param('my_model_name/w', 'value', 100); % Will change to 100 immediately
You can do similar things with arrays (i.e. a list of coefficients in your case).
HINT FOR YOU
You are using discrete transfer function block. Try the following:
1) Give your block a name e.g. fcn_1
2) In your script, type set_param('your_model_name/fcn_1', 'numerator', '[1 2]'); This will set the numerator value to [1 2]. Do the same for denominator.
3) You should be able to understand, through this exercise, how to handle the property names etc. so that you can change/get them using set_param/get_param.
I leave you to investigate further.
The short answer is that Simulink blocks are not really designed to do this. By definition, a transfer function is Liner-Time Invariant, meaning its characteristics (read coefficients) do not vary with time.
Having said that, there are some workarounds, such as the ones you mentioned in your question. These are the correct way to approach the problem I'm afraid, other than the set_param method suggested by #ha9u63ar. See also this blog on the subject on the MathWorks web site.

diagnostic for MATLAB ODE

I am solving a stiff PDE in MATLAB using ode15, and it often freezes depending on the initial conditions. I never actually get an error, it just won't finish even after 10 hours when it should take around 30 seconds to run. I am experimenting with different spatial and time node intervals, but it is hard, because I don't get feedback.
Is there some sort of equivalent to diagnostic for fsolve? stats is not useful because it only displays an output after fsolve is finished.
Check out the documentation on odeset, and specifically the stats option. I think you basically just want to set stats to on and you will get some feedback.
Also, depending on your ODE, you may need a different solver. About half way down the page on this page there is a list of most of the solvers available in MATLAB. Depending on whether your function is stiff or non-stiff, and how accurate you need to get, one of those might work better for you. Sometimes I just code them all in and comment out all but one until I find the one that runs the best for me, but check out the documentation on each if you want to find the "right" one for your application.
Your question is confusing because you refer to both ode15s and fsolve locking up. These are two completely different functions. One does numerical integration and the other solves for roots. Also, fsolve has no option called 'Stats' (see doc fsolve). If you want continuous output from fsolve use:
options = optimist('Display','iter');
[x,fval,exitflag] = fsolve(myfun,x0,options)
This will display the iteration count, number of function evaluations, the function value, and other stuff depending on what algorithm you use (the alorithm can be adjusted via the 'Algorithm' option). Again see doc fsolve for full details.
As far as the 'Stats' option with ode15s goes, it's not going to give you very much information. I doubt that it will you figure out why your system is halting (if it even is ode15s that you have a problem with). What you can try is using an output function via the 'OutputFcn' option of odeset. You can try the simple odeprint first:
options = odeset('OutputFcn',#odeprint)
which will print your state after each integration step. Type edit odeprint to see the code and how you might write your own output function if you need to do more.