forecast.HoltWinters is not getting mapped into C++ - c++

Based on the example code I was trying to run forecast method using c++ and RInside , but I am getting Read 100 items
Exception caught: not a matrix
Can somebody please take a look at my code.
#include <RInside.h>
int main ( int argc, char **argv) {
try {
// create an embedded R instance
RInside R ( argc, argv);
std::string txt =
"rain <- scan(\"http://robjhyndman.com/tsdldata/hurst/precip1.dat\",skip=1);"
"rainseries <- ts(rain,start=c(1813));"
"rainseriesforecasts <- HoltWinters(rainseries, beta=FALSE, gamma=FALSE);"
"suppressMessages(require(forecast));";
R.parseEvalQ(txt); // eval command, no return
Rcpp::NumericMatrix M((SEXP)R.parseEval("rainseriesforecasts2 <- forecast.HoltWinters(rainseriesforecasts, h=8)"));
Rcpp::StringVector cnames( (SEXP) R.parseEval("colnames(rainseriesforecasts2)"));
Rcpp::StringVector rnames( (SEXP) R.parseEval("rownames(rainseriesforecasts2)"));
std::cout << "\n\nAnd now from C++\n\n\t\t\t";
for (int i=0; i<cnames.size(); i++) {
std::cout << std::setw(11) << cnames[i] << "\t";
}
std::cout << std::endl;
for (int i=0; i<rnames.size(); i++) {
std::cout << std::setw(16) << rnames[i] << "\t";
for (int j=0; j<cnames.size(); j++) {
std::cout << std::setw(11) << M(i,j) << "\t";
}
std::cout << std::endl;
}
std::cout << std::endl;
} catch(std::exception& ex) {
std::cerr << "Exception caught: " << ex.what() << std::endl;
} catch(...) {
std::cerr << "Unknown exception caught" << std::endl;
}
}

This looks like a straight-up adaptation of one of the over a dozen examples I have included in the RInside sources -- so that is a good starting point.
The error you quote is an R error, not a C++ error so I would start by trying the few lines of R code by themselves in R. Pay particular attention to the class() of the returns you want to assign to make sure you do cast it to the right C++ types.
Edit: Ok, had some time to look at it. You were close, but as I suspected the types from the forecast package get in the way. Try this:
R.parseEvalQ(txt); // eval command, no return
Rcpp::NumericMatrix M((SEXP)R.parseEval("rainseriesforecasts2 <- as.matrix(as.data.frame(forecast.HoltWinters(rainseriesforecasts, h=8)))"));
Rcpp::StringVector cnames( (SEXP) R.parseEval("colnames(as.data.frame(rainseriesforecasts2))"));
Rcpp::StringVector rnames( (SEXP) R.parseEval("rownames(as.data.frame(rainseriesforecasts2))"));
and with that it works for me:
edd#dexter:~/svn/rinside/pkg/inst/examples/standard$ ./rinside_sample12
Read 100 items
And now from C++
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
1913 24.6782 19.1749 30.1815 16.2617 33.0947
1914 24.6782 19.1733 30.1831 16.2592 33.0972
1915 24.6782 19.1717 30.1847 16.2568 33.0996
1916 24.6782 19.1701 30.1863 16.2543 33.102
1917 24.6782 19.1685 30.1879 16.2519 33.1045
1918 24.6782 19.1669 30.1895 16.2495 33.1069
1919 24.6782 19.1653 30.1911 16.247 33.1094
1920 24.6782 19.1637 30.1926 16.2446 33.1118
edd#dexter:~/svn/rinside/pkg/inst/examples/standard$

Related

about : Scope of exception object in C++ : why don't I get the copy?

