Floating point exception and coredump using Virtual TMB - c++

I'm facing NA/NaN errors with my TMB code. Searching on the internet, I found that including fenv.h file into my code can give me a clue about the source of errors.
Since this example nan error does not work on Windows, I decided to follow an advice to run this example in Virtual TMB (Because my old desktop cannot afford to run more than one operating system).
But the new problem appeared. I get unused variable errors after running the code.
This code is copied and pasted from the link above.
cpp code
// Illustrates how to make the debugger catch a floating point error.
#include <TMB.hpp>
#include <fenv.h> // Extra line needed
template<class Type>
Type objective_function<Type>::operator() ()
{
feenableexcept(FE_INVALID | FE_OVERFLOW | FE_DIVBYZERO | FE_UNDERFLOW); // Extra line needed
DATA_SCALAR(lambda);
PARAMETER(x);
Type f;
f = sqrt(-1.); // FE_INVALID ( sqrt(-1.) returns NaN )
//f = 1./0.; // FE_DIVBYZERO ( division by zero )
//f = exp(100000.); // FE_OVERFLOW ( exp(100000.) returns Inf ) [Does not work on all platforms]
//f = exp(-100000.); // FE_UNDERFLOW ( exp(-100000.) returns 0 )
return f;
}
and here is the corresponding r code for Linux
data <- list(lambda = 25)
parameters <- list(x=1)
require(TMB)
compile('nan.cpp','-fno-gnu-unique -O0 -Wall')
dyn.load(dynlib('nan'))
model <- MakeADFun(data, parameters)
fit <- nlminb(model$par, model$fn, model$gr)
rep <- sdreport(model)
print(rep)
I attached my sessionInfo and the warning messages via image files.
Error
nan.cpp: In instantiation of 'Type objective_function<Type>::operator()() [with Type =double]':
/home/tmb/r/library/TMB/include/tmb_core.hpp:1416:16: required from here
nan.cpp:7:15:warning:unused variable 'lambda' [-Wunused -variable]
DATA_SCALAR(lambda);
^
/home/tmb/r/library/TMB/include/tmb_core.hpp:199:32: note: in definition of macro 'DATA_SCALAR'
#define DATA_SCALAR(name) Type name(asVector<Type>( \
nan.cpp:8:13: warning: unused variable 'x' [-Wunused-variable]
PARAMETER(x);
^
/home/tmb/r/library/TMB/include/tmb_core.hpp:182:30: note: in definition of macro 'PARAMETER'
How can I solve this problem?
Thanks!
Warning message:
Session Info:

Related

'=': cannot convert from 'int' to 'std::_Iosb<int>::_Fmtflags'

Trying to use ios format flags to format the string representation of Boost multiprecision cpp_int.
Everything works with gcc standard c++17, but in Visual Studio 2019 (v142) same standard, I'm getting a compilation error when using '|' operator to combine flags:
string format_cpp_int(boost::multiprecision::cpp_int& n, bool show_base, bool uppercase)
{
auto f = std::ios::hex;
if (show_base) f = f | std::ios::showbase;
if (uppercase) f = f | std::ios::uppercase;
return n.str(0, f);
}
Getting the following error:
Severity Code Description Project File Line Suppression State
Error C2440 '=': cannot convert from 'int' to 'std::_Iosb::_Fmtflags' (compiling source file main.cpp)
Is there some difference between c++17 support in gcc and VS that i'm not aware of?
Also trying to cast the result back to fmtflags doesn't seem to work either.
f = static_cast<std::ios::fmtflags>(f | std::ios::showbase);
is there another way to combine the flags and pass to cpp_int?
Because the keyword auto may get the underlying type, which may be implemented by the specific compiler.
You should write the type immediately:
std::ios::fmtflags f = std::ios::hex;
if (show_base) f = f | std::ios::showbase;
if (uppercase) f = f | std::ios::uppercase;

Rcpp and protobuf: double definition of Free macro

