Create EigenSolver from MatrixWrapper - eigen3

How to construct an EigenSolver from a MaxtrixWrapper?
test (also at godbolt.org)
#include <Eigen/Eigen>
using namespace Eigen;
template<typename D>
void f(const Eigen::DenseBase<D>& a) {
const Eigen::MatrixWrapper<const D> a2(a.derived());
Eigen::EigenSolver<typename Eigen::MatrixWrapper<const D>>
es(a2);
}
int main() {
ArrayXXf a(3, 3);
a = 1.0f;
f(a);
}
1st Error:
<...>/eigen3/Eigen/src/Eigenvalues/EigenSolver.h:71:10: error:
‘Options’ is not a member of
‘Eigen::EigenSolver<
Eigen::MatrixWrapper<
const Eigen::Array<float, -1, -1>
>
>::MatrixType {
aka Eigen::MatrixWrapper<const Eigen::Array<float, -1, -1> >}’
enum {

You don't. The solvers all want a plain Matrix<...> (or a Ref<Matrix<...> >) as template parameter. You can get the correct Matrix type using:
template<typename D>
void f(const Eigen::DenseBase<D>& a) {
Eigen::EigenSolver<typename D::PlainMatrix> es(a.derived().matrix());
}
The .derived().matrix() is actually optional here, since ArrayXXf gets converted to MatrixXf implicitly. (godbolt times out on this -- the EigenSolver is quite heavy for the compiler).

Related

How to create an Eigen::Ref to a fixed-sized matrix row?

I would like to write something like foo4 similar to foo3 in the Eigen::Ref doc here :
#include <Eigen/Dense>
using namespace Eigen;
void foo3(Ref<VectorXf, 0, Eigen::InnerStride<> >){};
void foo4(Ref<Vector3f, 0, Eigen::InnerStride<> >){};
int main()
{
Eigen::Matrix3f fmat = Eigen::Matrix3f::Identity();
Eigen::MatrixXf dmat = Eigen::Matrix3f::Identity();
foo3(dmat.row(1)); // OK
foo3(fmat.row(1)); // Error : YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES
foo4(fmat.row(1)); // Error : YOU_MIXED_MATRICES_OF_DIFFERENT_SIZES
}
I'm using Eigen version 3.3.7
You are getting size-mismatch errors, because you are trying to pass row-vectors where column vectors are expected.
There are two solutions:
Change the function to accept row-vectors:
void foo3(Ref<RowVectorXf, 0, Eigen::InnerStride<> >){};
void foo4(Ref<RowVector3f, 0, Eigen::InnerStride<> >){};
Explicitly transpose the vector you pass to the function:
foo3(fmat.row(1).transpose());
foo4(fmat.row(1).transpose());
Note that there are some cases where Eigen implicitly transposes row-vectors to column-vectors (like the following example). But generally, I would not rely on that and always explicitly transpose vectors to match the orientation:
Eigen::MatrixXd A(rows,cols);
Eigen::VectorXd v1 = A.row(0); // this works
Eigen::VectorXd v2 = A.row(0).transpose(); // more verbose, but what actually happens

Pass Lines of Code as an Argument in C

I'm working on a project in which I'm on a fairly strict word limit (I'm not 100% certain what qualifies as a word).
I'm looking to pass lines of code into a function as an argument, I've seen this done in JavaScript but I cannot find anything on it in C.
This is about what I'm looking for:
void onTime(int a, Code myCode) {
if(timer == a) {
//run myCode
}
}
And I could use it something like this:
onTime(45, {
//code
});
Is there a way in C that I can do something like this?
C doesn't allow inline code (referred to as lambda expressions in other languages) to be passed around. What you can do however is pass a pointer to an existing function.
// typedef for a function that takes no arguments and returns void
typedef void (*ftype)(void);
void func_to_run(void)
{
...
}
void onTime(int a, ftype code) {
if(timer == a) {
code();
}
}
You could then call it like this:
ontime(45, func_to_run);
If you want the function to be packaged with a set of values that it uses, similarly to C++ classes which have member functions which can access member variables, that involves some trickery.
Here's an example of how you might do something like this:
#include <stdio.h>
typedef int (*ftype)(int, int);
struct c {
int a;
int b;
ftype add_func;
ftype sub_func;
};
#define ADD(s) (s)->add_func((s)->a,(s)->b)
#define SUB(s) (s)->sub_func((s)->a,(s)->b)
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
void run(struct c *op)
{
printf("add result=%d\n", ADD(op));
printf("sub result=%d\n", SUB(op));
}
int main()
{
struct c c1 = { 1, 2, add, sub };
struct c c2 = { 3, 4, add, sub };
struct c c3 = { 6, 1, add, sub };
struct c c4 = { 9, 4, add, sub };
run(&c1);
run(&c2);
run(&c3);
run(&c4);
}
Here we define a struct c which contains function pointers for two functions and two other variables.
The macros ADD and SUB are used to run the "member" functions of the struct and pass them the "private" members to use. It hides the fact that the actual function being called is independent of the parameters being passed to it.
This code outputs:
add result=3
sub result=-1
add result=7
sub result=-1
add result=7
sub result=5
add result=13
sub result=5
Of course, once you start doing this you're (crudely) doing what C++ is doing and would probably be better off switching to C++ which is made for OOP and now supports lambdas.

Let a macro count its invocations

I've a huge C project with a module reading and managing configuration data. If I have to add a new configuration parameter, I'll have to edit several functions, e.g. as pseudo-code:
void read_configuration(config *c) {
read_param("p1", c->p1);
read_param("p2", c->p2);
read_param("p3", c->p3);
/* ... */
}
void dump_configuration(config *c) {
dump_param("p1", c->p1);
dump_param("p2", c->p2);
dump_param("p3", c->p3);
/* ... */
}
Is there a way to ensure by macro at compile time, that each location has at least the same count of parameters? I thought of making dump_param some kind of macro counting the invocations and then add something like
#if nr_read != nr_dump
#error "You forgot something, idiot!"
#endif
at the end of the module. I can't find a method to make the macro count its invocations, though...
Since the list of parameters is the same in both functions, how about factoring that out and avoid any possible mismatch ?
Using X-macros
#define X_CONFIG_PARAMS(config) \
X("p1", (config).p1) \
X("p2", (config).p2) \
X("p3", (config).p3)
void read_configuration(config *c) {
#define X(name, param) read_param(name, &param);
X_CONFIG_PARAMS(*c)
#undef X
}
void dump_configuration(config *c) {
#define X(name, param) dump_param(name, &param);
X_CONFIG_PARAMS(*c)
#undef X
}
Using function pointers
void alter_config(config *c, void(*func)(char const *name, Param *param)) {
func("p1", &c->p1);
func("p2", &c->p2);
func("p3", &c->p3);
}
void read_configuration(config *c) {
alter_config(c, read_param);
}
void dump_configuration(config *c) {
alter_config(c, dump_param);
}
Using an array and offsetof
struct param_info {
char const *name;
size_t config_offs;
};
param_info allParams[] = {
{"p1", offsetof(config, p1)},
{"p2", offsetof(config, p2)},
{"p3", offsetof(config, p3)}
};
void read_configuration(config *c) {
size_t paramCount = sizeof allParams / sizeof *allParams;
for(size_t i = 0; i < paramCount; ++i) {
Param *p = (Param*)((char*)config + allParams[i].config_offs);
read_param(allParams[i].name, p);
}
}
void dump_configuration(config *c) {
size_t paramCount = sizeof allParams / sizeof *allParams;
for(size_t i = 0; i < paramCount; ++i) {
Param *p = (Param*)((char*)config + allParams[i].config_offs);
dump_param(allParams[i].name, p);
}
}
I would rather let the preprocessor write the code in the first place.
It could look something like this:
Define the list of parameters in a separate file, say parameters.inc:
PARAM (p1)
PARAM (p2)
...
Then in the source code locally define the macro PARAM as required and let the preprocessor include and expand the contents of parameters.inc:
void read_configuration(config *c) {
#define PARAM(NAME) read_param(#NAME, c->NAME);
#include "parameters.inc"
#undef PARAM
}
void dump_configuration(config *c) {
#define PARAM(NAME) dump_param(#NAME, c->NAME);
#include "parameters.inc"
#undef PARAM
}
I don't think you can do this at compile time without ugly hacks.
What you could do: add a test to your test suite which replaces the header that contains the read_param() and dump_param() macros so they generate code which only updates a counter. Then, in the main() function of that test, place an assertion that compares both counters and fails if they're not equal.
You do have a test suite and run it at compile time, right? ;-)
However, I do agree with the comment that it's probably better to do this differently. In an approach called "table-driven programming", you turn the macro definition and data definition on their head (that is, you have the #define in your .c file and the use of the macro in the header rather than the other way around), you don't have this problem. Poul-Henning Kamp, of FreeBSD fame, explains very well how to that here.

When is CAMLparamX required?

I am writing an interface to a C-library using external declarations in OCaml. I used ctypes for testing but it involved a 100% overhead for fast calls (measured by a core_bench micro benchmark).
The functions look like this:
/* external _create_var : float -> int -> int -> int -> _npnum = "ocaml_tnp_number_create_var" ;; */
value ocaml_tnp_number_create_var(value v, value nr, value p, value o) {
//CAMLparam4(v, nr, p, o);
const int params = Int_val(p);
const int order = Int_val(o);
const int number = Int_val(nr);
const double value = Double_val(v);
return CTYPES_FROM_PTR(tnp_number_create_variable(value, number, params, order));
}
/* external _delete : _npnum -> unit = "ocaml_tnp_number_delete" ;; */
value ocaml_tnp_number_delete(value num) {
//CAMLparam1(num);
struct tnp_number* n = CTYPES_TO_PTR(num);
tnp_number_delete(n);
return Val_unit;
}
I borrowed the CTYPES_* macros, so I am basically moving pointers around as Int64 values.
#define CTYPES_FROM_PTR(P) caml_copy_int64((intptr_t)P)
#define CTYPES_TO_PTR(I64) ((void *)Int64_val(I64))
#define CTYPES_PTR_PLUS(I64, I) caml_copy_int64(Int64_val(I64) + I)
AFAIK, those values are represented as boxes which are tagged as "custom", which should be left untouched by the GC.
Do I need to uncomment the CAMLparamX macros to notify the GC about my usage or is it legal to omit them?
According to the comment in byterun/memory.h your function must start with a CAMLparamN macro with all value parameters.

How do I get SWIG to automatically wrap an emulated "this" pointer to a C struct?

I've got a simple C "class" I have implemented, using function pointers in a struct to implement the member functions, and passing a pointer to the struct as the first argument to each function, similar to the implicit "this" pointer in C++.
%module mytest
%{
typedef struct mytest mytest;
struct mytest {
int data;
int (*func1)(mytest *,int);
void (*func2)(mytest *,int);
};
int f1(mytest *me,int n) { return me->data + n; }
void f2(mytest *me,int n) { me->data += n; }
mytest *mytestNew(int n) {
mytest *me = (mytest*) malloc(sizeof(mytest));
me->data = n;
me->func1 = f1;
me->func2 = f2;
return me;
}
%}
typedef struct mytest mytest;
struct mytest {
int data;
int func1(mytest *,int);
void func2(mytest *,int);
};
extern mytest *mytestNew(int n);
Now my problem is, when the interface is created to whatever language I choose in the front end, I wind up having to explicitly pass the "this" pointer to the object, even though the language itself supports hiding this.
For instance, suppose I choose Python. I have to do something like this:
from mytest import *
m = mytestNew(1)
m.func1(m,0)
Where what I really want is to do it like this:
from mytest import *
m = mytestNew(1)
m.func1(0)
I know I could just write some wrapping code, but for my actual project I have a lot of functions in a lot of objects of existing C code, and multiplying this by every language that I want to support, this is just too much work! Is there some way to get SWIG to do this automatically?
You can do this in a language neutral way in SWIG with just two typemaps provided you name the parameter something consistent in the SWIG interface as well as the definitions to allow the typemaps to be applied selectively. (Unless you wanted all pointers to mytest to become "this" pointers by default of course)
The typemaps you need are:
// Make sure the wraqpped function doesn't expect an input for this:
%typemap(in,numinputs=0) mytest *me "$1=NULL;"
// Slightly abuse check typemap, but it needs to happen after the rest of the arguments have been set:
%typemap(check) mytest *me {
$1 = arg1;
}
The check typemap isn't really intended for use like this, but it's the easiest way to get the code to be injected after the arguments have been extracted from the target language and before the actual call is made.
You can also simplify the module with the help of a macro to avoid having to write and keep in sync the mapping between the function pointers and the members trick. I ended up with test.h as:
#ifdef SWIG
#define MEMBER(name, args) name args
#else
#define MEMBER(name, args) (*name) args
#endif
typedef struct mytest mytest;
struct mytest {
int data;
int MEMBER(func1,(mytest *me,int));
void MEMBER(func2,(mytest *me,int));
};
And the corresponding interface file (test.i):
%module test
%{
#include "test.h"
static int f1(mytest *me,int n) { return me->data + n; }
static void f2(mytest *me,int n) { me->data += n; }
%}
%extend mytest {
mytest(int n) {
$self->data = n;
$self->func1 = f1;
$self->func2 = f2;
}
}
%typemap(in,numinputs=0) mytest *me "$1=NULL;"
%typemap(check) mytest *me {
$1 = arg1;
}
%include "test.h"
(This interface file provides a constructor that "creates" the "object" exactly how a Java programmer would expect - you can call new and it sets the function pointers behind the scenes)

Resources