In question about scope of exception it is stated by Aj. that throw and catch clauses will create copies of the exception (unless reference is used I guess)
I tried myself a small toy code and I don't understand the result. here :
//g++ 7.4.0
#include <iostream>
using namespace std;
struct Some_error {
Some_error(float code):err_code(code){ cout << "Some_error(" << err_code << ")\n"; }
~Some_error() { cout << "~Some_error(" << err_code << ")\n"; }
Some_error(const Some_error& o):err_code(o.err_code+0.1) { cout << "Some_error(copy::" << err_code << ")\n"; }
Some_error(Some_error&& o):err_code(std::move(o.err_code)+.01){ cout << "Some_error(move::" << err_code << ")\n"; }
int get_code() const { return err_code; }
private : float err_code;
};
int do_task() {
if ( false ) return 42; else throw Some_error {1};
cout << "end do_task\n" ;
}
void taskmaster(){
try { auto result = do_task(); cout << "the answer is " << result << "\n" ; }
catch (Some_error e) { cout << "catch Some_error : " << e.get_code() << "\n" ; }
cout << "end taskmaster\n" ;
}
int main() { taskmaster(); }
the trace I get is as follows :
Some_error(1)
Some_error(copy::1.1)
catch Some_error : 1
~Some_error(1.1)
~Some_error(1)
end taskmaster
Now first, as I used no reference here, according to Aj., I would expect 2 copies to happen.
And second, there was a copy, that set err_code to 1.1, but the display is still 1.
Remark: just to be complete, I changed the catch to : catch(Some_error& e),
and then the trace looks fine to me :
Some_error(1)
catch Some_error : 1
~Some_error(1)
end taskmaster
I would expect 2 copies to happen.
Why? Only one copy is made by the catch block. Where would the second copy happen?
set err_code to 1.1, but the display is still 1.
Because get_code returns an int, so the floating point value gets truncated.

Reading out Pixel Values, png++, C++

I am trying to load the pixel rgb/ga information of a png image into a matrix, using the library png++, to do some computations with them.
My Code (which does not work at the moment):
#include <iostream>
#include <png++/image.hpp>
#include <png++/rgb_pixel.hpp>
int main(int argc, const char * argv[]) {
const std::string path="img_03.png";
png::image< png::basic_rgb_pixel <unsigned char> > pic(path);
pixel=pic.get_pixel(0, 0);
pixelp = &pixel;
std::cout << "value=" << pic[10][10].red << std::endl; //output: '?'
std::cout << "value=" << pixel.red << std::endl; //nothing
std::cout << "pointer=" << pixelp << std::endl; //delivers adress
pic.read(path);
std::cout << "value=" << pic[10][10].red << std::endl; //nothing
pic.write("picOutput.png"); //same picture
return 0;
}
However, none of those methods work to get the rgb values of each pixel.
If there is another way to get rgb/ga information of each pixel, please mention it.
The line pic.write("picOutput.png"); delivers the same png i loaded in the line pic.read(path). This is a personal exercise for me to get more used to C++, criticise my code as much as you can.
Thanks!
Here comes the solution:
change line:
std::cout << "value=" << pic[10][10].red << std::endl; //nothing
with:
std::cout << "value=" << (int) pic[10][10].red << std::endl; //nothing
because std::cout can't output types of unsigned char.
Thanks to Alex!
For in-depth explanation, look here:
cout not printing unsigned char

Boost locale compare throws EXC_BAD_ACCESS

