Using a scalar C function on a numpy vector - c

I have a library of C functions for scalars, e.g.
double f(double x, double y, double z) {
result = x + 2*y - 3*z;
return result;
}
I'd like to use these functions over numpy arrays, but would like to vectorise the operation somehow and avoid several C calls to f for each array element. Most examples that I have found are for functions that already support arrays (f(double *x) or f(double x[])).
What is the right approach here? Rewrite f to support arrays? (There are a lot of functions in the library.) Write a C wrapper, maybe using function pointers? Or do ctypes, cython, etc. offer a simpler alternative?
This has probably been asked hundreds of times, so even just a pointer to the appropriate documentation would be helpful.

Personally I'd say rewriting the functions to use arrays is the best and cleanest way to go. However, an alternative would be the already mentioned wrapper, but with using the original function as an inline function, e. g.
// Function
inline double f(double x, double y, double z) {
return x + 2*y - 3*z;
}
// Wrapper
void fWrapper(double *x, double *y, double *z, double *ret, int N) {
int i;
for (i = 0; i < N; i++) {
ret[i] = f(x[i], y[i], z[i]);
}
}
Now the compiler should replace the function call with the code of the function.

Related

How to convert from double pointer to gsl vector?

So i created this function to convert from double pointer to gsl vector :
void convert_dpvect_gslvect(int N, double *x, gsl_vector *gx)
{
gx->size = N;
for (int i = 0; i < N; i++) {
gx->data[i] = x[i];
}
}
does that make sense? i want to make sure that it coverts correctly. I would really appreciate your help with this.
By looking at the online documentation for gsl lib (link) we can find functions that already do what you want to do. As a general rule, whenever using a type defined in a library you should look for the provided functions to handle such type.
The rationale behind this is that they may take care of errors or other fields that you might forget while implementing your functions.
In your specific case, it seems that you have a vector of double and you want to assign each element to the elements of a gsl_vector. I say this because you do:
gx->data[i] = x[i]; // Access up to N elements from x
What we want is then the provided library function
void gsl_vector_set(gsl_vector *v, const size_t i, double x)
This function sets the value of the i-th element of a vector v to x. If i lies outside the allowed range of 0 to size - 1 then the error handler is invoked. An inline version of this function is used when HAVE_INLINE is defined.
In order to use it we need to be sure that we have allocated enough memory by creating a gsl_vector before. I assume that you have N elements, so the full code would be:
// assume x is already initialized with N elements
gsl_vector* V = gsl_vector_alloc(N);
for (int i = 0; i < N; i++) {
gsl_vector_set( V , i, x[i] );
}
Interestingly enough, by looking at the source code of gsl_vector_set it does something similar to what you came up with, but of course there are some nuisance that are crucial to the library, like checking the range and using the stride to account for different block sizes.
// from https://github.com/ampl/gsl/blob/master/vector/gsl_vector_double
INLINE_FUN
void
gsl_vector_set (gsl_vector * v, const size_t i, double x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}

Nested function pointers or function composition

I am working on C implementations of calculus operations (such as derivatives, integrals, etc...). As an example, here's the template definition of my derivative function:
double derivative(double (*f)(double), double x);
Let's say I want to compute the derivative of exp at 1, the call would then be: derivative(exp, 1);
Pretty basic stuff. Now my question is, how would I go about (if it is even possible) to pass a composition to my derivative function? I tried passing exp(cos) which got me
error: passing 'double (double)' to parameter of incompatible type 'double'.
How would I do it? Is it even possible?
I think you're asking for this:
double composition(double x) {
return exp(cos(x));
}
derivative(composition, 1);
Many languages allow you to do something like the following, but C doesn't have anon functions:
derivative(x => exp(cos(x)), 1);
If you want some sort of run-time control over the composition, you could write a function that evaluates an array of function pointers as a composition:
// calls functions in reverse order
double compose(size_t n, double (* const fc[])(double), double x)
{
while (n--)
{
x = fc[n](x);
}
return x;
}
This could be called from another version of your derivative function:
double derivative_composed(size_t n, double (* const fc[])(double), double x)
{
// Example implementation for illustrative purpose only.
double fx, fxh, h;
h = x / 1e10;
if (h == 0)
{
h = 1e-10;
}
fx = compose(n, fc, x);
fxh = compose(n, fc, x + h);
return (fxh - fx) / h;
}
To avoid repeated code, your original derivative function could be changed to be a wrapper that calls derivative_composed with a single function:
double derivative(double (* const f), double x)
{
return derivative_composed(1, &f, x);
}
Example usage:
int main(void)
{
double (* const fc[2])(double) = { exp, cos };
double x = 1.0;
double xprime = derivative_composed(2, fc, x);
printf("x = %f, xprime = %f\n", x, xprime);
}
Output:
x = 1.000000, xprime = -1.444407
C does not have any operation for function composition. To compute the derivative of exp∘cos, you can define a function expcos:
double expcos(double x)
{
return exp(cos(x));
}
and take the derivative of that.
For a more general solution, you could modify your derivative routine to take both a function pointer and a const void * to forward to the function. The function would take the const void * as a parameter, convert it to a pointer to a const structure of a type particular to that function, and take data from that structure. Then function composition can be implemented with a compose function that uses a structure containing two function pointers. However, it would mean you would need to use proxy routines for ordinary functions like exp and cos that accept but ignore the const void *.

