How to optimize a function existing as a embedded function block in simulink, part of MATLab, using fmincon? - optimization

function y = objfun(x)
sim('modelprototype.slx');
y = Y(1);
end
It is in simulink embedded func block.
Before that I ask for help, I will explain what I did and what I want;
I had a function as a script in matlab. Having entered the parameters to fmincon to optimize my fuction, It worked correctly. And iterated 9 times and lastly found the minimum value of my function;
But the problem is occured when I decided to write the function in a embedded function existing in simulink model. Like I did above I entered all parameters for fmincon it only iterates 3 times and the values are same. I could not find the minimum value.
Please help me to find a solution to optimize the function in simulink model like that same function written as ascript file in matlab.
I want to write the function indicated in that link in simulink embedded function block and optimize it;
You can find information from the link below;
-https://www.mathworks.com/help/optim/ug/output-functions.html
You can reach Code and File
-https://github.com/saibermehmet/MATLAB.git
I again indicate that I want to optimize the obj function when it is a embedded function block in simulink instead of a ordinary function m-file.

Related

How to get Elemwise{tanh,no_inplace}.0 value

I am using Deep learning Theano. How can I see the content of a variable like this: Elemwise{tanh,no_inplace}.0. It is the input data of logistic layer.
Suppose your variable is called t. Then you can evaluate it by calling t.eval(). This may fail if input data are needed. In that case you need to supply them by providing a dictionary like this t.eval({input_var1: value1, input_var2: value2}). This is the ad-hoc way of evaluating a theano-expression.
The way it works in real programs is to create a function taking the necessary input, for example: f = theano.function([input_var1, input_var2], t), will yield a function that takes two input variables, calculates t from them and outputs the result.
Right now, you don't seem to print values but operations. The output Elemwise{tanh,no_inplace}.0 means, that you have an element wise operation of tanh, that is not done in place. You still need to create a function that takes input and executes your operation. Then you need to call that function and print the result. You can read more about that in the graph-structure part of their tutorial.

How to allow end user write his own functions?

I'm modeling some financial products and each product has his own pricing formula.
In the application I would like to allow the end-user create his own product with the formula. And this formula can be used by my application to price the product.
Something like :
Formula as string = "f(x) = x * 2"
Dim Result as double = call(Formula, 1)
I know this is possible in Matlab :
f="#(x)(x*2)";
Result = feval(f,1);
I wrote a class in Matlab that implements this feature and integrated it in VB.Net project, but every function takes 4700 times the execution of the same function directly written in VB.Net which is not affordable regarding the business need.
Is that possible in .Net ?
You can look into MEF, so your end users would provide DLL modules in a certain format (see the link I mentioned), which would later be discovered in your program and executed at any given time.
Or use a math parser:
VB.Net- Evaluating Mathematical Expression in a String
Evaluate mathematical expression from a string using VB
But I feel that approach #1 would be more flexible.

Realtime Optimization in Dymola

I was wondering if anyone who has used the Optimization Library in Dymola has been able to utilize the RealtimeOptimization function without having explicit plant constitutive equations to input into the criteriaFunction? Specifically, I am trying to use some of my model's states as the criteria function, but when I input y[1] := mymodel.state; with or without quotes around the state, Dymola rejects the function. Any thoughts would be very helpful. Thank you.
It is not possible to have access to model variables inside a function. You have to provide the values of the variables through the inputs to the function. The task RealtimeOptimization is aimed to be called during the simulation of a Modelica model. The criteria function has the defined inputs nTuners, nCriteria, tuners[nTuners]. You can add additional input variables, see the Example Optimization.Tasks.RealtimeOptimization.Examples.Example02.RunSampled and the record UserData in the function Optimization.Tasks.RealtimeOptimization.Examples.Example02.criteriaFunc02. By these additional variables you could transfer some state variables into the critiera function.
Maybe we can assist you, if you provide more information about your setting. I am the main developer of the Optimization library in Dymola.
You could try adding outputs (Modelica.Blocks.Interfaces.RealOutputs) to the top level of the model and then linking these to the states by using Modelica.Blocks.Sources.RealExpression blocks.
Then when using the optimisation function goto the criteria page and use the Select button and select these outputs to add them as criteria.

Odd value returned by simple Fortran function

Just as a forward, I am a complete beginner when it comes to Fortran. I've spent quite awhile looking at the other questions on SO, but I couldn't identify a similar question to this, so please forgive me if my solution is either obvious, or already been answered :)
I'm attempting to learn how to correctly implement a self-written Fortran DLL in a VB.net application. I've been able to have VB recognize the DLL, and execute the function without any errors. The error comes rather as expected output compared to actual output.
My Fortran DLL function reads as follows:
function ex(i)
integer*4 i
ex=i+1
return
end
A very simple function that increments the passed parameter by one and returns the value. (I think). The VB Application has the following code.
<DllImport("ex.dll")> _
Public Shared Function ex(ByRef val As Integer) As Integer
End Function
Private Sub btn_Fortran_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Fortran.Click
Console.WriteLine(ex(1))
End Sub
So, I'm passing the ex function the integer value 1. So I would expect the value 2 to be written to the console. Instead, I get the value "1073741824" Not exactly equal. Any ideas where I'm obviously falling short?
Learning a language in a mixed language content is "a hard row to hoe". Note that value you obtained is 2**30.
In the fortran portion, you should also declare the return value of the function: "integer*4 function ex (i)" is the old fashioned way. You are probably getting ex as a real through implicit typing. It is a very good idea to include "implicit none" in all of your programs and procedures to prevent implicit typing. Many compilers include an option for the same purpose.
Late edit:
Here is a program that demonstrates what was happening by showing what value is obtained when the bit-pattern real value 2.0 is interpreted as an integer. First the program equates a real and an integer. In this case the compiler "knows" about the types and converts the value. In the second case the raw bit pattern is transferred without being converted.
program test_tc
real :: my_real
integer :: my_int
my_real = 2.0
my_int = my_real
write (*, *) my_int
my_int = transfer ( my_real, my_int )
write (*, *) my_int
end program test_tc
Output is:
2
1073741824
It appears that I was nearly on the right track, but the way in which I declared 'i' made some weird things happen. When using the following convention of
integer*4 :: ex, i
The function returns the correct value. So, my function looks like this
function ex(i)
integer*4 :: ex, i
ex=i+1
return
end function
Thanks both of you for the help. I upvoted both of you for simply opening my eyes to some aspect of the language I didn't fully understand beforehand.

Failure to Pass Arguments to a UDF in VBA for Excel 2007

I have a complex iterative spreadsheet in which I want to use a UDF to calculate the heat transfer coefficient of a heat exchanger. The function has 5 arguments (2 strings and 3 doubles). The strings and 1 double pass just fine. The remaining two don't seem to go through at all. A watch on problematic arguments shows them to be equal to zero. I tried redefining the arguments as variants, and then I can find the value I want in the "value2" field. However, as soon as I try to access it (via varName.Value2) it disappears (the watch suddenly lists the field as "Empty").
The cells passed into the function for the problematic arguments are heavily dependent on the rest of the spreadsheet, and their value changes almost every iteration.
Has anyone seen this before and know of a workaround?
I use UDFs with +6 input variables (the standard types as well as variants), and I have noticed (this is my interpreation of what happens) that sometimes the excel calc engine tries to trigger the UDF before all the input values become calced and available. From the debug view this is seen as the function making "false starts" and stopping to execute mid-procedure (thread is lost) so debugging-wise it shows a strange behaviour.
However, when written into a cell the function still calculates and returns correctly.