Eigen - Levenberg Marquardt algorithm: invalid template arguments on definition of permutation - java

I'm trying to use the Eigen implementation of Levenberg Marquardt algorithm on a Android application. In order to use Eigen, I'm using Android NDK and jni. I've already tested Eigen with simple calculations (like matrix creation and vector sums) and it works perfectly. However, when I tried to use the Levenberg Marquardt algorithm I got some errors on the LevenbergMarquardt.h file from Eigen's library.
First, here is my code. I based on this code:
Eigen::MatrixXd matrix(count, 3);
for (int i = 0; i < count; i++) {
Eigen::VectorXd t(3);
t << x[i], y[i], accuracy[i];
matrix.row(i) = t;
}
distance_functor functor(matrix, count);
Eigen::NumericalDiff<distance_functor> numDiff(functor);
Eigen::LevenbergMarquardt<Eigen::NumericalDiff<distance_functor>,double> lm(numDiff);
lm.parameters.maxfev = 2000;
lm.parameters.xtol = 1.49012e-08;
lm.parameters.ftol = 1.49012e-08;
lm.parameters.gtol = 0;
lm.parameters.epsfcn = 0;
Eigen::LevenbergMarquardtSpace::Status ret = lm.minimize(poseResult);
And those are the error that I got. The first two errors are in Eigen's library, and the last one is on the LevenbergMarquardt object creation. I've also included the respective line of code of the error, following the message:
Invalid template
arguments LevenbergMarquardt.h /jnimath/jni/unsupported/Eigen/src/LevenbergMarquardt line
121 Semantic Error
typedef PermutationMatrix<Dynamic,Dynamic> PermutationType;
Invalid template
arguments LevenbergMarquardt.h /jnimath/jni/unsupported/Eigen/src/NonLinearOptimization line
103 Semantic Error
PermutationMatrix<Dynamic,Dynamic> permutation;
Invalid template arguments test.cpp /jnimath/jni line 47 Semantic
Error
Eigen::LevenbergMarquardt,double> lm(numDiff);
The first two errors are really strange because there are some other typedefs using Dynamic and they are not throwing errors.
Also, I noticed that I got some symbol errors on the compilation, which are:
Symbol
'YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY'
could not be resolved Matrix.h /jnimath/jni/Eigen/src/Core line
277 Semantic Error
Symbol 'YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX' could not be
resolved Matrix.h /jnimath/jni/Eigen/src/Core line 224 Semantic Error
So, I have two questions:
Why am I getting errors on those lines?
Does anyone know how to fix that problem?
Thank you

Related

Wrong double to float precision loss with Groovy on Android

I am experiencing a problem which eventually is a bug. I am programming an Android app in Groovy on Android Studio. It gives me weird compilation errors with respect to the following code:
def foo(float s) {
s = s / 2 // compilation error with pointer at '/' position
s = s.toFloat() / 254 // no error
}
The compilation error occurs even if the first line within the function is swapped with the last line.
I also tried the code on my local Groovy 1.8.6 environment outside of Android Studio on the command line. It doesn't give any error.
Who can explain me this irregular behavior? Is this normal? Are there more clever ways to circumvent this? Should I send a bug ticket to Groovy?
I am using Android Studio 2.1.2 with Oracle JVM 1.8.0_92 and the following gradle dependencies:
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'org.codehaus.groovy:gradle-groovy-android-plugin:0.3.10'
compile 'org.codehaus.groovy:groovy:2.4.6:grooid'
Edit: Here comes the compilation error from Android Studio:
/path/to/androidproject/Bar.groovy: 199: [Static type checking] - Possible loss of precision from double to float
# line 199, column 19.
s = s / 2
^
Edit 2: The following code compiles even on Android:
def foo(float s) {
s = s * 2
}
Try:
s = s / 2.0f
or
s = (float) (s / 2)

How to call String[][] in R using rjava