I'm developing a C++ library and wanted to interface it with both Python and R.
The core idea is that R and Python are basically 'empty shells' used for plotting and not much else and all the core computation is done in C++, so that the interface is just a bunch of functions that run the equivalent of a C++ 'main' and return the output to R or Python instead of saving stuff to file.
My idea was to use goolge's protocol buffer in a server/client fashion: data is passed from Python (R) to C++ using a serialized message, is then deserialized in C++. Computation is run in C++ and to Python (R) is returned a list of bytes/strings corresponding each to a serialized proto object.
In Python, this works like a charm thanks to Pybind11.
However, in R I get a weird error:
/usr/include/google/protobuf/arena_impl.h:174:60: error: macro "Free" passed 3 arguments, but takes just 1
void (*block_dealloc)(void*, size_t));
I believe this issue is due to Rcpp defining a similar macro to protobuf.
The following MWE reproduces the same error.
This is the fold structure
.
├── src
│   ├── rcpp_exports.cpp
├── student.proto
└── test.R
in test.R
Rcpp::sourceCpp(file="src/rcpp_exports.cpp")
in rcpp_exports.cpp
#include <Rcpp.h>
using namespace Rcpp;
#include "student.pb.h"
// [[Rcpp::export]]
std::string foo() {
Student stud;
stud.set_grade(25);
return stud.DebugString();
}
in student.proto
syntax = "proto3";
message Student {
double grade = 1;
bool pass = 2;
}
the protobuf file is then compiled using
> protoc --proto_path=. --cpp_out=./src student.proto
and finally I run the test.R file
> Rscript test.R
Getting the following error log:
In file included from /usr/include/google/protobuf/arena.h:55:0,
from /home/mario/dev/tesi/test_rproto/src/student.pb.h:24,
from rcpp_exports.cpp:3:
/usr/include/google/protobuf/arena_impl.h:174:60: error: macro "Free" passed 3 arguments, but takes just 1
void (*block_dealloc)(void*, size_t));
^
In file included from /usr/share/R/include/R.h:91:0,
from /home/mario/R/x86_64-pc-linux-gnu-library/3.6/Rcpp/include/Rcpp/r/headers.h:63,
from /home/mario/R/x86_64-pc-linux-gnu-library/3.6/Rcpp/include/RcppCommon.h:29,
from /home/mario/R/x86_64-pc-linux-gnu-library/3.6/Rcpp/include/Rcpp.h:27,
from rcpp_exports.cpp:1:
/usr/share/R/include/R_ext/RS.h:74:37: error: expected identifier before ‘(’ token
#define Free(p) (R_chk_free( (void *)(p) ), (p) = NULL)
^
/usr/share/R/include/R_ext/RS.h:74:47: error: ‘parameter’ declared as function returning a function
#define Free(p) (R_chk_free( (void *)(p) ), (p) = NULL)
^
/usr/share/R/include/R_ext/RS.h:74:50: error: expected ‘)’ before ‘,’ token
#define Free(p) (R_chk_free( (void *)(p) ), (p) = NULL)
^
make: *** [rcpp_exports.o] Error 1
I would recommend a few things for defensive programming:
Do not flatten namespaces i.e. remove using namespace Rcpp; and call your functins explicitly with prefix.
Ask for stringent includes (which we can't retroactively make a default) by defining #define STRICT_R_HEADERS before including Rcpp.h or other R headers.
Use R functions without the remap, i.e Rf_error() by defining R_NO_REMAP but Rcpp should do that for you.
That should avoid the clash you found here by being a little liberal in what you included and how.
Lastly, we wrote RProtoBuf (and it actually had a hand in creating what is the current Rcpp too) well over a decade ago yet I never got that error message you have here. So it clearly can be avoided.

How to detect USRP usb type?

When i include uhd/usb_control.hpp in my main.cpp :
#include <uhd/transport/usb_control.hpp>
/* Some other includes */
int main (void)
{
uhd::transport::usb_control::sptr usbSpeed;
usbSpeed = uhd::transport::usb_control::make(handle, 0);
/* `handle` is a `usb_device_handle::vid_pid_pair_t` */
}
I got error from here:
static sptr make(usb_device_handle::sptr handle, const int interface);
Error:
unexpected token struct. Did you forget a ';'
struct: missing tag name
And another strange error in:
usbSpeed = uhd::transport::usb_control::make(handle, 0);
Error:
Cannot convert argument 2 from int to const int
The only implementation that i find for uhd::transport::usb_control::make is uhd/transport/usb_dummy_impl.cpp which only throw an exception.
Environment information:
Compiler: MS Visual Studio 2017
OS: MS Windows 10
C++ Standard: 17
How to fix those errors ? I only what to detect the USRP usb type. For this i read the uhd source code and i find the uhd/transport/usb_control.hpp, But I have encountered those errors.
maybe the cause of this unexpected behavior is related to your included files and a conflict between some of them, as you mentioned in addition of #include <uhd/transport/usb_control.hpp> you have some other includes. i suggest move this include line upper and lower of other includes and test your code again.
wish my suggest be useful.

error: jump to label 'foo' crosses initialization of 'bar'

The following C++ example fails to compile with gcc or clang, but only generates a warning with ICC, and nothing at all with MSVC:
int main(int argc, char *argv[])
{
if (argc < 2)
goto clean_up;
#if 1 // FAIL
int i = 0;
#elif 0 // workaround - OK
{
int i = 0;
}
#else // workaround - OK
int i;
i = 0;
#endif
clean_up:
return 0;
}
g++:
init.cpp:13: error: jump to label ‘clean_up’
init.cpp:4: error: from here
init.cpp:7: error: crosses initialization of ‘int i’
clang++:
init.cpp:4:9: error: cannot jump from this goto statement to its label
goto clean_up;
^
init.cpp:7:9: note: jump bypasses variable initialization
int i = 0;
^
ICC:
init.cpp(4): warning #589: transfer of control bypasses initialization of:
variable "i" (declared at line 7)
goto clean_up;
^
I understand the cause of the error, and for a simple example such as this it is fairly easy to work around (I've included a couple of possible workarounds in the example above), but I'm working on a large cross-platform legacy code base that is peppered with error-handling macros which use a similar goto construct. Other developers working with MSVC or ICC keep introducing inline initialisations which subsequently result in errors for gcc or clang builds (and of course they just ignore the warnings they get with MSVC/ICC).
So I need to find a way to either (a) make such cases result in errors on ICC/MSVC or (b) reduce them to warnings with gcc/clang. I tried -fpermissive with gcc but that doesn't seem to help.
For extra credit I'm also curious as to the rationale behind this error for simple scalar initialisation - I can see why jumping over a constructor might be problematic, but initialising an int as in the above example doesn't seem like it could ever be an issue, and simply splitting the definition+initialisation into a definition + assignment makes the error go away?
The MSVC flag for treating a warning as en error is /we n where n is the number of the warning.
For example, /we4326 flags warning number C4326 as an error.
See https://msdn.microsoft.com/en-us/library/thxezb7y.aspx for details.

Forcing preprocessor error with macro

Is there a way that I can force a preprocessor macro in C++ to emit an error? What I would like to do is define a macro UNKNOWN. I'm writing some code for a robot, and I don't yet know where all of the electronics are being plugged in. I'd like to be able to define the ports in some header file, like
const int MOTOR_PORT = 1;
const int FAN_PORT = 2;
//etc.
However, when I reach a port that I don't yet know, I want to be able to write something like
const int LED_PORT = UNKNOWN;
In debug mode, UNKNOWN would just be defined to some arbitrary value, like 0. However, when compiling in release mode, I want it to throw an error when UNKNOWN is used, so that unassigned ports don't end up in the final release. I know I can use the #error directive to force an error, but can I do something similar in a macro?
I've seen a solution using static_assert, but I unfortunately can't use C++11 for this platform.
Since #error can't result from a macro expansion, you can ensure that the macro expands to something that must be diagnosed, like a syntax error.
For example:
#ifdef RELEASE
#define UNKNOWN #Invalid_use_of_UNKNOWN
#else
#define UNKNOWN 0
#endif
const int MOTOR_PORT = 1;
const int FAN_PORT = 2;
const int LED_PORT = UNKNOWN;
int main(void) {
int x = LED_PORT;
}
The # character isn't part of C's basic character set, so its appearance outside a comment, character constant, or string literal should always result in an error message. ($ would work, except that accepting $ in identifiers is a common extension. ` would probably also work, but # stands out better.)
I've defined the macro so it produces a reasonable error message with gcc:
c.c:9:1: error: stray ‘#’ in program
c.c:9:22: error: ‘Invalid_use_of_UNKNOWN’ undeclared here (not in a function)
and with clang:
c.c:9:22: error: expected expression
const int LED_PORT = UNKNOWN;
^
c.c:2:17: note: expanded from:
#define UNKNOWN #Invalid_use_of_UNKNOWN
^
1 error generated.
(There's a _Pragma operator corresponding to the #pragma directive. It would be nice if there were an _Error operator as well, but there isn't.)
Well, this does not produce a complier error message like #error, but would compile in debug and fail in release:
#ifdef _DEBUG
# define UNKNOWN 1
#else
# define UNKNOWN
#endif
const int port1 = UNKNOWN; // fail in release
You could make a division by zero which will throw a compiler error:
#define UNKNOWN 0/0
The sizeof operator cannot be applied to an incomplete type, so try this:
// Declared, but not defined anywhere.
struct illegal_use_of_unknown_macro;
#define UNKNOWN (sizeof (illegal_use_of_unknown_macro))