Modelica external functions: C versus C99 - modelica

In Modelica it is possible to define external functions.
Chapter 12.9 of the spec says C and Fortran77 are supported,
C++ and Fortran90 might be supported in the future.
Now I wonder which versions of C are supported?
In particular I need the logarithmic gamma function which is available in C99, so I tried the following:
function lgamma "logarithmic gamma function"
input Real u;
output Real y;
external "C" y = lgamma(u);
end lgamma;
but it does not work, while powf works:
function powf "power function a^b"
input Real a;
input Real b;
output Real y;
external "C" y = powf(a,b);
end powf;
This probably happens because powf is available in C while lgamma was introduced in C99. But is this a limitation of Modelica, Dymola or of my compiler?
Is there a way to get C99 external functions to work?
On the Wikipedia list of C mathematical operations there are some more interesting function like error function erf and erfc, these would also be nice to have.

You can only assume that C89/90 code compiles in a Modelica compiler. This is mainly concerning syntax though (if you use Include annotations or Library="file.c").
The functions that are available mainly depend on the C library that your compiler links against. I guess Microsoft's C library does not contain lgamma, so it cannot be linked against.
On Linux/OpenModelica, the lgamma example does work as libm contains the function (it's compiling using c90 mode, but implicitly adding a double lgamma(double) declaration).
The powf example also compiles, but does not work correctly since your external "C" declaration states that it uses double precision floating point (and you cannot change this as of Modelica 3.2). powf will read half of a and use it as its first argument, then read the second half of a and use it as its second argument. b would be discarded. If you set the compiler flags to std=c99, the error is detected:
powf.h:23:15: error: conflicting types for ‘powf’
Note that if you use Dymola on Windows, you are most likely using Visual Studio. In that case, there is no C99 support except the parts that were copied from C++.

Related

How to tell if a function is built-in or self-defined by its name?

I generate a call graph of a complex MATLAB system, and I want to know which functions are built-in and mark them.
Whether a function is built-in or not is most easily seen by the which command. For a given function name it displays the full path to the file that defines the function. For example, on my machine I see
>> which eig
built-in (/Applications/MATLAB_R2018b.app/toolbox/matlab/matfun/eig)
>> which solve
/Users/robert/Documents/MATLAB/cvx/lib/#cvxprob/solve.m % cvxprob method
>> which nosuchfunctionhere
'nosuchfunctionhere' not found.
telling me that eig is a built-in function, and solve a function that is part of the package cvx, and that nosuchfunctionhere is defined nowhere.
MATLAB makes a distinction between "built-in functions" (i.e. no M-file or MEX-file exists, the code is built into the MATLAB executable) and other functions that are part of the MATLAB package but written as M-files or MEX-files.
As Robert showed, the which function will tell you if a function is "built-in" or not, and it will give you a path.
For example, eig is a built-in function (the path given is a file containing the documentation):
>> p = which('eig')
p =
'built-in (/Applications/MATLAB_R2017a.app/toolbox/matlab/matfun/#single/eig)'
imshow is not built-in, but part of the core MATLAB toolbox:
>> p=which('imshow')
p =
'/Applications/MATLAB_R2017a.app/toolbox/matlab/images/imshow.m'
imdilate is a function that comes with the Image Processing Toolbox:
>> p = which('imdilate')
p =
'/Applications/MATLAB_R2017a.app/toolbox/images/images/imdilate.m'
and prettyplot is a function I wrote myself:
>> p = which('prettyplot')
p =
'/Users/cris/matlab/toolbox/cris/prettyplot.m'
To distinguish between these 4 cases, first check to see if the returned string begins with "built-in", then check to see if it contains fullfile(matlabroot,'toolbox','matlab'), indicating it is part of the core MATLAB toolbox, then check to see if it contains fullfile(matlabroot,'toolbox'), indicating it is part of another official toolbox:
function_name = 'eig';
p = which(function_name);
if startsWith(p,'built-in')
disp('built-in')
elseif contains(p,fullfile(matlabroot,'toolbox','matlab'))
disp('part of core MATLAB toolbox')
elseif contains(p,fullfile(matlabroot,'toolbox'))
disp('part of an official MATLAB toolbox')
else
disp('not an official MATLAB function')
end
However, do note that some functions could be overloaded! And if you're examining your source code to check which functions are being used, you need to know the types of the arguments passed. For example:
>> which -all eig
built-in (/Applications/MATLAB_R2017a.app/toolbox/matlab/matfun/#single/eig) % single method
built-in (/Applications/MATLAB_R2017a.app/toolbox/matlab/matfun/#double/eig) % double method
/Users/cris/newdip/target/dip/share/DIPimage/#dip_image/eig.m % dip_image method
Here you can see that there are three eig functions, one is used if its input argument is of type single, one if it is double, and one if it is dip_image (a custom class). Depending on the input, the function eig used is built-in or a 3rd party function.
The sad part is, you won't know which one is used until you run your code. You can manually check what values the input variables have, sometimes it is clear. But this is not always the case, the type might depend on data outside of the function you're examining.
So, the best way to collect a list of functions your program uses is to run the profiler.
Another alternative: the MATLAB Compiler (a separate product) will collect all source M-files your function uses, and package them together into a single distributable package.
Although I think solutions based on which are better, for completeness, we should also consider the function exist for this. From the documentation:
exist name returns the type of name as a number. This list describes the type associated with each value:
0 — name does not exist or cannot be found for other reasons. For example, if name exists in a restricted folder to which MATLAB® does not have access, exist returns 0.
1 — name is a variable in the workspace.
2 — name is a file with extension .m, .mlx, or .mlapp, or name is the name of a file with a non-registered file extension (.mat, .fig, .txt).
3 — name is a MEX-file on your MATLAB search path.
4 — name is a loaded Simulink® model or a Simulink model or library file on your MATLAB search path.
5 — name is a built-in MATLAB function. This does not include classes.
6 — name is a P-code file on your MATLAB search path.
7 — name is a folder.
8 — name is a class. (exist returns 0 for Java classes if you start MATLAB with the -nojvm option.)
So when we try this on the examples shown earlier:
>> exist eig
ans =
5
>> exist solve
ans =
2
>> exist nosuchfunction
ans =
0
Just type open followed by the function name in command window
open function_name
And function_name will be displayed into editor, you might see Mathwork copyright inside it if it's a build in function otherwise it's not
This is how the copyright looks
% Copyright 1993-2016 The MathWorks, Inc.

Why does Octave/Matlab use function handles

What benefit does it get from treating functions specially? For example,
function n = f(x)
2*x
endfunction
f(2) //outputs 4
f = #f
f(2) //outputs 4
If handles can be called the same way as functions, then what benefit do we get from functions being treated specially. By specially I mean that variables referring to functions can't be passed as arguments:
function n = m(f,x)
f(x)
end
m(f,2) // generates error since f is called without arguments
Why aren't functions procedures (which are always pointed to by variables) like in other functional languages?
EDIT:
It seems like my question has been completely misunderstood, so I will rephrase it. Compare the following python code
def f(x):
return 2*x
def m(f,x):
return f(x)
m(f,3)
to the octave code
function n = f(x)
2*x
end
function n = m(f,x)
f(x)
end
m(#f,2) % note that we need the #
So my question then is, what exactly is a function "object" in octave? In python, it is simply a value (functions are primitive objects which can be assigned to variables). What benefit does octave/matlab get from treating functions differently from primitive objects like all other functional languages do?
What would the following variables point to (what does the internal structure look like?)
x = 2
function n = f(x)
2*x
end
g = #f
In python, you could simply assign g=f (without needing an indirection with #). Why does octave not also work this way? What do they get from treating functions specially (and not like a primitive value)?
Variables referring to functions can be passed as arguments in matlab. Create a file called func.m with the following code
function [ sqr ] = func( x )
sqr = x.^2;
end
Create a file called 'test.m' like this
function [ output ] = test( f, x )
output = f(x);
end
Now, try the following
f=#func;
output = test(f, 3);
There's no "why is it different". It's a design decision. That's just how matlab/octave works. Which is very similar to how, say, c works.
I do not have intricate knowledge of the inner workings of either, but presumably a function simply becomes a symbol which can be accessed at runtime and used to call the instructions specified in its definition (which could be either interpreted or precompiled instructions). A "function handle" on the other hand, is more comparable to a function pointer, which, just like c, can either be used to redirect to the function it's pointing to, or passed as an argument.
This allows matlab/octave to do stuff like define a function completely in its own file, and not require that file to be run / imported for the function to be loaded into memory. It just needs to be accessible (i.e. in the path), and when matlab/octave starts a new session, it will create the appropriate table of available functions / symbols that can be used in the session. Whereas with python, when you define a function in a file, you need to 'run' / import that file for the function definition to be loaded into memory, as a series of interpreted instructions in the REPL session itself. It's just a different way of doing things, and one isn't necessarily better than the other. They're just different design / implementation decisions. Both work very well.
As for whether matlab/octave is good for functional programming / designed with functional programming in mind, I would say that it would not be my language of choice for functional programming; you can do some interesting functional programming with it, but it was not the kind of programming that it was designed for; it was primarily designed with scientific programming in mind, and it excels at that.

MATLAB Coder Error: The function 'bwboundaries' is not supported for standalone code generation

I want to run MATLAB 2015b algorithm on Android device through NDK. So I need a standalone c code from algorithm. I used Matlab Coder for this, But I get this error:
The function 'bwboundaries' is not supported for standalone code generation. See the documentation for coder.extrinsic to learn how you can use this function in simulation.`
I used this function in this way:
[B,L]=bwboundaries(h1);
the h1 is an 280*500 logical array which comes from a Black & White image.
I searched and found this list: Functions and Objects Supported for C and C++ Code Generation
As we see there the bwboundaries declared in the list:
bwboundaries :
The conn and options arguments must be compile-time constants and the return value A can only be a full matrix, not a sparse matrix.
If you choose the generic MATLAB Host Computer target platform, generated code uses a precompiled, platform-specific shared library.
MATLAB Function Block support: No.
I don't understand it!! How should I use this function to have its c code?
OR Is there any function to use instead?
I see this SO questions which didn't help me:
q1 q2 q3

Is it possible to enforce input argument data types in MATLAB?

I would like to ensure that the input arguments to a user-defined MATLAB function (contained in an m-file) are of a certain type. I understand that MATLAB automatically assigns data types to variables (to the liking of some and the dismay of others), but I would like to know if there is an option of "strict data typing" in MATLAB, or something of the sort, especially for input arguments for a user-defined function.
I found a helpful explanation of MATLAB's "fundamental classes" (data types) at these two webpages:
http://www.mathworks.com/help/matlab/matlab_prog/fundamental-matlab-classes.html
http://www.mathworks.com/help/matlab/data-types_data-types.html
However, I have been unable to find an answer to the question of strict data typing, particularly for function input arguments. I thought it would be a pretty basic question that already had been answered in numerous places, but after extensive searching I have not yet found a conclusive answer. For now, I have been manually checking the data type using the is[TYPE]() functions and displaying an error message if it does not comply, though this seems sloppy and I wish I could just get MATLAB to enforce it for me.
Below is an example of a function in which I would like to specify the input argument data type. It resides in a file called strict_data_type_test.m in MATLAB's current path. In this function, I would like to force the variable yes_or_no to be of MATLAB's logical data type. I know I can use the islogical() function to manually check, but my question is if it is possible to have MATLAB enforce it for me. I also know that any non-zero double evaluates to true and a zero evaluates to false, but I want to force the user to send a logical to make sure the wrong argument was not sent in by accident, for example. Here is the example function:
function y = strict_data_type_test( x, yes_or_no )
% manual data type check can go here, but manual check is not desirable
if (yes_or_no)
y = 2 .* x;
else
y = -5 .* x;
end
end
Adding the data type before the input argument variable name (like in most programming languages) treats the data type text as another variable name instead of a data type identifier. From that it would seem that strict data typing is not possible in MATLAB by any means, but maybe one of you many gurus knows a useful trick, feature, or syntax that I have not been able to find.
validateattributes might also work for you, if there is an appropriate attribute for your case. For example if you want to enforce that yes_or_no is a logical scalar, you could try:
validateattributes(yes_or_no,{'logical'},{'scalar'})
Otherwise maybe an attribute like 'nonempty'.
I've gotten some great responses so I can't pick just one as the "accepted answer", but to summarize what I've learned from you all so far:
No, MATLAB does not have built-in strict data typing for function input arguments
MATLAB compiles the code before running, so manual validation checking should not be very taxing on performance (the profiler can be used to assess this)
Many helpful methods of doing the manual validation checking exist, listed here in order of most relevant to least relevant for what I was trying to do:
inputParser class
validateattributes()
Error/exception handling (throw(), error(), assert(), etc.)
MATLAB's built-in state detection functions (a.k.a predicate functions)
I can look through some MathWorks-provided MATLAB functions (or Statistics toolbox functions) for ideas on how to validate input arguments by typing edit followed by the function name. Two suggested functions to look at are normpdf() (from the Statistics toolbox) and integral(). Some other functions I found helpful to look at are dot() and cross().
Other thoughts:
It would appear that the inputParser class was the overall concensus on the most professional way to validate input arguments. It was noted on a related (but not duplicate) stackoverflow post that the newer MathWorks functions tend to make use of this class, suggesting that it may be the best and most up-to-date choice.
Since the MathWorks-provided MATLAB functions do not appear to enforce strict input argument data typing, this further suggests that even if it was possible to do so, it may not be a recommended approach.
MATLAB seems to regard "error handling" and "exception handling" as two different concepts. For example, here are two links to MATLAB's Documentation Center that show how MathWorks considers "error handling" and "exception handling" differently: MathWorks Documentation Center article on Error Handling, MathWorks Documentation Center article on Exception Handling. A relevant StackOverflow post has been made on this topic and can be found here (link). I contacted MathWorks and added some new information about this topic to that post, so if you are interested you may read more by following that link.
Matlab provides an 'inputParser' which allows to check inputs. Besides this you can use assertions:
assert(islogical(yes_or_no),'logical input expected')
To ensure the correct number of input arguments, use narginchk.
btw: Take a look in some Matlab functions like edit integral and check how tmw deals with this.
You may find writing this sort of code tedious or worry that it degrades performance:
if ~islogical(yes_or_no) && ~isscalar(yes_or_no)
error('test:NotLogicalType','Second argument must be logical (Boolean).');
end
if yes_or_no
y = 2 .* x;
else
y = -5 .* x;
end
Recall, however, that Matlab compiles the code before running so even if you need to test many conditions it will be quite fast. Run the profiler to see.
Another option in some cases (maybe not your example) is to use a lazier method. This option lets your code run with whatever inputs were provided, but uses a try/catch block to trap any error:
try
if yes_or_no
y = 2 .* x;
else
y = -5 .* x;
end
catch me
...
error('test:NotLogicalType','Second argument must be logical (Boolean).');
% rethrow(me);
end
The code above would produce an error if yes_or_no was a cell array for example (it will still allow non-Boolean, non-scalar, etc. values for yes_or_no though, but Matlab is often overly permissive). You can then either generate a custom error message, detect, what kind of error was thrown and try something else, etc. Many of the functions in the Statistics toolbox use this approach (e.g., type edit normpdf in your command window) for better or worse.

how to test a variable is a function handle or not in Matlab

How to test/validate a variable is a function handle in matlab ?
it may be something like:
f=#(x)x+1
isFunctionHandle(f)
the is* build-in functions seems not support these kind testing? anyone know? many thanks
The right way is indeed by means of an is* function, namely isa:
if isa(f, 'function_handle')
% f is a handle
else
% f is not a handle
end
edit:
For completeness, I'd like to point out that using class() works for checking if something is a function handle.
However, unlike isa, this doesn't generalize well to other aspects of MATLAB such as object-oriented programming (OOP) that are having an increasing impact on how MATLAB works (e.g. the plot functionality, the control toolbox, the identification toolbox, ... are heavily based on OOP).
For people familiar with OOP: isa also checks the super types (parent types) of the x object for someClass, while strcmp(class(x), 'someClass') obviously only checks for the exact type.
For people who don't know OOP: I recommend to use isa(x, 'someClass') instead of strcmp(class(x), 'someClass') as that is the most convenient (and commonly useful) behavior of the two.
You can use the class() function:
f = #(x)x+1
f =
#(x)x+1
>> class(f)
ans =
function_handle
(This is a string containing the text 'function_handle')