Is it possible to "typedef"(of sorts) a function prototype?

I have multiple functions that are similar to each other - they take in the same arguments, and return the same type:
double mathFunction_1(const double *values, const size_t array_length);
I already use typedef'd pointers to those functions, as I store them as an array to easily use any number of them on the same data, map them etc.:
typedef double (* MathFunction_ptr )(const double *, const size_t);
double proxy(MathFunction_ptr mathfun_ptr, const double *values, const size_t array_length);
What I want to achieve, is a similar ease-of-use with declaring and defining the functions, as I already have with using pointers to them.
Thus, I was thinking about using a similar typedef to make it easier for me to write the actual functions. I tried doing it like this:
// declaration
typedef double MathFunction (const double *values, const size_t array_length);
MathFunction mathFunction_2;
The following approach works partially. It lets me "save a few keystrokes" in the declaration, however the definition has to be fully typed out.
double mathFunction_2(const double *values, const size_t array_length)
{
// ...
}
What I found by searching more for this issue is this: Can a function prototype typedef be used in function definitions?
However it doesn't provide many alternatives, and only reaffirms that what I tried to do in my other experiments is forbidden according to the Standard. The only alternative it provides is using
#define FUNCTION(name) double name(const double* values, size_t array_length)
which sounds clunky to me(as I'm wary and skeptical of using the preprocessor).
What are the alternatives to what I'm trying to do?
Two other approaches I tried that don't work(and, as I just read, are forbidden and absolutely wrong according to the C standard 6.9.1):
1.This approach doesn't work, as it means that I'm telling it to define a variable mathFunction_2(I believe that variable is treated as a pointer, though I don't understand this well enough yet) like a function:
MathFunction mathFunction_2
{
// ...
}
2.This approach doesn't work, as it means I'm telling it to create a function which returns a function(unacceptable in the C language):
MathFunction mathFunction_2()
{
// ...
}
You could use a typedef for the signature (see also this):
typedef double MathFunction_ty (const double *, const size_t);
and then declare several functions of the same signature:
MathFunction_ty func1, func2;
or declare some function pointer using that:
MathFunction_ty* funptr;
etc... All this in C11, read n1570.
however the definition has to be fully typed out.
Of course, since you need to give a name to each formal parameter (and such names are not part of the type of the function) in the function's definition. Therefore
double func1(const double*p, const size_t s) {
return (double)s * p[0];
}
and
double func1(cont double*arr, const size_t ix) {
return arr[ix];
}
have the same type (the one denoted by MathFunction_ty above), even if their formal parameters (or formal arguments) are named differently.
You might abuse of the preprocessor and have an ugly macro to shorten the definition of such functions:
// ugly code:
#define DEFINE_MATH_FUNCTION(Fname,Arg1,Arg2) \
double Fname (const double Arg1, const size_t Arg2)
DEFINE_MATH_FUNCTION(func1,p,s) { return (double)s * p[0]; }
I find such code confusing and unreadable. I don't recommend coding like that, even if it is certainly possible. But sometimes I do code something similiar (for other reasons).
(BTW, imagine if C required every first formal argument to be named $1, every second formal argument to be named $2, etc...; IMHO that would make a much less readable programming langage; so formal parameter's name matters to the human reader, even if systematic names would make the compiler's life simpler)
Read also about λ-calculus, anonymous functions (C don't have them but C++ has lambda expressions), closures (they are not C functions, because they have closed values so mix code with data; C++ has std::function-s), callbacks (a necessary convention to "mimick" closures)... Read SICP, it will improve your thinking about C or C++. Look also into that answer.
Unfortunately in C I don't believe there is any way to do what you're asking without using preprocessor macros, and personally at least I agree with your assessment that they are clunky and to be avoided (though this is a matter of opinion and open to debate).
In C++ you could potentially take advantage of auto parameters in lambdas.
The example function signatures you show here really aren't complicated and I wouldn't worry about the perceived duplication. If the signatures were much more complicated, I would view this as a "code smell" that your design could be improved, and I'd focus my efforts there rather than on syntactic methods to shorten the declaration. That just isn't the case here.
Yes, you can. Indeed, that's the purpose of the typedef declaration, to use a type identifier to declare a type of variable. The only thing is that when you use such a declaration in a header file:
typedef int (*callback_ptr)(int, double, char *);
and then you declare something like:
callback_ptr function_to_callback;
it's not clear that you are declaring a function pointer and the number and type of the parameters, but despite of this, everything is correct.
Finally, I want to note you something particularly special. When you deal with something like this, it is normally far cheaper and quick to go to the compiler and try some example. If the compiler does what you want without any complaint, the most probable thing is that you are correct.
#include <stdio.h>
#include <math.h>
typedef double (*ptr_to_mathematical_function)(double);
extern double find_zero(ptr_to_mathematical_function f, double aprox_a, double aprox_b, double epsilon);
int main()
{
#define P(exp) printf(#exp " ==> %lg\n", exp)
P(find_zero(cos, 1.4, 1.6, 0.000001));
P(find_zero(sin, 3.0, 3.2, 0.000001));
P(find_zero(log, 0.9, 1.5, 0.000001));
}
double find_zero(
ptr_to_mathematical_function f,
double a, double b, double eps)
{
double f_a = f(a), f_b = f(b);
double x = a, f_x = f_a;
do {
x = (a*f_b - b*f_a) / (f_b - f_a);
f_x = f(x);
if (fabs(x - a) < fabs(x - b)) {
b = x; f_b = f_x;
} else {
a = x; f_a = f_x;
}
} while(fabs(a-b) >= eps);
return x;
}
The second, and main part of your question, if you are having such a problem, the only way you can solve it is via using macros (see how I repeated the above printf(3) function calls with similar, but not identical parameter lists, and how the problem is solved below):
#define MY_EXPECTED_PROTOTYPE(name) double name(double x)
and then, in the definitions, just use:
MY_EXPECTED_PROTOTYPE(my_sin) {
return sin(x);
}
MY_EXPECTED_PROTOTYPE(my_cos) {
return cos(x);
}
MY_EXPECTED_PROTOTYPE(my_tan) {
return tan(x);
}
...
that will expand to:
double my_sin(double x) {
...
double my_cos(double x) {
...
double my_tan(double x) {
...
you can even use it in the header file, like:
MY_EXPECTED_PROTOTYPE(my_sin);
MY_EXPECTED_PROTOTYPE(my_cos);
MY_EXPECTED_PROTOTYPE(my_tan);
As it has been pointed in other answers, there are other languages (C++) that give support for this and much more, but I think this is out of scope here.

C preprocessor syntax for multi-statement function?

#include <stdio.h>
#define mean(x,N) ( double _sum=0.0; for (int _i=0;_i<N;++_i) _sum+=x[_i]; _sum/N )
int main() {
const int N=100;
int i[N]; double d[N];
// here we fill the arrays with data, and then
printf("%f %f %f\n", mean(i,N), mean(d,N));
}
how does one define the macro appropriately in pure C, or accomplish this in another way without coding two functions?
A macro will not work in this situation.
A parameter to a function must be an expression. What you have above is not an expression but a sequence of statements. You can't get around this with the loop you have.
Just define functions, one accepting a double * and an int and the other a accepting a int * and an int, to perform this action. Don't use a macro where a function will do.
There is no portable way to write a macro to return a value from a statement, especially a complex statement. You want to use a macro to implement a polymorphic thing... You can use C++ overloaded functions for this purpose.
For C, you can write a macro that updates a variable and pass that variable to printf. Beware that macros are notorious sources of non trivial bugs.
You could also use C11 generic functions, but support for these is often missing.
Here is an attempt:
#include <stdio.h>
#define set_mean(res,x,N) do { res = 0; for (int i_ = 0; i_ < (N); i_++) res += (x)[i_]; res /= (N); } while (0)
int main(void) {
const int N = 100;
int i[N];
double d[N];
double ires, dres;
// here we fill the arrays with data, and then
set_mean(ires, i, N);
set_mean(dres, d, N);
printf("%f %f %f\n", ires, dres);
}

Is it possible to write a function which returns a pointer to a function different from the function in its argument?

I have recently stumbled on this curious thought while handling a C code.
I have written a function which returns a double and takes in as argument the pointer to a function and a certain number of parameters, namely
double template_1(double (*)(double),...);
this function correctly identifies a certain property of a real function
double f(double );
represented as a pointer in template_1, in order to maketemplate_1 valid for every real function I might plug-in.
Now I had to write another function, let it be:
double derivative(double (*)(double),double);
double derivative(double (*f)(double),double x){
double epsilon = ...;
return ( f(x+epsilon)-f(x-epsilon) )/(2.0*epsilon);
}
again with f in the argument to make it work for every f.
My question is: since I would like to use derivative in template_1 without modifying it, is it possible to write a function which takes derivative and spits out something that has the form of double (*)(double ) ?
My idea was to define typedef double (*real_function)(double);
and then to define
real_function g(double (*derivative)(double (*)(double),double ) )
which I'd like it to spit out something like: double derivative_2(double x); so that I could define something like g(derivative) = double (*h)( double); directly in template_1 argument
unfortunately I don't have the faintest idea of how to make this work, or even if it can work.
There are a couple ways to do anonymous functions in C. As the comments said, they aren't portable. But depending on the use case you may find this useful: Anonymous functions using GCC statement expressions
A couple of people have seemed to have similar issues, not sure how portable they are but they may be resourceful:
https://github.com/graphitemaster/lambdapp
https://github.com/Leushenko/C99-Lambda
Basically, if there's a way to architect your program in a way that doesn't require anonymous functions, then do it that way. If you have no other option, then I would give one of these a shot.
Warning: I am a C++ developer with little C knowledge so everything that follows is likely unidiomatic C.
As KerrekSB said, you would need to carry some state with your function. This is not possible with raw functions but you can define a struct that carries the state and add a function that works with this struct. This obviously has the drawback of losing the nice function call syntax. I whipped up an example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef double (*raw_fptr)(double);
struct real_function;
typedef double (*evaluate_function)(struct real_function*, double);
struct real_function {
evaluate_function evaluate;
};
typedef struct real_function real_function;
double evaluate(real_function *f, double x) {
if(f) {
return f->evaluate(f, x);
}
return NAN;
}
struct raw_real_function {
real_function real_function_base;
raw_fptr raw_function;
};
typedef struct raw_real_function raw_real_function;
double evaluate_raw_real_function(real_function *f_base, double x) {
if(f_base) {
raw_real_function *f = (raw_real_function*)f_base;
return f->raw_function(x);
}
return NAN;
}
raw_real_function make_raw_real_function(raw_fptr function) {
raw_real_function result;
result.raw_function = function;
result.real_function_base.evaluate = evaluate_raw_real_function;
return result;
}
struct derive_real_function {
real_function real_function_base;
real_function *function_to_derive;
};
typedef struct derive_real_function derive_real_function;
double derive(real_function *f_base, double x) {
derive_real_function *f = (derive_real_function*)f_base;
double epsilon = 1e-3;
double upper = evaluate(f->function_to_derive, x+epsilon);
double lower = evaluate(f->function_to_derive, x-epsilon);
double result = (upper - lower)/(2.0*epsilon);
return result;
}
derive_real_function make_derivative(real_function * function_to_derive) {
derive_real_function result;
result.real_function_base.evaluate = derive;
result.function_to_derive = function_to_derive;
return result;
}
double x_cubed(double x) {
return x * x * x;
}
int main(int argc, char **argv) {
raw_real_function x_cubed_wrapped = make_raw_real_function(x_cubed);
derive_real_function derived = make_derivative(&x_cubed_wrapped.real_function_base);
derive_real_function derived_twice = make_derivative(&derived.real_function_base);
double x = atof(argv[1]);
double derivative = evaluate(&derived.real_function_base, x);
double second_derivative = evaluate(&derived_twice.real_function_base, x);
printf("derivative of x^3 at %f = %f\n", x, derivative);
printf("second derivative of x^3 at %f = %f\n", x, second_derivative);
return 0;
}
See (a slight variaton, due to input limitations) running here.
How does it work? I faked some inheritance with the structs real_function, raw_real_function and derive_real_function to generate virtual function calls. The struct real_function serves as the container of a virtual function table consisting of only the entry evaluate. This function pointer points to the "derived" structs' relevant evaluate function:
raw_real_function instances point to evaluate_raw_real_function (as initialized in make_raw_real_function. derive_real_function instances point evaluate to derive (as initialized in make_derivative).
When calling evaluate on the real_function_base member, it will call the associated evaluation function, which casts the real_function* to it's associated struct pointer and does what is needed with that information.
Since everything is just a real_function*, we can chain them at will but need to convert "normal" functions into the real_function format, that's what make_raw_real_function does.
If you have a function my_fancy_function:
double my_fancy_function (double x) { return sin(x) + cos(x); }
Then, you can use a helper macro that creates the derived function for you.
#define DEFINE_DERIVATIVE_OF(FUNC) \
double derivative_of_ ## FUNC (double x) { \
return derivative(FUNC, x); \
}
DEFINE_DERIVATIVE_OF(my_fancy_function)
You then pass this newly defined function to your template.
template_1(derivative_of_my_fancy_function, x, y, z);

Resources