The following trivial usage of Boost's locale library generates a runtime error:
#include <boost/locale.hpp>
int main(int argc, const char * argv[]) {
boost::locale::generator gen;
std::locale loc = gen("");
std::locale::global(loc);
std::wstring a=L"Façade", b=L"facade";
bool eq = std::use_facet<boost::locale::collator<wchar_t>>(loc).compare(
boost::locale::collator_base::secondary,
a, b
) == 0;
if (eq) std::cout << "OK" << std::endl;
return 0;
}
The debugger traps the error in collator.hpp here:
int compare(level_type level,string_type const &l,string_type const &r) const
{
---> return do_compare(level,l.data(),l.data()+l.size(),r.data(),r.data()+r.size());
}
The error is "Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)"
I'm on a late 2013 iMac running macOS Sierra version 10.12 with Xcode 8.0 (8A218a) and boost-1.61.0_1. In hopes that maybe I just failed to install ICU with Boost, I just ran this:
brew install boost --with-icu4c --cxx11
This sample is based on Boost's own documentation:
http://www.boost.org/doc/libs/1_49_0/libs/locale/doc/html/index.html
Thoughts? Thank you.
---- EDIT -----
I tried dumping out info about the default locale:
std::cout << std::use_facet<boost::locale::info>(loc).name() << std::endl;
It contained simply "C" and the other attributes were not what I expected. I thus got explicit in my setup:
boost::locale::generator gen;
std::locale loc = gen("en_US.UTF-8");
std::locale::global(loc);
std::cout << std::use_facet<boost::locale::info>(loc).name() << std::endl;
std::cout << std::use_facet<boost::locale::info>(loc).language() << std::endl;
std::cout << std::use_facet<boost::locale::info>(loc).country() << std::endl;
std::cout << std::use_facet<boost::locale::info>(loc).variant() << std::endl;
std::cout << std::use_facet<boost::locale::info>(loc).encoding() << std::endl;
std::cout << std::use_facet<boost::locale::info>(loc).utf8() << std::endl;
Which output:
en_US.UTF-8
en
US
utf-8
1
Sadly, this did not help. Also, I noticed that the following code didn't work as expected:
const std::string g = "grüßEN";
std::cout << boost::locale::normalize(g, boost::locale::norm_nfc) << std::endl;
std::cout << boost::locale::normalize(g, boost::locale::norm_nfd) << std::endl;
std::cout << boost::locale::normalize(g, boost::locale::norm_nfkc) << std::endl;
std::cout << boost::locale::normalize(g, boost::locale::norm_nfkd) << std::endl;
It output all the same strings:
grüßEN
grüßEN
grüßEN
grüßEN
This seem to suggest there's something screwy with my install of Boost or ICU.

missing data in popen call

my program compiles without error and appears to run through all of the steps correctly. It is supposed to make a php call and return data. tcpdump does show the request going out so popen is being executed, but the receiving party never updates.
The only discrepancy I can find, is that the command variable appears to be missing data.
# .trol.o
market max price is 0.00638671 at position 0
php coin.php 155 0.006387
0.00638672
the second line in the output is the command I am sending to popen
cout << command << endl; -> php coin.php 155 0.006387
that number is supposed to be the same as the one under it 0.00638672
The number 6 and the number 2 have been chopped off somehow.
How do I get the correct data into my popen command?
code:
void mngr(){
//vector defs
vector<std::string> buydat;
vector<std::string> markdat;
vector<std::string> pricedat;
vector<std::string> purchaseid;
vector<double> doublePdat;
vector<double> doubleMdat;
doublePdat.reserve(pricedat.size());
doubleMdat.reserve(markdat.size());
char buybuff[BUFSIZ];
char command[70];
char sendbuy[12];
buydat = getmyData();
markdat = getmarketbuyData();
//string match "Buy" and send results to new vector with pricedat.push_back()
for(int b = 2; b < buydat.size(); b+=7){
if ( buydat[b] == "Buy" ) {
pricedat.push_back(buydat[b+1]);
}
}
transform(pricedat.begin(), pricedat.end(), back_inserter(doublePdat), [](string const& val) {return stod(val);});
transform(markdat.begin(), markdat.end(), back_inserter(doubleMdat), [](string const& val) {return stod(val);});
auto biggestMy = std::max_element(std::begin(doublePdat), std::end(doublePdat));
std::cout << "my max price is " << *biggestMy << " at position " << std::distance(std::begin(doublePdat), biggestMy) << std::endl;
auto biggestMark = std::max_element(std::begin(doubleMdat), std::end(doubleMdat));
std::cout << "market max price is " << *biggestMark << " at position " << std::distance(std::begin(doubleMdat), biggestMark) << std::endl;
if (biggestMy > biggestMark){
cout << "Biggest is Mine!" << endl;
}
else if (biggestMy < biggestMark){
//cout << "Biggest is market!";
*biggestMark += 0.00000001;
sprintf(sendbuy,"%f",*biggestMark);
sprintf(command, "php coin.php 155 %s",sendbuy);
FILE *markbuy = popen(command, "r");
if (markbuy == NULL) perror ("Error opening file");
while(fgets(buybuff, sizeof(buybuff), markbuy) != NULL){
size_t h = strlen(buybuff);
//clean '\0' from fgets
if (h && buybuff[h - 1] == '\n') buybuff[h - 1] = '\0';
if (buybuff[0] != '\0') purchaseid.push_back(buybuff);
}
cout << command << endl;
cout << *biggestMark << endl;
}
}
I would try to use long float format instead of float as the type of biggestMark should be evaluated as iterator across doubles. I mean try to change sprintf(sendbuy,"%f",*biggestMark); to sprintf(sendbuy,"%lf",*biggestMark);. Hope this would help.

