/** * Extract the exception error string from the python interpreter. * * This function assumes the gil is acquired. See \ref python_thread_guard. * * Code adapted from http://stackoverflow.com/questions/1418015/how-to-get-python-exception-text */ std::string parse_python_error() { PyObject *exc,*val,*tb; PyErr_Fetch(&exc,&val,&tb); PyErr_NormalizeException(&exc,&val,&tb); python::handle<> hexc(exc),hval(python::allow_null(val)),htb(python::allow_null(tb)); if(!hval) { return python::extract<std::string>(python::str(hexc)); } else { python::object traceback(python::import("traceback")); python::object format_exception(traceback.attr("format_exception")); python::object formatted_list(format_exception(hexc,hval,htb)); python::object formatted(python::str("").join(formatted_list)); return python::extract<std::string>(formatted); } }
void getHessVec(Vector<Real> &hv, SampleGenerator<Real> &sampler) { RiskVector<Real> &hs = Teuchos::dyn_cast<RiskVector<Real> >(hv); std::vector<Real> myhval(5,0.0), hval(5,0.0); myhval[0] = RiskMeasure<Real>::val_; myhval[1] = valLam_; myhval[2] = valLam2_; myhval[3] = valMu_; myhval[4] = valMu2_; sampler.sumAll(&myhval[0],&hval[0],5); std::vector<Real> stat(2,0.0); stat[0] = (vlam_ * hval[1] + vmu_ * hval[0] + hval[2])/xlam_; stat[1] = (vlam_ * hval[0] + vmu_ * hval[3] + hval[4])/xlam_; hs.setStatistic(stat); sampler.sumAll(*(RiskMeasure<Real>::hv_),*dualVector_); hs.setVector(*dualVector_); }
/// Adapted from http://stackoverflow.com/a/6576177/1689220 std::string pyerr_to_string(void) { PyObject *exc, *val, *tb; bp::object formatted_list, formatted; PyErr_Fetch(&exc, &val, &tb); // wrap exception, value, traceback with bp::handle for auto memory management bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb)); // import "traceback" module bp::object traceback(bp::import("traceback")); if (!tb) { bp::object format_exception_only(traceback.attr("format_exception_only")); formatted_list = format_exception_only(hexc, hval); } else { bp::object format_exception(traceback.attr("format_exception")); formatted_list = format_exception(hexc, hval, htb); } formatted = bp::str("\n").join(formatted_list); return bp::extract<std::string>(formatted); }
uint16_t f2h(float f) { half hval(f); return hval.bits(); }