/** * Set up a full multi-dimensional grid-scan. * Currently this only emulates a 'factored' grid-scan with 'sky x Freq x f1dot ...' , but * keeps all details within the DopplerScan module for future extension to real multidimensional * grids. * * NOTE: Use 'XLALNextDopplerPos()' to step through this template grid. * */ DopplerFullScanState * XLALInitDopplerFullScan ( const DopplerFullScanInit *init /**< [in] initialization parameters */ ) { XLAL_CHECK_NULL ( init != NULL, XLAL_EINVAL ); DopplerFullScanState *thisScan; XLAL_CHECK_NULL ( (thisScan = LALCalloc (1, sizeof(*thisScan) )) != NULL, XLAL_ENOMEM ); thisScan->gridType = init->gridType; /* store the user-input spinRange (includes refTime) in DopplerFullScanState */ thisScan->spinRange.refTime = init->searchRegion.refTime; memcpy ( thisScan->spinRange.fkdot, init->searchRegion.fkdot, sizeof(PulsarSpins) ); memcpy ( thisScan->spinRange.fkdotBand, init->searchRegion.fkdotBand, sizeof(PulsarSpins) ); // check that some old metric-codes aren't used with refTime!=startTime, which they don't handle correctly switch ( thisScan->gridType ) { case GRID_METRIC: case GRID_METRIC_SKYFILE: case GRID_SPINDOWN_SQUARE: /* square parameter space */ case GRID_SPINDOWN_AGEBRK: /* age-braking index parameter space */ XLAL_CHECK_NULL ( XLALGPSDiff ( &init->startTime, &init->searchRegion.refTime ) == 0, XLAL_EINVAL, "NOTE: gridType={metric,4,spin-square,spin-age-brk} only work for refTime (%f) == startTime (%f)!\n", XLALGPSGetREAL8(&(init->searchRegion.refTime)), XLALGPSGetREAL8(&(init->startTime)) );; break; default: break; } /* which "class" of template grid to generate?: factored, or full-multidim ? */ switch ( thisScan->gridType ) { /* emulate old 'factored' grids 'sky x f0dot x f1dot x f2dot x f3dot': */ case GRID_FLAT: case GRID_ISOTROPIC: case GRID_METRIC: case GRID_FILE_SKYGRID: case GRID_METRIC_SKYFILE: /* backwards-compatibility mode */ XLAL_CHECK_NULL ( XLALInitFactoredGrid ( thisScan, init ) == XLAL_SUCCESS, XLAL_EFUNC ); break; /* ----- multi-dimensional covering of full parameter space ----- */ case GRID_FILE_FULLGRID: XLAL_CHECK_NULL ( XLALLoadFullGridFile ( thisScan, init ) == XLAL_SUCCESS, XLAL_EFUNC ); break; case GRID_SPINDOWN_SQUARE: /* square parameter space */ case GRID_SPINDOWN_AGEBRK: /* age-braking index parameter space */ { const size_t n = 2 + PULSAR_MAX_SPINS; /* Check that the reference time is the same as the start time */ XLAL_CHECK_NULL ( XLALGPSCmp ( &thisScan->spinRange.refTime, &init->startTime) == 0, XLAL_EINVAL, "\nGRID_SPINDOWN_{SQUARE,AGEBRK}: This option currently restricts the reference time to be the same as the start time.\n"); /* Create a vector to hold lattice tiling parameter-space points */ XLAL_CHECK_NULL ( (thisScan->spindownTilingPoint = gsl_vector_alloc(n)) != NULL, XLAL_ENOMEM, "\nGRID_SPINDOWN_{SQUARE,AGEBRK}: gsl_vector_alloc failed\n"); /* Create a lattice tiling */ XLAL_CHECK_NULL ( (thisScan->spindownTiling = XLALCreateLatticeTiling(n)) != NULL, XLAL_EFUNC ); /* Parse the sky region string and check that it consists of only one point, and set bounds on it */ SkyRegion XLAL_INIT_DECL(sky); XLAL_CHECK_NULL ( XLALParseSkyRegionString ( &sky, init->searchRegion.skyRegionString ) == XLAL_SUCCESS, XLAL_EFUNC ); XLAL_CHECK_NULL ( sky.numVertices == 1, XLAL_EINVAL, "\nGRID_SPINDOWN_{SQUARE,AGEBRK}: This option can only handle a single sky position.\n"); XLAL_CHECK_NULL ( sky.vertices[0].system == COORDINATESYSTEM_EQUATORIAL, XLAL_EINVAL, "\nGRID_SPINDOWN_{SQUARE,AGEBRK}: This option only understands COORDINATESYSTEM_EQUATORIAL\n"); XLAL_CHECK_NULL ( XLALSetLatticeTilingConstantBound(thisScan->spindownTiling, 0, sky.vertices[0].longitude, sky.vertices[0].longitude) == XLAL_SUCCESS, XLAL_EFUNC ); XLAL_CHECK_NULL ( XLALSetLatticeTilingConstantBound(thisScan->spindownTiling, 1, sky.vertices[0].latitude, sky.vertices[0].latitude) == XLAL_SUCCESS, XLAL_EFUNC ); if (sky.vertices) { XLALFree (sky.vertices); } /* Set up parameter space */ if (thisScan->gridType == GRID_SPINDOWN_SQUARE) { /* square parameter space */ /* Set square bounds on the frequency and spindowns */ for (size_t i = 0; i < PULSAR_MAX_SPINS; ++i) { XLAL_CHECK_NULL ( XLALSetLatticeTilingConstantBound(thisScan->spindownTiling, 2 + i, init->searchRegion.fkdot[i], init->searchRegion.fkdot[i] + init->searchRegion.fkdotBand[i]) == XLAL_SUCCESS, XLAL_EFUNC ); } } else if (thisScan->gridType == GRID_SPINDOWN_AGEBRK) { /* age-braking index parameter space */ /* Get age and braking index from extra arguments */ const REAL8 spindownAge = init->extraArgs[0]; const REAL8 minBraking = init->extraArgs[1]; const REAL8 maxBraking = init->extraArgs[2]; /* Set age-braking index parameter space */ XLAL_CHECK_NULL ( XLAL_SUCCESS == XLALSetLatticeTilingConstantBound(thisScan->spindownTiling, 2, init->searchRegion.fkdot[0], init->searchRegion.fkdot[0] + init->searchRegion.fkdotBand[0]), XLAL_EFUNC ); XLAL_CHECK_NULL ( XLAL_SUCCESS == XLALSetLatticeTilingF1DotAgeBrakingBound(thisScan->spindownTiling, 2, 3, spindownAge, minBraking, maxBraking), XLAL_EFUNC ); XLAL_CHECK_NULL ( XLAL_SUCCESS == XLALSetLatticeTilingF2DotBrakingBound(thisScan->spindownTiling, 2, 3, 4, minBraking, maxBraking), XLAL_EFUNC ); /* This current only goes up to second spindown, so bound higher dimensions */ for (size_t i = 3; i < PULSAR_MAX_SPINS; ++i) { XLAL_CHECK_NULL ( XLAL_SUCCESS == XLALSetLatticeTilingConstantBound(thisScan->spindownTiling, 2 + i, init->searchRegion.fkdot[i], init->searchRegion.fkdot[i] + init->searchRegion.fkdotBand[i]), XLAL_EFUNC ); } } /* Create a lattice tiling with Anstar lattice and spindown metric */ gsl_matrix* metric; XLAL_CHECK_NULL ( (metric = gsl_matrix_alloc(n, n)) != NULL, XLAL_ENOMEM ); gsl_matrix_set_identity(metric); gsl_matrix_view spin_metric = gsl_matrix_submatrix(metric, 2, 2, PULSAR_MAX_SPINS, PULSAR_MAX_SPINS); XLAL_CHECK_NULL ( XLALSpindownMetric(&spin_metric.matrix, init->Tspan) == XLAL_SUCCESS, XLAL_EFUNC ); XLAL_CHECK_NULL ( XLALSetTilingLatticeAndMetric(thisScan->spindownTiling, "Ans", metric, init->metricMismatch) == XLAL_SUCCESS, XLAL_EFUNC ); /* Create iterator over flat lattice tiling */ XLAL_CHECK_NULL ( (thisScan->spindownTilingItr = XLALCreateLatticeTilingIterator(thisScan->spindownTiling, n)) != NULL, XLAL_EFUNC ); /* Cleanup */ gsl_matrix_free(metric); } break; default: XLAL_ERROR_NULL ( XLAL_EINVAL, "\nInvalid grid type '%d'\n\n", init->gridType ); break; } /* switch gridType */ /* we're ready */ thisScan->state = STATE_READY; /* return result */ return thisScan; } // XLALInitDopplerFullScan()
/* * Calculates a function at x, and returns the rusult. */ static VALUE rb_gsl_function_eval(VALUE obj, VALUE x) { gsl_function *F = NULL; VALUE ary, proc, params, result, arynew, x2; gsl_vector *v = NULL, *vnew = NULL; gsl_matrix *m = NULL, *mnew = NULL; size_t i, j, n; Data_Get_Struct(obj, gsl_function, F); ary = (VALUE) F->params; proc = rb_ary_entry(ary, 0); params = rb_ary_entry(ary, 1); if (CLASS_OF(x) == rb_cRange) x = rb_gsl_range2ary(x); switch (TYPE(x)) { case T_FIXNUM: case T_BIGNUM: case T_FLOAT: if (NIL_P(params)) result = rb_funcall(proc, RBGSL_ID_call, 1, x); else result = rb_funcall(proc, RBGSL_ID_call, 2, x, params); return result; break; case T_ARRAY: // n = RARRAY(x)->len; n = RARRAY_LEN(x); arynew = rb_ary_new2(n); for (i = 0; i < n; i++) { x2 = rb_ary_entry(x, i); Need_Float(x2); if (NIL_P(params)) result = rb_funcall(proc, RBGSL_ID_call, 1, x2); else result = rb_funcall(proc, RBGSL_ID_call, 2, x2, params); rb_ary_store(arynew, i, result); } return arynew; break; default: #ifdef HAVE_NARRAY_H if (NA_IsNArray(x)) { double *ptr1, *ptr2; struct NARRAY *na; GetNArray(x, na); ptr1 = (double *) na->ptr; n = na->total; ary = na_make_object(NA_DFLOAT, na->rank, na->shape, CLASS_OF(x)); ptr2 = NA_PTR_TYPE(ary, double*); for (i = 0; i < n; i++) { x2 = rb_float_new(ptr1[i]); if (NIL_P(params)) result = rb_funcall(proc, RBGSL_ID_call, 1, x2); else result = rb_funcall(proc, RBGSL_ID_call, 2, x2, params); ptr2[i] = NUM2DBL(result); } return ary; } #endif #ifdef HAVE_NMATRIX_H if (NM_IsNMatrix(x)) { double *ptr1, *ptr2; NM_DENSE_STORAGE *nm; nm = NM_STORAGE_DENSE(x); ptr1 = (double *) nm->elements; n = NM_DENSE_COUNT(x); ary = rb_nmatrix_dense_create(FLOAT64, nm->shape, nm->dim, nm->elements, n); ptr2 = (double*)NM_DENSE_ELEMENTS(ary); for (i = 0; i < n; i++) { x2 = rb_float_new(ptr1[i]); if (NIL_P(params)) result = rb_funcall(proc, RBGSL_ID_call, 1, x2); else result = rb_funcall(proc, RBGSL_ID_call, 2, x2, params); ptr2[i] = NUM2DBL(result); } return ary; } #endif if (VECTOR_P(x)) { Data_Get_Struct(x, gsl_vector, v); vnew = gsl_vector_alloc(v->size); for (i = 0; i < v->size; i++) { x2 = rb_float_new(gsl_vector_get(v, i)); if (NIL_P(params)) result = rb_funcall(proc, RBGSL_ID_call, 1, x2); else result = rb_funcall(proc, RBGSL_ID_call, 2, x2, params); gsl_vector_set(vnew, i, NUM2DBL(result)); } return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew); } else if (MATRIX_P(x)) { Data_Get_Struct(x, gsl_matrix, m); mnew = gsl_matrix_alloc(m->size1, m->size2); for (i = 0; i < m->size1; i++) { for (j = 0; j < m->size2; j++) { x2 = rb_float_new(gsl_matrix_get(m, i, j)); if (NIL_P(params)) result = rb_funcall(proc, RBGSL_ID_call, 1, x2); else result = rb_funcall(proc, RBGSL_ID_call, 2, x2, params); gsl_matrix_set(mnew, i, j, NUM2DBL(result)); } } return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, mnew); } else { rb_raise(rb_eTypeError, "wrong argument type"); } break; } /* never reach here */ return Qnil; }
// [[Rcpp::export]] Rcpp::List fitData(Rcpp::DataFrame ds) { const size_t ncoeffs = NCOEFFS; const size_t nbreak = NBREAK; const size_t n = N; size_t i, j; Rcpp::DataFrame D(ds); // construct the data.frame object RcppGSL::vector<double> y = D["y"]; // access columns by name, RcppGSL::vector<double> x = D["x"]; // assigning to GSL vectors RcppGSL::vector<double> w = D["w"]; gsl_bspline_workspace *bw; gsl_vector *B; gsl_vector *c; gsl_matrix *X, *cov; gsl_multifit_linear_workspace *mw; double chisq, Rsq, dof, tss; bw = gsl_bspline_alloc(4, nbreak); // allocate a cubic bspline workspace (k = 4) B = gsl_vector_alloc(ncoeffs); X = gsl_matrix_alloc(n, ncoeffs); c = gsl_vector_alloc(ncoeffs); cov = gsl_matrix_alloc(ncoeffs, ncoeffs); mw = gsl_multifit_linear_alloc(n, ncoeffs); gsl_bspline_knots_uniform(0.0, 15.0, bw); // use uniform breakpoints on [0, 15] for (i = 0; i < n; ++i) { // construct the fit matrix X double xi = gsl_vector_get(x, i); gsl_bspline_eval(xi, B, bw); // compute B_j(xi) for all j for (j = 0; j < ncoeffs; ++j) { // fill in row i of X double Bj = gsl_vector_get(B, j); gsl_matrix_set(X, i, j, Bj); } } gsl_multifit_wlinear(X, w, y, c, cov, &chisq, mw); // do the fit dof = n - ncoeffs; tss = gsl_stats_wtss(w->data, 1, y->data, 1, y->size); Rsq = 1.0 - chisq / tss; Rcpp::NumericVector FX(151), FY(151); // output the smoothed curve double xi, yi, yerr; for (xi = 0.0, i=0; xi < 15.0; xi += 0.1, i++) { gsl_bspline_eval(xi, B, bw); gsl_multifit_linear_est(B, c, cov, &yi, &yerr); FX[i] = xi; FY[i] = yi; } Rcpp::List res = Rcpp::List::create(Rcpp::Named("X")=FX, Rcpp::Named("Y")=FY, Rcpp::Named("chisqdof")=Rcpp::wrap(chisq/dof), Rcpp::Named("rsq")=Rcpp::wrap(Rsq)); gsl_bspline_free(bw); gsl_vector_free(B); gsl_matrix_free(X); gsl_vector_free(c); gsl_matrix_free(cov); gsl_multifit_linear_free(mw); y.free(); x.free(); w.free(); return(res); }
void CrossVal(const gsl_matrix* XTrainData, const gsl_matrix* YTrainData, const gsl_matrix* XTestData, const gsl_matrix* YTestData, const int FOLD, const double* Lambda, const int sizelambda, int* layer_sizes, int num_layers, const int num_iterations, const int batch_size, const double step_size) { int N_obs = XTrainData->size1; int YFeatures = YTrainData->size2; int XFeatures = XTrainData->size2; int GroupSize = N_obs/FOLD; int Nlambda = sizelambda; printf("________"); int* seq_fold; seq_fold = rand_fold(N_obs,FOLD); for (int i = 0; i < N_obs; i++){ printf("%d\n",seq_fold[i]); } gsl_matrix* Xfolds[FOLD]; for (int d = 0; d < FOLD; d++) Xfolds[d] = gsl_matrix_alloc(GroupSize,XFeatures); gsl_matrix* Yfolds[FOLD]; for (int d = 0; d < FOLD; d++) Yfolds[d] = gsl_matrix_alloc(GroupSize,YFeatures); SplitFoldfunc(XTrainData, FOLD, seq_fold, Xfolds); SplitFoldfunc(YTrainData, FOLD, seq_fold, Yfolds); gsl_matrix* CvTrainX[FOLD]; for (int d = 0; d < FOLD; d++) CvTrainX[d] = gsl_matrix_calloc(GroupSize*(FOLD-1), XFeatures); gsl_matrix* CvTrainY[FOLD]; for (int d = 0; d < FOLD; d++) CvTrainY[d] = gsl_matrix_calloc(GroupSize*(FOLD-1), YFeatures); combinefold(Xfolds, Yfolds, N_obs, FOLD, GroupSize, XFeatures, YFeatures, CvTrainX, CvTrainY); gsl_vector* results_lambda; results_lambda = gsl_vector_alloc((size_t) Nlambda); double results[Nlambda][FOLD]; #pragma omp parallel for collapse(2) for (int i = 0; i < Nlambda; i++){ for (int j = 0; j < FOLD; j++){ printf("Lambda=%G\n", Lambda[i]); printf("fold not included = %d\n", j); gsl_vector* vec_cv_trainX[N_obs-GroupSize]; for (int u = 0; u < (N_obs-GroupSize); u++ ){ vec_cv_trainX[u] = gsl_vector_alloc(XFeatures); } for (int c = 0; c < (N_obs-GroupSize); c++){ gsl_matrix_get_row(vec_cv_trainX[c], CvTrainX[j], c); } //for (int a = 0; a < (N_obs-GroupSize); a++){ //printf("%G %G\n",gsl_vector_get(vec_cv_trainX[a],0), gsl_vector_get(vec_cv_trainX[a],1)); //printf("%d\n", a); //} gsl_vector* vec_cv_trainY; vec_cv_trainY = gsl_vector_alloc(N_obs-GroupSize); gsl_matrix_get_col(vec_cv_trainY, CvTrainY[j], 0); //for (int y = 0; y < (N_obs-GroupSize); y++){ //printf("%G\n",gsl_vector_get(vec_cv_trainY,y)); //printf("%d\n",y); //} //Note that always Y will be 1 column, so well defined. gsl_matrix* output_weights[num_layers-1]; gsl_vector* output_biases[num_layers-1]; init_bias_object(output_biases, (layer_sizes+1), num_layers-1); init_weight_object(output_weights, layer_sizes, num_layers); printf("Lambda = %G\n",Lambda[i]); NeuralNets(layer_sizes, num_layers, vec_cv_trainX, vec_cv_trainY, num_iterations, batch_size, step_size, output_weights, output_biases, (N_obs-GroupSize), XFeatures, Lambda[i]); gsl_vector* vec_cv_valX[GroupSize]; for (int u = 0; u < (GroupSize); u++){ vec_cv_valX[u] = gsl_vector_alloc(XFeatures); } for (int c = 0; c < GroupSize; c++){ gsl_matrix_get_row(vec_cv_valX[c], Xfolds[j], c); } gsl_vector* vec_cv_valY; vec_cv_valY = gsl_vector_alloc(GroupSize); gsl_matrix_get_col(vec_cv_valY, Yfolds[j], 0); results[i][j] = correct_guesses(vec_cv_valX, vec_cv_valY, output_biases, output_weights, GroupSize, num_layers, layer_sizes); printf("Result=%G\n thread = %d\n",results[i][j],omp_get_thread_num()); gsl_vector_free(vec_cv_valY); for (int u = 0; u < (GroupSize); u++){ gsl_vector_free(vec_cv_valX[u]); } gsl_vector_free(vec_cv_trainY); for (int u = 0; u < (GroupSize); u++){ gsl_vector_free(vec_cv_trainX[u]); } printf("i=%d,j=%d,Fold=%d,Nlambda=%d\n",i , j, FOLD, Nlambda); } } //gsl_vector* results_lambda; //results_lambda = gsl_vector_alloc((size_t) Nlambda); double results_mean_fold[Nlambda]; for (int w = 0; w < Nlambda; w++) results_mean_fold[w] = 0; for (int s = 0; s < Nlambda ; s++){ for (int m = 0; m < FOLD ; m++){ printf("Result = %G\n", results[s][m]); } } for (int s = 0; s < Nlambda ; s++){ for (int m = 0; m < FOLD ; m++){ results_mean_fold[s] = results[s][m]+ results_mean_fold[s]; } gsl_vector_set(results_lambda, s, results_mean_fold[s]/(FOLD)); } for (int s = 0; s < Nlambda ; s++){ printf("Lambda = %G, Success = %G\n", Lambda[s], gsl_vector_get(results_lambda, s)); } double OptimalLambda = gsl_vector_max(results_lambda); printf("Optimal Lambda = %G\n", OptimalLambda); gsl_matrix* output_weights_all[num_layers-1]; gsl_vector* output_biases_all[num_layers-1]; init_bias_object(output_biases_all, (layer_sizes+1), num_layers-1); init_weight_object(output_weights_all, layer_sizes, num_layers); gsl_vector* vec_cv_trainX_all[N_obs]; for (int u = 0; u < (N_obs); u++){ vec_cv_trainX_all[u] = gsl_vector_alloc(XFeatures); } for (int c = 0; c < N_obs; c++){ gsl_matrix_get_row(vec_cv_trainX_all[c], XTrainData, c); } gsl_vector* vec_cv_trainY_all; vec_cv_trainY_all = gsl_vector_alloc(N_obs); gsl_matrix_get_col(vec_cv_trainY_all, YTrainData, 0); NeuralNets(layer_sizes, num_layers, vec_cv_trainX_all, vec_cv_trainY_all, num_iterations, batch_size, step_size, output_weights_all, output_biases_all, N_obs, XFeatures, OptimalLambda); int N_obs_test = XTestData->size1; gsl_vector* vec_cv_testX[N_obs_test]; for (int u = 0; u < (N_obs_test); u++){ vec_cv_testX[u] = gsl_vector_alloc(XFeatures); } for (int c = 0; c < N_obs_test; c++){ gsl_matrix_get_row(vec_cv_testX[c], XTestData, c); } gsl_vector* vec_cv_testY; vec_cv_testY = gsl_vector_alloc(N_obs_test); gsl_matrix_get_col(vec_cv_testY, YTestData, 0); //Note that always Y will be 1 column, so well defined. double Test_error = correct_guesses(vec_cv_testX, vec_cv_testY, output_biases_all, output_weights_all, N_obs_test, num_layers, layer_sizes); printf("Test Error =%G\n",1.0-Test_error); }
/* Populate field variables by SPR */ void _SnacRemesher_RecoverNode( void* _context, unsigned node_lI ) { Snac_Context* context = (Snac_Context*)_context; Mesh* mesh = context->mesh; MeshLayout* layout = (MeshLayout*)mesh->layout; HexaMD* decomp = (HexaMD*)layout->decomp; NodeLayout* nLayout = layout->nodeLayout; Snac_Node* node = Snac_Node_At( context, node_lI ); Coord* coord = Snac_NodeCoord_P( context, node_lI ); Index nodeElementCount = context->mesh->nodeElementCountTbl[node_lI]; Index nodeElement_I; Element_DomainIndex* elements; gsl_matrix* matA; gsl_vector* vecaStrain[6]; gsl_vector* vecaStress[6]; gsl_vector* vecaMaterial_I; gsl_vector* vecaDensity; gsl_vector* vecbStrain[6]; gsl_vector* vecbStress[6]; gsl_vector* vecbMaterial_I; gsl_vector* vecbDensity; Index i,j; IJK ijk; Node_GlobalIndex node_gI = _MeshDecomp_Node_LocalToGlobal1D( decomp, node_lI ); Node_GlobalIndex gNodeI = decomp->nodeGlobal3DCounts[0]; Node_GlobalIndex gNodeJ = decomp->nodeGlobal3DCounts[1]; Node_GlobalIndex gNodeK = decomp->nodeGlobal3DCounts[2]; Node_GlobalIndex intNode_gI; Node_DomainIndex intNode_lI; unsigned int isBoundaryNode=0, patchCenterNum=1, patchCenterI, patchCenterList[2]; RegularMeshUtils_Node_1DTo3D( decomp, node_gI, &ijk[0], &ijk[1], &ijk[2] ); /* If boundary node, find a (topologically?) nearest interior node. Loosely following Khoei and Gharehbaghi, 2007, The superconvergent patch recovery techinique and data transfer operators in 3D plasticity problems, Finite Elements in Analysis and Design 43 (2007) 630-- 648. */ if( (gNodeI>2) && (ijk[0]==0) ) { ijk[0] += 1; isBoundaryNode = 1; } if( (gNodeI>2) && (ijk[0]==decomp->nodeGlobal3DCounts[0]-1) ) { ijk[0] -= 1; isBoundaryNode = 1; } if( (gNodeJ>2) && (ijk[1]==0) ) { ijk[1] += 1; isBoundaryNode = 1; } if( (gNodeJ>2) && (ijk[1]==decomp->nodeGlobal3DCounts[1]-1) ) { ijk[1] -= 1; isBoundaryNode = 1; } if( (gNodeK>2) && (ijk[2]==0) ) { ijk[2] += 1; isBoundaryNode = 1; } if( (gNodeK>2) && (ijk[2]==decomp->nodeGlobal3DCounts[2]-1) ) { ijk[2] -= 1; isBoundaryNode = 1; } /* node_lI itself always becomes a patch center, and if the current node is a boundary node, find an interior node and add it to the patch center list. */ patchCenterList[0] = node_lI; if( isBoundaryNode ) { patchCenterNum=2; intNode_gI = ijk[0]+gNodeI*ijk[1]+gNodeI*gNodeJ*ijk[2]; patchCenterList[1] = Mesh_NodeMapGlobalToLocal( mesh, intNode_gI ); } /* initialize gsl vectors and matrix. */ matA = gsl_matrix_alloc(4,4); gsl_matrix_set_zero( matA ); vecaMaterial_I = gsl_vector_alloc(4); gsl_vector_set_zero( vecaMaterial_I ); vecbMaterial_I = gsl_vector_alloc(4); gsl_vector_set_zero( vecbMaterial_I ); vecaDensity = gsl_vector_alloc(4); gsl_vector_set_zero( vecaDensity ); vecbDensity = gsl_vector_alloc(4); gsl_vector_set_zero( vecbDensity ); for(i=0;i<6;i++) { vecaStrain[i] = gsl_vector_alloc(4); gsl_vector_set_zero( vecaStrain[i] ); vecaStress[i] = gsl_vector_alloc(4); gsl_vector_set_zero( vecaStress[i] ); vecbStrain[i] = gsl_vector_alloc(4); gsl_vector_set_zero( vecbStrain[i] ); vecbStress[i] = gsl_vector_alloc(4); gsl_vector_set_zero( vecbStress[i] ); } /* For each patch center */ for( patchCenterI=0; patchCenterI < patchCenterNum; patchCenterI++ ) { /* For each incident element, find inicident tets. */ for( nodeElement_I = 0; nodeElement_I < nodeElementCount; nodeElement_I++ ) { Element_DomainIndex element_dI = context->mesh->nodeElementTbl[patchCenterList[patchCenterI]][nodeElement_I]; if( element_dI < mesh->elementDomainCount ) { Index elementTetra_I; Snac_Element* element = Snac_Element_At( context, element_dI ); /* Extract the element's node indices. Note that there should always be eight of these. */ { Element_GlobalIndex element_gI; elements = Memory_Alloc_Array( Node_DomainIndex, nodeElementCount, "SnacRemesher" ); element_gI = Mesh_ElementMapDomainToGlobal( mesh, element_dI ); nLayout->buildElementNodes( nLayout, element_gI, elements ); } /* Convert global node indices to domain. */ { unsigned eltNode_i; for( eltNode_i = 0; eltNode_i < nodeElementCount; eltNode_i++ ) { elements[eltNode_i] = Mesh_NodeMapGlobalToDomain( mesh, elements[eltNode_i] ); } } /* For each incident tetrahedron in the incident element, add up contributions to P, A, and b as in Zienkiewicz and Zhu (1992), p. 1336 */ for( elementTetra_I = 0; elementTetra_I < Node_Element_Tetrahedra_Count;elementTetra_I++ ) { Tetrahedra_Index tetra_I = NodeToTetra[nodeElement_I][elementTetra_I]; Coord tCrds[4]; double positionP[4] = {1.0,0.0,0.0,0.0}; Index ii,jj; /* Extract the tetrahedron's coordinates. */ Vector_Set( tCrds[0], mesh->nodeCoord[elements[TetraToNode[tetra_I][0]]] ); Vector_Set( tCrds[1], mesh->nodeCoord[elements[TetraToNode[tetra_I][1]]] ); Vector_Set( tCrds[2], mesh->nodeCoord[elements[TetraToNode[tetra_I][2]]] ); Vector_Set( tCrds[3], mesh->nodeCoord[elements[TetraToNode[tetra_I][3]]] ); for(ii=1;ii<4;ii++) for(jj=0;jj<4;jj++) positionP[ii] += (0.25f * tCrds[jj][ii-1]); for(ii=0;ii<4;ii++) { double tmp; tmp = gsl_vector_get(vecbStrain[0],ii) + positionP[ii]*element->tetra[tetra_I].strain[0][0]; gsl_vector_set(vecbStrain[0],ii,tmp); tmp = gsl_vector_get(vecbStrain[1],ii) + positionP[ii]*element->tetra[tetra_I].strain[1][1]; gsl_vector_set(vecbStrain[1],ii,tmp); tmp = gsl_vector_get(vecbStrain[2],ii) + positionP[ii]*element->tetra[tetra_I].strain[2][2]; gsl_vector_set(vecbStrain[2],ii,tmp); tmp = gsl_vector_get(vecbStrain[3],ii) + positionP[ii]*element->tetra[tetra_I].strain[0][1]; gsl_vector_set(vecbStrain[3],ii,tmp); tmp = gsl_vector_get(vecbStrain[4],ii) + positionP[ii]*element->tetra[tetra_I].strain[0][2]; gsl_vector_set(vecbStrain[4],ii,tmp); tmp = gsl_vector_get(vecbStrain[5],ii) + positionP[ii]*element->tetra[tetra_I].strain[1][2]; gsl_vector_set(vecbStrain[5],ii,tmp); tmp = gsl_vector_get(vecbStress[0],ii) + positionP[ii]*element->tetra[tetra_I].stress[0][0]; gsl_vector_set(vecbStress[0],ii,tmp); tmp = gsl_vector_get(vecbStress[1],ii) + positionP[ii]*element->tetra[tetra_I].stress[1][1]; gsl_vector_set(vecbStress[1],ii,tmp); tmp = gsl_vector_get(vecbStress[2],ii) + positionP[ii]*element->tetra[tetra_I].stress[2][2]; gsl_vector_set(vecbStress[2],ii,tmp); tmp = gsl_vector_get(vecbStress[3],ii) + positionP[ii]*element->tetra[tetra_I].stress[0][1]; gsl_vector_set(vecbStress[3],ii,tmp); tmp = gsl_vector_get(vecbStress[4],ii) + positionP[ii]*element->tetra[tetra_I].stress[0][2]; gsl_vector_set(vecbStress[4],ii,tmp); tmp = gsl_vector_get(vecbStress[5],ii) + positionP[ii]*element->tetra[tetra_I].stress[1][2]; gsl_vector_set(vecbStress[5],ii,tmp); /* tmp = gsl_vector_get(vecbMaterial_I,ii) + positionP[ii]*((double)(element->tetra[tetra_I].material_I)+0.5); */ tmp = gsl_vector_get(vecbMaterial_I,ii) + positionP[ii]*pow(10.0,(double)(element->tetra[tetra_I].material_I)); gsl_vector_set(vecbMaterial_I,ii,tmp); tmp = gsl_vector_get(vecbDensity,ii) + positionP[ii]*element->tetra[tetra_I].density; gsl_vector_set(vecbDensity,ii,tmp); for(jj=0;jj<4;jj++) { tmp = gsl_matrix_get(matA,ii,jj) + positionP[ii]*positionP[jj]; gsl_matrix_set(matA,ii,jj,tmp); } } /* end of verteces of a tet. */ } /* end of incident tets. */ } /* if within my domain */ } /* end of incident elements. */ } /* end of patchCenterI */ /* compute parameter vectors. */ { int s; gsl_permutation * p = gsl_permutation_alloc (4); gsl_linalg_LU_decomp (matA, p, &s); for(i=0;i<6;i++) { gsl_linalg_LU_solve (matA, p, vecbStrain[i], vecaStrain[i]); gsl_linalg_LU_solve (matA, p, vecbStress[i], vecaStress[i]); } gsl_linalg_LU_solve (matA, p, vecbMaterial_I, vecaMaterial_I); gsl_linalg_LU_solve (matA, p, vecbDensity, vecaDensity); /* printf ("x = \n"); */ /* gsl_vector_fprintf (stdout, x, "%g"); */ gsl_permutation_free (p); } /* zero the arrays to store recovered field. */ /* probably not necessary. */ /* for(i=0;i<6;i++) { */ /* node->strainSPR[i] = 0.0f; */ /* node->stressSPR[i] = 0.0f; */ /* } */ /* Recover using the parameter vectors. */ for(j=0;j<6;j++) { node->strainSPR[j] = gsl_vector_get(vecaStrain[j],0); node->stressSPR[j] = gsl_vector_get(vecaStress[j],0); for(i=0;i<3;i++) { node->strainSPR[j] += gsl_vector_get(vecaStrain[j],i+1)*(*coord)[i]; node->stressSPR[j] += gsl_vector_get(vecaStress[j],i+1)*(*coord)[i]; } } node->material_ISPR = gsl_vector_get(vecaMaterial_I,0); for(i=0;i<3;i++) node->material_ISPR += gsl_vector_get(vecaMaterial_I,i+1)*(*coord)[i]; node->densitySPR = gsl_vector_get(vecaDensity,0); for(i=0;i<3;i++) node->densitySPR += gsl_vector_get(vecaDensity,i+1)*(*coord)[i]; /* free gsl vectors and matrix. */ gsl_matrix_free( matA ); gsl_vector_free( vecaMaterial_I ); gsl_vector_free( vecbMaterial_I ); gsl_vector_free( vecaDensity ); gsl_vector_free( vecbDensity ); for(i=0;i<6;i++) { gsl_vector_free( vecaStrain[i] ); gsl_vector_free( vecaStress[i] ); gsl_vector_free( vecbStrain[i] ); gsl_vector_free( vecbStress[i] ); } /* Free the element node array. */ FreeArray( elements ); /* end of recovery. */ }
int GMRFLib_gsl_ginv(gsl_matrix * A, double tol, int rankdef) { /* * replace n x n matrix A with its generlized inverse. if TOL > 0, use that tolerance. If rankdef is set, use that. If both are set, give an error. */ assert(A && (A->size1 == A->size2)); gsl_matrix *U = GMRFLib_gsl_duplicate_matrix(A); gsl_matrix *V = gsl_matrix_alloc(A->size1, A->size2); gsl_vector *S = gsl_vector_alloc(A->size1); gsl_vector *work = gsl_vector_alloc(A->size1); gsl_linalg_SV_decomp(U, V, S, work); size_t i; double one = 1.0, zero = 0.0; double s_max = gsl_vector_get(S, 0); gsl_matrix *M1 = gsl_matrix_alloc(A->size1, A->size2); gsl_matrix *M2 = gsl_matrix_alloc(A->size1, A->size2); assert(!(tol > 0.0 && (rankdef >= 0 && rankdef <= (int) A->size1))); if (tol > 0.0){ for(i = 0; i < A->size1; i++){ double s = gsl_vector_get(S, i); if (s < tol * s_max) { gsl_matrix_set(M2, i, i, 0.0); } else { gsl_matrix_set(M2, i, i, 1.0/s); } } } else { assert(rankdef >= 0); assert(rankdef <= (int)A->size1); double first = gsl_vector_get(S, 0); double last = gsl_vector_get(S, A->size1-1); for(i = 0; i < A->size1; i++){ double s = gsl_vector_get(S, i); if (first > last){ // do not use the last 'rdef's if (i < (int) A->size1 - rankdef){ gsl_matrix_set(M2, i, i, 1.0/s); } else { gsl_matrix_set(M2, i, i, 0.0); } } else { // do not use the first 'rdef's if (i < rankdef){ gsl_matrix_set(M2, i, i, 0.0); } else { gsl_matrix_set(M2, i, i, 1.0/s); } } } } gsl_blas_dgemm(CblasNoTrans, CblasTrans, one, M2, U, zero, M1); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, one, V, M1, zero, M2); gsl_matrix_memcpy(A, M2); gsl_matrix_free(U); gsl_matrix_free(V); gsl_matrix_free(M1); gsl_matrix_free(M2); gsl_vector_free(S); gsl_vector_free(work); return GMRFLib_SUCCESS; }
void calibrationManager::calculateWeights(vector <ofPoint> trackedPoints, vector <ofPoint> knownPoints){ int length = trackedPoints.size(); int nTerms = 6; gsl_matrix * x = gsl_matrix_alloc(length,nTerms); gsl_vector * yx = gsl_vector_alloc(length); gsl_vector * yy = gsl_vector_alloc(length); gsl_vector * w = gsl_vector_alloc(nTerms); double * ptr; double * ptrScreenX; double * ptrScreenY; ptr = gsl_matrix_ptr(x,0,0); ptrScreenX = gsl_vector_ptr(yx,0); ptrScreenY = gsl_vector_ptr(yy,0); for (int i = 0; i < length; i++){ float xPosEye = trackedPoints[i].x; float yPosEye = trackedPoints[i].y; // was -- Ax + Bx^2 + Cy + Dy^2 + Exy + Fx^3 + Gy^3 + H // now -- Ax + Bx^2 + Cy + Dy^2 + Exy + F *ptr++ = xPosEye; *ptr++ = xPosEye*xPosEye; *ptr++ = yPosEye; *ptr++ = yPosEye*yPosEye; *ptr++ = xPosEye*yPosEye; //*ptr++ = xPosEye*xPosEye*xPosEye; // the cubed term was too much, it seemed like. //*ptr++ = yPosEye*yPosEye*yPosEye; *ptr++ = 1; *ptrScreenX++ = knownPoints[i].x; *ptrScreenY++ = knownPoints[i].y; } gsl_vector *cx = gsl_vector_calloc(nTerms); gsl_vector *cy = gsl_vector_calloc(nTerms); gsl_matrix *cov = gsl_matrix_calloc(nTerms, nTerms); double chisq; gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc(length, nTerms); int res = gsl_multifit_linear (x, yx, cx, cov, &chisq, work); int res2 = gsl_multifit_linear (x, yy, cy, cov, &chisq, work); double * xptr = gsl_vector_ptr(cx,0); double * yptr = gsl_vector_ptr(cy,0); printf("-------------------------------------------- \n"); for (int i = 0; i < nTerms; i++){ printf("cx %i = %f \n", i, xptr[i]); cxfit[i] = xptr[i]; } for (int i = 0; i < nTerms; i++){ printf("cy %i = %f \n", i, yptr[i]); cyfit[i] = yptr[i]; } printf("-------------------------------------------- \n"); bBeenFit = true; //std::exit(0); //return ; }
// get the row vector vector< double > Matrix::getRow( int row ) const { gsl_vector* v = gsl_vector_alloc( nCols() ); gsl_matrix_get_row( v, data, row ); return gsl2vector( v ); }
// get the column vector vector< double > Matrix::getCol( int col ) const { gsl_vector* v = gsl_vector_alloc( nRows() ); gsl_matrix_get_col( v, data, col ); return gsl2vector( v ); }
void test_eigen_genherm(void) { size_t N_max = 20; size_t n, i; gsl_rng *r = gsl_rng_alloc(gsl_rng_default); for (n = 1; n <= N_max; ++n) { gsl_matrix_complex * A = gsl_matrix_complex_alloc(n, n); gsl_matrix_complex * B = gsl_matrix_complex_alloc(n, n); gsl_matrix_complex * ma = gsl_matrix_complex_alloc(n, n); gsl_matrix_complex * mb = gsl_matrix_complex_alloc(n, n); gsl_vector * eval = gsl_vector_alloc(n); gsl_vector * evalv = gsl_vector_alloc(n); gsl_vector * x = gsl_vector_alloc(n); gsl_vector * y = gsl_vector_alloc(n); gsl_vector_complex * work = gsl_vector_complex_alloc(n); gsl_matrix_complex * evec = gsl_matrix_complex_alloc(n, n); gsl_eigen_genherm_workspace * w = gsl_eigen_genherm_alloc(n); gsl_eigen_genhermv_workspace * wv = gsl_eigen_genhermv_alloc(n); for (i = 0; i < 5; ++i) { create_random_herm_matrix(A, r, -10, 10); create_random_complex_posdef_matrix(B, r, work); gsl_matrix_complex_memcpy(ma, A); gsl_matrix_complex_memcpy(mb, B); gsl_eigen_genhermv(ma, mb, evalv, evec, wv); test_eigen_genherm_results(A, B, evalv, evec, i, "random", "unsorted"); gsl_matrix_complex_memcpy(ma, A); gsl_matrix_complex_memcpy(mb, B); gsl_eigen_genherm(ma, mb, eval, w); /* eval and evalv have to be sorted? not sure why */ gsl_vector_memcpy(x, eval); gsl_vector_memcpy(y, evalv); gsl_sort_vector(x); gsl_sort_vector(y); test_eigenvalues_real(y, x, "genherm, random", "unsorted"); gsl_eigen_genhermv_sort(evalv, evec, GSL_EIGEN_SORT_VAL_ASC); test_eigen_genherm_results(A, B, evalv, evec, i, "random", "val/asc"); gsl_eigen_genhermv_sort(evalv, evec, GSL_EIGEN_SORT_VAL_DESC); test_eigen_genherm_results(A, B, evalv, evec, i, "random", "val/desc"); gsl_eigen_genhermv_sort(evalv, evec, GSL_EIGEN_SORT_ABS_ASC); test_eigen_genherm_results(A, B, evalv, evec, i, "random", "abs/asc"); gsl_eigen_genhermv_sort(evalv, evec, GSL_EIGEN_SORT_ABS_DESC); test_eigen_genherm_results(A, B, evalv, evec, i, "random", "abs/desc"); } gsl_matrix_complex_free(A); gsl_matrix_complex_free(B); gsl_matrix_complex_free(ma); gsl_matrix_complex_free(mb); gsl_vector_free(eval); gsl_vector_free(evalv); gsl_vector_free(x); gsl_vector_free(y); gsl_vector_complex_free(work); gsl_matrix_complex_free(evec); gsl_eigen_genherm_free(w); gsl_eigen_genhermv_free(wv); } gsl_rng_free(r); } /* test_eigen_genherm() */
int main (int argc, char **argv) { int i=0, j=0, n=0, nl=0, k=0, posi=0, posj=0, posk=0, ncol=0, nrow=0; double xi=0.0, yi=0.0, yy=0.0, ei=0.0, sumsq=0.0, med=0.0; gsl_matrix *X=NULL, *cov=NULL; gsl_vector *y=NULL, *w=NULL, *c=NULL; MRI_IMAGE *im = NULL; double *dar = NULL; gsl_multifit_linear_workspace *work=NULL; if (argc != 2) { fprintf (stderr,"usage: fitanje_1sign data > outfile\n"); exit (-1); } /* slower than specific code you had but more convenient. It allows you to use all the column and row selections we can do with filenames. Also, keeps you fron worrying about dimensions. The problem with your code was assuming you had 13 columns always That was not the case for stat5_fitcoef. OK, that was caused by a problem in the scripts. That is fixed, but I leave this change here anyway. */ fprintf(stderr,"Patience, reading %s... ", argv[1]); im = mri_read_double_1D (argv[1]); if (!im) { fprintf(stderr,"Error: Failed to read matrix data from %s\n", argv[1]); return(-1); } ncol = im->ny; nrow = im->nx; fprintf (stderr,"Have %d cols, %d rows\nNow fitting...", ncol, nrow); n = ncol-3; /* now just get the array and kill the rest */ dar = MRI_DOUBLE_PTR(im); /* make sure that pointer is set to NULL in im, or risk hell */ mri_clear_data_pointer(im) ; if (im) mri_free(im); im = NULL; /* now kill im */ X = gsl_matrix_alloc (n, 5); y = gsl_vector_alloc (n); c = gsl_vector_alloc (5); cov = gsl_matrix_alloc (5, 5); for (i = 0; i < n; i++) { xi = i+1; gsl_matrix_set (X, i, 0, 1.0); gsl_matrix_set (X, i, 1, xi); gsl_matrix_set (X, i, 2, xi*xi); gsl_matrix_set (X, i, 3, xi*xi*xi); gsl_matrix_set (X, i, 4, xi*xi*xi*xi); // printf ("%lg ",xi); } /*make header printf ("matrvola\n"); ZSS: By adding # to the text line, I made the output file be a .1D format */ fprintf(stdout, "#%s_0\t%s_1\t%s_2\t%s_3\t%s_4\n", argv[1],argv[1],argv[1],argv[1],argv[1]); // go by lines - signatures /* pre-allocate, I think this should be just fine, there should be no need to reinitialize work all the time */ work = gsl_multifit_linear_alloc (n, 5); for (nl=0; nl<nrow; ++nl) { posi = (int)dar[nl]; posj = (int)dar[nl+ nrow]; posk = (int)dar[nl+2*nrow]; for (k = 3; k < ncol; k++) { gsl_vector_set (y, k-3, dar[nl+k*nrow]); } gsl_multifit_linear (X, y, c, cov, &sumsq, work); /* printf ( "\n # best fit: Y = %g + %g X + %g X^2 +%g X^3 + %g X^4\n", C(0), C(1), C(2), C(3), C(4)); printf ("# sumsq = %g\n", sumsq); */ fprintf (stdout, "%11g\t%11g\t%11g\t%11g\t%11g\n", C(0), C(1), C(2), C(3), C(4)); /* printf ("# covariance matrix:\n"); printf ("[ %+.5e, %+.5e, %+.5e \n", COV(0,0), COV(0,1), COV(0,2)); printf (" %+.5e, %+.5e, %+.5e \n", COV(1,0), COV(1,1), COV(1,2)); printf (" %+.5e, %+.5e, %+.5e ]\n", COV(2,0), COV(2,1), COV(2,2)); printf ("# chisq = %g\n", chisq); */ } gsl_multifit_linear_free (work); work = NULL; free(dar); dar = NULL; /* done with input array */ gsl_vector_free (y); gsl_vector_free (c); gsl_matrix_free (cov); gsl_matrix_free (X); //gsl_vector_free (w); fprintf (stderr,"\n"); return 0; }
void test_eigen_symm_results (const gsl_matrix * A, const gsl_vector * eval, const gsl_matrix * evec, size_t count, const char * desc, const char * desc2) { const size_t N = A->size1; size_t i, j; double emax = 0; gsl_vector * x = gsl_vector_alloc(N); gsl_vector * y = gsl_vector_alloc(N); /* check eigenvalues */ for (i = 0; i < N; i++) { double ei = gsl_vector_get (eval, i); if (fabs(ei) > emax) emax = fabs(ei); } for (i = 0; i < N; i++) { double ei = gsl_vector_get (eval, i); gsl_vector_const_view vi = gsl_matrix_const_column(evec, i); gsl_vector_memcpy(x, &vi.vector); /* compute y = A x (should = lambda v) */ gsl_blas_dgemv (CblasNoTrans, 1.0, A, x, 0.0, y); for (j = 0; j < N; j++) { double xj = gsl_vector_get (x, j); double yj = gsl_vector_get (y, j); double eixj = chop_subnormals(ei * xj); gsl_test_abs(yj, eixj, emax * 1e8 * GSL_DBL_EPSILON, "%s, eigenvalue(%d,%d), %s", desc, i, j, desc2); } } /* check eigenvectors are orthonormal */ for (i = 0; i < N; i++) { gsl_vector_const_view vi = gsl_matrix_const_column(evec, i); double nrm_v = gsl_blas_dnrm2(&vi.vector); gsl_test_rel (nrm_v, 1.0, N * GSL_DBL_EPSILON, "%s, normalized(%d), %s", desc, i, desc2); } for (i = 0; i < N; i++) { gsl_vector_const_view vi = gsl_matrix_const_column(evec, i); for (j = i + 1; j < N; j++) { gsl_vector_const_view vj = gsl_matrix_const_column(evec, j); double vivj; gsl_blas_ddot (&vi.vector, &vj.vector, &vivj); gsl_test_abs (vivj, 0.0, N * GSL_DBL_EPSILON, "%s, orthogonal(%d,%d), %s", desc, i, j, desc2); } } gsl_vector_free(x); gsl_vector_free(y); }
void solveB3(double A, double B, int n) { int i,j; double outp, arg; const double step1=(B-A)/(n+1.0), step=(B-A)/(n-1.0), c0=f_dd_B_3(0.0)/step/step,c1=f_dd_B_3(1.0)/step/step ; gsl_matrix * sys = gsl_matrix_alloc (n+2, n+2); gsl_vector * x = gsl_vector_alloc (n+2); gsl_vector * b = gsl_vector_alloc (n+2); for(i=0;i<n+2;i++) { if(i==0) { gsl_vector_set(b,0,0.0); gsl_matrix_set(sys, 0,0,f_B_3(-1.0)); gsl_matrix_set(sys, 0,1,f_B_3(0.0)); gsl_matrix_set(sys, 0,2,f_B_3(1.0)); } if(i!=0 && i!=n+1) { gsl_vector_set(b,i, f((double)(i-1)*step+A)); gsl_matrix_set(sys,i,i-1,c1); gsl_matrix_set(sys,i,i,c0); gsl_matrix_set(sys,i,i+1,c1); } if(i==n+1) { gsl_vector_set(b,i,0.0); gsl_matrix_set(sys,n+1,n-1,f_B_3(-1.0)); gsl_matrix_set(sys,n+1,n,f_B_3(0.0)); gsl_matrix_set(sys,n+1,n+1,f_B_3(1.0)); } } //gsl_matrix_fprintf (stdout, sys, "%g"); gsl_permutation * p = gsl_permutation_alloc (n+2); gsl_linalg_LU_decomp (sys, p, &i); gsl_linalg_LU_solve (sys, p, b, x); //gsl_vector_fprintf (stdout, x, "%g"); FILE *op; op = fopen("./output/plot.b3", "w"); for(arg = A; arg<=B; arg+=step) { outp = 0.0; for(i=0;i<n+2;i++) outp += gsl_vector_get(x,i)*f_B_3((arg-step*(double)(i-1))/step); fprintf(op,"%f %f\n",arg,outp); } fclose(op); op = fopen("./output/plot.b3.err", "w"); for(arg = A; arg<=B; arg+=0.01) { outp = 0.0; for(i=0;i<n+2;i++) outp += gsl_vector_get(x,i)*f_B_3((arg-step*(double)(i-1))/step); fprintf(op,"%f %f\n",arg,fabs(outp-f_e(arg))); } fclose(op); op = fopen("./output/solution", "w"); for(arg=A;arg<=B;arg+=0.01) { fprintf(op,"%f %f\n",arg,f_e(arg)); } fclose(op); }
int test_fdf(const char * desc, gsl_multimin_function_fdf *f, initpt_function initpt, const gsl_multimin_fdfminimizer_type *T) { int status; size_t iter = 0; double step_size; gsl_vector *x = gsl_vector_alloc (f->n); gsl_multimin_fdfminimizer *s; fcount = 0; gcount = 0; (*initpt) (x); step_size = 0.1 * gsl_blas_dnrm2 (x); s = gsl_multimin_fdfminimizer_alloc(T, f->n); gsl_multimin_fdfminimizer_set (s, f, x, step_size, 0.1); #ifdef DEBUG printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g"); #endif do { iter++; status = gsl_multimin_fdfminimizer_iterate(s); #ifdef DEBUG printf("%i: \n",iter); printf("x "); gsl_vector_fprintf (stdout, s->x, "%g"); printf("g "); gsl_vector_fprintf (stdout, s->gradient, "%g"); printf("f(x) %g\n",s->f); printf("dx %g\n",gsl_blas_dnrm2(s->dx)); printf("status=%d\n", status); printf("\n"); #endif if (status == GSL_ENOPROG) break; status = gsl_multimin_test_gradient(s->gradient,1e-3); } while (iter < 5000 && status == GSL_CONTINUE); /* If no error in iteration, test for numerical convergence */ if (status == GSL_CONTINUE || status == GSL_ENOPROG) status = (fabs(s->f) > 1e-5); gsl_test(status, "%s, on %s: %i iters (fn+g=%d+%d), f(x)=%g", gsl_multimin_fdfminimizer_name(s),desc, iter, fcount, gcount, s->f); gsl_multimin_fdfminimizer_free(s); gsl_vector_free(x); return status; }
int DPMHC_xi_smplr(struct str_DPMHC *ptr_DPMHC_data, int i_J, struct str_firm_data *a_firm_data) { int j,i; int i_K = ptr_DPMHC_data->i_K; int i_n = ptr_DPMHC_data->v_y->size; // is this the same as i_J??? if (i_n != i_J){ fprintf(stderr,"Error in DPMN_xi_smplr(): DPMHC.v_y length does not equal i_J\n"); exit(1); } double d_sumT_si; gsl_vector_int *vi_S = ptr_DPMHC_data->vi_S; gsl_matrix *m_theta = ptr_DPMHC_data->m_DPtheta; double d_A = ptr_DPMHC_data->d_A; double d_mu_si, d_tau_si, d_ei; double d_mean_j, d_var_j; double d_xi_j; int i_Ti; int i_factors = (a_firm_data[0].v_beta)->size; gsl_vector *v_ret; gsl_matrix *m_factors; gsl_vector *v_betai; gsl_vector *v_rstar_i; gsl_matrix *m_Xi; gsl_matrix_view mv_Xi; double d_rstar_j; double d_s2i; for(j=0;j<i_K;j++){ d_mu_si = mget(m_theta,j,0); d_tau_si = mget(m_theta,j,2); d_rstar_j = 0.; d_sumT_si = 0; for(i=0;i<i_J;i++){ if( vget_int(vi_S,i) == j ){ d_ei = vget(ptr_DPMHC_data->v_e,i); m_factors = a_firm_data[i].m_factors; i_Ti = a_firm_data[i].i_ni; d_s2i = a_firm_data[i].d_s2; m_Xi = gsl_matrix_alloc(i_Ti,i_factors); mv_Xi = gsl_matrix_submatrix(m_factors,0,0,i_Ti,i_factors); gsl_matrix_memcpy(m_Xi,&mv_Xi.matrix); v_betai = a_firm_data[i].v_beta; v_ret = a_firm_data[i].v_ret; v_rstar_i = gsl_vector_alloc(i_Ti); gsl_vector_memcpy(v_rstar_i,v_ret); gsl_blas_dgemv(CblasNoTrans, -1.0, m_Xi, v_betai, 1.0, v_rstar_i); gsl_vector_add_constant(v_rstar_i, -d_mu_si); gsl_vector_scale(v_rstar_i, 1./(sqrt(d_tau_si) * d_ei) ); d_rstar_j += sum(v_rstar_i); d_sumT_si += i_Ti/(d_s2i/(d_tau_si * d_ei * d_ei) ); gsl_matrix_free(m_Xi); gsl_vector_free(v_rstar_i); } } d_var_j = 1./( 1./(d_A * d_A) + d_sumT_si); d_mean_j = d_rstar_j * d_var_j; d_xi_j = d_mean_j + gsl_ran_gaussian_ziggurat(rng, sqrt(d_var_j) ); mset(m_theta, j, 1, d_xi_j); // printf("%d: eta = %g lambda^2 = %g\n",j, mget(m_theta,j,0), mget(m_theta,j,1) ); } return 0; }
gsl_vector* vector2gsl( const vector< double >& v ) { gsl_vector* result = gsl_vector_alloc( v.size() ); for ( int i = 0; i < v.size(); i++ ) gsl_vector_set( result, i, v[ i ] ); return result; }
/* Run PAM */ static void pam_run(pam_partition p, size_t max_iters) { if (p->k == p->M->size1) { /* Simple case */ return; } size_t i, j, k, m, n, trimmed_size = p->M->size1 - p->k, any_swaps = 0, iter = 0; size_t *medoids, *trimmed; double c, current_cost; gsl_vector *cost = gsl_vector_alloc(trimmed_size); gsl_vector_ulong *cl_index = gsl_vector_ulong_alloc(p->cl_index->size); gsl_vector *cl_dist = gsl_vector_alloc(p->cl_dist->size); medoids = malloc(sizeof(size_t) * p->k); trimmed = malloc(sizeof(size_t) * (p->M->size1 - p->k)); j = 0; k = 0; for (i = 0; i < p->M->size1; i++) { if (gsl_vector_uchar_get(p->in_set, i)) medoids[j++] = i; else { assert(!pam_always_select(p, i)); trimmed[k++] = i; } } assert(j == p->k); assert(k == p->M->size1 - p->k); do { if (PAM_VERBOSE) fprintf(stderr, "Iteration %lu\n", iter); any_swaps = 0; /* For every medoid, m, swap with every non-medoid, compute cost */ for (i = 0; i < p->k; i++) { m = medoids[i]; /* If medoid is in the always_select set, no action. */ if (pam_always_select(p, m)) continue; current_cost = pam_total_cost(p); /* Try every non-medoid */ gsl_vector_set_all(cost, FLT_MAX); for (j = 0; j < trimmed_size; j++) { n = trimmed[j]; c = pam_swap_update_cost(p, m, n, cl_index, cl_dist); gsl_vector_set(cost, j, c); } /* Find the minimum cost from all swaps */ j = gsl_vector_min_index(cost); if (gsl_vector_get(cost, j) < current_cost) { /* Current cost beaten */ any_swaps = 1; n = trimmed[j]; assert(n != m); assert(!gsl_vector_uchar_get(p->in_set, n)); assert(gsl_vector_uchar_get(p->in_set, m)); if (PAM_VERBOSE) fprintf(stderr, "SWAP: %lu->%lu [%f -> %f]\n", m, n, current_cost, gsl_vector_get(cost, j)); gsl_vector_uchar_swap_elements(p->in_set, m, n); /* Move n to medoids, m to trimmed */ trimmed[j] = m; medoids[i] = n; /* Recalculate cached values */ pam_swap_cost(p, m, n); } } } while (any_swaps && ++iter < max_iters); if (PAM_VERBOSE) { fprintf(stderr, "Done in %lu iterations. Final config:\n", iter); gsl_vector_uchar_fprintf(stderr, p->in_set, "%d"); fprintf(stderr, "Final cost: %f\n", pam_total_cost(p)); } gsl_vector_free(cost); gsl_vector_ulong_free(cl_index); gsl_vector_free(cl_dist); free(medoids); free(trimmed); }
gsl_vector * gsl_vector_dup(const gsl_vector * v){ gsl_vector * copy = gsl_vector_alloc(v->size); gsl_vector_memcpy(copy,v); return copy; }
//Train all the samples using naive stochastic gradient descent tnn_error tnn_trainer_class_train_nsgd(tnn_trainer_class *t, gsl_matrix *inputs, size_t *labels){ tnn_error ret; tnn_state *sin; tnn_param *p; gsl_vector *rd; gsl_vector *pw; gsl_vector_view in; gsl_vector_view lb; double eps; size_t i,j; //Routine check if(t->t != TNN_TRAINER_CLASS_TYPE_NSGD){ return TNN_ERROR_TRAINER_CLASS_MISTYPE; } //Check the input TNN_MACRO_ERRORTEST(tnn_machine_get_sin(&t->m, &sin),ret); if(inputs->size2 != sin->size){ return TNN_ERROR_STATE_INCOMP; } //Set the loss output dx to be 1 gsl_vector_set(&t->l.output->dx, 0, 1.0); //Get the parameter and allocate rd and pw TNN_MACRO_ERRORTEST(tnn_machine_get_param(&t->m, &p), ret); rd = gsl_vector_alloc(p->size); pw = gsl_vector_alloc(p->size); if(rd == NULL || pw == NULL){ return TNN_ERROR_GSL; } //Into the main loop for(eps = DBL_MAX, ((tnn_trainer_class_nsgd*)t->c)->titer = 0; eps > ((tnn_trainer_class_nsgd*)t->c)->epsilon && ((tnn_trainer_class_nsgd*)t->c)->titer < ((tnn_trainer_class_nsgd*)t->c)->niter; ((tnn_trainer_class_nsgd*)t->c)->titer = ((tnn_trainer_class_nsgd*)t->c)->titer + ((tnn_trainer_class_nsgd*)t->c)->eiter){ //Copy the previous pw TNN_MACRO_GSLTEST(gsl_blas_dcopy(p->x, pw)); for(i = 0; i < ((tnn_trainer_class_nsgd*)t->c)->eiter; i = i + 1){ j = (((tnn_trainer_class_nsgd*)t->c)->titer + i)%inputs->size1; //Check the label if(labels[j] >= t->lset->size1){ return TNN_ERROR_STATE_INCOMP; } //Get the inputs and label vector lb = gsl_matrix_row(t->lset, labels[j]); in = gsl_matrix_row(inputs, j); //Copy the data into the input/label and do forward and backward propagation TNN_MACRO_GSLTEST(gsl_blas_dcopy(&in.vector, &sin->x)); TNN_MACRO_GSLTEST(gsl_blas_dcopy(&lb.vector, &t->label->x)); TNN_MACRO_ERRORTEST(tnn_machine_fprop(&t->m), ret); TNN_MACRO_ERRORTEST(tnn_loss_fprop(&t->l), ret); TNN_MACRO_ERRORTEST(tnn_loss_bprop(&t->l), ret); TNN_MACRO_ERRORTEST(tnn_machine_bprop(&t->m), ret); //Compute the accumulated regularization paramter TNN_MACRO_ERRORTEST(tnn_reg_d(&t->r, p->x, rd), ret); TNN_MACRO_GSLTEST(gsl_blas_daxpy(t->lambda, rd, p->dx)); //Compute the parameter update TNN_MACRO_GSLTEST(gsl_blas_daxpy(-((tnn_trainer_class_nsgd*)t->c)->eta, p->dx, p->x)); } //Compute the 2 square norm of difference of p as eps TNN_MACRO_GSLTEST(gsl_blas_daxpy(-1.0, p->x, pw)); eps = gsl_blas_dnrm2(pw); } return TNN_ERROR_SUCCESS; }
void QwtHistogram::loadData() { if (d_matrix){ loadDataFromMatrix(); return; } int r = abs(d_end_row - d_start_row) + 1; QVarLengthArray<double> Y(r); int ycol = d_table->colIndex(title().text()); int size = 0; for (int i = 0; i<r; i++ ){ QString yval = d_table->text(i, ycol); if (!yval.isEmpty()){ bool valid_data = true; Y[size] = ((Graph *)plot())->locale().toDouble(yval, &valid_data); if (valid_data) size++; } } if(size < 2 || (size==2 && Y[0] == Y[1])){//non valid histogram double X[2]; Y.resize(2); for (int i = 0; i<2; i++ ){ Y[i] = 0; X[i] = 0; } setData(X, Y.data(), 2); return; } int n; gsl_histogram *h; if (d_autoBin){ n = 10; h = gsl_histogram_alloc (n); if (!h) return; gsl_vector *v = gsl_vector_alloc (size); for (int i = 0; i<size; i++ ) gsl_vector_set (v, i, Y[i]); double min, max; gsl_vector_minmax (v, &min, &max); gsl_vector_free (v); d_begin = floor(min); d_end = ceil(max); d_bin_size = (d_end - d_begin)/(double)n; gsl_histogram_set_ranges_uniform (h, floor(min), ceil(max)); } else { n = int((d_end - d_begin)/d_bin_size + 1); h = gsl_histogram_alloc (n); if (!h) return; double *range = new double[n+2]; for (int i = 0; i<= n+1; i++ ) range[i] = d_begin + i*d_bin_size; gsl_histogram_set_ranges (h, range, n+1); delete[] range; } for (int i = 0; i<size; i++ ) gsl_histogram_increment (h, Y[i]); #ifdef Q_CC_MSVC QVarLengthArray<double> X(n); //stores ranges (x) and bins (y) #else double X[n]; //stores ranges (x) and bins (y) #endif Y.resize(n); for (int i = 0; i<n; i++ ){ Y[i] = gsl_histogram_get (h, i); double lower, upper; gsl_histogram_get_range (h, i, &lower, &upper); X[i] = lower; } #ifdef Q_CC_MSVC setData(X.data(), Y.data(), n); #else setData(X, Y.data(), n); #endif d_mean = gsl_histogram_mean(h); d_standard_deviation = gsl_histogram_sigma(h); d_min = gsl_histogram_min_val(h); d_max = gsl_histogram_max_val(h); gsl_histogram_free (h); }
void checkSLE(const gsl_matrix* A, const gsl_vector* x, const gsl_vector* b, const int N) { // TODO - make complete logging to the file // print("Checking the solution of the SLE ... "); // Checking on condition number of matrix A int signum; gsl_permutation *perm = gsl_permutation_alloc(N); gsl_matrix *LU = gsl_matrix_alloc(N, N); gsl_matrix *invA = gsl_matrix_alloc(N, N); gsl_matrix_memcpy(LU, A); gsl_linalg_LU_decomp(LU, perm, &signum); gsl_linalg_LU_invert(LU, perm, invA); gsl_matrix_free(LU); gsl_permutation_free(perm); gsl_vector *row = gsl_vector_alloc(N); double normA = 0; double normInvA = 0; for(int i = 0; i < N; i++) { gsl_matrix_get_row(row, A, i); double dasum = gsl_blas_dasum(row); if (dasum > normA) normA = dasum; gsl_matrix_get_row(row, invA, i); dasum = gsl_blas_dasum(row); if (dasum > normInvA) normInvA = dasum; } double conditionNumber = normA * normInvA; if (conditionNumber > 1000) //print("Condition number of matrix of SLE is ", conditionNumber); gsl_vector_free(row); // Checking on Ax == b gsl_vector *tmp = gsl_vector_alloc(N); gsl_vector_memcpy(tmp, b); // tmp = A*x - b, i.e. error gsl_blas_dgemv(CblasNoTrans, 1, A, x, -1, tmp); for(int i = 0; i < N; i++) { if (fabs(gsl_vector_get(tmp, i) / gsl_vector_get(b, i)) > 1e-8) { if (gsl_vector_get(b, i) == 0) { if (fabs(gsl_vector_get(tmp, i)) > 1e-8) print("Ax =", gsl_vector_get(tmp, i), "at string", i, ". But b = 0 here."); } else { print("( Ax - b ) / b =", gsl_vector_get(tmp, i) / gsl_vector_get(b, i), "at string", i); } } } // Checking on inv(A)b == x gsl_vector_memcpy(tmp, x); // tmp = inv(A)*b - x, i.e. error gsl_blas_dgemv(CblasNoTrans, 1, invA, b, -1, tmp); for(int i = 0; i < N; i++) { if (fabs(gsl_vector_get(tmp, i) / gsl_vector_get(x, i)) > 1e-8) print("( inv(A)b - x ) / x =", gsl_vector_get(tmp, i) / gsl_vector_get(x, i), "at string ", i); } gsl_vector_free(tmp); gsl_matrix_free(invA); // TODO - make complete logging to the file // print("Checking is done."); }
/* coefficients as well */ double singleChi(const double *sampletimes, const float *vals, const float *stderrs, long ndata, long nharmonics, double tstart, double frequency, float *harmoniccoeffs) { #define MAXHARM 17 int i, j, d; int result; double alpha[2*MAXHARM+1][2*MAXHARM+1]; double beta[2*MAXHARM+1]; double chisqred; gsl_matrix *alpha_gsl = gsl_matrix_alloc(2 * nharmonics + 1,2 * nharmonics + 1); gsl_vector *beta_gsl = gsl_vector_alloc(2 * nharmonics + 1); gsl_vector *x_gsl = gsl_vector_alloc(2 * nharmonics + 1); assert(nharmonics <= MAXHARM); for (i = 0 ; i < 2*nharmonics+1 ; i++) { beta[i] = 0; for (j = 0 ; j < 2*nharmonics+1 ; j++) alpha[i][j] = 0; } for (d = 0 ; d < ndata ; d++) { for (i = 0 ; i < 2*nharmonics+1 ; i++) { double invvar = 1/(stderrs[d] * stderrs[d]); beta[i] += vals[d] * invvar * Mfunc(i, (sampletimes[d] - tstart) * frequency * 2 * M_PI); for (j = 0 ; j < 2*nharmonics+1 ; j++) alpha[i][j] += invvar * Mfunc(i, (sampletimes[d] - tstart) * frequency * 2 * M_PI) * Mfunc(j, (sampletimes[d] - tstart) * frequency * 2 * M_PI); } } for (i = 0 ; i < 2*nharmonics+1 ; i++) { gsl_vector_set(beta_gsl, i, beta[i]); for (j = 0 ; j < 2*nharmonics+1 ; j++) gsl_matrix_set(alpha_gsl, i, j, alpha[i][j]); } result = gsl_linalg_HH_solve(alpha_gsl, beta_gsl, x_gsl); /* x = alpha^-1 beta */ assert(result == 0); gsl_blas_ddot(x_gsl, beta_gsl, &chisqred); if (harmoniccoeffs) { for (i = 0 ; i < 2*nharmonics+1 ; i++) { harmoniccoeffs[i] = gsl_vector_get(x_gsl, i); } } gsl_matrix_free(alpha_gsl); gsl_vector_free(beta_gsl); gsl_vector_free(x_gsl); return chisqred; }
//! main function for Conditioning experiment int main() { // set up random number generator: gsl_rng_env_setup(); r = gsl_rng_alloc(gsl_rng_default); gsl_rng_set(r, RANDOM_SEED); // initialise the specifice parameters for this simulation. initDerivedParams(); //char filename[1024]; //sprintf(filename, "data/conditioning_%d_%4f_%d.dat", TRAININGCYCLES, ETA, TAU_ALPHA); FILE *F = fopen(FILENAME, "w+b"); //! output file name gsl_vector *psp = gsl_vector_alloc(NPRE); //! to hold PSPs gsl_vector *pspS = gsl_vector_alloc(NPRE); //! to hold (filtered?) PSPs gsl_vector *sue = gsl_vector_alloc(NPRE); //! "positive" part of PSP fur integration gsl_vector *sui = gsl_vector_alloc(NPRE); //! "negative" part of PSP fur integration gsl_vector *pspTilde = gsl_vector_alloc(NPRE); //! low pass (2nd) filtered PSS gsl_vector *wB = gsl_vector_alloc(NPRE); //! weights of connections to Bacon neuron gsl_vector *wW = gsl_vector_alloc(NPRE); //! weights of connections to Water neuron gsl_vector *wR = gsl_vector_alloc(NPRE); //! weights of connections to Reward neuron gsl_vector *ou = gsl_vector_alloc(NPRE); //! xxxx gsl_vector *oum = gsl_vector_alloc(NPRE); //! xxx gsl_vector *pres = gsl_vector_alloc(NPRE); //! xxx //! short-hand pointer to the datastructures above. double *pspP = gsl_vector_ptr(psp,0); double *pspSP = gsl_vector_ptr(pspS,0); double *sueP = gsl_vector_ptr(sue,0); double *suiP = gsl_vector_ptr(sui,0); double *pspTildeP = gsl_vector_ptr(pspTilde,0); double *wBP = gsl_vector_ptr(wB,0); double *wWP = gsl_vector_ptr(wW,0); double *wRP = gsl_vector_ptr(wR,0); double *ouP = gsl_vector_ptr(ou,0); double *oumP = gsl_vector_ptr(oum,0); double *presP = gsl_vector_ptr(pres,0); // initialise data structures: for(int i=0; i<NPRE; i++) { *(pspP+i) = 0; *(sueP+i) = 0; *(suiP+i) = 0; // random connections to B, W, and R neurons *(wBP+i) = gsl_ran_gaussian(r, .04) + .07; *(wWP+i) = gsl_ran_gaussian(r, .04) + .07; *(wRP+i) = gsl_ran_gaussian(r, .04) + .07; } /*! Bacon neuron: - uB soma potential - uVB potential from dendrited alone - rU rate from some - rVB rate from dentritic input alone and then the same for W,R neurons */ double uB = 0, uVB = 0, rUB = 0, rVB = 0; double uW = 0, uVW = 0, rUW = 0, rVW = 0; double uR = 0, uVR = 0, rUR = 0, rVR = 0; //! we only recorded activites of this many pres int nOfRecordedPre = 50; //! this describes the length of the network state we store int stateLength = 4 * nOfRecordedPre + 12; //! the states consistes of u, uV, rU, rV of all recorded pres and of B,R,W neurons. double *state[stateLength]; for(int i = 0; i < nOfRecordedPre; i++) { *(state + 0*nOfRecordedPre + i) = wBP + i; // points to weight vector of connection to B etc *(state + 1*nOfRecordedPre + i) = wWP + i; *(state + 2*nOfRecordedPre + i) = wRP + i; *(state + 3*nOfRecordedPre + i) = presP + i; // points to presP values } *(state + 4*nOfRecordedPre) = &uB; // points to potential u of B etc *(state + 4*nOfRecordedPre+1) = &uVB; *(state + 4*nOfRecordedPre+2) = &rUB; *(state + 4*nOfRecordedPre+3) = &rVB; *(state + 4*nOfRecordedPre+4) = &uW; *(state + 4*nOfRecordedPre+5) = &uVW; *(state + 4*nOfRecordedPre+6) = &rUW; *(state + 4*nOfRecordedPre+7) = &rVW; *(state + 4*nOfRecordedPre+8) = &uR; *(state + 4*nOfRecordedPre+9) = &uVR; *(state + 4*nOfRecordedPre+10) = &rUR; *(state + 4*nOfRecordedPre+11) = &rVR; // pointers to input currents xxx to do with B,W,R //! \todo why initialised this way? double *IB, *IW, *IR = I1, *ou_t, uI; double IRf = 1; //! reward factor /* Start of simulations */ // repeat for all training cycles for( int s = 0; s < TRAININGCYCLES; s++) { // apply Bacon and Water stimulus alternatinglly with corresponding reward if( s%2==0 ) { ou_t = OU2; IB = I2; IW = I1; IRf = .5; } else { ou_t = OU1; IB = I1; IW = I2; IRf = 1; } // now for all time bins: for( int t = 0; t < TIMEBINS; t++) { for( int i = 0; i < NPRE; i++) { mixOUs(ouP + i, ou_t[t * NPRE + i], MIX[t], oumP + i); updatePre(sueP+i, suiP+i, pspP + i, pspSP + i, pspTildeP + i, *(presP + i) = spiking(DT * phi(*(oumP + i)), gsl_ran_flat(r,0,1))); } updateMembrane(&uB, &uVB, &uI, wB, psp, IB[t], 0); updateMembrane(&uW, &uVW, &uI, wW, psp, IW[t], 0); updateMembrane(&uR, &uVR, &uI, wR, psp, IRf*IR[t], 0); //rUB = spiking(phi(uB), gsl_ran_flat(r,0,1)); rVB = phi(uVB); //rUW = spiking(phi(uW), gsl_ran_flat(r,0,1)); rVW = phi(uVW); //rUR = spiking(phi(uR), gsl_ran_flat(r,0,1)); rVR = phi(uVR); //! do calculates on the potentials only, not the actual spikes: rUB = phi(uB); rVB = phi(uVB); rUW = phi(uW); rVW = phi(uVW); rUR = phi(uR); rVR = phi(uVR); for(int i = 0; i < NPRE; i++) { updateWeight(wBP + i, rUB, *(pspTildeP+i), rVB, *(pspSP+i)); updateWeight(wWP + i, rUW, *(pspTildeP+i), rVW, *(pspSP+i)); updateWeight(wRP + i, rUR, *(pspTildeP+i), rVR, *(pspSP+i)); } // write out states after the first 10 cycles: if(s > TRAININGCYCLES - 9 ) { for(int i=0; i<stateLength; i++) { fwrite(*(state+i), sizeof(double), 1, F); } } } } gsl_vector_free(psp); gsl_vector_free(pspS); gsl_vector_free(wB); gsl_vector_free(wW); gsl_vector_free(wR); free(ou); free(oum); free(OU1); free(OU2); free(MIX); free(I1); free(I2); fclose(F); return 0; }
/* Produce a vector of chisquared values as a function of frequency */ void fastChi(const double *sampletimes, const float *vals, const float *stderrs, long ndata, long nharmonics, double deltat, long nrealpoints, long nchivalues, double tstart, float *dovstorage, float *oovstorage, float *chireductionlist) { int d; int i; int h; float invdeltat = 1/deltat; gsl_matrix *alpha = gsl_matrix_alloc(2 * nharmonics + 1,2 * nharmonics + 1); gsl_vector *beta = gsl_vector_alloc(2 * nharmonics + 1); gsl_vector *x = gsl_vector_alloc(2 * nharmonics + 1); float *cosdata = malloc((nharmonics + 1) * sizeof(float)); float *sindata = malloc((nharmonics + 1) * sizeof(float)); float *cosvar = malloc((2*nharmonics + 1) * sizeof(float)); float *sinvar = malloc((2*nharmonics + 1) * sizeof(float)); /* if the pointers point somewhere, assume that they point to the right place */ assert(sampletimes && vals && stderrs && dovstorage && oovstorage && chireductionlist); assert(nchivalues * 2 * nharmonics <= nrealpoints); /* FIXME: change 2 to 1 when */ /* using aliasing */ assert(cosdata && sindata && cosvar && sinvar); memset(dovstorage, 0, nrealpoints * sizeof(float)); memset(oovstorage, 0, nrealpoints * sizeof(float)); for (d = 0 ; d < ndata ; d++) { long tindex = (sampletimes[d] - tstart) * invdeltat; float inv_variance = 1/(stderrs[d] * stderrs[d]); assert(tindex >= 0 && tindex < nrealpoints); /* adding rather than setting averages measurments that */ /* fall in same timebin. It does, however, reduce the d.o.f. */ /* and subsequently improperly reduces the chisquared. */ /* This is a minor point. */ /* dov: _d_ata _o_ver _v_ariance oov: _o_ne _o_ver _v_ariance */ dovstorage[tindex] += vals[d] * inv_variance; oovstorage[tindex] += inv_variance; } gsl_fft_real_float_radix2_transform(dovstorage, 1, nrealpoints); gsl_fft_real_float_radix2_transform(oovstorage, 1, nrealpoints); cosdata[0] = dovstorage[0]; /* The constant (0f) terms are the same for all f */ cosvar[0] = oovstorage[0]; for (i = 1 ; i < nchivalues ; i++) { for (h = 1 ; h <= nharmonics ; h++) { cosdata[h] = dovstorage[i*h]; sindata[h] = dovstorage[nrealpoints - (i * h)] * FFTSIGNCONVENTION; } for (h = 1 ; h <= 2*nharmonics ; h++) { /* put alias wrapping in here */ cosvar[h] = oovstorage[i*h]; sinvar[h] = oovstorage[nrealpoints - (i * h)] * FFTSIGNCONVENTION; } chireductionlist[i] = calcChiReduction(nharmonics, cosdata, sindata, cosvar, sinvar, alpha, beta, x); } gsl_matrix_free(alpha); gsl_vector_free(beta); gsl_vector_free(x); free(cosdata); free(sindata); free(cosvar); free(sinvar); }
int main (int argc, char **argv){ FILE *in; char filename[265]; double *M; double *M_T; double *Y, *X; float x,y; double valx, valy, num, fx, chi; int pos; int j,n; int nlines, degree; /*get arguments*/ strcpy(filename, argv[1]); if(!(in=fopen(filename, "r"))){ printf("problem opening file %s\n", filename); exit(1); } nlines = count_lines(filename); degree = atoi(argv[2]) + 1; /*errors*/ if (degree<=1){ printf("The program needs a degree greater that 0\n"); exit(1); } if (argc!=3){ printf("Start the program as ./a.out data degree\n"); } /*memory allocation*/ if (!(M = malloc(nlines * degree * sizeof(double)))){ fprintf(stderr, "Problem with memory allocation\n"); exit(1); } if (!(Y = malloc(nlines * sizeof(double)))){ fprintf(stderr, "Problem with memory allocation\n"); exit(1); } if (!(X = malloc(nlines * sizeof(double)))){ fprintf(stderr, "Problem with memory allocation\n"); exit(1); } /* the Matrix and Y vector*/ for(n=0; n<nlines; n++){ fscanf(in,"%f %f\n", &x, &y); X[n] = x; //X vector Y[n] = y; //Y vector; for(j=0;j<degree;j++){ pos = j + (degree * n); M[pos] = pow(x,j); //matrix } } /*GSL matrix*/ gsl_matrix_view m = gsl_matrix_view_array (M, nlines, degree); gsl_matrix *c = gsl_matrix_alloc(degree,degree); gsl_blas_dgemm (CblasTrans, CblasNoTrans, 1.0, &m.matrix, &m.matrix, 0.0, c); /*inverse c by LU decomposition*/ int s=0; gsl_permutation *p = gsl_permutation_alloc(degree); gsl_linalg_LU_decomp (c,p,&s); gsl_matrix *inv = gsl_matrix_alloc(degree,degree); gsl_linalg_LU_invert (c,p,inv); /*compute inv * m_t*/ gsl_matrix *b = gsl_matrix_alloc(degree,nlines); gsl_blas_dgemm (CblasNoTrans, CblasTrans, 1.0, inv, &m.matrix, 0.0, b); /*compute b*Y*/ gsl_vector *res = gsl_vector_alloc(degree); gsl_vector_view yv = gsl_vector_view_array (Y, nlines); gsl_blas_dgemv (CblasNoTrans, 1.0, b, &yv.vector, 0.0, res); for(n=0;n<degree;n++){ num = gsl_vector_get(res,n); printf("a_%d %f\n",n,num); } /*chi-squared calculation*/ chi = 0.0; for(n=0;n<nlines;n++){ fx = 0.0; valx = X[n]; valy = Y[n]; for(j=0;j<degree;j++){ num = gsl_vector_get (res,j); fx = fx + pow(valx,j)*num; } chi = chi + pow(valy-fx,2); } chi = chi/nlines; printf("chi2 %f\n",chi); fclose(in); return 0; }
int main(int argc, char **argv) { gsl_matrix *Original; gsl_matrix *Mtr_Cov; FILE *input; int num_lineas; int i,j,k; double var; /*--------------------------------------------------------- Verifica cuales archivos fueron usados como input y se asegura de que solo haya cargado uno. -----------------------------------------------------------*/ printf("Este programa se ejecutó con %d argumento(s):\n",argc-1); for(i=1;i<argc;i++){ printf("%s\n", argv[i]); } if(argc!=2){ printf("se necesita 1 argumento además del nombre del ejecutable!,\n EXIT!\n"); exit(1); } else{ printf("El archivo a usar es %s\n", argv[1]); } //-------------------------------------------------------- input=fopen(argv[1],"r"); if(!input){ printf("surgió un problema abriendo el archivo\n"); exit(1); } /*--------------------------------------------------------- toma como archivo base el primer argumento y cuenta sus lineas -----------------------------------------------------------*/ num_lineas=0; while ((var = fgetc(input)) != EOF){ if (var =='\n') ++num_lineas; } //printf("Número de lineas del archivo:\n -->%d\n",num_lineas); /*--------------------------------------------------------- Data allocation -----------------------------------------------------------*/ rewind(input); Original=gsl_matrix_alloc((num_lineas),24); // printf("\nOriginal\n"); gsl_matrix_fscanf(input,Original); //gsl_matrix_fprintf (stdout, Original, "%g"); //CheckPoint //printf("matriz escaneada\n"); /*--------------------------------------------------------- Promedio -----------------------------------------------------------*/ float *prom; int y; prom=malloc((num_lineas) * sizeof(float)); //printf("...\n"); for(k=0;k<num_lineas;k++){ float suma=0.0; for(y=0;y<24;y++){ suma+=gsl_matrix_get(Original,k,y); } prom[k]=suma/24.0; } printf("Checkpoint... Promedios\n"); /*--------------------------------------------------------- Efectos en la matriz -----------------------------------------------------------*/ Mtr_Cov=gsl_matrix_alloc(num_lineas,num_lineas); //printf("...\n"); int l,n,m; double sprite=0; for(l=0;l<num_lineas;l++){ for(m=0;m<num_lineas;m++){ for(n=1;n<24;n++){ double flan=gsl_matrix_get(Original,m,n); double agua=prom[m]; double frutino=gsl_matrix_get(Original,l,n); double tang=prom[l]; double jarra1=(flan-agua); double jarra2=(frutino-tang); //printf("%g %g\n",jarra1,jarra2); sprite=sprite+(jarra1*jarra2)/24; } gsl_matrix_set(Mtr_Cov,m,l,sprite); sprite=0; }} /*--------------------------------------------------------- Matriz de covarianza creada; sacar vectores y valores propios de la matriz. -----------------------------------------------------------*/ /* int pa,po; double can; for(pa=0;pa<num_lineas;pa++){ for(po=0;po<num_lineas;po++){ can=gsl_matrix_get(Mtr_Cov,po,pa); printf("%f ",can); } printf("\n"); } */ gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (num_lineas); gsl_vector *eval = gsl_vector_alloc (num_lineas); gsl_matrix *evec = gsl_matrix_alloc (num_lineas,num_lineas); gsl_eigen_symmv (Mtr_Cov, eval, evec, w); gsl_eigen_symmv_sort (eval, evec,GSL_EIGEN_SORT_ABS_ASC); /*--------------------------------------------------------- PON ESA COSA HORROROSA AHI O VERAS!!! -----------------------------------------------------------*/ FILE *Out1; FILE *Out2; Out1 = fopen("JorgeHayek_eigenvalues.dat", "w"); Out2 = fopen("JorgeHayek_eigenvectors.dat", "w"); fprintf(Out1,"EigenValues:\n"); fprintf(Out2,"EigenVectors:\n"); for (i = 0; i < num_lineas; i++) { double eval_i = gsl_vector_get (eval, i); fprintf (Out1,"%g\n", eval_i); } for (i = 0; i < 11; i++) {fprintf(Out2,"--------------------------------------------\nVector %d\n--------------------------------------------\n",i); gsl_vector_view evec_i = gsl_matrix_column (evec, i); gsl_vector_fprintf (Out2, &evec_i.vector, "%g"); } /*--------------------------------------------------------- FIN -----------------------------------------------------------*/ gsl_vector_free (eval); gsl_matrix_free (evec); gsl_matrix_free(Original); fclose(input); return 0; }
static VALUE rb_gsl_function_graph(int argc, VALUE *argv, VALUE obj) { #ifdef HAVE_GNU_GRAPH gsl_function *F = NULL; gsl_vector *v = NULL; double x, y; char opt[256] = "", command[1024]; size_t i, n; int flag = 0; FILE *fp = NULL; VALUE ary, params, proc; switch (argc) { case 2: Check_Type(argv[1], T_STRING); strcpy(opt, STR2CSTR(argv[1])); /* no break, do next */ case 1: if (CLASS_OF(argv[0]) == rb_cRange) argv[0] = rb_gsl_range2ary(argv[0]); if (TYPE(argv[0]) == T_ARRAY) { // n = RARRAY(argv[0])->len; n = RARRAY_LEN(argv[0]); v = gsl_vector_alloc(n); flag = 1; for (i = 0; i < n; i++) gsl_vector_set(v, i, NUM2DBL(rb_ary_entry(argv[0], i))); } else if (rb_obj_is_kind_of(argv[0], cgsl_vector)) { Data_Get_Struct(argv[0], gsl_vector, v); n = v->size; flag = 0; } else { rb_raise(rb_eTypeError, "wrong argument type %s (Array or GSL::Vector expected)", rb_class2name(CLASS_OF(argv[0]))); } break; default: rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc); break; } Data_Get_Struct(obj, gsl_function, F); ary = (VALUE) F->params; proc = rb_ary_entry(ary, 0); params = rb_ary_entry(ary, 1); sprintf(command, "graph -T X -g 3 %s", opt); fp = popen(command, "w"); if (fp == NULL) rb_raise(rb_eIOError, "GNU graph not found."); for (i = 0; i < n; i++) { x = gsl_vector_get(v, i); if (NIL_P(params)) y = NUM2DBL(rb_funcall(proc, RBGSL_ID_call, 1, rb_float_new(x))); else y = NUM2DBL(rb_funcall(proc, RBGSL_ID_call, 2, rb_float_new(x), params)); fprintf(fp, "%e %e\n", x, y); } fflush(fp); pclose(fp); fp = NULL; if (flag == 1) gsl_vector_free(v); return Qtrue; #else rb_raise(rb_eNoMethodError, "not implemented"); return Qfalse; #endif }
int multi_fit_engine_prepare(struct multi_fit_engine *fit) { struct fit_parameters const * common = fit->common_parameters; struct fit_parameters const * priv = fit->private_parameters; struct fit_config *cfg = & fit->config; size_t nb_total_params; assert(fit->spectra_list != NULL); nb_total_params = common->number + fit->samples_number * priv->number; /* We suppose that all the spectra are of the same kind, so we just look the first one */ fit->system_kind = fit->spectra_list[0]->config.system; if(fit->config.spectr_range.active) { int k; for(k = 0; k < fit->samples_number; k++) spectr_cut_range(fit->spectra_list[k], fit->config.spectr_range.min, fit->config.spectr_range.max); } build_multi_fit_engine_cache(fit); switch(fit->system_kind) { int k, npt; case SYSTEM_REFLECTOMETER: for(npt = 0, k = 0; k < fit->samples_number; k++) { npt += spectra_points(fit->spectra_list[k]); } fit->mffun.f = & refl_multifit_f; fit->mffun.df = & refl_multifit_df; fit->mffun.fdf = & refl_multifit_fdf; fit->mffun.n = npt; fit->mffun.p = nb_total_params; fit->mffun.params = fit; break; case SYSTEM_ELLISS_AB: case SYSTEM_ELLISS_PSIDEL: for(npt = 0, k = 0; k < fit->samples_number; k++) { npt += 2 * spectra_points(fit->spectra_list[k]); } fit->mffun.f = & elliss_multifit_f; fit->mffun.df = & elliss_multifit_df; fit->mffun.fdf = & elliss_multifit_fdf; fit->mffun.n = npt; fit->mffun.p = nb_total_params; fit->mffun.params = fit; break; default: return 1; } if(! cfg->threshold_given) { cfg->chisq_threshold = (fit->system_kind == SYSTEM_REFLECTOMETER ? 5.0E3 : 2.0E5); } cfg->chisq_threshold *= fit->samples_number; fit->results = gsl_vector_alloc(nb_total_params); fit->chisq = gsl_vector_alloc(fit->samples_number); fit->initialized = 1; return 0; }
static int update_bundle(bundle_method_state_t *state, const gsl_vector *new_sgr, const double lin_error_sgr, const gsl_vector *lambda, const gsl_vector *aggr_sgr, const double lin_error_aggr_sgr, const size_t serious_step) { bundle_element *current; bundle_element *item; bundle_element *item_aggr_sgr; bundle_element *item_largest_lin_error; size_t i; int status; /* at first: drop all inactive bundle elements, i.e. elements with lambda(j)=0, because they do not contribute to the trial point y */ /* second: drop the bundle elemen (if necessary ) with the largest linearization error */ current = state->head; item_largest_lin_error = NULL; item_aggr_sgr = NULL; for(i=0; i<lambda->size; i++) { if(!serious_step && current->state == 2) { item_aggr_sgr = current; current = current->next; } else if((fabs(gsl_vector_get(lambda,i))<state->lambda_min && current->state != 0) || (serious_step && current->state == 2)) { item = current; current = current->next; status = remove_element(item, &(state->head), &(state->tail)); (state->bundle_size)--; } else { if(item_largest_lin_error == NULL || fabs(current->lin_error) > fabs(item_largest_lin_error->lin_error)) item_largest_lin_error = current; if (current->state ==0 && serious_step) current->state = 1; current = current->next; } } if(state->bundle_size >= state->bundle_size_max) { status = remove_element(item_largest_lin_error, &(state->head), &(state->tail)); (state->bundle_size)--; if(state->bundle_size >= state->bundle_size_max-1 && !serious_step && item_aggr_sgr == NULL) { if(state->head->state != 0) item_largest_lin_error = state->head; else item_largest_lin_error = state->head->next; for(item = item_largest_lin_error->next; item != NULL; item=item->next) { if(fabs(item->lin_error) > fabs(item_largest_lin_error->lin_error) && item->state != 0) item_largest_lin_error = item; } status = remove_element(item_largest_lin_error, &(state->head), &(state->tail)); (state->bundle_size)--; } } /* add the new element to the bundle */ item = malloc(sizeof(bundle_element)); if (item == 0) { GSL_ERROR ("failed to allocate space for a new bundle element", GSL_ENOMEM); } item->sgr = gsl_vector_alloc(new_sgr->size); if (item->sgr == 0) { free(item); GSL_ERROR ("failed to allocate space for a subgradient in the new bundle element", GSL_ENOMEM); } status = gsl_blas_dcopy(new_sgr,item->sgr); item->lin_error = lin_error_sgr; if(serious_step) item->state = 0; else item->state = 1; status = insert_element(item, &(state->head), &(state->tail)); (state->bundle_size)++; if(!serious_step) { if(item_aggr_sgr == NULL) { item = malloc(sizeof(bundle_element)); if (item == 0) { GSL_ERROR ("failed to allocate space for a new bundle element", GSL_ENOMEM); } item->sgr = gsl_vector_alloc(new_sgr->size); if (item->sgr == 0) { free(item); GSL_ERROR ("failed to allocate space for a subgradient in the new bundle element", GSL_ENOMEM); } status = gsl_blas_dcopy(aggr_sgr,item->sgr); item->lin_error = lin_error_aggr_sgr; item->state = 2; status = insert_element(item, &(state->head), &(state->tail)); (state->bundle_size)++; } else { status = gsl_blas_dcopy(aggr_sgr,item_aggr_sgr->sgr); item_aggr_sgr->lin_error = lin_error_aggr_sgr; } } return GSL_SUCCESS; }
/** Executes the algorithm * * @throw runtime_error Thrown if algorithm cannot execute */ void DiffractionEventCalibrateDetectors::exec() { // Try to retrieve optional properties const int maxIterations = getProperty("MaxIterations"); const double peakOpt = getProperty("LocationOfPeakToOptimize"); // Get the input workspace EventWorkspace_sptr inputW = getProperty("InputWorkspace"); // retrieve the properties const std::string rb_params = getProperty("Params"); // Get some stuff from the input workspace // We make a copy of the instrument since we will be moving detectors in // `inputW` but want to access original positions (etc.) via `detList` below. const auto &dummyW = create<EventWorkspace>(*inputW, 1, inputW->binEdges(0)); Instrument_const_sptr inst = dummyW->getInstrument(); // Build a list of Rectangular Detectors std::vector<boost::shared_ptr<RectangularDetector>> detList; // --------- Loading only one bank ---------------------------------- std::string onebank = getProperty("BankName"); bool doOneBank = (!onebank.empty()); for (int i = 0; i < inst->nelements(); i++) { boost::shared_ptr<RectangularDetector> det; boost::shared_ptr<ICompAssembly> assem; boost::shared_ptr<ICompAssembly> assem2; det = boost::dynamic_pointer_cast<RectangularDetector>((*inst)[i]); if (det) { if (det->getName() == onebank) detList.push_back(det); if (!doOneBank) detList.push_back(det); } else { // Also, look in the first sub-level for RectangularDetectors (e.g. PG3). // We are not doing a full recursive search since that will be very long // for lots of pixels. assem = boost::dynamic_pointer_cast<ICompAssembly>((*inst)[i]); if (assem) { for (int j = 0; j < assem->nelements(); j++) { det = boost::dynamic_pointer_cast<RectangularDetector>((*assem)[j]); if (det) { if (det->getName() == onebank) detList.push_back(det); if (!doOneBank) detList.push_back(det); } else { // Also, look in the second sub-level for RectangularDetectors (e.g. // PG3). // We are not doing a full recursive search since that will be very // long for lots of pixels. assem2 = boost::dynamic_pointer_cast<ICompAssembly>((*assem)[j]); if (assem2) { for (int k = 0; k < assem2->nelements(); k++) { det = boost::dynamic_pointer_cast<RectangularDetector>( (*assem2)[k]); if (det) { if (det->getName() == onebank) detList.push_back(det); if (!doOneBank) detList.push_back(det); } } } } } } } } // set-up minimizer std::string inname = getProperty("InputWorkspace"); std::string outname = inname + "2"; // getProperty("OutputWorkspace"); IAlgorithm_sptr algS = createChildAlgorithm("SortEvents"); algS->setProperty("InputWorkspace", inputW); algS->setPropertyValue("SortBy", "X Value"); algS->executeAsChildAlg(); // Write DetCal File std::string filename = getProperty("DetCalFilename"); std::fstream outfile; outfile.open(filename.c_str(), std::ios::out); if (detList.size() > 1) { outfile << "#\n"; outfile << "# Mantid Optimized .DetCal file for SNAP with TWO detector " "panels\n"; outfile << "# Old Panel, nominal size and distance at -90 degrees.\n"; outfile << "# New Panel, nominal size and distance at +90 degrees.\n"; outfile << "#\n"; outfile << "# Lengths are in centimeters.\n"; outfile << "# Base and up give directions of unit vectors for a local\n"; outfile << "# x,y coordinate system on the face of the detector.\n"; outfile << "#\n"; outfile << "# " << DateAndTime::getCurrentTime().toFormattedString("%c") << "\n"; outfile << "#\n"; outfile << "6 L1 T0_SHIFT\n"; IComponent_const_sptr source = inst->getSource(); IComponent_const_sptr sample = inst->getSample(); outfile << "7 " << source->getDistance(*sample) * 100 << " 0\n"; outfile << "4 DETNUM NROWS NCOLS WIDTH HEIGHT DEPTH DETD " "CenterX CenterY CenterZ BaseX BaseY BaseZ " "UpX UpY UpZ\n"; } Progress prog(this, 0.0, 1.0, detList.size()); for (int det = 0; det < static_cast<int>(detList.size()); det++) { std::string par[6]; par[0] = detList[det]->getName(); par[1] = inname; par[2] = outname; std::ostringstream strpeakOpt; strpeakOpt << peakOpt; par[3] = strpeakOpt.str(); par[4] = rb_params; // --- Create a GroupingWorkspace for this detector name ------ CPUTimer tim; IAlgorithm_sptr alg2 = AlgorithmFactory::Instance().create("CreateGroupingWorkspace", 1); alg2->initialize(); alg2->setProperty("InputWorkspace", inputW); alg2->setPropertyValue("GroupNames", detList[det]->getName()); std::string groupWSName = "group_" + detList[det]->getName(); alg2->setPropertyValue("OutputWorkspace", groupWSName); alg2->executeAsChildAlg(); par[5] = groupWSName; std::cout << tim << " to CreateGroupingWorkspace\n"; const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; gsl_vector *ss, *x; gsl_multimin_function minex_func; // finally do the fitting int nopt = 6; int iter = 0; int status = 0; /* Starting point */ x = gsl_vector_alloc(nopt); gsl_vector_set(x, 0, 0.0); gsl_vector_set(x, 1, 0.0); gsl_vector_set(x, 2, 0.0); gsl_vector_set(x, 3, 0.0); gsl_vector_set(x, 4, 0.0); gsl_vector_set(x, 5, 0.0); /* Set initial step sizes to 0.1 */ ss = gsl_vector_alloc(nopt); gsl_vector_set_all(ss, 0.1); /* Initialize method and iterate */ minex_func.n = nopt; minex_func.f = &Mantid::Algorithms::gsl_costFunction; minex_func.params = ∥ gsl_multimin_fminimizer *s = gsl_multimin_fminimizer_alloc(T, nopt); gsl_multimin_fminimizer_set(s, &minex_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if (status) break; double size = gsl_multimin_fminimizer_size(s); status = gsl_multimin_test_size(size, 1e-2); } while (status == GSL_CONTINUE && iter < maxIterations && s->fval != -0.000); // Output summary to log file if (s->fval != -0.000) movedetector(gsl_vector_get(s->x, 0), gsl_vector_get(s->x, 1), gsl_vector_get(s->x, 2), gsl_vector_get(s->x, 3), gsl_vector_get(s->x, 4), gsl_vector_get(s->x, 5), par[0], getProperty("InputWorkspace")); else { gsl_vector_set(s->x, 0, 0.0); gsl_vector_set(s->x, 1, 0.0); gsl_vector_set(s->x, 2, 0.0); gsl_vector_set(s->x, 3, 0.0); gsl_vector_set(s->x, 4, 0.0); gsl_vector_set(s->x, 5, 0.0); } std::string reportOfDiffractionEventCalibrateDetectors = gsl_strerror(status); if (s->fval == -0.000) reportOfDiffractionEventCalibrateDetectors = "No events"; g_log.information() << "Detector = " << det << "\n" << "Method used = " << "Simplex" << "\n" << "Iteration = " << iter << "\n" << "Status = " << reportOfDiffractionEventCalibrateDetectors << "\n" << "Minimize PeakLoc-" << peakOpt << " = " << s->fval << "\n"; // Move in cm for small shifts g_log.information() << "Move (X) = " << gsl_vector_get(s->x, 0) * 0.01 << " \n"; g_log.information() << "Move (Y) = " << gsl_vector_get(s->x, 1) * 0.01 << " \n"; g_log.information() << "Move (Z) = " << gsl_vector_get(s->x, 2) * 0.01 << " \n"; g_log.information() << "Rotate (X) = " << gsl_vector_get(s->x, 3) << " \n"; g_log.information() << "Rotate (Y) = " << gsl_vector_get(s->x, 4) << " \n"; g_log.information() << "Rotate (Z) = " << gsl_vector_get(s->x, 5) << " \n"; Kernel::V3D CalCenter = V3D(gsl_vector_get(s->x, 0) * 0.01, gsl_vector_get(s->x, 1) * 0.01, gsl_vector_get(s->x, 2) * 0.01); Kernel::V3D Center = detList[det]->getPos() + CalCenter; int pixmax = detList[det]->xpixels() - 1; int pixmid = (detList[det]->ypixels() - 1) / 2; BoundingBox box; detList[det]->getAtXY(pixmax, pixmid)->getBoundingBox(box); double baseX = box.xMax(); double baseY = box.yMax(); double baseZ = box.zMax(); Kernel::V3D Base = V3D(baseX, baseY, baseZ) + CalCenter; pixmid = (detList[det]->xpixels() - 1) / 2; pixmax = detList[det]->ypixels() - 1; detList[det]->getAtXY(pixmid, pixmax)->getBoundingBox(box); double upX = box.xMax(); double upY = box.yMax(); double upZ = box.zMax(); Kernel::V3D Up = V3D(upX, upY, upZ) + CalCenter; Base -= Center; Up -= Center; // Rotate around x baseX = Base[0]; baseY = Base[1]; baseZ = Base[2]; double deg2rad = M_PI / 180.0; double angle = gsl_vector_get(s->x, 3) * deg2rad; Base = V3D(baseX, baseY * cos(angle) - baseZ * sin(angle), baseY * sin(angle) + baseZ * cos(angle)); upX = Up[0]; upY = Up[1]; upZ = Up[2]; Up = V3D(upX, upY * cos(angle) - upZ * sin(angle), upY * sin(angle) + upZ * cos(angle)); // Rotate around y baseX = Base[0]; baseY = Base[1]; baseZ = Base[2]; angle = gsl_vector_get(s->x, 4) * deg2rad; Base = V3D(baseZ * sin(angle) + baseX * cos(angle), baseY, baseZ * cos(angle) - baseX * sin(angle)); upX = Up[0]; upY = Up[1]; upZ = Up[2]; Up = V3D(upZ * cos(angle) - upX * sin(angle), upY, upZ * sin(angle) + upX * cos(angle)); // Rotate around z baseX = Base[0]; baseY = Base[1]; baseZ = Base[2]; angle = gsl_vector_get(s->x, 5) * deg2rad; Base = V3D(baseX * cos(angle) - baseY * sin(angle), baseX * sin(angle) + baseY * cos(angle), baseZ); upX = Up[0]; upY = Up[1]; upZ = Up[2]; Up = V3D(upX * cos(angle) - upY * sin(angle), upX * sin(angle) + upY * cos(angle), upZ); Base.normalize(); Up.normalize(); Center *= 100.0; // << det+1 << " " outfile << "5 " << detList[det]->getName().substr(4) << " " << detList[det]->xpixels() << " " << detList[det]->ypixels() << " " << 100.0 * detList[det]->xsize() << " " << 100.0 * detList[det]->ysize() << " " << "0.2000" << " " << Center.norm() << " "; Center.write(outfile); outfile << " "; Base.write(outfile); outfile << " "; Up.write(outfile); outfile << "\n"; // clean up dynamically allocated gsl stuff gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free(s); // Remove the now-unneeded grouping workspace AnalysisDataService::Instance().remove(groupWSName); prog.report(detList[det]->getName()); } // Closing outfile.close(); }