I am preparing an R wrapper for a java code that I didn't write myself (and in fact I don't know java). I am trying to use rJava for the first time and I am struggling to get the .jcall right.
Here is an extract of the java code for which I write a wrapper:
public class Model4R{
[...cut...]
public String[][] runModel(String dir, String initFileName, String[] variableNames, int numSims) throws Exception {
[...cut...]
dir and initFileName are character strings for the directory and file name with initial conditions, variable names is a list of character strings that I would write like this in R: c("var1", "var2", "var3", ...) and can be of length from one to five. Finally, numSim is an integer.
Here is my tentative R code for a wrapper function:
runmodel <- function(dir, inFile, varNames, numSim){
hjw <- .jnew("Model4R")
out <- .jcall(hjw, "[[Ljava/lang/String", "runModel", as.character(dir), as.character(inFile), as.vector(varNames), as.integer(numSim))
return(out)
}
The error in R is:
Error in .jcall(hjw, "[[Ljava/lang/String", "runModel", as.character(dir),
: method runModel with signature (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;II)[[Ljava/lang/String not found
I suspect that the JNI type isn't correct for String[][]. Anyhow, any help that could direct me towards a solution would be welcome!
You're missing a semicolon at the end of the JNI for String[][] - it should be "[[Ljava/lang/String;". Also, I think you need to call .jarray instead of as.vector on varNames. The R error is telling you that rJava thinks the class of the third argument is Ljava/lang/String; instead of [Ljava/lang/String;.

NullPointerException on return new[]

I have a very strange problem with NullPointerException. Code example is as follows:
...
... public String[] getParams(...) {
... ...
... ...
143 return new String[] {
144 getUserFullName(),
145 StringUtil.formatDate(sent),
. tiltu,
. StringUtil.initCap(user.getName()),
. vuosi.toString(),
. asiatyyppi[0] + " " + lisatiedot[0],
. asiatyyppi[1] + " " + lisatiedot[1],
. alaviitteet[0],
152 alaviitteet[1]};
153 }
Now, I have got an issue from production having a stack trace:
java.lang.NullPointerException
at package.EmailService.getParams(EmailService.java:143)
...
I am unable to produce that kind of stack trace myself. It maybe some environment issue that for some reason line numbers don't match. If I have null references on any variable stack trace points to that specific line but never to line 143.
But what I want to ask is: is it possible to produce NullPointerException at line 143 specifically?
The line number in the stack trace comes from the LineNumberTable attribute in the class file. (See JVM specification)
It would be no problem to output the right line number for a subexpression - all the compiler has to do is to say that from byte-code index x to y, there is a correspondence with source code line z.
But up to and including Java 1.7 there was a bug in the compiler, that was fixed in 1.8:
https://bugs.openjdk.java.net/browse/JDK-7024096
A DESCRIPTION OF THE PROBLEM : linenumbertable in compiled code only
has line numbers for starts of statements. When a statement is using
method chaining or other "fluent Interface" style API's a single
statement can span tens of lines and contain hundreds on method
invocations.
Currently an exception throw from within any of these methods will
have the linenumber of the first line of the enclosing statement which
makes it very hard to debug which method call is having a problem.
linnumbertable should have correct line numbers for every method
invocation.
--
BT2:EVALUATION
It seems simple enough to fix this, but its kinda risky at the end of
the jdk7 development cycle, targetting to jdk8.
So in 1.7, you would get the wrong reported line number for these kind of subexpressions (if they occurred within the same method though - if you invoked another method in a subexpression, and that other method caused a NullPointerException, you would see it reported there - this is probably why the bug isn't always a big problem)
One way you could work around this is by taking the Java 8 compiler to compile your source code, and use the flags javac -source 1.7 -target 1.7. But it would be better and safer to upgrade your prod environment to 1.8.
Consider your original code which defines a new String array:
return new String[] {
getUserFullName(),
StringUtil.formatDate(sent),
tiltu,
StringUtil.initCap(user.getName()),
vuosi.toString(),
asiatyyppi[0] + " " + lisatiedot[0],
asiatyyppi[1] + " " + lisatiedot[1],
alaviitteet[0],
alaviitteet[1]};
}
If any of the elements of the inline array should trigger a NullPointerException the JVM will interpret the Exception as having occurred on the line where the definition began. In other words, the JVM will view the above code as being the same as:
return new String[] { getUserFullName(), StringUtil.formatDate(sent), tiltu, StringUtil.initCap user.getName()), vuosi.toString(), asiatyyppi[0] + " " + lisatiedot[0], asiatyyppi[1] + " " + lisatiedot[1], alaviitteet[0], alaviitteet[1]}; }
where everything is on one line.
If you really want to handle NullPointerExceptions here, you should define the variables outside the instantiaition.

Z3 Java Possible Memory Leak?

I have a strange memory problem with Java library of Z3 which I couldn't figure where the problem is. Oddly, I can't reproduce the problem on a Windows machine where I have Java 7 (I most probably have slightly older version of Z3 there though). The problem occurs on a MacOSx 10.6.8 with Java 6 and Z3 v4.3.2. I have an application that uses Z3 for analysis. I tracked the following piece of code as the (initial) source of the problem:
Symbol eNames = con.mkSymbol(domainName);
Symbol[] symbols = new Symbol[values.length];
for (int i = 0; i < values.length; i++) symbols[i] = con.mkSymbol(values[i]);
System.out.println("Before ENUMSORT");
//EnumSort eSort = con.mkEnumSort(domainName, values);
EnumSort eSort = con.mkEnumSort(eNames,symbols);
System.out.println("After ENUM SORT ...");
When I run the application I get the following after "Before ENUMSORT" is printed:
java(55938,0x100501000) malloc: *** error for object 0x10200f1b8: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
I know this is not a good way of debugging especially when there is a memory problem but it is very difficult to debug the code since it originates from JNI. When I look at the Z3 code here (https://github.com/Z3Prover/z3/blob/master/src/api/api_datatype.cpp) I couldn't figure what the source of the problem is. I assume that the method Z3_mk_enumeration_sort is called from mkEnumSort method in Java. When I change the call of mkEnumSort in my code to a form like
EnumSort eSort = con.mkEnumSort(domainName,new String[]{"X","Y"});
the problem seems gone. What do you think, what could be the source of the problem?
Any help is highly appreciated.

Groovy Syntax Checking in Java

I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. The Java implementation below works OK but the resulting message contains some undesired elements (in bold). I'm looking for a way to list warnings and errors individually.
I'm using this maven dependency: groovy-all 2.1.1
try {
new GroovyShell().parse(groovyCode);
} catch(CompilationFailedException cfe) {
System.out.println(cfe.getMessage());
}
Output:
startup failed:
Script1.groovy: 1: unexpected token: n # line 1, column 19.
def factorial(n) n == 1 ? 1 : n * factorial(n - 1) }
^
1 error
Would not make much sense to parse the error message. Try to look into
CompilationFailedException.getUnit()
ProcessingUnit.getErrorCollector()
ErrorCollector.getWarnings() & getErrors()
EDIT
Ok, looks like unit is null on the CompilationFailedException. Try catching MultipleCompilationErrorsException instead:
try {
new GroovyShell().parse(groovyCode);
} catch(MultipleCompilationErrorsException cfe) {
ErrorCollector errorCollector = cfe.getErrorCollector();
System.out.println("Errors: "+errorCollector.getErrorCount());
}
Btw, take a look at the ErrorCollector sources, you might find write method useful to output the info about compilation errors.

Categories

Resources