segmentation fault that goes away by using iostream

So this is gnarly. I have a piece of code that used the Columbia Physics System c++ library. I get a segfault when I run it, most probably because the classes: CgArg, and vector f_field_in, etc are uninitialised. I used Valgrind and found that indeed the various arguments were pointing to invalid memory.
The strange this is that if I insert an iostream call anywhere in the two functions, the segfault goes away. I found out when I put flags in places to debug. It also doesn't segfault if I define an integer and write a simple cin >>. That's why I think it's something to do with iostream.
If you know of any reason why a call to iostream would somehow give pieces of code to the arguments, I'd be very thankful if you shared it with me.
#include <iostream>
using namespace std;
#include <config.h>
#include <util/lattice.h>
#include <util/dirac_op.h>
#include <util/gjp.h>
#include <interface.h>
#define CLOVER_MAT_SIZE 72
USING_NAMESPACE_CPS
// Same function for clover matrix and its inverse.
static
void interface(double *h_quda_clover, double *h_cps_clover)
{
h_quda_clover[0]=h_cps_clover[0]; // c00_00_re = C0.x, A0
...and lots more of this stuff...
h_quda_clover[35+36]=h_cps_clover[34+36]; // c32_31_im = C8.w, A5
}
static
void fill_h_clover_inv(Lattice &lat, int site[], double *h_quda_clover_inv_site)
{
double h_cps_clover_inv[72];
Vector *f_field_out, *f_field_in;
CgArg *arg;
CnvFrmType convert=CNV_FRM_NO;
DiracOpClover dirac(lat,f_field_out,f_field_in,arg,convert);
//cout << "B: " << site << endl;
//cout << "B: site: " << site[0] << ' ' << site[1] << ' ' << site[2] << ' ' << site[3] << endl;
dirac.SiteCloverMat(site,h_cps_clover_inv);
interface(h_quda_clover_inv_site,h_cps_clover_inv);
}
void fill_h_clover_inv_all(Lattice &lat, double *h_quda_clover_inv, int parity)
{
double *ptr=h_quda_clover_inv;
int nsites[4];
nsites[0]=GJP.XnodeSites();
nsites[1]=GJP.YnodeSites();
nsites[2]=GJP.ZnodeSites();
nsites[3]=GJP.TnodeSites();
int site[4];
cout << "A: " << site << endl;
for (site[3] = 0; site[3] < nsites[3]; ++(site[3])) {
for (site[2] = 0; site[2] < nsites[2]; ++(site[2])) {
for (site[1] = 0; site[1] < nsites[1]; ++(site[1])) {
site[0] = (site[3] + site[2] + site[1] + parity)%2;
for (; site[0] < nsites[0]; site[0] += 2) {
//cout << "A: site: " << site[0] << ' ' << site[1] << ' ' << site[2] << ' ' << site[3] << endl;
fill_h_clover_inv(lat,site,ptr);
ptr += CLOVER_MAT_SIZE;
}
}
}
}
}
The problem was with some uninitialised arguments being passed to DiracOpClover. Once we initialised CgArg properly,
CgArg cg_arg;
cg_arg.mass=1.0
everything was hunky dory!!
Thank for the help everyone.