Real GreensFunction3DRadInf::Rn(unsigned int n, Real r, Real t, gsl_integration_workspace* workspace, Real tol) const { Real integral; Real error; p_corr_R_params params = { this, n, r, t }; gsl_function F = { reinterpret_cast<double (*)(double, void*)>(&p_corr_R_F), ¶ms }; const Real umax(sqrt(40.0 / (this->getD() * t))); gsl_error_handler_t* old_handler = gsl_set_error_handler(&my_gsl_error_handler); // gsl_error_handler_t* old_handler = gsl_set_error_handler_off(); gsl_integration_qag(&F, 0.0, umax, tol, THETA_TOLERANCE, 2000, GSL_INTEG_GAUSS61, workspace, &integral, &error); gsl_set_error_handler(old_handler); return integral; }
double np_eq(double n, vec n_ext, set_const * C) { double res; int status; gsl_error_handler_t * def = gsl_set_error_handler_off(); double sum = 0.0; for (int i = 0; i < n_ext.size(); i++){ sum += n_ext[i]; } double _n = n; double xmin = 0.0, xmax = 0.2 * _n; status = 1; while ((status != 0) && (xmax < n)){ status = np_eq_solve(n, n_ext, xmin, xmax, C, res); xmax += 0.1*_n; } if (status != 0){ printf("! \n"); // std::ofstream ofs("np.dat"); // func_np_params params = {n, C, n_ext}; // for (int i = 0; i < 100; i++){ // ofs << n*i/100 << "," << func_np(n*i/100, ¶ms) << endl; // } // ofs.close(); res = 0.95*_n; } //printf("np_eq(%f, %f), ntot = %f, status = %i, res = %f, \n", // n_ext[0], n_ext[4], n, status, res); //printf("np_eq status = %i", status); gsl_set_error_handler(def); if (res < 0){ res = 0.0; } return res; }
void chol_inverse_cov_matrix(optstruct* options, gsl_matrix* temp_matrix, gsl_matrix* result_matrix, double* final_determinant_c){ int cholesky_test, i; double determinant_c = 0.0; gsl_error_handler_t *temp_handler; // disable the default handler // do a cholesky decomp of the cov matrix, LU is not stable for ill conditioned matrices temp_handler = gsl_set_error_handler_off(); cholesky_test = gsl_linalg_cholesky_decomp(temp_matrix); if(cholesky_test == GSL_EDOM){ fprintf(stderr, "trying to cholesky a non postive def matrix, in emulate-fns.c sorry...\n"); exit(1); } gsl_set_error_handler(temp_handler); // find the determinant and then invert // the determinant is just the trace squared determinant_c = 1.0; for(i = 0; i < options->nmodel_points; i++) determinant_c *= gsl_matrix_get(temp_matrix, i, i); determinant_c = determinant_c * determinant_c; //printf("det CHOL:%g\n", determinant_c); gsl_linalg_cholesky_invert(temp_matrix); gsl_matrix_memcpy(result_matrix, temp_matrix); *final_determinant_c = determinant_c; }
double BesselFunction::integrate( const Subpixel& pixel_center) const { gsl_error_handler_t * old_handler=gsl_set_error_handler_off(); double val = -1, abserr; dStorm::threed_info::ZPosition plane_z = dynamic_cast<const dStorm::threed_info::Lens3D&> (*trafo.optics.depth_info(dStorm::Direction_X)) .z_position(); int_info->delta_z = plane_z * 1E-6f * si::meter - fluorophore.z(); int_info->orig_position = pixel_center; int_info->function = this; gsl_function func; func.function = &BesselFunction::wavelength_callback; func.params = int_info.get(); if ( false ) { int status = gsl_integration_qags( &func, lambda.value()-15E-9, lambda.value()+15E-9, 0, 1E-3, int_info->integration_size, int_info->lambda, &val, &abserr ); assert( ! status ); gsl_set_error_handler(old_handler); return val / 30E-9; } else { double val = wavelength_callback( lambda.value(), func.params ); return val; } }
double Qag2D::compute() { gsl_error_handler_t *handler = gsl_set_error_handler_off(); // Result and absolute error estimate double r = NaN; size_t callLimitPerDim = (size_t)(sqrt((double)callLimit)/61.0); if(callLimitPerDim == 0) { callLimitPerDim = 1; } for(size_t i = 0; i < 2; ++i) { QagRule& rule = ruleChain.getRule(i); rule.setDivisionLimit(callLimitPerDim); rule.setEpsabs(absErrTol); rule.setEpsrel(relErrTol); } QagRule& xRule = ruleChain.getRule(0); QagRule& yRule = ruleChain.getRule(1); xRule.setBoundary(boundary.l(0), boundary.u(0)); yRule.setBoundary(boundary.l(1), boundary.u(1)); ruleChain.setIntegrand(integrand); r = ruleChain.compute(); absErrEst = xRule.getAbsoluteErrorEstimate(); relErrEst = absErrEst / fabs(r); gsl_set_error_handler(handler); return r; }
// [[Rcpp::export]] bool gslResetErrorHandler() { if (ptr_gsl_error_handler_t == NULL) { return false; } ptr_gsl_error_handler_t = gsl_set_error_handler(ptr_gsl_error_handler_t); return true; }
/* Set up a new ROM model, using data contained in dir */ static int SEOBNRROMdata_Init(SEOBNRROMdata *romdata, const char dir[]) { // set up ROM int ncx = 159; // points in q int ncy = 49; // points in chi int N = ncx*ncy; // size of the data matrix for one SVD-mode int ret = XLAL_FAILURE; /* Create storage for structures */ if(romdata->setup) { XLALPrintError("WARNING: You tried to setup the SEOBNRv1ROMEffectiveSpin model that was already initialised. Ignoring\n"); return (XLAL_FAILURE); } gsl_set_error_handler(&err_handler); (romdata)->cvec_amp = gsl_vector_alloc(N*nk_amp); (romdata)->cvec_phi = gsl_vector_alloc(N*nk_phi); (romdata)->Bamp = gsl_matrix_alloc(nk_amp, nk_amp); (romdata)->Bphi = gsl_matrix_alloc(nk_phi, nk_phi); (romdata)->cvec_amp_pre = gsl_vector_alloc(N); ret=load_data(dir, (romdata)->cvec_amp, (romdata)->cvec_phi, (romdata)->Bamp, (romdata)->Bphi, (romdata)->cvec_amp_pre); if(XLAL_SUCCESS==ret) romdata->setup=1; else SEOBNRROMdata_Cleanup(romdata); return (ret); }
int gaussian_valid(const gaussian_t* dist) { if (!(dist && dist->dim > 0 && dist->mean->size == dist->dim)) { return 0; } // check positive definite if (gaussian_isdiagonal(dist)) { size_t i = 0; for (i = 0; i < dist->dim; i++) { double x = gsl_vector_get(dist->diag, i); if (!isnormal(x) || x <= 0) { return 0; } } } else { gsl_matrix* v = gsl_matrix_alloc(dist->dim, dist->dim); gsl_matrix_memcpy(v, dist->cov); gsl_set_error_handler_off(); int status = gsl_linalg_cholesky_decomp(v); gsl_set_error_handler(NULL); gsl_matrix_free(v); if (status == GSL_EDOM) { return 0; } } return 1; }
int mcmclib_cholesky_decomp(gsl_matrix* A) { gsl_error_handler_t *hnd = gsl_set_error_handler_off(); int status = gsl_linalg_cholesky_decomp(A); gsl_set_error_handler(hnd); if(status != GSL_SUCCESS) return status; return GSL_SUCCESS; }
CAMLprim value ml_gsl_error_init(value init) { static gsl_error_handler_t *old; if(ml_gsl_err_handler == NULL) ml_gsl_err_handler = caml_named_value("mlgsl_err_handler"); if (Bool_val(init)) { gsl_error_handler_t *prev; prev = gsl_set_error_handler(&ml_gsl_error_handler); if (prev != ml_gsl_error_handler) old = prev; } else gsl_set_error_handler(old); return Val_unit; }
/* Update parameters using an implicit solver for * equation (17) of Girolami and Calderhead (2011). * Arguments: * state: a pointer to internal working storage for RMHMC. * model: a pointer to the rmhmc_model structure with pointers to user defined functions. * N: number of parameters. * stepSize: integration step-size. * Result: * The method directly updates the new_x array in the state structure. * returns 0 for success or non-zero for failure. */ static int parametersNewtonUpdate(rmhmc_params* state, rmhmc_model* model, int N , double stepSize){ gsl_vector_view new_x_v = gsl_vector_view_array(state->new_x, N); gsl_vector_view new_p_v = gsl_vector_view_array(state->new_momentum, N); gsl_matrix_view new_cholM_v = gsl_matrix_view_array(state->new_cholMx, N, N); /* temp copy of parameters */ gsl_vector_view x0_v = gsl_vector_view_array(state->btmp, N); gsl_vector_memcpy(&x0_v.vector, &new_x_v.vector); /* temp copy of inverse Metric */ gsl_matrix_view new_invM_v = gsl_matrix_view_array(state->new_invMx, N, N); gsl_matrix_view invM0_v = gsl_matrix_view_array(state->tmpM, N, N); gsl_matrix_memcpy(&invM0_v.matrix, &new_invM_v.matrix); gsl_vector_view a_v = gsl_vector_view_array(state->atmp, N); /* a = invM0*pNew */ /* TODO: replace gsl_blas_dgemv with gsl_blas_dsymv since invM0_v.matrix is symetric */ gsl_blas_dgemv(CblasNoTrans, 1.0, &invM0_v.matrix, &new_p_v.vector, 0.0, &a_v.vector); int iterations = state->fIt; int flag = 0; int i; for (i = 0; i < iterations; i++) { /* new_x = invM_new*p_new */ /* TODO: replace gsl_blas_dgemv with gsl_blas_dsymv since inew_invM_v.matrix is symetric */ gsl_blas_dgemv(CblasNoTrans, 1.0, &new_invM_v.matrix, &new_p_v.vector, 0.0, &new_x_v.vector); /* Calculates new_x_v = x0 + 0.5*stepSize*(invM_0*newP + newInvM*newP) */ gsl_vector_add(&new_x_v.vector, &a_v.vector); gsl_vector_scale(&new_x_v.vector, 0.5*stepSize); gsl_vector_add(&new_x_v.vector, &x0_v.vector); /* calculate metric at the current position or update everything if this is the last iteration */ if ( (i == iterations-1) ) /* call user defined function for updating all quantities */ model->PosteriorAll(state->new_x, model->m_params, &state->new_fx, state->new_dfx, state->new_cholMx, state->new_dMx); else /* call user defined function for updating only the metric ternsor */ model->Metric(state->new_x, model->m_params, state->new_cholMx); /* calculate cholesky factor for current metric */ gsl_error_handler_t* old_handle = gsl_set_error_handler_off(); flag = gsl_linalg_cholesky_decomp( &new_cholM_v.matrix ); if (flag != 0){ fprintf(stderr,"RMHMC: matrix not positive definite in parametersNewtonUpdate.\n"); return flag; } gsl_set_error_handler(old_handle); /* calculate inverse for current metric */ gsl_matrix_memcpy(&new_invM_v.matrix, &new_cholM_v.matrix ); gsl_linalg_cholesky_invert(&new_invM_v.matrix); } return flag; }
void Init_gsl_error(VALUE module) { Init_rb_gsl_define_GSL_CONST(module); gsl_set_error_handler(&rb_gsl_error_handler); define_module_functions(module); rb_gsl_define_exceptions(module); }
int Integration::integrate(gsl_function F) { gsl_set_error_handler_off(); // https://www.gnu.org/software/gsl/manual/html_node/QAGI-adaptive-integration-on-infinite-intervals.html#QAGI-adaptive-integration-on-infinite-intervals int ret = gsl_integration_qagi(&F, epsabs, epsrel, limit, workspace, &result, &abserr); if (ret) { fprintf(stderr, "Integration failed with a error [ %s ]\n", gsl_strerror(ret)); } gsl_set_error_handler(gsl_error); return ret; }
//inverse of real (symmetric) positive defined matrix //as a by-product we may obtain the square root of the determinant of A int InvRPD(Matrix &R, Matrix &A, double *LogDetSqrt, Matrix *ExternChol) { assert(A.nRow() == A.nCol()); assert(R.nRow() == R.nCol()); assert(A.nRow() == R.nCol()); Matrix *Chol; //Make the auxiliar matrix equal to A if (ExternChol == NULL) Chol = new Matrix( A.nRow(), A.nCol()); else Chol = ExternChol; R.Iden(); //Make R the identity Chol->copy(A); //Chol->print("A=\n"); gsl_error_handler_t *hand = gsl_set_error_handler_off (); int res = gsl_linalg_cholesky_decomp(Chol->Ma()); gsl_set_error_handler(hand); if (res == GSL_EDOM) { //printf("Matrix::InvRPD: Warning: Non positive definite matrix.\n"); //exit(0); return 0; } assert(res != GSL_EDOM); //Check that everything went well //solve for the cannonical vectors to obtain the inverse in R for (int i=0; i<R.nRow(); i++) { //R.print("R=\n"); gsl_linalg_cholesky_svx( Chol->Ma(), R.AsColVec(i)); } if (LogDetSqrt != NULL) { *LogDetSqrt = 0.0; for (int i=0; i<Chol->nRow(); i++) { *LogDetSqrt += log(Chol->ele( i, i)); //multiply the diagonal elements } } if (ExternChol == NULL) delete Chol; return 1; }
static VALUE rb_gsl_set_error_handler(int argc, VALUE *argv, VALUE module) { if (rb_block_given_p()) { eHandler = RB_GSL_MAKE_PROC; gsl_set_error_handler(&rb_gsl_my_error_handler); return Qtrue; } switch (argc) { case 0: gsl_set_error_handler(&rb_gsl_error_handler); return Qtrue; break; case 1: CHECK_PROC(argv[0]); eHandler = argv[0]; gsl_set_error_handler(&rb_gsl_my_error_handler); return Qtrue; break; default: rb_raise(rb_eArgError, "too many arguments (%d for 0 or 1 Proc)", argc); break; } }
void *rdist_new(t_symbol *msg, short argc, t_atom *argv){ t_rdist *x; int i; t_atom ar[2]; x = (t_rdist *)newobject(rdist_class); // create a new instance of this object x->r_out0 = outlet_new(x, 0); x->r_numVars = 0; // set up the random number generator gsl_rng_env_setup(); // waterman14 was the fastest according to my tests x->r_rng = gsl_rng_alloc((const gsl_rng_type *)gsl_rng_waterman14); // seed it by reading from /dev/random on mac os x and // something similar on windows gsl_rng_set(x->r_rng, makeseed()); // this is really f*****g important. if there's an error and the gsl's // default handler gets called, it aborts the program! gsl_set_error_handler(rdist_errorHandler); // setup a workspace x->r_output_buffer = (t_atom *)malloc(RDIST_DEFAULT_BUF_SIZE * sizeof(t_atom)); // init the lib. just gensyms all the distribution names librdist_init(); // handle the args. this should be done with attributes. if(argc){ if(argv[0].a_type == A_SYM){ rdist_anything(x, argv[0].a_w.w_sym, argc - 1, argv + 1); } } else { SETFLOAT(&(ar[0]), 0.); SETFLOAT(&(ar[1]), 1.); rdist_anything(x, gensym("uniform"), 2, ar); } return x; }
double f_eq(vec n, set_const * C){ int status = 1; double lo = 1e-9; double hi = 0.4; double trystep = 0.01; double res; gsl_error_handler_t * def = gsl_set_error_handler_off(); while ((status != 0) && (hi < 1.0)){ // printf("hi = %f\n", hi); status = f_eq_solve(n, C, lo, hi, &res); if (status != 0){ hi += trystep; } } gsl_set_error_handler(def); return res; }
int main (void) { gsl_function F_cos, F_func1, F_func2, F_func3, F_func4; const gsl_min_fminimizer_type * fminimizer[4] ; const gsl_min_fminimizer_type ** T; gsl_ieee_env_setup (); fminimizer[0] = gsl_min_fminimizer_goldensection; fminimizer[1] = gsl_min_fminimizer_brent; fminimizer[2] = 0; F_cos = create_function (f_cos) ; F_func1 = create_function (func1) ; F_func2 = create_function (func2) ; F_func3 = create_function (func3) ; F_func4 = create_function (func4) ; gsl_set_error_handler (&my_error_handler); for (T = fminimizer ; *T != 0 ; T++) { test_f (*T, "cos(x) [0 (3) 6]", &F_cos, 0.0, 3.0, 6.0, M_PI); test_f (*T, "x^4 - 1 [-3 (-1) 17]", &F_func1, -3.0, -1.0, 17.0, 0.0); test_f (*T, "sqrt(|x|) [-2 (-1) 1.5]", &F_func2, -2.0, -1.0, 1.5, 0.0); test_f (*T, "func3(x) [-2 (3) 4]", &F_func3, -2.0, 3.0, 4.0, 1.0); test_f (*T, "func4(x) [0 (0.782) 1]", &F_func4, 0, 0.782, 1.0, 0.8); test_f_e (*T, "invalid range check [4, 0]", &F_cos, 4.0, 3.0, 0.0, M_PI); test_f_e (*T, "invalid range check [1, 1]", &F_cos, 1.0, 1.0, 1.0, M_PI); test_f_e (*T, "invalid range check [-1, 1]", &F_cos, -1.0, 0.0, 1.0, M_PI); } test_bracket("cos(x) [1,2]",&F_cos,1.0,2.0,15); test_bracket("sqrt(|x|) [-1,0]",&F_func2,-1.0,0.0,15); test_bracket("sqrt(|x|) [-1,-0.6]",&F_func2,-1.0,-0.6,15); test_bracket("sqrt(|x|) [-1,1]",&F_func2,-1.0,1.0,15); exit (gsl_test_summary ()); }
/* Initialise RMHMC kernel with initial parameters x. * Arguments: * kernel: a pointer to the RMHMC kernel structure. * x: an array of N doubles with initial parameters. N must be * equal to kernel->N. * Result: * returns 0 for success and non-zero for error. */ static int rmhmc_kernel_init(mcmc_kernel* kernel, const double* x){ int res,i,n; n = kernel->N; rmhmc_params* params = (rmhmc_params*)kernel->kernel_params; /* copy x to the kernel x state */ for ( i=0; i < n; i++) kernel->x[i] = x[i]; rmhmc_model* model = kernel->model_function; /* call user function to update all required quantities */ res = model->PosteriorAll(x, model->m_params, &(params->fx), params->dfx, params->cholMx, params->dMx); /* TODO: write a proper error handler */ if (res != 0){ fprintf(stderr,"rmhmc_kernel_init: Likelihood function failed\n"); return 1; } /* calculate cholesky factor for current metric */ gsl_matrix_view cholMx_v = gsl_matrix_view_array(params->cholMx,n,n); gsl_error_handler_t* old_handle = gsl_set_error_handler_off(); res = gsl_linalg_cholesky_decomp( &cholMx_v.matrix ); if (res != 0){ fprintf(stderr,"Error: matrix not positive definite in rmhmc_init.\n"); return -1; } gsl_set_error_handler(old_handle); /* calculate inverse for current metric */ gsl_matrix_view invMx_v = gsl_matrix_view_array(params->invMx,n,n); gsl_matrix_memcpy(&invMx_v.matrix, &cholMx_v.matrix ); gsl_linalg_cholesky_invert(&invMx_v.matrix); /* calculate trace terms from equation (15) in Girolami and Calderhead (2011) */ calculateTraceTerms(n, params->invMx, params->dMx, params->tr_invM_dM); return 0; }
void gsl_err_env_setup (void) { const char * p = getenv("GSL_ERROR_MODE") ; if (p == 0) /* GSL_ERROR_MODE environment variable is not set */ return ; if (*p == '\0') /* GSL_ERROR_MODE environment variable is empty */ return ; printf("GSL_ERROR_MODE=\"") ; if (STR_EQ(p, "abort")) { gsl_set_error_handler (NULL); printf("abort") ; } printf("\"\n") ; }
double sncp_model::propose_new_parameters(double alpha,double z,double previous_height, double bound,double norm){ gsl_error_handler_t * old_handler = gsl_set_error_handler_off(); double new_value=NAN; int count =0; while(new_value!=new_value){ double u = gsl_ran_flat(m_r,0,1); u*=norm; new_value = gsl_cdf_gamma_Pinv(u,alpha,1.0/(double)z); //if(new_value!=new_value) // cout<<u<<" "<<norm<<" "<<bound<<" "<<alpha<<" "<<z<<" "<<previous_height<<endl; count++; if(count>20 and bound>0){ new_value=(previous_height+bound)/2; //cout<<new_value<<endl; } } gsl_set_error_handler(old_handler); return new_value; }
void experiment::run_experiment() { parameter pdebug = get_param("debugprint"); parameter pdebug_f = get_param("debugprint_file"); pdebug.strvalue=pdebug_f.strvalue; std::string sverbfile=get_param_s("verbose_file"); bool bverbose=(get_param_i("verbose_mode")==1); std::ofstream fverbose; if (sverbfile.compare("cout")==0) gout=&std::cout; else { fverbose.open(sverbfile.c_str()); gout=&fverbose; }; //used algorithms std::string sexp_type=get_param_s("exp_type"); std::string salgo_match=get_param_s("algo"); std::istrstream istr(salgo_match.c_str()); std::vector<std::string>v_salgo_match; std::string stemp; while (istr>>stemp) v_salgo_match.push_back(stemp); //used initialization algorithms std::string salgo_init=get_param_s("algo_init_sol"); std::istrstream istrinit(salgo_init.c_str()); std::vector<std::string>v_salgo_init; while (istrinit>>stemp) v_salgo_init.push_back(stemp); if (v_salgo_init.size()!=v_salgo_match.size()) { printf("Error: algo and algo_init_sol do not have the same size\n"); exit(0); }; double dalpha_ldh=get_param_d("alpha_ldh"); if ((dalpha_ldh<0) ||(dalpha_ldh>1)) { printf("Error:alpha_ldh should be between 0 and 1 \n"); exit(0); }; graph g(get_config()); graph h(get_config()); char cformat1='D',cformat2='D'; if (bverbose) *gout<<"Data loading"<<std::endl; g.load_graph(get_param_s("graph_1"),'A',cformat1); h.load_graph(get_param_s("graph_2"),'A',cformat2); if (get_param_i("graph_dot_print")==1){ g.printdot("g.dot");h.printdot("h.dot");}; // Matrix of local similarities between graph vertices std::string strfile=get_param_s("C_matrix"); int N1 =g.get_adjmatrix()->size1; int N2 =h.get_adjmatrix()->size1; gsl_matrix* gm_ldh=gsl_matrix_alloc(N1,N2); FILE *f=fopen(strfile.c_str(),"r"); if (f!=NULL){ gsl_set_error_handler_off(); int ierror=gsl_matrix_fscanf(f,gm_ldh); fclose(f); gsl_set_error_handler(NULL); if (ierror!=0){ printf("Error: C_matrix is not correctly defined \n"); exit(0);}; } else { if (bverbose) *gout<<"C matrix is set to constant"<<std::endl; dalpha_ldh=0; gsl_matrix_set_all(gm_ldh,1.0/(N1*N2)); }; //inverse the sign if C is a distance matrix if (get_param_i("C_matrix_dist")==1) gsl_matrix_scale(gm_ldh,-1); if (bverbose) *gout<<"Graph synhronization"<<std::endl; synchronize(g,h,&gm_ldh); //Cycle over all algoirthms for (int a=0;a<v_salgo_match.size();a++) { //initialization algorithm* algo_i=get_algorithm(v_salgo_init[a]); algo_i->read_config(get_config_string()); algo_i->set_ldhmatrix(gm_ldh); match_result mres_i=algo_i->gmatch(g,h,NULL,NULL,dalpha_ldh); delete algo_i; //main algorithm algorithm* algo=get_algorithm(v_salgo_match[a]); algo->read_config(get_config_string()); algo->set_ldhmatrix(gm_ldh); match_result mres_a=algo->gmatch(g,h,(mres_i.gm_P_exact!=NULL)?mres_i.gm_P_exact:mres_i.gm_P, NULL,dalpha_ldh); mres_a.vd_trace.clear(); mres_a.salgo=v_salgo_match[a]; v_mres.push_back(mres_a); delete algo; }; gsl_matrix_free(gm_ldh); printout(); }
int main(int argc, char *argv[]) { // initialize QT QApplication app(argc, argv); QString globalConfigFile = QDir::homePath () + "/.sfviewer.config"; // setup debugging if( GlobalSettings::isDebug()) { Debug::verbocity = 10; Debug::displayLevel = true; Debug::displaySource = true; Debug::setReceiver ( new MyDebugReceiver( "/tmp/fitsviewer.dbg.txt")); } else { Debug::verbocity = 0; Debug::displayLevel = false; Debug::displaySource = false; } dbg(1) << "*******************************************************************\n"; dbg(1) << " FitsViewer starting\n"; dbg(1) << "*******************************************************************\n"; dbg(1) << "Ideal thread count (qt): " << QThread::idealThreadCount() << "\n"; dbg(1) << "Ideal thread count (c++11): " << std::thread::hardware_concurrency() << "\n"; dbg(1) << "Global thread pool: " << QThreadPool::globalInstance()->maxThreadCount() << "\n"; { int nt = 0; #pragma omp parallel { #pragma omp critical { nt ++; dbg(1) << "thread " << nt << " reporting\n"; } } dbg(1) << "detected " << nt << "OMP threads\n"; } // install QT error handler qInstallMsgHandler(myMessageOutput); // install GSL error handler gsl_set_error_handler( gslErrorHandler); try { // initialize PureWeb CSI::Library::Initialize(); CSI::Threading::UiDispatcher::InitMessageThread(); CSI::PureWeb::Server::StateManagerServer server; CSI::PureWeb::Server::StateManager stateManager("fitsviewer"); // add a callback to listen to PureWeb shutdown event server.ShutdownRequested() += OnPureWebShutdown; // register tickler stateManager.PluginManager().RegisterPlugin("QTMessageTickler", new QTMessageTickler()); // connect server.Start(&stateManager); // DEBUG if(1){ ScopedDebug dbg__( "Startup paramters:", 1); for( auto kv : server.StartupParameters()) { std::string key = kv.first.ToAscii().begin(); std::string val = kv.second.ToAscii().begin(); dbg(1) << "key/val = " << key << " / " << val << "\n"; } } // figure out which file to load FitsFileLocation flocToLoad; VisualizationStartupParameters vsp; { // convert PureWeb params to std::map, so that we don't propagate dependencies // on PureWeb all across the system std::map< QString, QString > myMap; for( auto kv : server.StartupParameters()) myMap[ kv.first.ToAscii().begin() ] = kv.second.ToAscii().begin(); vsp = determineStartupParameters( myMap); } // check for errors if( vsp.error) { dbg(0) << ConsoleColors::error() << "Error: could not figure out startup parameters." << ConsoleColors::resetln() << " -> " << vsp.errorString << "\n" << "Will try to load the default file\n"; flocToLoad = FitsFileLocation::fromLocal( GlobalSettings::defaultImage()); } else { dbg(1) << "Startup parameters ===================================\n" << " title: " << vsp.title << "\n" << " path: " << vsp.path << "\n" << " id: " << vsp.id << "\n" << " stamp: " << vsp.stamp << "\n" << "======================================================\n" ; flocToLoad = FitsFileLocation::fromElgg( vsp.id, vsp.path, vsp.stamp); } if( vsp.title.isEmpty()) vsp.title = "N/A"; // const Collections::Map<CSI::String, CSI::String> & pars = // server.StartupParameters(); // { // QString fileId, stamp, path; // if( pars.ContainsKey( "fileid")) // fileId = pars["fileid"].ToAscii().begin(); // if( pars.ContainsKey( "timestamp")) // stamp = pars["timestamp"].ToAscii().begin(); // if( pars.ContainsKey( "filepath")) // path = pars["filepath"].ToAscii().begin(); // // dbg(1) << "fileId = " << fileId << "\n" // // << "stamp = " << stamp << "\n" // // << "path = " << path << "\n"; // if( !( fileId.isEmpty() || stamp.isEmpty() || path.isEmpty())) { // flocToLoad = FitsFileLocation::fromElgg( fileId, path, stamp); // dbg(1) << "floc2load = " << flocToLoad.toStr() << "\n"; // } // } dbg(1) << "will try to load file: " << flocToLoad.toStr() << "\n"; dbg(1) << " ... i.e: " << flocToLoad.getLocalFname() << "\n"; dbg(1) << "if that fails, will load: " << GlobalSettings::defaultImage() << "\n"; dbg(1) << "if that fails too, i'll probably crash :(\n"; // start up the controller FvController fvc ( app.arguments ()); fvc.setDefaultFileToOpen( FitsFileLocation::fromLocal( GlobalSettings::defaultImage())); fvc.start (); fvc.setTitle( vsp.title); fvc.loadFileAuto( flocToLoad); // give up control to Qt event loop int ret = app.exec(); s_stop.Set(); return ret; } catch (QString s) { fatalError( s); } catch (const char * s) { fatalError( s); } catch (const std::string & s) { fatalError(s); } catch (const std::runtime_error & err) { fatalError ( err.what()); } catch (const std::exception & err) { fatalError ( err.what()); } catch (...) { fatalError( "Unknown exception occured"); } // test std::function< void(double) > f; class ABC { public: void operator()(double val) { dbg(1) << "Yay " << val; } }; ABC abc; abc(7.1); f = abc; f(1.7); }
int main (void) { gsl_ieee_env_setup (); test_func (); test_float_func (); test_long_double_func (); test_ulong_func (); test_long_func (); test_uint_func (); test_int_func (); test_ushort_func (); test_short_func (); test_uchar_func (); test_char_func (); test_complex_func (); test_complex_float_func (); test_complex_long_double_func (); test_text (); test_float_text (); #if HAVE_PRINTF_LONGDOUBLE test_long_double_text (); #endif test_ulong_text (); test_long_text (); test_uint_text (); test_int_text (); test_ushort_text (); test_short_text (); test_uchar_text (); test_char_text (); test_complex_text (); test_complex_float_text (); #if HAVE_PRINTF_LONGDOUBLE test_complex_long_double_text (); #endif test_binary (); test_float_binary (); test_long_double_binary (); test_ulong_binary (); test_long_binary (); test_uint_binary (); test_int_binary (); test_ushort_binary (); test_short_binary (); test_uchar_binary (); test_char_binary (); test_complex_binary (); test_complex_float_binary (); test_complex_long_double_binary (); gsl_set_error_handler (&my_error_handler); test_trap (); test_float_trap (); test_long_double_trap (); test_ulong_trap (); test_long_trap (); test_uint_trap (); test_int_trap (); test_ushort_trap (); test_short_trap (); test_uchar_trap (); test_char_trap (); test_complex_trap (); test_complex_float_trap (); test_complex_long_double_trap (); exit (gsl_test_summary ()); }
double QFFitFunctionFCSDistributionDIntGaussian::evaluate(double t, const double* data) const { const int nonfl_comp=data[FCSDLG_n_nonfluorescent]; const double N=data[FCSDLG_n_particle]; const double nf_tau1=data[FCSDLG_nonfl_tau1]/1.0e6; const double nf_theta1=data[FCSDLG_nonfl_theta1]; const double nf_tau2=data[FCSDLG_nonfl_tau2]/1.0e6; const double nf_theta2=data[FCSDLG_nonfl_theta2]; const double D1=data[FCSDLG_diff_coeff1]; const double D1_sigma=data[FCSDLG_diff_coeff_sigma]; const double D_min=data[FCSDLG_D_range_min]; const double D_max=data[FCSDLG_D_range_max]; const double wxy=data[FCSDLG_focus_width]/1e3; const double background=data[FCSDiff_background]; const double cr=data[FCSDLG_count_rate]; double backfactor=qfSqr(cr-background)/qfSqr(cr); if (fabs(cr)<1e-15) backfactor=1; double gamma=data[FCSDLG_focus_struct_fac]; if (gamma==0) gamma=1; const double gamma2=sqr(gamma); const double offset=data[FCSDLG_offset]; if (N>0) { register double diff=0.0; double diff1=0.0; double diff2=0.0; double error=0; QFFitFunctionFCSDistributionDIntGaussian_intparam p; p.gamma=gamma; p.DC=D1; p.DSigma=D1_sigma; p.wxy=wxy; p.tau=t; gsl_function F; F.function = &QFFitFunctionFCSDistributionDIntGaussian_f; F.params = &p; gsl_function FD; FD.function = &QFFitFunctionFCSDistributionDIntGaussian_fd; FD.params = &p; gsl_error_handler_t * old_h=gsl_set_error_handler_off(); gsl_integration_qags(&F, D_min, D1, 0, 1e-7, wN, w, &diff1, &error); gsl_integration_qags(&F, D1, D_max, 0, 1e-7, wN, w, &diff2, &error); diff=diff1+diff2; gsl_integration_qags(&FD, D_min, D1, 0, 1e-7, wN, w, &diff1, &error); gsl_integration_qags(&FD, D1, D_max, 0, 1e-7, wN, w, &diff2, &error); diff=diff/(diff1+diff2); gsl_set_error_handler(old_h); double pre=1.0; if (nonfl_comp==1) { pre=(1.0-nf_theta1+nf_theta1*exp(-t/nf_tau1))/(1.0-nf_theta1); } else if (nonfl_comp==2) { pre=(1.0-nf_theta1+nf_theta1*exp(-t/nf_tau1)-nf_theta2+nf_theta2*exp(-t/nf_tau2))/(1.0-nf_theta1-nf_theta2); } return offset+pre/N*diff*backfactor; } else { const double Dtau=qfSqr(wxy)/4.0/t; return -1.0*exp(-0.5*qfSqr((Dtau-D1)/D1_sigma))/N*backfactor; } }
double *bayestar_sky_map_toa_phoa_snr( long *npix, /* Input: number of HEALPix pixels. */ double gmst, /* Greenwich mean sidereal time in radians. */ int nifos, /* Input: number of detectors. */ const float (**responses)[3], /* Pointers to detector responses. */ const double **locations, /* Pointers to locations of detectors in Cartesian geographic coordinates. */ const double *toas, /* Input: array of times of arrival with arbitrary relative offset. (Make toas[0] == 0.) */ const double *phoas, /* Input: array of phases of arrival with arbitrary relative offset. (Make phoas[0] == 0.) */ const double *snrs, /* Input: array of SNRs. */ const double *w_toas, /* Input: sum-of-squares weights, (1/TOA variance)^2. */ const double *w1s, /* Input: first moments of angular frequency. */ const double *w2s, /* Input: second moments of angular frequency. */ const double *horizons, /* Distances at which a source would produce an SNR of 1 in each detector. */ double min_distance, double max_distance, int prior_distance_power) /* Use a prior of (distance)^(prior_distance_power) */ { long nside; long maxpix; long i; double d1[nifos]; double *P; gsl_permutation *pix_perm; double complex exp_i_phoas[nifos]; /* Hold GSL return values for any thread that fails. */ int gsl_errno = GSL_SUCCESS; /* Storage for old GSL error handler. */ gsl_error_handler_t *old_handler; /* Maximum number of subdivisions for adaptive integration. */ static const size_t subdivision_limit = 64; /* Subdivide radial integral where likelihood is this fraction of the maximum, * will be used in solving the quadratic to find the breakpoints */ static const double eta = 0.01; /* Use this many integration steps in 2*psi */ static const int ntwopsi = 16; /* Number of integration steps in cos(inclination) */ static const int nu = 16; /* Number of integration steps in arrival time */ static const int nt = 16; /* Rescale distances so that furthest horizon distance is 1. */ { double d1max; memcpy(d1, horizons, sizeof(d1)); for (d1max = d1[0], i = 1; i < nifos; i ++) if (d1[i] > d1max) d1max = d1[i]; for (i = 0; i < nifos; i ++) d1[i] /= d1max; min_distance /= d1max; max_distance /= d1max; } (void)w2s; /* FIXME: remove unused parameter */ for (i = 0; i < nifos; i ++) exp_i_phoas[i] = exp_i(phoas[i]); /* Evaluate posterior term only first. */ P = bayestar_sky_map_toa_adapt_resolution(&pix_perm, &maxpix, npix, gmst, nifos, locations, toas, w_toas, autoresolution_count_pix_toa_phoa_snr); if (!P) return NULL; /* Determine the lateral HEALPix resolution. */ nside = npix2nside(*npix); /* Zero all pixels that didn't meet the TDOA cut. */ for (i = maxpix; i < *npix; i ++) { long ipix = gsl_permutation_get(pix_perm, i); P[ipix] = -INFINITY; } /* Use our own error handler while in parallel section to avoid concurrent * calls to the GSL error handler, which if provided by the user may not * be threadsafe. */ old_handler = gsl_set_error_handler(my_gsl_error); /* Compute posterior factor for amplitude consistency. */ #pragma omp parallel for firstprivate(gsl_errno) lastprivate(gsl_errno) for (i = 0; i < maxpix; i ++) { /* Cancel further computation if a GSL error condition has occurred. * * Note: if one thread sets gsl_errno, not necessarily all thread will * get the updated value. That's OK, because most failure modes will * cause GSL error conditions on all threads. If we cared to have any * failure on any thread terminate all of the other threads as quickly * as possible, then we would want to insert the following pragma here: * * #pragma omp flush(gsl_errno) * * and likewise before any point where we set gsl_errno. */ if (gsl_errno != GSL_SUCCESS) goto skip; { long ipix = gsl_permutation_get(pix_perm, i); double complex F[nifos]; double theta, phi; int itwopsi, iu, it, iifo; double accum = -INFINITY; double complex exp_i_toaphoa[nifos]; double dtau[nifos], mean_dtau; /* Prepare workspace for adaptive integrator. */ gsl_integration_workspace *workspace = gsl_integration_workspace_alloc(subdivision_limit); /* If the workspace could not be allocated, then record the GSL * error value for later reporting when we leave the parallel * section. Then, skip to the next loop iteration. */ if (!workspace) { gsl_errno = GSL_ENOMEM; goto skip; } /* Look up polar coordinates of this pixel */ pix2ang_ring(nside, ipix, &theta, &phi); toa_errors(dtau, theta, phi, gmst, nifos, locations, toas); for (iifo = 0; iifo < nifos; iifo ++) exp_i_toaphoa[iifo] = exp_i_phoas[iifo] * exp_i(w1s[iifo] * dtau[iifo]); /* Find mean arrival time error */ mean_dtau = gsl_stats_wmean(w_toas, 1, dtau, 1, nifos); /* Look up antenna factors */ for (iifo = 0; iifo < nifos; iifo++) { XLALComputeDetAMResponse( (double *)&F[iifo], /* Type-punned real part */ 1 + (double *)&F[iifo], /* Type-punned imag part */ responses[iifo], phi, M_PI_2 - theta, 0, gmst); F[iifo] *= d1[iifo]; } /* Integrate over 2*psi */ for (itwopsi = 0; itwopsi < ntwopsi; itwopsi++) { const double twopsi = (2 * M_PI / ntwopsi) * itwopsi; const double complex exp_i_twopsi = exp_i(twopsi); /* Integrate over u from u=-1 to u=1. */ for (iu = -nu; iu <= nu; iu++) { const double u = (double)iu / nu; const double u2 = gsl_pow_2(u); double A = 0, B = 0; double breakpoints[5]; int num_breakpoints = 0; double log_offset = -INFINITY; /* The log-likelihood is quadratic in the estimated and true * values of the SNR, and in 1/r. It is of the form A/r^2 + B/r, * where A depends only on the true values of the SNR and is * strictly negative and B depends on both the true values and * the estimates and is strictly positive. * * The middle breakpoint is at the maximum of the log-likelihood, * occurring at 1/r=-B/2A. The lower and upper breakpoints occur * when the likelihood becomes eta times its maximum value. This * occurs when * * A/r^2 + B/r = log(eta) - B^2/4A. * */ /* Perform arrival time integral */ double accum1 = -INFINITY; for (it = -nt/2; it <= nt/2; it++) { const double t = mean_dtau + LAL_REARTH_SI / LAL_C_SI * it / nt; double complex i0arg_complex = 0; for (iifo = 0; iifo < nifos; iifo++) { const double complex tmp = F[iifo] * exp_i_twopsi; /* FIXME: could use - sign here to avoid conj below, but * this probably just sets our sign convention relative to * detection pipeline */ double complex phase_rhotimesr = 0.5 * (1 + u2) * creal(tmp) + I * u * cimag(tmp); const double abs_rhotimesr_2 = cabs2(phase_rhotimesr); const double abs_rhotimesr = sqrt(abs_rhotimesr_2); phase_rhotimesr /= abs_rhotimesr; i0arg_complex += exp_i_toaphoa[iifo] * exp_i(-w1s[iifo] * t) * phase_rhotimesr * gsl_pow_2(snrs[iifo]); } const double i0arg = cabs(i0arg_complex); accum1 = logaddexp(accum1, log(gsl_sf_bessel_I0_scaled(i0arg)) + i0arg - 0.5 * gsl_stats_wtss_m(w_toas, 1, dtau, 1, nifos, t)); } /* Loop over detectors */ for (iifo = 0; iifo < nifos; iifo++) { const double complex tmp = F[iifo] * exp_i_twopsi; /* FIXME: could use - sign here to avoid conj below, but * this probably just sets our sign convention relative to * detection pipeline */ double complex phase_rhotimesr = 0.5 * (1 + u2) * creal(tmp) + I * u * cimag(tmp); const double abs_rhotimesr_2 = cabs2(phase_rhotimesr); const double abs_rhotimesr = sqrt(abs_rhotimesr_2); A += abs_rhotimesr_2; B += abs_rhotimesr * snrs[iifo]; } A *= -0.5; { const double middle_breakpoint = -2 * A / B; const double lower_breakpoint = 1 / (1 / middle_breakpoint + sqrt(log(eta) / A)); const double upper_breakpoint = 1 / (1 / middle_breakpoint - sqrt(log(eta) / A)); breakpoints[num_breakpoints++] = min_distance; if(lower_breakpoint > breakpoints[num_breakpoints-1] && lower_breakpoint < max_distance) breakpoints[num_breakpoints++] = lower_breakpoint; if(middle_breakpoint > breakpoints[num_breakpoints-1] && middle_breakpoint < max_distance) breakpoints[num_breakpoints++] = middle_breakpoint; if(upper_breakpoint > breakpoints[num_breakpoints-1] && upper_breakpoint < max_distance) breakpoints[num_breakpoints++] = upper_breakpoint; breakpoints[num_breakpoints++] = max_distance; } { /* * Set log_offset to the maximum of the logarithm of the * radial integrand evaluated at all of the breakpoints. */ int ibreakpoint; for (ibreakpoint = 0; ibreakpoint < num_breakpoints; ibreakpoint++) { const double new_log_offset = log_radial_integrand( breakpoints[ibreakpoint], A, B, prior_distance_power); if (new_log_offset < INFINITY && new_log_offset > log_offset) log_offset = new_log_offset; } } { /* Perform adaptive integration. Stop when a relative * accuracy of 0.05 has been reached. */ inner_integrand_params integrand_params = {A, B, log_offset, prior_distance_power}; const gsl_function func = {radial_integrand, &integrand_params}; double result, abserr; int ret = gsl_integration_qagp(&func, &breakpoints[0], num_breakpoints, DBL_MIN, 0.05, subdivision_limit, workspace, &result, &abserr); /* If the integrator failed, then record the GSL error * value for later reporting when we leave the parallel * section. Then, break out of the loop. */ if (ret != GSL_SUCCESS) { gsl_errno = ret; gsl_integration_workspace_free(workspace); goto skip; } /* Take the logarithm and put the log-normalization back in. */ result = log(result) + integrand_params.log_offset + accum1; /* Accumulate result. */ accum = logaddexp(accum, result); } } } /* Discard workspace for adaptive integrator. */ gsl_integration_workspace_free(workspace); /* Store log posterior. */ P[ipix] = accum; } skip: /* this statement intentionally left blank */; } /* Restore old error handler. */ gsl_set_error_handler(old_handler); /* Free permutation. */ gsl_permutation_free(pix_perm); /* Check if there was an error in any thread evaluating any pixel. If there * was, raise the error and return. */ if (gsl_errno != GSL_SUCCESS) { free(P); GSL_ERROR_NULL(gsl_strerror(gsl_errno), gsl_errno); } /* Exponentiate and normalize posterior. */ pix_perm = get_pixel_ranks(*npix, P); if (!pix_perm) { free(P); return NULL; } exp_normalize(*npix, P, pix_perm); gsl_permutation_free(pix_perm); return P; }
double *bayestar_sky_map_toa_snr( long *npix, /* Input: number of HEALPix pixels. */ double gmst, /* Greenwich mean sidereal time in radians. */ int nifos, /* Input: number of detectors. */ const float (**responses)[3], /* Pointers to detector responses. */ const double **locations, /* Pointers to locations of detectors in Cartesian geographic coordinates. */ const double *toas, /* Input: array of times of arrival with arbitrary relative offset. (Make toas[0] == 0.) */ const double *snrs, /* Input: array of SNRs. */ const double *w_toas, /* Input: sum-of-squares weights, (1/TOA variance)^2. */ const double *horizons, /* Distances at which a source would produce an SNR of 1 in each detector. */ double min_distance, double max_distance, int prior_distance_power) /* Use a prior of (distance)^(prior_distance_power) */ { long nside; long maxpix; long i; double d1[nifos]; double *P; gsl_permutation *pix_perm; /* Hold GSL return values for any thread that fails. */ int gsl_errno = GSL_SUCCESS; /* Storage for old GSL error handler. */ gsl_error_handler_t *old_handler; /* Maximum number of subdivisions for adaptive integration. */ static const size_t subdivision_limit = 64; /* Subdivide radial integral where likelihood is this fraction of the maximum, * will be used in solving the quadratic to find the breakpoints */ static const double eta = 0.01; /* Use this many integration steps in 2*psi */ static const int ntwopsi = 16; /* Number of integration steps in cos(inclination) */ static const int nu = 16; /* Rescale distances so that furthest horizon distance is 1. */ { double d1max; memcpy(d1, horizons, sizeof(d1)); for (d1max = d1[0], i = 1; i < nifos; i ++) if (d1[i] > d1max) d1max = d1[i]; for (i = 0; i < nifos; i ++) d1[i] /= d1max; min_distance /= d1max; max_distance /= d1max; } /* Evaluate posterior term only first. */ P = bayestar_sky_map_toa_adapt_resolution(&pix_perm, &maxpix, npix, gmst, nifos, locations, toas, w_toas, autoresolution_count_pix_toa_snr); if (!P) return NULL; /* Determine the lateral HEALPix resolution. */ nside = npix2nside(*npix); /* Zero pixels that didn't meet the TDOA cut. */ for (i = 0; i < maxpix; i ++) { long ipix = gsl_permutation_get(pix_perm, i); P[ipix] = log(P[ipix]); } for (; i < *npix; i ++) { long ipix = gsl_permutation_get(pix_perm, i); P[ipix] = -INFINITY; } /* Use our own error handler while in parallel section to avoid concurrent * calls to the GSL error handler, which if provided by the user may not * be threadsafe. */ old_handler = gsl_set_error_handler(my_gsl_error); /* Compute posterior factor for amplitude consistency. */ #pragma omp parallel for firstprivate(gsl_errno) lastprivate(gsl_errno) for (i = 0; i < maxpix; i ++) { /* Cancel further computation if a GSL error condition has occurred. * * Note: if one thread sets gsl_errno, not necessarily all thread will * get the updated value. That's OK, because most failure modes will * cause GSL error conditions on all threads. If we cared to have any * failure on any thread terminate all of the other threads as quickly * as possible, then we would want to insert the following pragma here: * * #pragma omp flush(gsl_errno) * * and likewise before any point where we set gsl_errno. */ if (gsl_errno != GSL_SUCCESS) goto skip; { long ipix = gsl_permutation_get(pix_perm, i); double F[nifos][2]; double theta, phi; int itwopsi, iu, iifo; double accum = -INFINITY; /* Prepare workspace for adaptive integrator. */ gsl_integration_workspace *workspace = gsl_integration_workspace_alloc(subdivision_limit); /* If the workspace could not be allocated, then record the GSL * error value for later reporting when we leave the parallel * section. Then, skip to the next loop iteration. */ if (!workspace) { gsl_errno = GSL_ENOMEM; goto skip; } /* Look up polar coordinates of this pixel */ pix2ang_ring(nside, ipix, &theta, &phi); /* Look up antenna factors */ for (iifo = 0; iifo < nifos; iifo ++) { XLALComputeDetAMResponse(&F[iifo][0], &F[iifo][1], responses[iifo], phi, M_PI_2 - theta, 0, gmst); F[iifo][0] *= d1[iifo]; F[iifo][1] *= d1[iifo]; } /* Integrate over 2*psi */ for (itwopsi = 0; itwopsi < ntwopsi; itwopsi++) { const double twopsi = (2 * M_PI / ntwopsi) * itwopsi; const double costwopsi = cos(twopsi); const double sintwopsi = sin(twopsi); /* Integrate over u; since integrand only depends on u^2 we only * have to go from u=0 to u=1. We want to include u=1, so the upper * limit has to be <= */ for (iu = 0; iu <= nu; iu++) { const double u = (double)iu / nu; const double u2 = gsl_pow_2(u); const double u4 = gsl_pow_2(u2); double A = 0, B = 0; double breakpoints[5]; int num_breakpoints = 0; double log_offset = -INFINITY; /* The log-likelihood is quadratic in the estimated and true * values of the SNR, and in 1/r. It is of the form A/r^2 + B/r, * where A depends only on the true values of the SNR and is * strictly negative and B depends on both the true values and * the estimates and is strictly positive. * * The middle breakpoint is at the maximum of the log-likelihood, * occurring at 1/r=-B/2A. The lower and upper breakpoints occur * when the likelihood becomes eta times its maximum value. This * occurs when * * A/r^2 + B/r = log(eta) - B^2/4A. * */ /* Loop over detectors */ for (iifo = 0; iifo < nifos; iifo++) { const double Fp = F[iifo][0]; /* `plus' antenna factor times r */ const double Fx = F[iifo][1]; /* `cross' antenna factor times r */ const double FpFx = Fp * Fx; const double FpFp = gsl_pow_2(Fp); const double FxFx = gsl_pow_2(Fx); const double rhotimesr2 = 0.125 * ((FpFp + FxFx) * (1 + 6*u2 + u4) - gsl_pow_2(1 - u2) * ((FpFp - FxFx) * costwopsi + 2 * FpFx * sintwopsi)); const double rhotimesr = sqrt(rhotimesr2); /* FIXME: due to roundoff, rhotimesr2 can be very small and * negative rather than simply zero. If this happens, don't accumulate the log-likelihood terms for this detector. */ if (rhotimesr2 > 0) { A += rhotimesr2; B += rhotimesr * snrs[iifo]; } } A *= -0.5; { const double middle_breakpoint = -2 * A / B; const double lower_breakpoint = 1 / (1 / middle_breakpoint + sqrt(log(eta) / A)); const double upper_breakpoint = 1 / (1 / middle_breakpoint - sqrt(log(eta) / A)); breakpoints[num_breakpoints++] = min_distance; if(lower_breakpoint > breakpoints[num_breakpoints-1] && lower_breakpoint < max_distance) breakpoints[num_breakpoints++] = lower_breakpoint; if(middle_breakpoint > breakpoints[num_breakpoints-1] && middle_breakpoint < max_distance) breakpoints[num_breakpoints++] = middle_breakpoint; if(upper_breakpoint > breakpoints[num_breakpoints-1] && upper_breakpoint < max_distance) breakpoints[num_breakpoints++] = upper_breakpoint; breakpoints[num_breakpoints++] = max_distance; } { /* * Set log_offset to the maximum of the logarithm of the * radial integrand evaluated at all of the breakpoints. */ int ibreakpoint; for (ibreakpoint = 0; ibreakpoint < num_breakpoints; ibreakpoint++) { const double new_log_offset = log_radial_integrand( breakpoints[ibreakpoint], A, B, prior_distance_power); if (new_log_offset < INFINITY && new_log_offset > log_offset) log_offset = new_log_offset; } } { /* Perform adaptive integration. Stop when a relative * accuracy of 0.05 has been reached. */ inner_integrand_params integrand_params = {A, B, log_offset, prior_distance_power}; const gsl_function func = {radial_integrand, &integrand_params}; double result, abserr; int ret = gsl_integration_qagp(&func, &breakpoints[0], num_breakpoints, DBL_MIN, 0.05, subdivision_limit, workspace, &result, &abserr); /* If the integrator failed, then record the GSL error * value for later reporting when we leave the parallel * section. Then, break out of the loop. */ if (ret != GSL_SUCCESS) { gsl_errno = ret; gsl_integration_workspace_free(workspace); goto skip; } /* Take the logarithm and put the log-normalization back in. */ result = log(result) + integrand_params.log_offset; /* Accumulate result. */ accum = logaddexp(accum, result); } } } /* Discard workspace for adaptive integrator. */ gsl_integration_workspace_free(workspace); /* Accumulate (log) posterior terms for SNR and TDOA. */ P[ipix] += accum; } skip: /* this statement intentionally left blank */; } /* Restore old error handler. */ gsl_set_error_handler(old_handler); /* Free permutation. */ gsl_permutation_free(pix_perm); /* Check if there was an error in any thread evaluating any pixel. If there * was, raise the error and return. */ if (gsl_errno != GSL_SUCCESS) { free(P); GSL_ERROR_NULL(gsl_strerror(gsl_errno), gsl_errno); } /* Exponentiate and normalize posterior. */ pix_perm = get_pixel_ranks(*npix, P); if (!pix_perm) { free(P); return NULL; } exp_normalize(*npix, P, pix_perm); gsl_permutation_free(pix_perm); return P; }
/** * Initializations for which static initialization can't/shouldn't * be relied upon. Common to executable and Python extension. */ static void _jit_initialization( void ) { opt_na_regex = mtm_default_NA_regex; memset( &_matrix, 0, sizeof(struct mtm_matrix) ); gsl_set_error_handler( _error_handler ); }
static VALUE rb_gsl_set_default_error_handler(VALUE module) { gsl_set_error_handler(&rb_gsl_error_handler); return Qtrue; }
int main (void) { gsl_function F_sin, F_cos, F_func1, F_func2, F_func3, F_func4, F_func5, F_func6; gsl_function_fdf FDF_sin, FDF_cos, FDF_func1, FDF_func2, FDF_func3, FDF_func4, FDF_func5, FDF_func6; const gsl_root_fsolver_type * fsolver[4] ; const gsl_root_fdfsolver_type * fdfsolver[4] ; const gsl_root_fsolver_type ** T; const gsl_root_fdfsolver_type ** S; gsl_ieee_env_setup(); fsolver[0] = gsl_root_fsolver_bisection; fsolver[1] = gsl_root_fsolver_brent; fsolver[2] = gsl_root_fsolver_falsepos; fsolver[3] = 0; fdfsolver[0] = gsl_root_fdfsolver_newton; fdfsolver[1] = gsl_root_fdfsolver_secant; fdfsolver[2] = gsl_root_fdfsolver_steffenson; fdfsolver[3] = 0; F_sin = create_function (sin_f) ; F_cos = create_function (cos_f) ; F_func1 = create_function (func1) ; F_func2 = create_function (func2) ; F_func3 = create_function (func3) ; F_func4 = create_function (func4) ; F_func5 = create_function (func5) ; F_func6 = create_function (func6) ; FDF_sin = create_fdf (sin_f, sin_df, sin_fdf) ; FDF_cos = create_fdf (cos_f, cos_df, cos_fdf) ; FDF_func1 = create_fdf (func1, func1_df, func1_fdf) ; FDF_func2 = create_fdf (func2, func2_df, func2_fdf) ; FDF_func3 = create_fdf (func3, func3_df, func3_fdf) ; FDF_func4 = create_fdf (func4, func4_df, func4_fdf) ; FDF_func5 = create_fdf (func5, func5_df, func5_fdf) ; FDF_func6 = create_fdf (func6, func6_df, func6_fdf) ; gsl_set_error_handler (&my_error_handler); for (T = fsolver ; *T != 0 ; T++) { test_f (*T, "sin(x) [3, 4]", &F_sin, 3.0, 4.0, M_PI); test_f (*T, "sin(x) [-4, -3]", &F_sin, -4.0, -3.0, -M_PI); test_f (*T, "sin(x) [-1/3, 1]", &F_sin, -1.0 / 3.0, 1.0, 0.0); test_f (*T, "cos(x) [0, 3]", &F_cos, 0.0, 3.0, M_PI / 2.0); test_f (*T, "cos(x) [-3, 0]", &F_cos, -3.0, 0.0, -M_PI / 2.0); test_f (*T, "x^20 - 1 [0.1, 2]", &F_func1, 0.1, 2.0, 1.0); test_f (*T, "sqrt(|x|)*sgn(x)", &F_func2, -1.0 / 3.0, 1.0, 0.0); test_f (*T, "x^2 - 1e-8 [0, 1]", &F_func3, 0.0, 1.0, sqrt (1e-8)); test_f (*T, "x exp(-x) [-1/3, 2]", &F_func4, -1.0 / 3.0, 2.0, 0.0); test_f (*T, "(x - 1)^7 [0.9995, 1.0002]", &F_func6, 0.9995, 1.0002, 1.0); test_f_e (*T, "invalid range check [4, 0]", &F_sin, 4.0, 0.0, M_PI); test_f_e (*T, "invalid range check [1, 1]", &F_sin, 1.0, 1.0, M_PI); test_f_e (*T, "invalid range check [0.1, 0.2]", &F_sin, 0.1, 0.2, M_PI); } for (S = fdfsolver ; *S != 0 ; S++) { test_fdf (*S,"sin(x) {3.4}", &FDF_sin, 3.4, M_PI); test_fdf (*S,"sin(x) {-3.3}", &FDF_sin, -3.3, -M_PI); test_fdf (*S,"sin(x) {0.5}", &FDF_sin, 0.5, 0.0); test_fdf (*S,"cos(x) {0.6}", &FDF_cos, 0.6, M_PI / 2.0); test_fdf (*S,"cos(x) {-2.5}", &FDF_cos, -2.5, -M_PI / 2.0); test_fdf (*S,"x^{20} - 1 {0.9}", &FDF_func1, 0.9, 1.0); test_fdf (*S,"x^{20} - 1 {1.1}", &FDF_func1, 1.1, 1.0); test_fdf (*S,"sqrt(|x|)*sgn(x) {1.001}", &FDF_func2, 0.001, 0.0); test_fdf (*S,"x^2 - 1e-8 {1}", &FDF_func3, 1.0, sqrt (1e-8)); test_fdf (*S,"x exp(-x) {-2}", &FDF_func4, -2.0, 0.0); test_fdf_e (*S,"max iterations x -> +Inf, x exp(-x) {2}", &FDF_func4, 2.0, 0.0); test_fdf_e (*S,"max iterations x -> -Inf, 1/(1 + exp(-x)) {0}", &FDF_func5, 0.0, 0.0); } test_fdf (gsl_root_fdfsolver_steffenson, "(x - 1)^7 {0.9}", &FDF_func6, 0.9, 1.0); /* now summarize the results */ exit (gsl_test_summary ()); }