Search is not available for this dataset
text
string
meta
dict
/* * Copyright (c) 2016-2021 lymastee, All rights reserved. * Contact: lymastee@hotmail.com * * This file is part of the gslib project. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef texbatch_dfe6f3b4_430b_4424_98b6_d6b23235dc22_h #define texbatch_dfe6f3b4_430b_4424_98b6_d6b23235dc22_h #include <gslib/std.h> #include <ariel/type.h> #include <ariel/image.h> #include <ariel/rectpack.h> #include <ariel/rendersys.h> __ariel_begin__ typedef render_texture2d texture2d; #define _GS_BATCH_TEXTURE #if defined(_GS_BATCH_TEXTURE) #define location_key texture2d* #elif defined(_GS_BATCH_IMAGE) #define location_key const image* #endif class tex_batcher { public: typedef unordered_map<location_key, rectf> location_map; public: tex_batcher(); bool is_empty() const { return _rect_packer.is_empty(); } float get_width() const { return _rect_packer.get_width() + _gap; } float get_height() const { return _rect_packer.get_height() + _gap; } void add_image(const image* p); void add_texture(texture2d* p); void arrange(); const location_map& get_location_map() const { return _location_map; } texture2d* create_texture(rendersys* rsys) const; void create_packed_image(image& img) const; void tracing() const; protected: rect_packer _rect_packer; location_map _location_map; float _gap; private: void prepare_input_list(rp_input_list& inputs); }; __ariel_end__ #endif
{ "alphanum_fraction": 0.7254601227, "avg_line_length": 33.0126582278, "ext": "h", "hexsha": "3f1d42137d390340375fa265457dd71c140989b7", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_path": "include/ariel/texbatch.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_path": "include/ariel/texbatch.h", "max_line_length": 82, "max_stars_count": 9, "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_path": "include/ariel/texbatch.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "num_tokens": 626, "size": 2608 }
/* #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_rng.h> //#include "gsl-sprng.h" #include <mpi.h> #include <time.h> #include <unistd.h> const int SAMPLENUM = 1000; int obsnum; gsl_rng * r; int procnum; typedef struct { int prey; int predator0; int predator1; } lvstate; typedef struct { double time; double rawdata; } obsdata; void simPrior(lvstate *simData, MPI_Datatype datatype, MPI_Comm comm); void rowsample(int *rows, double *w); void stepLV(lvstate *state, double *t0p, double *dtp, double *lvParam, MPI_Datatype datatype, MPI_Comm comm); void peturb(double *lvParam, MPI_Datatype datatype, MPI_Comm comm); double obsLik(lvstate *mystate, double obs) { const double SIGMA = 20.0; return log(gsl_ran_gaussian_pdf((obs - mystate->prey), SIGMA)); } void mpiStepLV(lvstate *simData, double *t0p, double *dtp, double *lvParam, MPI_Datatype datatype, MPI_Comm comm) { //printf("...callStepLV..."); int j, offset, destNode, sourceNode, rank; int procnum, avgsize, samplemod; double t0, dt; MPI_Status status; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD, &procnum); //const unsigned int MAX_MPI_BUFFER = 524300000; //printf("rank in mpiStepLV %i \n", rank); //for (j = 0; j < SAMPLENUM; j++) { //MPI_Bcast(&simData[j].predator, 1, MPI_INT, 0, comm); //MPI_Bcast(&simData[j].prey, 1, MPI_INT, 0, comm); //} MPI_Bcast(lvParam, 5, MPI_DOUBLE, 0, comm); MPI_Bcast(t0p, 1, MPI_DOUBLE, 0, comm); MPI_Bcast(dtp, 1, MPI_DOUBLE, 0, comm); avgsize = SAMPLENUM/(procnum-1); samplemod = SAMPLENUM%(procnum-1); t0 = *t0p; dt = *dtp; if (rank==0) { //send tasks to other nodes offset = 0; for (destNode=1; destNode<procnum; destNode++){ //MPI_Send(&lvParam, 3, MPI_DOUBLE, destNode, 0, MPI_COMM_WORLD); MPI_Send(&offset, 1, MPI_INT, destNode, 0, MPI_COMM_WORLD); for (j=0;j<avgsize;j++) { MPI_Send(&simData[offset+j].prey, 1, MPI_INT, destNode, 0, MPI_COMM_WORLD); MPI_Send(&simData[offset+j].predator0, 1, MPI_INT, destNode, 0, MPI_COMM_WORLD); MPI_Send(&simData[offset+j].predator1, 1, MPI_INT, destNode, 0, MPI_COMM_WORLD); } offset = offset + avgsize; } for (j=0;j<samplemod;j++){ stepLV(simData+offset+j, &t0, &dt, lvParam, MPI_FLOAT, MPI_COMM_WORLD); } // Wait to receive results from each node for (sourceNode=1; sourceNode<procnum; sourceNode++){ MPI_Recv(&offset, 1, MPI_INT, sourceNode, 0, MPI_COMM_WORLD, &status); for (j=0;j<avgsize;j++) { MPI_Recv(&simData[offset+j].prey, 1, MPI_INT, sourceNode, 0, MPI_COMM_WORLD, &status); MPI_Recv(&simData[offset+j].predator0, 1, MPI_INT, sourceNode, 0, MPI_COMM_WORLD, &status); MPI_Recv(&simData[offset+j].predator1, 1, MPI_INT, sourceNode, 0, MPI_COMM_WORLD, &status); } } } else if(rank>0 && rank<procnum) { //Receive data distributed from master node MPI_Recv(&offset, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); for (j=0;j<avgsize;j++) { MPI_Recv(&simData[offset+j].prey, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); MPI_Recv(&simData[offset+j].predator0, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); MPI_Recv(&simData[offset+j].predator1, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); } //doing stepLV for every slave processor/node for (j=0;j<avgsize;j++) { stepLV(simData+offset+j, &t0, &dt, lvParam, MPI_FLOAT, MPI_COMM_WORLD); } //printf("---5---"); MPI_Send(&offset, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); for (j=0;j<avgsize;j++) { MPI_Send(&simData[offset+j].prey, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); MPI_Send(&simData[offset+j].predator0, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); MPI_Send(&simData[offset+j].predator1, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } } //MPI_Buffer_detach( &buff, &b_size ); return; } //particle filter: output new estimated lvstate and its likehood void pfPropPar(lvstate ppstate[16], obsdata *myobsdata, double *lvParam, double *ll, MPI_Datatype datatype, MPI_Comm comm) { int rank, procnum; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD, &procnum); typedef struct { lvstate *vpptuple; } stateVec; int i, j, k, l; double timeUnit = 2.0; int deltaTimeUnit = 1; double delTime = timeUnit * deltaTimeUnit; double curTime = 0.0; double lw[SAMPLENUM]; double w[SAMPLENUM]; double wSum; double maxLw; double likehood = 0.0; unsigned int rows[SAMPLENUM]; lvstate *simData = malloc(SAMPLENUM * sizeof(lvstate)); if (simData == NULL) { printf("Fail to initiate simData...EXIT!"); goto freeMem; } else { memset(simData, 0, SAMPLENUM * sizeof(lvstate)); } //initiate state: get simulated prey-predator tuple stateVec *myStateVec = malloc(obsnum * sizeof(stateVec)); if (myStateVec == NULL) { printf("Fail to initiate myStateVec...Exit"); goto freeMem; } memset(myStateVec, 0, obsnum * sizeof(stateVec)); stateVec *tempStateVec = malloc(obsnum * sizeof(stateVec)); if (tempStateVec == NULL) { printf("Fail to initiate tempStateVec...Exit"); goto freeMem; } memset(tempStateVec, 0, obsnum * sizeof(stateVec)); if (rank==0) { simPrior(simData, MPI_FLOAT, MPI_COMM_WORLD); *ll = 0.0; if ((tempStateVec + 0)->vpptuple == NULL) { (tempStateVec + 0)->vpptuple = (lvstate*) malloc( SAMPLENUM * sizeof(lvstate)); if ((tempStateVec + 0)->vpptuple == NULL) { printf("Fail to initiate myStateVec->vpptuple...Exit"); goto freeMem; } } memset(tempStateVec[0].vpptuple, 0, SAMPLENUM * sizeof(lvstate)); for (j = 0; j < SAMPLENUM; j++) { ((tempStateVec + 0)->vpptuple + j)->predator0 = (simData + j)->predator0; ((tempStateVec + 0)->vpptuple + j)->predator1 = (simData + j)->predator1; ((tempStateVec + 0)->vpptuple + j)->prey = (simData + j)->prey; } } for (i = 1; i < obsnum; i++) { curTime = myobsdata[i-1].time; wSum = 0.0; if (rank==0) { if ((tempStateVec + i)->vpptuple == NULL) { (tempStateVec + i)->vpptuple = (lvstate*) malloc( SAMPLENUM * sizeof(lvstate)); if ((tempStateVec + i)->vpptuple == NULL) { printf("Fail to initiate myStateVec->vpptuple...Exit"); goto freeMem; } memset((tempStateVec + i)->vpptuple, 0, SAMPLENUM * sizeof(lvstate)); } } mpiStepLV(simData, &curTime, &delTime, lvParam, MPI_FLOAT, MPI_COMM_WORLD); if (rank==0) { for (j = 0; j < SAMPLENUM; j++) { ((tempStateVec + i)->vpptuple + j)->predator0 = (simData + j)->predator0; ((tempStateVec + i)->vpptuple + j)->predator1 = (simData + j)->predator1; ((tempStateVec + i)->vpptuple + j)->prey = (simData + j)->prey; lw[j] = obsLik(((tempStateVec + i)->vpptuple + j), myobsdata[i].rawdata); } //get the max line weight for (j = 0; j < SAMPLENUM; j++) { if (j == 0) { maxLw = lw[0]; } else { if (lw[j] > maxLw) { maxLw = lw[j]; } } } //normalize the line wight and output list w[] for (l = 0; l < SAMPLENUM; l++) { w[l] = exp(lw[l] - maxLw); wSum = wSum + w[l]; } rowsample(rows, w); //reorganize the vector with only keeping the rows in 'rows' for (k = 0; k <= i; k++) { if ((myStateVec + k)->vpptuple == NULL) { //printf("init mystatevec \n"); (myStateVec + k)->vpptuple = (lvstate*) malloc( SAMPLENUM * sizeof(lvstate)); if ((myStateVec + k)->vpptuple == NULL) { printf("Fail to initiate myStateVec->vpptuple...Exit"); goto freeMem; } } for (j = 0; j < SAMPLENUM; j++) { ((myStateVec + k)->vpptuple + j)->predator0 = ((tempStateVec + k)->vpptuple + rows[j])->predator0; ((myStateVec + k)->vpptuple + j)->predator1 = ((tempStateVec + k)->vpptuple + rows[j])->predator1; ((myStateVec + k)->vpptuple + j)->prey = ((tempStateVec + k)->vpptuple + rows[j])->prey; } for (j = 0; j < SAMPLENUM; j++) { ((tempStateVec + k)->vpptuple + j)->predator0 = ((myStateVec + k)->vpptuple + j)->predator0; ((tempStateVec + k)->vpptuple + j)->predator1 = ((myStateVec + k)->vpptuple + j)->predator1; ((tempStateVec + k)->vpptuple + j)->prey = ((myStateVec + k)->vpptuple + j)->prey; } } for (j = 0; j < SAMPLENUM; j++) { simData[j].predator0 = ((myStateVec + i)->vpptuple + j)->predator0; simData[j].predator1 = ((myStateVec + i)->vpptuple + j)->predator1; simData[j].prey = ((myStateVec + i)->vpptuple + j)->prey; } likehood = likehood + maxLw + log(wSum/SAMPLENUM); //printf("likehood: %f, maxLW: %f, mean: %f, wSum: %f\n", likehood, maxLw, log(wSum/SAMPLENUM), wSum); *ll = likehood; rows[SAMPLENUM] = 0; } } if (rank==0) { for (i = 0; i < obsnum; i++) { ppstate[i].prey = ((myStateVec + i)->vpptuple + 0)->prey; ppstate[i].predator0 = ((myStateVec + i)->vpptuple + 0)->predator0; ppstate[i].predator1 = ((myStateVec + i)->vpptuple + 0)->predator1; } } freeMem: if (myStateVec != NULL) { for (i = 0; ((myStateVec + i)->vpptuple != NULL) && i < obsnum; i++) { free((myStateVec + i)->vpptuple); (myStateVec + i)->vpptuple = NULL; } free(myStateVec); myStateVec = NULL; } if (tempStateVec != NULL) { for (i = 0; NULL != (tempStateVec + i)->vpptuple && i < obsnum; i++) { free((tempStateVec + i)->vpptuple); (tempStateVec + i)->vpptuple = NULL; } free(tempStateVec); tempStateVec = NULL; } if (simData != NULL) { free(simData); simData = NULL; } } void stepLV(lvstate *state, double *t0p, double *dtp, double *lvParam, MPI_Datatype datatype, MPI_Comm comm) { int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD, &procnum); register double t0 = *t0p, dt = *dtp, t; register double h0, h1, h2, h3, h4, h5, u, l0, l1, l2, l3, l4; register int prey, predator0, predator1; prey = state->prey; predator0 = state->predator0; predator1 = state->predator1; l0 = lvParam[0]; l1 = lvParam[1]; l2 = lvParam[2]; l3 = lvParam[3]; l4 = lvParam[4]; while (dt > 0) { h1 = l0 * prey; h2 = l1 * prey * predator0; h3 = l2 * prey * predator1; h4 = l3 * predator0; h5 = l4 * predator1; h0 = h1 + h2 + h3 + h4 + h5; if ((h0 < (1e-10)) || (prey >= 1000000)) t = 1e99; else { t = gsl_ran_exponential(r, 1/h0); } if (t > dt) { state->prey = prey; state->predator0 = predator0; state->predator1 = predator1; return; } else { u = gsl_rng_uniform(r); if (u < (h1 / h0)) { prey = prey + 1; } else if (u < ((h1 + h2) / h0)) { prey = prey - 1; predator0 = predator0 + 1; } else if (u < ((h1 + h2 + h3) / h0)) { prey = prey - 1; predator1 = predator1 + 1; } else if (u < ((h1 + h2 + h3 + h4) / h0)) { predator0 = predator0 - 1; } else { predator1 = predator1 - 1; } dt = dt - t; } } return; } //mcmc process void runPmmhPath(int its, double *lvParam, double *obslik, lvstate ppstate[16], obsdata *myobsdata, MPI_Datatype datatype, MPI_Comm comm) { int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD, &procnum); int i, j; double propParam[5]; double curParam[5]; double ll; double propMll, curMll = -1e99; lvstate curPath[obsnum]; lvstate propPath[obsnum]; FILE *fp = fopen("mcmc-out.txt", "wab+"); if (fp == NULL) { printf("file is null.\n"); return; } if (rank==0) { fprintf(fp, "th1,th2,th3,th4,th5,"); for (i = 0; i <= 30; i++) { if ((i % 2) == 0) { if (i == 30) { fprintf(fp, "x%i,y0_%i,y1_%i", i, i, i); } else { fprintf(fp, "x%i,y0_%i,y1_%i,", i, i, i); } } } fprintf(fp, "\n"); memcpy(curPath, ppstate, sizeof(lvstate) * obsnum); memcpy(curParam, lvParam, sizeof(double) * 5); } for (i = its; i > 0; i--) { memcpy(propParam, curParam, sizeof(double) * 5); peturb(propParam, MPI_FLOAT, MPI_COMM_WORLD); pfPropPar(propPath, myobsdata, propParam, &ll, MPI_FLOAT, MPI_COMM_WORLD); if (rank==0) { //printf("likelihood %f, parameter %f, %f, %f, %f, %f:\n", ll, propParam[0], propParam[1], propParam[2], propParam[3], propParam[4]); propMll = ll; if (log(gsl_ran_flat(r, 0.0, 1.0)) < (propMll - curMll)) { curMll = propMll; memcpy(curParam, propParam, sizeof(double) * 5); memcpy(curPath, propPath, sizeof(lvstate) * obsnum); } } if (rank==0) { printf("run for the %ith iteration.\n", i); //write current parameters and state sequence into output fprintf(fp, "%f,%f,%f,%f,%f,", curParam[0], curParam[1], curParam[2], curParam[3], curParam[4]); for (j = 0; j < obsnum; j++) { if (j == (obsnum - 1)) { fprintf(fp, "%i,%i,%i", curPath[j].prey, curPath[j].predator0, curPath[j].predator1); } else { fprintf(fp, "%i,%i,%i,", curPath[j].prey, curPath[j].predator0, curPath[j].predator1); } } fprintf(fp, "\n"); printf("end for the %ith iteration.\n", i); } } fclose(fp); } void rowsample(int *rows, double *w) { gsl_ran_discrete_t * grdp; int row; int i; grdp = gsl_ran_discrete_preproc(SAMPLENUM, w); for (i = 0; i < SAMPLENUM; i++) { row = (int) gsl_ran_discrete(r, grdp); rows[i] = row; } gsl_ran_discrete_free(grdp); return; } void peturb(double *lvParam, MPI_Datatype datatype, MPI_Comm comm) { int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); if (rank==0) { const double SIGMA = 0.035; lvParam[0] = lvParam[0] * exp(gsl_ran_gaussian(r, SIGMA)); lvParam[1] = lvParam[1] * exp(gsl_ran_gaussian(r, SIGMA)); lvParam[2] = lvParam[2] * exp(gsl_ran_gaussian(r, SIGMA)); lvParam[3] = lvParam[3] * exp(gsl_ran_gaussian(r, SIGMA)); lvParam[4] = lvParam[4] * exp(gsl_ran_gaussian(r, SIGMA)); } return; } //to get the prior simulate value of prey and predator void simPrior(lvstate *simData, MPI_Datatype datatype, MPI_Comm comm) { int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); int i; const double PREY_MEAN = 800.0; const double PRED0_MEAN = 500.0; const double PRED1_MEAN = 600.0; for (i = 0; i < SAMPLENUM; i++) { simData[i].prey = gsl_ran_poisson(r, PREY_MEAN); simData[i].predator0 = gsl_ran_poisson(r, PRED0_MEAN); simData[i].predator1 = gsl_ran_poisson(r, PRED1_MEAN); } return; } void runModel(int its, MPI_Datatype datatype, MPI_Comm comm) { int rank; MPI_Comm_rank(MPI_COMM_WORLD,&rank); obsnum = 16; obsdata myobsdata[obsnum]; lvstate mylvstate[obsnum]; double ll = 0.0; double lvParam[5] = { 10.0, 0.005, 0.0025, 6.0, 3.0 }; //produce time list(with even number in) if (rank==0) { int i; int j = 0; for (i = 0; i <= 30; i++) { if ((i % 2) == 0) { myobsdata[j].time = (double) i; j++; } } //read external txt file FILE *file = fopen("LV12.txt", "r"); char line[1024]; if (file == NULL) { printf("file is null.\n"); exit(EXIT_FAILURE); } if (file != NULL) { i = 0; while (fgets(line, 1024, file)) { myobsdata[i].rawdata = atof(line); i++; } fclose(file); } } runPmmhPath(its, lvParam, &ll, mylvstate, myobsdata, MPI_FLOAT, MPI_COMM_WORLD); return; } int main(int argc,char *argv[]) { int its, i, rank; double x, can, a, alpha, Nsum, mytime, maxtime, mintime; clock_t begin, end; double time_spent; begin = clock(); const gsl_rng_type * T; long seed; gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc(T); seed = time(NULL) * getpid(); // set seed gsl_rng_set(r, seed); MPI_Init(NULL, NULL); MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD, &procnum); if (argc == 1) { its = 50; } else { its = atoi(argv[1]); } runModel(its, MPI_FLOAT, MPI_COMM_WORLD); if (rank==0) { printf("Starting lv-pmcmc ...\n"); printf("Running for %i", its); printf(" iterations, Done.\n"); } gsl_rng_free (r); // here, do your time-consuming job end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; if (rank==0){ printf("Time consuming in total is %f\n", time_spent); } MPI_Finalize(); return(EXIT_SUCCESS); } */
{ "alphanum_fraction": 0.6250235656, "avg_line_length": 26.3897180763, "ext": "c", "hexsha": "49ee4774541cb3ed43323953ccdb7b0b939d2862", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "scania/scania-pmcmc", "max_forks_repo_path": "MPI/main/bayeskitMPILV2.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "scania/scania-pmcmc", "max_issues_repo_path": "MPI/main/bayeskitMPILV2.c", "max_line_length": 136, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "scania/scania-pmcmc", "max_stars_repo_path": "MPI/main/bayeskitMPILV2.c", "max_stars_repo_stars_event_max_datetime": "2018-01-31T04:07:03.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-31T04:07:03.000Z", "num_tokens": 5694, "size": 15913 }
// The MIT License (MIT) // // Copyright (c) 2018 Mateusz Pusz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <gsl/gsl-lite.hpp> #include <units/bits/external/hacks.h> #include <utility> inline constexpr struct validated_tag { } validated; template<std::movable T, std::predicate<T> Validator> class validated_type { T value_; public: using value_type = T; static constexpr bool validate(const T& value) { return Validator()(value); } constexpr explicit validated_type(const T& value) noexcept(std::is_nothrow_copy_constructible_v<T>) requires std::copyable<T> : value_(value) { gsl_Expects(validate(value_)); } constexpr explicit validated_type(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>) : value_(std::move(value)) { gsl_Expects(validate(value_)); } constexpr validated_type(const T& value, validated_tag) noexcept(std::is_nothrow_copy_constructible_v<T>) requires std::copyable<T> : value_(value) { } constexpr validated_type(T&& value, validated_tag) noexcept(std::is_nothrow_move_constructible_v<T>) : value_(std::move(value)) { } constexpr explicit(false) operator T() const noexcept(std::is_nothrow_copy_constructible_v<T>) requires std::copyable<T> { return value_; } constexpr T& value() & noexcept = delete; constexpr const T& value() const& noexcept { return value_; } constexpr T&& value() && noexcept { return std::move(value_); } constexpr const T&& value() const&& noexcept { return std::move(value_); } bool operator==(const validated_type&) const requires std::equality_comparable<T> = default; auto operator<=>(const validated_type&) const requires std::three_way_comparable<T> = default; };
{ "alphanum_fraction": 0.7339548225, "avg_line_length": 34.012195122, "ext": "h", "hexsha": "bf44bbbcaa948ba002d7e196223e9c36d3d48803", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8c0f9d4f8ef712633d4709bac1cbd00b71b50570", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chiphogg/units", "max_forks_repo_path": "example/include/validated_type.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "8c0f9d4f8ef712633d4709bac1cbd00b71b50570", "max_issues_repo_issues_event_max_datetime": "2022-02-24T01:18:54.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-24T01:18:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chiphogg/units", "max_issues_repo_path": "example/include/validated_type.h", "max_line_length": 107, "max_stars_count": null, "max_stars_repo_head_hexsha": "8c0f9d4f8ef712633d4709bac1cbd00b71b50570", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chiphogg/units", "max_stars_repo_path": "example/include/validated_type.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 640, "size": 2789 }
#ifndef __UTIL_H #define __UTIL_H #include <glib.h> #include <gsl/gsl_matrix.h> struct _CLArgumentEntry { GString *block; char *label; }; struct _LabeledMatrix { gsl_matrix *mat; char **labels1; char **labels2; }; typedef struct _LabeledMatrix LabeledMatrix ; typedef struct _CLArgumentEntry CLArgumentEntry ; char *complearn_make_temp_dir_name(void); char *complearn_make_temp_dir(void); int make_directory(const char *name); int complearn_make_directory_if_necessary(const char *name); GString *complearn_read_whole_file(const char *fname); int complearn_count_strings(const char * const * str); int complearn_remove_directory_recursively(const char *dirname, int f_err_out); GString *complearn_read_whole_file_ptr(FILE *fp); GString *complearn_read_whole_file_io(GIOChannel *gio); GSList *complearn_read_directory_of_files(const char *dirname); GSList *complearn_read_list_of_files(const char *filename); GSList *complearn_read_list_of_strings(const char *filename); gsl_matrix *complearn_average_matrix(gsl_matrix *a); gsl_matrix *complearn_svd_project(gsl_matrix *a); CLArgumentEntry *complearn_new_arg(GString *block, const char *label); int complearn_get_pid(void); char *complearn_get_hostname(); char ** complearn_dupe_strings(const char * const * str); char ** complearn_fix_labels(char **inp); char *complearn_make_temp_file_name(void); char *complearn_chdir(const char *newdir); int complearn_write_file(const char *fname, const GString *f); void complearn_mrbreaker(void); #endif
{ "alphanum_fraction": 0.8092715232, "avg_line_length": 32.1276595745, "ext": "h", "hexsha": "ec0c8ba6de675f7de21fc27b4158e8b72ed64f56", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "rudi-cilibrasi/classic-complearn", "max_forks_repo_path": "src/complearn/util.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z", "max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "rudi-cilibrasi/classic-complearn", "max_issues_repo_path": "src/complearn/util.h", "max_line_length": 79, "max_stars_count": 2, "max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "rudi-cilibrasi/classic-complearn", "max_stars_repo_path": "src/complearn/util.h", "max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z", "num_tokens": 389, "size": 1510 }
#pragma once #include <array> #include <gsl/span> #include <sam.h> namespace mcu { #define EEPROM [[gnu::section(".eeprom")]] class FlashEEPROM { public: FlashEEPROM() = delete; template <typename T> static void write(const T* flashAddress, const T& src) noexcept { write(flashAddress, gsl::span(&src, 1)); } template <typename T> static T read(const T* flashAddress) noexcept { T result; read(flashAddress, gsl::span(&result, 1)); return result; } template <typename T> static void write(const T* flashAddress, gsl::span<const T> src) noexcept { write(reinterpret_cast<const std::byte*>(flashAddress), gsl::as_bytes(src)); } template <typename T> static void read(const T* flashAddress, gsl::span<T> dst) noexcept { read(reinterpret_cast<const std::byte*>(flashAddress), gsl::as_writable_bytes(dst)); } static void write(const std::byte* flashAddress, gsl::span<const std::byte> src) noexcept; static void read(const std::byte* flashAddress, gsl::span<std::byte> dst) noexcept; static void commit() noexcept; static bool needsCommit() noexcept { return cacheDirty; } private: using Page = std::array<unsigned, FLASH_PAGE_SIZE / sizeof(unsigned)>; using Row = std::array<Page, 4>; static constexpr size_t RowSize = sizeof(Row); static constexpr uintptr_t RowOffsetMask = sizeof(Row) - 1; union Cache { std::array<std::byte, sizeof(Row)> bytes; Row pages; }; static Cache cache; static Row* cacheTag; static bool cacheDirty; static void cacheRow(Row* row) noexcept; static void copyPage(const Page& src, Page& dst) noexcept; }; } // namespace mcu
{ "alphanum_fraction": 0.7134866377, "avg_line_length": 24.7538461538, "ext": "h", "hexsha": "df76f5232c4201504f94ac9746c8d90259e36055", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dachsei/platform-samd20", "max_forks_repo_path": "include/flash_eeprom.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dachsei/platform-samd20", "max_issues_repo_path": "include/flash_eeprom.h", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "520ecaefb0a0c1b92be281d5834f44e927995190", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dachsei/platform-samd20", "max_stars_repo_path": "include/flash_eeprom.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 420, "size": 1609 }
/* Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com> Licensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <cblas.h> #include "morn_tensor.h" struct TensorResizePara { MLayer *prev; int height; int width; int res_valid; }; void *mTensorResizePara(MList *ini,char *name) { struct TensorResizePara *para = (struct TensorResizePara *)mMalloc(sizeof(struct TensorResizePara)); para->prev = mNetworkLayer(ini,mINIRead(ini,name,"prev")); mException((para->prev == NULL),EXIT,"invalid prev"); para->res_valid = (strcmp("Input",mLayerType(para->prev))!=0); para->height= DFLT; mINIRead(ini,name,"height","%d",&(para->height)); para->width = DFLT; mINIRead(ini,name,"width" ,"%d",&(para->width )); return para; } struct HandleTensorResize { int *lx; int *ly; float *wx; float *wy; }; void endTensorResize(void *info) { struct HandleTensorResize *handle = (struct HandleTensorResize *)info; if(handle->lx !=NULL) mFree(handle->lx); if(handle->ly !=NULL) mFree(handle->ly); if(handle->wx !=NULL) mFree(handle->wx); if(handle->wy !=NULL) mFree(handle->wy); } #define HASH_TensorResize 0xb6f42d3a void TensorResizeSet(MLayer *layer) { if(layer->state != DFLT) return; struct TensorResizePara *para = (struct TensorResizePara *)(layer->para); MTensor *in = para->prev->tns; MTensor *res= para->prev->res; MTensor *out= layer->tns; MHandle *hdl=mHandle(out,TensorResize); struct HandleTensorResize *handle = (struct HandleTensorResize *)(hdl->handle); if(para->height<=0) para->height= in->height; if(para->width <=0) para->width = in->width; mTensorRedefine(out,in->batch,in->channel,para->height,para->width,NULL); if(morn_network_flag==MORN_TRAIN) { if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,in->data); else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL); } if(handle->lx !=NULL) {mFree(handle->lx);} handle->lx=(int *)mMalloc(para->width *sizeof(int)); if(handle->ly !=NULL) {mFree(handle->ly);} handle->ly=(int *)mMalloc(para->height*sizeof(int)); if(handle->wx !=NULL) {mFree(handle->wx);} handle->wx=(float *)mMalloc(para->width *sizeof(float)); if(handle->wy !=NULL) {mFree(handle->wy);} handle->wy=(float *)mMalloc(para->height*sizeof(float)); float kx = (float)(in->width)/(float)(out->width); for(int i=0;i<out->width;i++) { float l=kx*((float)i-0.5); if(l<0) l=0.0f;else if(l>=in->width-1) l=(float)(in->width)-1.00001; handle->lx[i] = (int)l; handle->wx[i] = (float)(handle->lx[i]+1)-l; } float ky = (float)(in->height)/(float)(out->height); for(int i=0;i<out->height;i++) { float l=ky*((float)i-0.5); if(l<0) l=0.0f;else if(l>=in->height-1) l=(float)(in->height)-1.00001; handle->ly[i] = (int)l; handle->wy[i] = (float)(handle->ly[i]+1)-l; } hdl->valid = 1; } void mTensorResizeForward(MLayer *layer) { mException(INVALID_POINTER(layer),EXIT,"invalid input"); mException(strcmp("Resize",mLayerType(layer)),EXIT,"invalid layer type"); struct TensorResizePara *para = (struct TensorResizePara *)(layer->para); MTensor *in = para->prev->tns; MTensor *out=layer->tns; TensorResizeSet(layer); MHandle *hdl=mHandle(out,TensorResize); struct HandleTensorResize *handle = (struct HandleTensorResize *)(hdl->handle); int in_size = in->width* in->height; int out_size =out->width*out->height; for(int h=0;h<out->height;h++)for(int w=0;w<out->width;w++) { int out_idx = h*out->width+w; int in_idx1 =(handle->ly[h] )*in->width + (handle->lx[w] ); int in_idx2 =(handle->ly[h] )*in->width + (handle->lx[w]+1); int in_idx3 =(handle->ly[h]+1)*in->width + (handle->lx[w] ); int in_idx4 =(handle->ly[h]+1)*in->width + (handle->lx[w]+1); float w1 = ( handle->wy[h])*( handle->wx[w]); float w2 = ( handle->wy[h])*(1.0-handle->wx[w]); float w3 = (1.0-handle->wy[h])*( handle->wx[w]); float w4 = (1.0-handle->wy[h])*(1.0-handle->wx[w]); for(int b=0;b<in->batch;b++)for(int c=0;c<in->channel;c++) { out->data[b][c*out_size+out_idx] = in->data[b][c*in_size+in_idx1]*w1 +in->data[b][c*in_size+in_idx2]*w2 +in->data[b][c*in_size+in_idx3]*w3 +in->data[b][c*in_size+in_idx4]*w4; } } layer->state = MORN_FORWARD; } void mTensorResizeBackward(MLayer *layer) { mException(INVALID_POINTER(layer),EXIT,"invalid input"); mException(strcmp("Resize",mLayerType(layer)),EXIT,"invalid layer type"); struct TensorResizePara *para = (struct TensorResizePara *)(layer->para); if(para->res_valid==0) return; MTensor *res= para->prev->res; MTensor *out= layer->res; MHandle *hdl=mHandle(layer->tns,TensorResize); struct HandleTensorResize *handle = (struct HandleTensorResize *)(hdl->handle); mException((hdl->valid == 0),EXIT,"no forward operate"); int in_size =res->width*res->height; int out_size =out->width*out->height; if(para->prev->state == MORN_FORWARD) { for(int b=0;b<res->batch;b++) memset(res->data[b],0,in_size*res->channel*sizeof(float)); para->prev->state = MORN_BACKWARD; } for(int h=0;h<out->height;h++)for(int w=0;w<out->width;w++) { int out_idx = h*out->width+w; int in_idx1 =(handle->ly[h] )*res->width + (handle->lx[w] ); int in_idx2 =(handle->ly[h] )*res->width + (handle->lx[w]+1); int in_idx3 =(handle->ly[h]+1)*res->width + (handle->lx[w] ); int in_idx4 =(handle->ly[h]+1)*res->width + (handle->lx[w]+1); float w1 = ( handle->wy[h])*( handle->wx[w]); float w2 = ( handle->wy[h])*(1.0-handle->wx[w]); float w3 = (1.0-handle->wy[h])*( handle->wx[w]); float w4 = (1.0-handle->wy[h])*(1.0-handle->wx[w]); for(int b=0;b<res->batch;b++)for(int c=0;c<res->channel;c++) { res->data[b][c*in_size+in_idx1] += out->data[b][c*out_size+out_idx]*w1; res->data[b][c*in_size+in_idx2] += out->data[b][c*out_size+out_idx]*w2; res->data[b][c*in_size+in_idx3] += out->data[b][c*out_size+out_idx]*w3; res->data[b][c*in_size+in_idx4] += out->data[b][c*out_size+out_idx]*w4; } } }
{ "alphanum_fraction": 0.5977090809, "avg_line_length": 38.9569892473, "ext": "c", "hexsha": "2cd03eb6e3eb5ce7a26c47426cb94e10d2a0fe10", "lang": "C", "max_forks_count": 35, "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z", "max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z", "max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ishine/Morn", "max_forks_repo_path": "src/deep_learning/morn_tensor_resize.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ishine/Morn", "max_issues_repo_path": "src/deep_learning/morn_tensor_resize.c", "max_line_length": 501, "max_stars_count": 121, "max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ishine/Morn", "max_stars_repo_path": "src/deep_learning/morn_tensor_resize.c", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z", "num_tokens": 2184, "size": 7246 }
#include "ridc.h" #include <stdlib.h> #include <stdio.h> #include <cmath> #include <gsl/gsl_linalg.h> #ifndef _BRUSSELATOR_H_ #define _BRUSSELATOR_H_ class Brusselator_GSL : public ODE { public: Brusselator_GSL(int my_neq, int my_nt, double my_ti, double my_tf, double my_dt) { neq = my_neq; nt = my_nt; ti = my_ti; tf = my_tf; dt = my_dt; } void rhs(double t, double *u, double *f) { /** user implemented rhs function, u'=rhs(t,u) @return (by reference) f: rhs(t,u) @param t current time step @param u solution u at time t @param f rhs(t,u) */ double A = 1.0; double B = 3.0; double alpha = 0.02; double dx = 1.0/(neq+1); int Nx = neq/2; f[0] = A+u[0]*u[0]*u[Nx] -(B+1.0)*u[0] +alpha/dx/dx*(u[1]-2*u[0]+1.0); f[Nx-1] = A+u[Nx-1]*u[Nx-1]*u[2*Nx-1] -(B+1.0)*u[Nx-1] + alpha/dx/dx*(1.0-2*u[Nx-1]+u[Nx-2]); f[Nx] = B*u[0]- u[0]*u[0]*u[Nx] + alpha/dx/dx*(u[Nx+1]-2*u[Nx]+3.0); f[2*Nx-1] = B*u[Nx-1]- u[Nx-1]*u[Nx-1]*u[2*Nx-1] + alpha/dx/dx*(3.0-2*u[2*Nx-1]+u[2*Nx-2]); for (int i=1; i<Nx-1; i++) { f[i] = A + u[i]*u[i]*u[Nx+i] -(B+1.0)*u[i] +alpha/dx/dx*(u[i+1]-2*u[i]+u[i-1]); f[Nx+i] = B*u[i]- u[i]*u[i]*u[Nx+i] + alpha/dx/dx*(u[Nx+i+1]-2*u[Nx+i]+u[Nx+i-1]); } } void step(double t, double * u, double * unew) { /** user implemented step function, for advancing the solution from t to t+dt @return (by reference) unew: solution at time t+dt @param t current time step @param u solution u at time t @param unew solution at time t+dt */ double tnew = t + dt; double NEWTON_TOL = 1.0e-14; int NEWTON_MAXSTEP = 1000; double * J; double * stepsize; double * uguess; stepsize = new double[neq]; uguess = new double[neq]; J = new double[neq*neq]; // GSL gsl_matrix_view m; gsl_vector_view b; gsl_vector *x = gsl_vector_alloc(neq); gsl_permutation *p = gsl_permutation_alloc(neq); // set initial condition for (int i=0; i<neq; i++) { uguess[i] = u[i]; } double maxstepsize; int counter=0; int * pivot = new int[neq]; while (1) { // create rhs newt(tnew,u,uguess,stepsize); // compute numerical Jacobian jac(tnew,uguess,J); m = gsl_matrix_view_array(J,neq,neq); b = gsl_vector_view_array(stepsize,neq); int s; // presumably, this is some flag info gsl_linalg_LU_decomp (&m.matrix,p,&s); gsl_linalg_LU_solve (&m.matrix,p,&b.vector, x); // check for convergence maxstepsize = 0.0; for (int i = 0; i<neq; i++) { uguess[i] = uguess[i] - x->data[i]; if (std::abs(stepsize[i])>maxstepsize) { maxstepsize = std::abs(x->data[i]); } } // if update sufficiently small enough if ( maxstepsize < NEWTON_TOL) { break; } counter++; //error if too many steps if (counter > NEWTON_MAXSTEP) { fprintf(stderr,"max Newton iterations reached\n"); exit(42); } } // end Newton iteration for (int i=0; i<neq; i++) { unew[i] = uguess[i]; } delete [] pivot; delete [] uguess; delete [] stepsize; delete [] J; gsl_permutation_free (p); gsl_vector_free (x); } private: void newt(double t, double *uprev, double *uguess, double *g){ /** Helper function to compute the next Newton step for solving a system of equations @return (by reference) g how far from zero we are @param t current time step @param uguess current solution guess @param uprev solution at previous time step @param g how far from zero we are, returned by reference */ rhs(t,uguess,g); for (int i =0; i<neq; i++) { g[i] = uguess[i]-uprev[i]-dt*g[i]; } } void jac(double t, double *u, double *J){ /** Helper function to the Jacobian matrix (using finite differences) for advancing the solution from time t(n) to t(n+1) using an implicit Euler step on a system of equations @return (by reference) J the Jacobian for the Newton step @param t current time step @param u function value at the current time step @param J Jacobian, returned by reference */ double d = 1e-5; // numerical Jacobian approximation double *u1; double *f1; double *f; // need to allocate memory u1 = new double[neq]; f1 = new double[neq]; f = new double[neq]; // note, instead of using newt, use rhs for efficiency rhs(t,u,f); for (int i = 0; i<neq; i++) { for (int j = 0; j<neq; j++) { u1[j] = u[j]; } u1[i] = u1[i] + d; rhs(t,u1,f1); for (int j = 0; j<neq; j++) { J[j*neq+i] = -dt*(f1[j]-f[j])/d; } J[i*neq+i] = 1.0+J[i*neq+i]; } // need to delete memory delete [] u1; delete [] f1; delete [] f; } }; #endif // _BRUSSELATOR_H_
{ "alphanum_fraction": 0.5515880844, "avg_line_length": 25.0940594059, "ext": "h", "hexsha": "f1ac954190677774cba4bfa3699ec07180dae822", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2020-10-27T09:56:10.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-22T19:06:52.000Z", "max_forks_repo_head_hexsha": "ea911bf53d6010f8dec3dc0c0a89980713e34eb8", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ongbw/ridc", "max_forks_repo_path": "examples/brusselator_gsl/brusselator.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ea911bf53d6010f8dec3dc0c0a89980713e34eb8", "max_issues_repo_issues_event_max_datetime": "2015-08-10T21:09:44.000Z", "max_issues_repo_issues_event_min_datetime": "2015-07-27T21:14:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ongbw/ridc", "max_issues_repo_path": "examples/brusselator_gsl/brusselator.h", "max_line_length": 88, "max_stars_count": 5, "max_stars_repo_head_hexsha": "ea911bf53d6010f8dec3dc0c0a89980713e34eb8", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ongbw/ridc", "max_stars_repo_path": "examples/brusselator_gsl/brusselator.h", "max_stars_repo_stars_event_max_datetime": "2019-11-10T06:10:19.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-09T21:03:45.000Z", "num_tokens": 1721, "size": 5069 }
/* gsl_splinalg.h * * Copyright (C) 2012-2014 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_SPLINALG_H__ #define __GSL_SPLINALG_H__ #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_spmatrix.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* iteration solver type */ typedef struct { const char *name; void * (*alloc) (const size_t n, const size_t m); int (*iterate) (const gsl_spmatrix *A, const gsl_vector *b, const double tol, gsl_vector *x, void *); double (*normr)(const void *); void (*free) (void *); } gsl_splinalg_itersolve_type; typedef struct { const gsl_splinalg_itersolve_type * type; double normr; /* current residual norm || b - A x || */ void * state; } gsl_splinalg_itersolve; /* available types */ GSL_VAR const gsl_splinalg_itersolve_type * gsl_splinalg_itersolve_gmres; /* * Prototypes */ gsl_splinalg_itersolve * gsl_splinalg_itersolve_alloc(const gsl_splinalg_itersolve_type *T, const size_t n, const size_t m); void gsl_splinalg_itersolve_free(gsl_splinalg_itersolve *w); const char *gsl_splinalg_itersolve_name(const gsl_splinalg_itersolve *w); int gsl_splinalg_itersolve_iterate(const gsl_spmatrix *A, const gsl_vector *b, const double tol, gsl_vector *x, gsl_splinalg_itersolve *w); double gsl_splinalg_itersolve_normr(const gsl_splinalg_itersolve *w); __END_DECLS #endif /* __GSL_SPLINALG_H__ */
{ "alphanum_fraction": 0.7111289675, "avg_line_length": 31.1125, "ext": "h", "hexsha": "265b6ae60b659991dd6f0a242ee354bae9476373", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/gsl_splinalg.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/splinalg/gsl_splinalg.h", "max_line_length": 81, "max_stars_count": 7, "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_splinalg.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 645, "size": 2489 }
// Copyright [1999-2017] EMBL-European Bioinformatics Institute // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> #include <math.h> #include <gsl/gsl_cdf.h> #include "multiSet.h" typedef struct setComparisonData_st { Multiset * multi; } SetComparisonData; void SetComparisonSeek(WiggleIterator * iter, const char * chrom, int start, int finish) { SetComparisonData * data = (SetComparisonData* ) iter->data; seekMultiset(data->multi, chrom, start, finish); pop(iter); } //////////////////////////////////////////////////////// // T-test //////////////////////////////////////////////////////// void TTestReductionPop(WiggleIterator * wi) { if (wi->done) return; SetComparisonData * data = (SetComparisonData *) wi->data; Multiset * multi = data->multi; if (multi->done) { wi->done = true; return; } // Go to first position where both of the sets have at least one value while (!multi->inplay[0] || !multi->inplay[1]) { popMultiset(multi); if (multi->done) { wi->done = true; return; } } wi->chrom = multi->chrom; wi->start = multi->start; wi->finish = multi->finish; // Compute measurements double sum1, sum2, sumSq1, sumSq2; int count1, count2; int index; sum1 = sum2 = 0; sumSq1 = sumSq2 = 0; count1 = multi->multis[0]->count; count2 = multi->multis[1]->count; for (index = 0; index < multi->multis[0]->count; index++) { if (multi->multis[0]->inplay[index]) { sum1 += multi->values[0][index]; sumSq1 += multi->values[0][index] * multi->values[0][index]; } } for (index = 0; index < multi->multis[1]->count; index++) { if (multi->multis[1]->inplay[index]) { sum2 += multi->values[1][index]; sumSq2 += multi->values[1][index] * multi->values[1][index]; } } // To avoid divisions by 0: if (count1 == 0 || count2 == 0) { wi->value = NAN; popMultiset(multi); return; } double mean1 = sum1 / count1; double mean2 = sum2 / count2; double meanSq1 = sumSq1 / count1; double meanSq2 = sumSq2 / count2; double var1 = meanSq1 - mean1 * mean1; double var2 = meanSq2 - mean2 * mean2; // To avoid divisions by 0: if (var1 + var2 == 0) { wi->value = NAN; popMultiset(multi); return; } // T-statistic double t = (mean1 - mean2) / sqrt(var1 / count1 + var2 / count2); if (t < 0) t = -t; // Degrees of freedom double nu = (var1 / count1 + var2 / count2) * (var1 / count1 + var2 / count2) / ((var1 * var1) / (count1 * count1 * (count1 - 1)) + (var2 * var2) / (count2 * count2 * (count2 - 1))); // P-value wi->value = 2 * gsl_cdf_tdist_Q(t, nu); // Update inputs popMultiset(multi); } WiggleIterator * TTestReduction(Multiset * multi) { SetComparisonData * data = (SetComparisonData *) calloc(1, sizeof(SetComparisonData)); if (multi->count != 2 || multi->multis[0]->count < 3 || multi->multis[1]->count < 3) { puts("The t-test function only works for two sets with enough elements to compute variance"); exit(1); } data->multi = multi; return newWiggleIterator(data, &TTestReductionPop, &SetComparisonSeek, NAN); } //////////////////////////////////////////////////////// // F-test //////////////////////////////////////////////////////// typedef struct ftestData_st { Multiset * multi; int * counts; double * means; int total_count; } FTestData; void FTestSeek(WiggleIterator * iter, const char * chrom, int start, int finish) { FTestData * data = (FTestData* ) iter->data; seekMultiset(data->multi, chrom, start, finish); pop(iter); } void FTestReductionPop(WiggleIterator * wi) { if (wi->done) return; FTestData * data = (FTestData *) wi->data; Multiset * multi = data->multi; if (multi->done) { wi->done = true; return; } // Go to first position where both of the sets have at least one value while (!multi->inplay[0] || !multi->inplay[1]) { popMultiset(multi); if (multi->done) { wi->done = true; return; } } wi->chrom = multi->chrom; wi->start = multi->start; wi->finish = multi->finish; // Compute means double mean = 0; int groups = multi->count; int index, index2; for (index = 0; index < groups; index++) { Multiplexer * mplx = multi->multis[index]; data->means[index] = 0; for (index2 = 0; index < mplx->count; index++) { if (mplx->inplay[index2]) data->means[index] += mplx->values[index2]; else data->means[index] += mplx->iters[index2]->default_value; } mean += data->means[index]; data->means[index] /= data->counts[index]; } mean /= data->total_count; double inter = 0; double intra = 0; for (index = 0; index < groups; index++) { Multiplexer * mplx = multi->multis[index]; inter += mplx->count * (data->means[index] - mean) * (data->means[index] - mean); for (index2 = 0; index < mplx->count; index++) { if (mplx->inplay[index2]) intra += (mplx->values[index2] - data->means[index]) * (mplx->values[index2] - data->means[index]); else intra += (mplx->iters[index2]->default_value - data->means[index]) * (mplx->iters[index2]->default_value - data->means[index]); } } // F-statistic inter /= groups - 1; intra /= data->total_count - groups; double f = inter / intra; // P-value wi->value = 2 * gsl_cdf_fdist_Q(f, multi->count - 1, data->total_count - multi->count); // Update inputs popMultiset(multi); } WiggleIterator * FTestReduction(Multiset * multi) { FTestData * data = (FTestData *) calloc(1, sizeof(FTestData)); data->multi = multi; data->means = calloc(multi->count, sizeof(double)); data->counts = calloc(multi->count, sizeof(int)); int index; for (index = 0; index < multi->count; index++) { data->counts[index] = multi->multis[index]->count; data->total_count += data->counts[index]; } return newWiggleIterator(data, &FTestReductionPop, &FTestSeek, NAN); } //////////////////////////////////////////////////////// // Mann-Whitney U (Wilcoxon rank-sum test) //////////////////////////////////////////////////////// typedef struct valueSetPair_st { double value; bool set; } ValueSetPair; typedef struct mwuData_st { Multiset * multi; int n1; int n2; int N; // Pre-allocated table for sorting ValueSetPair * rankingTable; // For normal approximation bool normalApproximation; double mu_U, sigma_U; } MWUData; void MWUSeek(WiggleIterator * iter, const char * chrom, int start, int finish) { MWUData * data = (MWUData* ) iter->data; seekMultiset(data->multi, chrom, start, finish); pop(iter); } static int compareValueSetPairs(const void * A, const void * B) { ValueSetPair * vspA = (ValueSetPair *) A; ValueSetPair * vspB = (ValueSetPair *) B; if (vspA->value < vspB->value) return -1; if (vspA->value > vspB->value) return 1; return 0; } void MWUReductionPop(WiggleIterator * wi) { if (wi->done) return; MWUData * data = (MWUData *) wi->data; Multiset * multi = data->multi; if (multi->done) { wi->done = true; return; } // Go to first position where both of the sets have at least one value while (!multi->inplay[0] || !multi->inplay[1]) { popMultiset(multi); if (multi->done) { wi->done = true; return; } } wi->chrom = multi->chrom; wi->start = multi->start; wi->finish = multi->finish; // Compute measurements int index; ValueSetPair * vspPtr = data->rankingTable; for (index = 0; index < data->n1; index++) { if (multi->multis[0]->inplay[index]) vspPtr->value = multi->values[0][index]; else vspPtr->value = multi->multis[0]->iters[index]->default_value; if (isnan(vspPtr->value)) { wi->value = NAN; popMultiset(multi); return; } vspPtr->set = false; vspPtr++; } for (index = 0; index < data->n2; index++) { if (multi->multis[1]->inplay[index]) vspPtr->value = multi->values[1][index]; else vspPtr->value = multi->multis[1]->iters[index]->default_value; if (isnan(vspPtr->value)) { wi->value = NAN; popMultiset(multi); return; } vspPtr->set = true; vspPtr++; } qsort(data->rankingTable, data->N, sizeof(ValueSetPair), compareValueSetPairs); // Sum of ranks of elements of set 1 double U1 = 0; // Rolling count of elements of set 1 seen prior on the list int prev = 0; // Warns you when you have a tie with the previously visited Value-Set pairs int ties = 0; int previousTies = 0; vspPtr = data->rankingTable; for (index = 0; index < data->N && prev < data->n1; index++) { if (!vspPtr->set) { U1 += index - prev; if (ties) { // Look for ties on the table prior to the current position and after the last occurence of an element of set 1. int index2; for (index2 = index + 1; index2 < data->N && data->rankingTable[index2].value == vspPtr->value && data->rankingTable[index2].set; index2++) previousTies++; U1 -= previousTies / 2.0; U1 += (ties - previousTies) / 2.0; if (previousTies == ties) previousTies = ties = 0; } else { int index2; // Look for ties with next values for (index2 = index + 1; index2 < data->N && data->rankingTable[index2].value == vspPtr->value; index2++) if (data->rankingTable[index2].set) ties++; if (ties) U1 += ties / 2.0; } prev++; } vspPtr++; } if (data->normalApproximation) { if (U1 > data->mu_U) wi->value = 2 * erf((data->mu_U - U1) / data->sigma_U); else wi->value = 2 * erf((U1 - data->mu_U) / data->sigma_U); } // Update inputs popMultiset(multi); } WiggleIterator * MWUReduction(Multiset * multi) { MWUData * data = (MWUData *) calloc(1, sizeof(MWUData)); if (multi->count != 2 || multi->multis[0]->count == 0 || multi->multis[1]->count == 0) { puts("The Mann-Whitney U function only works for two non-empty sets"); exit(1); } data->multi = multi; data->n1 = multi->multis[0]->count; data->n2 = multi->multis[1]->count; data->N = data->n1 + data->n2; data->rankingTable = calloc(data->N, sizeof(ValueSetPair)); if (true) { // Ideally, tables could be used for small values of n1 and n2 data->normalApproximation = true; data->mu_U = data->n1 * data->n2 / 2; data->sigma_U = sqrt(data->n1 * data->n2 * (data->n1 + data->n2 + 1) / 12); } return newWiggleIterator(data, &MWUReductionPop, &MWUSeek, NAN); }
{ "alphanum_fraction": 0.6272958463, "avg_line_length": 27.1534526854, "ext": "c", "hexsha": "16f6d5dd32ac9f849ad90607ff9d835b60065fbe", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "867b6ce6fcfa7aa02c4ff647adb6e4a25744e06a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "juettemann/WiggleTools", "max_forks_repo_path": "src/setComparisons.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "867b6ce6fcfa7aa02c4ff647adb6e4a25744e06a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "juettemann/WiggleTools", "max_issues_repo_path": "src/setComparisons.c", "max_line_length": 183, "max_stars_count": null, "max_stars_repo_head_hexsha": "867b6ce6fcfa7aa02c4ff647adb6e4a25744e06a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "juettemann/WiggleTools", "max_stars_repo_path": "src/setComparisons.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3301, "size": 10617 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gbpInterpolate.h> // params is not used at the moment but we must allow for // it to meet the required ADaPS function definition void free_interpolate(void **interp, void *params) { if((*interp) != NULL) { SID_free(SID_FARG((interp_info *)(*interp))->x); SID_free(SID_FARG((interp_info *)(*interp))->y); gsl_interp_free(((interp_info *)(*interp))->interp); gsl_interp_accel_free(((interp_info *)(*interp))->accel); SID_free(SID_FARG * interp); } }
{ "alphanum_fraction": 0.6602254428, "avg_line_length": 32.6842105263, "ext": "c", "hexsha": "9956115ec58b01bf6b583f69989396569ffde763", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpInterpolate/free_interpolate.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpInterpolate/free_interpolate.c", "max_line_length": 65, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpInterpolate/free_interpolate.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 163, "size": 621 }
#include <gsl/gsl_spline.h> #include "param.h" #include "root_func.h" #include "eos_pres.h" #include "global.h" double root_func (double rho, void *params) { struct param *root_func_params = (struct param *) params; double (*pres) (double, void *); pres = &eos_pres; return (tmp_pres - pres (rho, root_func_params)); }
{ "alphanum_fraction": 0.6951219512, "avg_line_length": 21.8666666667, "ext": "c", "hexsha": "2a50fd589d383237c854cf3e55473bc5deb72bae", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_forks_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_forks_repo_name": "bcfriesen/TOV_solver", "max_forks_repo_path": "src/root_func.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_issues_repo_name": "bcfriesen/TOV_solver", "max_issues_repo_path": "src/root_func.c", "max_line_length": 59, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5288ad6972b47143e1ce57e282f516143f07b158", "max_stars_repo_licenses": [ "BSD-2-Clause-FreeBSD" ], "max_stars_repo_name": "bcfriesen/TOV_solver", "max_stars_repo_path": "src/root_func.c", "max_stars_repo_stars_event_max_datetime": "2015-11-14T02:27:58.000Z", "max_stars_repo_stars_event_min_datetime": "2015-11-14T02:27:58.000Z", "num_tokens": 91, "size": 328 }
#pragma once #include "iparam.h" #include "iparamlist.h" #include "iflag.h" #include "iarg.h" #include "iarglist.h" #include "icommand.h" #include "optioninfo.h" #include "format.h" #include <sfun/string_utils.h> #include <cmdlime/usageinfoformat.h> #include <gsl/gsl> #include <utility> #include <vector> #include <memory> #include <algorithm> #include <iomanip> namespace cmdlime::detail{ using namespace gsl; namespace str = sfun::string_utils; inline std::string adjustedToLineBreak(std::string line, std::string& text) { if (!text.empty() && !isspace(text.front())){ auto trimmedLine = str::trimFront(line); if (std::find_if(trimmedLine.begin(), trimmedLine.end(), [](auto ch){return std::isspace(ch);}) == trimmedLine.end()) return line; while(!isspace(line.back())){ text.insert(text.begin(), 1, line.back()); line.pop_back(); } } return line; } inline std::string popLine(std::string& text, std::size_t width, bool firstLine = false) { auto newLinePos = text.find('\n'); if (newLinePos != std::string::npos && newLinePos <= width){ auto line = text.substr(0, newLinePos); text.erase(text.begin(), text.begin() + static_cast<int>(newLinePos + 1)); if (!firstLine) line = str::trimFront(line); return line; } auto line = text.substr(0, width); if (text.size() < width) text.clear(); else text.erase(text.begin(), text.begin() + static_cast<int>(width)); if (!firstLine) line = str::trimFront(line); return adjustedToLineBreak(line, text); } template <typename T> inline std::vector<not_null<T*>> getParamsByOptionality(const std::vector<not_null<T*>>& params, bool isOptional) { auto result = std::vector<not_null<T*>>{}; std::copy_if(params.begin(), params.end(), std::back_inserter(result), [isOptional](auto param){return param->isOptional() == isOptional;}); return result; } template <typename T> const std::string& getName(T& option) { return option.info().name(); } template <typename T> const std::string& getType(T& option) { return option.info().type(); } template <typename T> const std::string& getDescription(T& option) { return option.info().description(); } template <FormatType formatType> class UsageInfoCreator{ public: UsageInfoCreator(std::string programName, UsageInfoFormat outputSettings, const std::vector<not_null<IParam*>>& params, const std::vector<not_null<IParamList*>>& paramLists, std::vector<not_null<IFlag*>> flags, std::vector<not_null<IArg*>> args, IArgList* argList, std::vector<not_null<ICommand*>> commands) : programName_(std::move(programName)) , params_(getParamsByOptionality(params, false)) , optionalParams_(getParamsByOptionality(params, true)) , paramLists_(getParamsByOptionality(paramLists, false)) , optionalParamLists_(getParamsByOptionality(paramLists, true)) , flags_(std::move(flags)) , args_(std::move(args)) , argList_(argList) , commands_(std::move(commands)) , outputSettings_(outputSettings) , maxOptionNameSize_(maxOptionNameLength() + outputSettings.columnsSpacing) { } std::string createDetailed() { return minimizedUsageInfo() + argsInfo() + paramsInfo() + paramListsInfo() + optionsInfo() + optionalParamListsInfo() + flagsInfo() + commandsInfo(); } std::string create() { return usageInfo(); } private: using OutputFormatter = typename Format<formatType>::outputFormatter; std::string usageInfo() { auto result = "Usage: " + programName_ + " "; if (!commands_.empty()) result += "[commands] "; for (auto arg : args_) result += OutputFormatter::argUsageName(*arg) + " "; for (auto param : params_) result += OutputFormatter::paramUsageName(*param) + " "; for (auto paramList : paramLists_) result += OutputFormatter::paramListUsageName(*paramList) + " "; for (auto param : optionalParams_) result += OutputFormatter::paramUsageName(*param) + " "; for (auto paramList : optionalParamLists_) result += OutputFormatter::paramListUsageName(*paramList) + " "; for (auto flag : flags_) result += OutputFormatter::flagUsageName(*flag) + " "; if (argList_) result += OutputFormatter::argListUsageName(*argList_); result += "\n"; return result; } std::string minimizedUsageInfo() { auto result = "Usage: " + programName_ + " "; if (!commands_.empty()) result += "[commands] "; for (auto arg : args_) result += OutputFormatter::argUsageName(*arg) + " "; for (auto param : params_) result += OutputFormatter::paramUsageName(*param) + " "; for (auto paramList : paramLists_) result += OutputFormatter::paramListUsageName(*paramList) + " "; if (!optionalParams_.empty() || !optionalParamLists_.empty()) result += "[params] "; if (!flags_.empty()) result += "[flags] "; if (argList_) result += OutputFormatter::argListUsageName(*argList_); result += "\n"; return result; } std::string paramsInfo() { auto result = std::string{"Parameters:\n"}; if (params_.empty()) return result; for (const auto& param : params_){ const auto name = OutputFormatter::paramDescriptionName(*param, outputSettings_.nameIndentation) + "\n"; result += makeConfigFieldInfo(name, getDescription(*param)); } return result; } std::string paramListsInfo() { auto result = std::string{}; if (paramLists_.empty()) return result; for (const auto paramList : paramLists_){ const auto name = OutputFormatter::paramListDescriptionName(*paramList, outputSettings_.nameIndentation) + "\n"; auto description = getDescription(*paramList); if (!description.empty()) description += "\n(multi-value)"; else description += "multi-value"; result += makeConfigFieldInfo(name, description); } return result; } std::string optionsInfo() { if (optionalParams_.empty()) return {}; auto result = std::string{}; for (const auto option : optionalParams_){ auto description = getDescription(*option); if (!description.empty()){ if (!option->defaultValue().empty()) description += "\n(optional, default: " + option->defaultValue() + ")"; else description += "\n(optional)"; } else{ if (!option->defaultValue().empty()) description += "optional, default: " + option->defaultValue(); else description += "optional"; } result += makeConfigFieldInfo(OutputFormatter::paramDescriptionName(*option, outputSettings_.nameIndentation) + "\n", description); } return result; } std::string optionalParamListsInfo() { if (optionalParamLists_.empty()) return {}; auto result = std::string{}; for (const auto option : optionalParamLists_){ auto description = getDescription(*option); if (!description.empty()){ description += "\n(multi-value, "; if (!option->defaultValue().empty()) description += "optional, default: " + option->defaultValue() + ")"; else description += "optional)"; } else{ description += "multi-value, "; if (!option->defaultValue().empty()) description += "optional, default: " + option->defaultValue(); else description += "optional"; } result += makeConfigFieldInfo(OutputFormatter::paramListDescriptionName(*option, outputSettings_.nameIndentation) + "\n", description); } return result; } std::string argsInfo() { if (args_.empty() && !argList_) return {}; auto result = std::string{"Arguments:\n"}; for (const auto arg : args_) result += makeConfigFieldInfo(OutputFormatter::argDescriptionName(*arg, outputSettings_.nameIndentation) + "\n", getDescription(*arg)); if (argList_){ auto description = getDescription(*argList_); if (!description.empty()){ description += "\n(multi-value"; if (argList_->isOptional()){ if (!argList_->defaultValue().empty()) description += ", optional, default: " + argList_->defaultValue() + ")"; else description += ", optional)"; } else description += ")"; } else{ description += "multi-value"; if (argList_->isOptional()){ if (!argList_->defaultValue().empty()) description += ", optional, default: " + argList_->defaultValue(); else description += ", optional"; } } result += makeConfigFieldInfo(OutputFormatter::argListDescriptionName(*argList_, outputSettings_.nameIndentation) + "\n", description); } return result; } std::string flagsInfo() { if (flags_.empty()) return {}; auto result = std::string{"Flags:\n"}; for (const auto flag : flags_) result += makeConfigFieldInfo(OutputFormatter::flagDescriptionName(*flag, outputSettings_.nameIndentation) + "\n", getDescription(*flag)); return result; } std::string commandsInfo() { if (commands_.empty()) return {}; auto result = std::string{"Commands:\n"}; for (const auto command : commands_){ auto nameStream = std::stringstream{}; if (outputSettings_.nameIndentation) nameStream << std::setw(outputSettings_.nameIndentation) << " "; nameStream << getName(*command) << " [options]"; result += makeConfigFieldInfo(nameStream.str(), getDescription(*command)); } return result; } int maxOptionNameLength() { auto length = 0; auto updateLength = [&length](std::string name) { auto firstLine = true; do { auto nameLine = popLine(name, 100, firstLine); length = std::max(length, static_cast<int>(nameLine.size())); firstLine = false; } while(!name.empty()); }; for (auto param : params_) updateLength(OutputFormatter::paramDescriptionName(*param, outputSettings_.nameIndentation)); for (auto option : optionalParams_) updateLength(OutputFormatter::paramDescriptionName(*option, outputSettings_.nameIndentation)); for (auto flag : flags_) updateLength(OutputFormatter::flagDescriptionName(*flag, outputSettings_.nameIndentation)); for (auto arg : args_) updateLength(OutputFormatter::argDescriptionName(*arg, outputSettings_.nameIndentation)); if (argList_) updateLength(OutputFormatter::argListDescriptionName(*argList_, outputSettings_.nameIndentation)); return length; } std::string makeConfigFieldInfo(std::string name, std::string description) { auto maxNameWidth = std::min(outputSettings_.maxNameColumnWidth, maxOptionNameSize_); const auto columnSeparatorWidth = 1; const auto leftColumnWidth = columnSeparatorWidth + maxNameWidth; const auto rightColumnWidth = static_cast<std::size_t>(outputSettings_.terminalWidth - leftColumnWidth); const auto descriptionWidth = rightColumnWidth - 2; auto stream = std::stringstream{}; auto firstLine = true; while (!name.empty()){ auto nameLine = popLine(name, static_cast<std::size_t>(maxNameWidth), firstLine); const auto descriptionLine = popLine(description, descriptionWidth, firstLine); if (firstLine) stream << std::setw(maxNameWidth) << std::left << nameLine << " " << descriptionLine << std::endl; else stream << std::setw(maxNameWidth) << std::left << nameLine << " " << descriptionLine << std::endl; firstLine = false; } while(!description.empty()){ auto descriptionLine = popLine(description, descriptionWidth); stream << std::setw(leftColumnWidth) << " " << " " << descriptionLine << std::endl; } return stream.str(); } private: std::string programName_; std::vector<not_null<IParam*>> params_; std::vector<not_null<IParam*>> optionalParams_; std::vector<not_null<IParamList*>> paramLists_; std::vector<not_null<IParamList*>> optionalParamLists_; std::vector<not_null<IFlag*>> flags_; std::vector<not_null<IArg*>> args_; IArgList* argList_; std::vector<not_null<ICommand*>> commands_; UsageInfoFormat outputSettings_; int maxOptionNameSize_; }; }
{ "alphanum_fraction": 0.5743567692, "avg_line_length": 35.5038167939, "ext": "h", "hexsha": "d9c6b6d0a0ef1923fa425eda5cbc14f36cffcb2f", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_line_length": 150, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 2969, "size": 13953 }
#include <bindings.cmacros.h> #include <gsl/gsl_multiset.h> BC_INLINE2(gsl_multiset_get,gsl_multiset*,size_t,size_t)
{ "alphanum_fraction": 0.813559322, "avg_line_length": 23.6, "ext": "c", "hexsha": "9ef9e5f443fb55d72ee21813543235cc87086684", "lang": "C", "max_forks_count": 19, "max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z", "max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "flip111/bindings-dsl", "max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/Multisets.c", "max_issues_count": 23, "max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "flip111/bindings-dsl", "max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/Multisets.c", "max_line_length": 56, "max_stars_count": 25, "max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "flip111/bindings-dsl", "max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/Multisets.c", "max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z", "num_tokens": 35, "size": 118 }
#pragma once #include <d3d11.h> #include <DirectXMath.h> #include <map> #include <gsl\gsl> #include "DrawableGameComponent.h" #include "GaussianBlur.h" #include "FullScreenRenderTarget.h" #include "FullScreenQuad.h" #include <winrt\Windows.Foundation.h> namespace Library { class FullScreenQuadMaterial; struct BloomSettings { float BloomThreshold{ 0.45f }; float BlurAmount{ 2.0f }; float BloomIntensity{ 1.25f }; float BloomSaturation{ 1.0f }; float SceneIntensity{ 1.0f }; float SceneSaturation{ 1.0f }; }; enum class BloomDrawModes { Normal = 0, GlowMap, BlurredGlowMap, End }; class Bloom final : public DrawableGameComponent { RTTI_DECLARATIONS(Bloom, DrawableGameComponent) public: Bloom(Game& game, const BloomSettings& bloomSettings = DefaultBloomSettings); Bloom(const Bloom&) = delete; Bloom(Bloom&&) = default; Bloom& operator=(const Bloom&) = delete; Bloom& operator=(Bloom&&) = default; ~Bloom() = default; ID3D11ShaderResourceView* SceneTexture() const; void SetSceneTexture(winrt::com_ptr<ID3D11ShaderResourceView> sceneTexture); const BloomSettings& GetBloomSettings() const; void SetBloomSettings(const BloomSettings& bloomSettings); BloomDrawModes DrawMode() const; const std::string& DrawModeString() const; void SetDrawMode(BloomDrawModes drawMode); virtual void Initialize() override; virtual void Draw(const GameTime& gameTime) override; inline static const BloomSettings DefaultBloomSettings{ 0.45f, 2.0f, 1.25f, 1.0f, 1.0f, 1.0f }; private: static const std::map<BloomDrawModes, std::string> DrawModeDisplayNames; struct PixelCBufferPerObject { float BloomThreshold; float BloomIntensity; float BloomSaturation; float SceneIntensity; float SceneSaturation; DirectX::XMFLOAT3 Padding; PixelCBufferPerObject(const BloomSettings& bloomSettings) : BloomThreshold(bloomSettings.BloomThreshold), BloomIntensity(bloomSettings.BloomIntensity), BloomSaturation(bloomSettings.BloomSaturation), SceneIntensity(bloomSettings.SceneIntensity), SceneSaturation(bloomSettings.SceneSaturation), Padding() { } PixelCBufferPerObject& operator=(const BloomSettings& bloomSettings) { BloomThreshold = bloomSettings.BloomThreshold; BloomIntensity = bloomSettings.BloomIntensity; BloomSaturation = bloomSettings.BloomSaturation; SceneIntensity = bloomSettings.SceneIntensity; SceneSaturation = bloomSettings.SceneSaturation; return *this; } }; enum class BloomShaderClass { Extract = 0, Composite, NoBloom }; void DrawNormal(const GameTime& gameTime); void DrawGlowMap(const GameTime& gameTime); void DrawBlurredGlowMap(const GameTime& gameTime); FullScreenQuad mFullScreenQuad; FullScreenRenderTarget mRenderTarget; GaussianBlur mGaussianBlur; winrt::com_ptr<ID3D11ShaderResourceView> mSceneTexture; winrt::com_ptr<ID3D11Buffer> mPixelCBufferPerObject; PixelCBufferPerObject mPixelCBufferPerObjectData; BloomDrawModes mDrawMode{ BloomDrawModes::Normal }; std::map<BloomDrawModes, std::function<void(const GameTime& gameTime)>> mDrawFunctions; std::map<BloomShaderClass, winrt::com_ptr<ID3D11ClassInstance>> mShaderClassInstances; BloomSettings mBloomSettings; }; }
{ "alphanum_fraction": 0.7661068702, "avg_line_length": 28.4782608696, "ext": "h", "hexsha": "5357e22958712a83524cd67b5ede590ca68c114f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_forks_repo_path": "source/Library.Shared/Bloom.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_issues_repo_path": "source/Library.Shared/Bloom.h", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl", "max_stars_repo_path": "source/Library.Shared/Bloom.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 895, "size": 3275 }
#ifndef SIMULATION_STEPS #define SIMULATION_STEPS #include <gsl/gsl_matrix.h> extern void calculateLIFTVolMat(int N, int Np, gsl_matrix **LIFT, gsl_matrix **VolMat, gsl_matrix** MassMatrix); extern void store_mesh(char *Mesh); extern void initialize(); extern void time_evolution(double FinalTime); extern void boundary_conditions(); #endif
{ "alphanum_fraction": 0.7942028986, "avg_line_length": 24.6428571429, "ext": "h", "hexsha": "99ad90b3bece4af4488412a3f6bffb6bfed3fba9", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z", "max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "evalseth/DG-RAIN", "max_forks_repo_path": "1DCode/SimulationSteps.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "evalseth/DG-RAIN", "max_issues_repo_path": "1DCode/SimulationSteps.h", "max_line_length": 112, "max_stars_count": 1, "max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "evalseth/DG-RAIN", "max_stars_repo_path": "1DCode/SimulationSteps.h", "max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z", "num_tokens": 81, "size": 345 }
#pragma once #include <gsl/gsl_assert> #include <src/util/Logging.h> #ifndef NDEBUG //#define MI_EXPECTS(x) Expects(x) //#define MI_ENSURES(x) Ensures(x) #define MI_EXPECTS(x) \ do { \ if (!(x)) { \ LOG(ERROR) << "assertion failed: " << #x; \ std::terminate(); \ } \ } while (0) #define MI_ENSURES(x) \ do { \ if (!(x)) { \ LOG(ERROR) << "assertion failed: " << #x; \ std::terminate(); \ } \ } while (0) #else #define MI_EXPECTS(x) #define MI_ENSURES(x) #endif
{ "alphanum_fraction": 0.530726257, "avg_line_length": 18.5172413793, "ext": "h", "hexsha": "066712388bd696d0760e9a9a20f0d6733d23551f", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "oldas1/Riner", "max_forks_repo_path": "src/common/Assert.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "oldas1/Riner", "max_issues_repo_path": "src/common/Assert.h", "max_line_length": 51, "max_stars_count": null, "max_stars_repo_head_hexsha": "492804079eb223e6d4ffd5f5f44283162eaf421b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "oldas1/Riner", "max_stars_repo_path": "src/common/Assert.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 167, "size": 537 }
#include <math.h> #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <gsl/gsl_math.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multimin.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_linalg.h> #include <getopt.h> #include <string.h> #include "libhdr" #include "Library_DFE_v1.8.h" /* version 1.7.3: -added: constant population support -added: generate gamma distribution deviates -added: generate beta distribution deviates -added: generate gamma+beta distribution deviates to compile: gcc -O3 -o bin/Multi_DFE_gen_v1.8 Multi_DFE_gen_v1.8.c Library_DFE_v1.8.c tmatrix_routines.c genlib.c nrlib.c nrutil.c -lm -lgsl -lgslcblas -w example run: GSL_RNG_SEED=1 ~/Multi_DFE_est/source/bin/Multi_DFE_gen_v1.8 -N1 100 -N2 100 -nalleles 20 -t 100 -f0 0.9 -neutral 1000000 -selected 1000000 -mode 9 -conpop 1 -exp_mean 0.05 -file 1.out #-gamma_alpha 10 -gamma_beta 0.5 #-exp_mean 0.02 -beta_alpha 10 -beta_beta 1 #-exp_mean 0.02 -gamma_alpha 1000 -gamma_beta 50 #-gamma_alpha 70 -gamma_beta 0.07 -gamma2_alpha 1000 -gamma2_beta 50 #-exp_mean 0.05 */ /*Global variable declaration*/ int selmode=0; int n_sfs=0; int nspikes=1;//default a single spike int N1,N2=100; int max_n2d=2000; double saveresults[100]; int n2_step=0, conpop=0, output_egf_mode=0; /*Function list*/ double load_FV(int n1,int n2,int t2,double s,double f0,double *mean_FV); /******************************************************************************/ double load_FV(int n1,int n2,int t2,double s,double f0,double *mean_FV) { static double egf_vec1_lower[maxnd+1], egf_vec2_lower[maxnd+1], egf_vec1_upper[maxnd+1], egf_vec2_upper[maxnd+1], egf_vec1[maxnd+1], egf_vec2[maxnd+1],egf_vec[maxnd+1]; double *gamma_density_vec; int i=0,j=0,file_size_bytes=0; int t2_upper=0; int t2_real=t2; int n1d=2*n1; int n2d=2*n2; char *buffer_p1_t2_lower, *buffer_p2_t2_lower, *buffer_p1_t2_upper, *buffer_p2_t2_upper, *buffer_const_pop; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (!conpop) { get_upper_lower_int(t2_real, &t2_lower, &t2_upper, n_t2_evaluated, t2_evaluated_vec); if ((t2_lower==undefined_int)||(t2_upper==undefined_int)) { return undefined; } //printf("\n%d",t2_lower); //printf("\n%f",s); file_size_bytes=compute_file_size_bytes(n2); //Read buffers /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// buffer_p1_t2_lower = (char*) malloc (file_size_bytes); buffer_p1_t2_upper = (char*) malloc (file_size_bytes); buffer_p2_t2_lower = (char*) malloc (file_size_bytes); buffer_p2_t2_upper = (char*) malloc (file_size_bytes); read_phase1_phase2_file_into_buffer(n1,1, n2, t2_lower, buffer_p1_t2_lower, file_size_bytes); read_phase1_phase2_file_into_buffer(n1,1, n2, t2_upper, buffer_p1_t2_upper, file_size_bytes); read_phase1_phase2_file_into_buffer(n1,2, n2, t2_lower, buffer_p2_t2_lower, file_size_bytes); read_phase1_phase2_file_into_buffer(n1,2, n2, t2_upper, buffer_p2_t2_upper, file_size_bytes); get_binary_egf_vec(buffer_p1_t2_lower, n2, t2_lower, s, egf_vec1_lower); get_binary_egf_vec(buffer_p1_t2_upper, n2, t2_upper, s, egf_vec1_upper); get_binary_egf_vec(buffer_p2_t2_lower, n2, t2_lower, s, egf_vec2_lower); get_binary_egf_vec(buffer_p2_t2_upper, n2, t2_upper, s, egf_vec2_upper); //End reading buffers /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Averaging vectors w(s) and x(s) compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper, egf_vec1_lower, egf_vec1_upper, egf_vec1, n2d); compute_weighted_average_egf_vec(t2_real, t2_lower, t2_upper, egf_vec2_lower, egf_vec2_upper, egf_vec2, n2d); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //dumpvector(egf_vec1,0,210,"egf_vec1"); //printf("\n%d\t%d",t2_lower, t2_upper); //dumpvector(egf_vec2,0,210,"egf_vec2"); compute_weighted_average( mean_FV, egf_vec1, egf_vec2, n1d, n2d); free(buffer_p1_t2_lower); free(buffer_p2_t2_lower); free(buffer_p1_t2_upper); free(buffer_p2_t2_upper); } else//constant population { if (2*n1 > max_n2d) { printf("ERROR: Value of 2*n1 %d exceeds max_n2d %d\n", n1, max_n2d); gabort("Program terminating", 0); } file_size_bytes = compute_file_size_bytes(n1); // printf("const pop: file_size_bytes %d\n", file_size_bytes); monitorinput(); buffer_const_pop = (char*) malloc (file_size_bytes); read_const_pop_file_into_buffer(n1, buffer_const_pop, file_size_bytes); get_const_pop_egf_vec(s, n1, mean_FV, buffer_const_pop, 1); free(buffer_const_pop); } return (1); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static int verbose_flag; main(argc,argv) int argc; char **argv; { int i=0,j=0; int nalleles=0; double f0=0; int t=0; int nspikes=0; int sampleS=0,sampleN=0; double beta_alpha=0,beta_beta=0,gamma_alpha=0, gamma_beta=0,gamma2_alpha=0,gamma2_beta=0,exp_mean=0,exp_mean2=0, sel_coeff1=0,sel_coeff2=0,sel_coeff3=0,prob1=0,prob2=0,prob3=0; char *sfs_filename; /* location parameters measured Mean,squared mean,harmonic mean */ double MEAN_S=0,MEAN_S2=0,MEAN_H=0,fix_prob=0; int c; while (1) { static struct option long_options[] = { /* These options set a flag. */ // {"verbose", no_argument, &verbose_flag, 1}, // {"brief", no_argument, &verbose_flag, 0}, /* These options don't set a flag. We distinguish them by their indices. */ {"N1", required_argument,0, 'a'}, {"N2", required_argument,0, 'b'}, {"nalleles", required_argument, 0, 'c'}, {"t", required_argument, 0, 'd'}, {"f0", required_argument, 0, 'e'}, {"neutral", required_argument, 0, 'f'}, {"selected", required_argument, 0, 'g'}, {"mode", required_argument, 0, 'h'}, {"nspikes", required_argument, 0, 'i'}, {"gamma_alpha", required_argument, 0, 'j'}, {"gamma_beta", required_argument, 0, 'k'}, {"beta_alpha", required_argument, 0, 'l'}, {"beta_beta", required_argument, 0, 'm'}, {"gamma2_alpha", required_argument, 0, 'n'}, {"gamma2_beta", required_argument, 0, 'o'}, {"exp_mean", required_argument, 0, 'p'}, {"conpop", required_argument, 0, 'q'}, {"file", required_argument, 0, 'r'}, {"exp_mean2", required_argument, 0, 's'}, {"s1", required_argument, 0, 't'}, {"s2", required_argument, 0, 'u'}, {"s3", required_argument, 0, 'v'}, {"p1", required_argument, 0, 'w'}, {"p2", required_argument, 0, 'x'}, {"p3", required_argument, 0, 'y'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long_only (argc, argv, "", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; printf ("option %s", long_options[option_index].name); if (optarg) printf (" with arg %s", optarg); printf ("\nalleles"); break; case 'a': N1=atoi(optarg); break; case 'b': N2=atoi(optarg); break; case 'c': nalleles=atoi(optarg); break; case 'd': t=atof(optarg); break; case 'e': f0=atof(optarg); break; case 'f': sampleS=atoi(optarg); break; case 'g': sampleN=atoi(optarg); break; case 'h': selmode=atoi(optarg); break; case 'i': nspikes=atoi(optarg); break; case 'j': gamma_alpha=atof(optarg); break; case 'k': gamma_beta=atof(optarg); break; case 'l': beta_alpha=atof(optarg); break; case 'm': beta_beta=atof(optarg); break; case 'n': gamma2_alpha=atof(optarg); break; case 'o': gamma2_beta=atof(optarg); break; case 'p': exp_mean=atof(optarg); break; case 'q': conpop=atoi(optarg); break; case 'r': sfs_filename=optarg; break; case 's': exp_mean2=atof(optarg); break; case 't': sel_coeff1=atof(optarg); break; case 'u': sel_coeff2=atof(optarg); break; case 'v': sel_coeff3=atof(optarg); break; case 'w': prob1=atof(optarg); break; case 'x': prob2=atof(optarg); break; case 'y': prob3=atof(optarg); break; case '?': /* getopt_long already printed an error message. */ break; default: abort (); } } /* Print any remaining command line arguments (not options). */ if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); putchar ('\n'); } double n1d=2*N1; double n2d=2*N2; /*find n_e*/ double prop[4],n_es=0; double n_e=calculate_ne(N1,N2,t); /*Set up Spikes*/ double * spikes_vec = (double*) calloc (nspikes+1, sizeof(double)); double * prob_vec = (double*) calloc (nspikes+1, sizeof(double)); for(i = 1; i <= nspikes; i++){ printf("Give s for spike %d:\n", i); scanf("%lf",&spikes_vec[i]); } spikes_vec[0]=0; double sum_prob=0; for(i = 1; i <= nspikes-1; i++){ printf("Give probability of Spike %d:\n", i); scanf("%lf",&prob_vec[i]); sum_prob+=prob_vec[i]; } prob_vec[nspikes]=1-sum_prob; prob_vec[0]=0; double **FVSX= calloc(maxnd+1, sizeof(double *)); for(i = 1; i <= nspikes; i++){ FVSX[i] = calloc(maxnd+1, sizeof(double)); } double * FV0 = (double*) calloc (maxnd+1, sizeof(double)); /*Set up Tables*/ get_data_path(data_path); set_up_file_name(N1, s_evaluated_vec_file_const, s_evaluated_vec_file); set_up_file_name(N1, s_range_file_const, s_range_file); get_s_evaluated_vec(s_evaluated_vec, &n_s_evaluated, &n_s_evaluated_file, s_evaluated_vec_file); get_s_ranges(); if (!conpop) { set_up_file_name(N1, n2_evaluated_vec_file_const, n2_evaluated_vec_file); set_up_file_name(N1, t2_evaluated_vec_file_const, t2_evaluated_vec_file); set_up_file_name(N1, phase_1_dir_const, phase_1_dir); set_up_file_name(N1, phase_2_dir_const, phase_2_dir); get_int_evaluated_vec(t2_evaluated_vec,&n_t2_evaluated, &t2_lower, &t2_step,&t2_evaluated_vec_file); get_int_evaluated_vec(n2_evaluated_vec,&n_n2_evaluated, &n2_lower, &n2_step,&n2_evaluated_vec_file); } else { set_up_file_name(N1, "", const_pop_dir); } /* calculate neutral frequency vector*/ load_FV(N1,N2,t,0.0,f0,FV0); /*Sampling of sites*/ int * discrete0 = (int*) calloc (nalleles+2, sizeof(int)); int * discrete1 = (int*) calloc (nalleles+2, sizeof(int)); const gsl_rng_type * T; double selcoeff=0,uniform=0; gsl_rng_env_setup(); T = gsl_rng_taus; gsl_rng *rgen =gsl_rng_alloc(T); printf("%f,%f\n",gamma_alpha,gamma_beta); i=1; while (i<=sampleN) {// loop for sampling starts here i++; uniform=gsl_rng_uniform (rgen); double * FVS = (double*) calloc (maxnd+1, sizeof(double)); selcoeff=0; switch(selmode) { case 0:case 1: break; case 2: selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha); break; case 3: selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta); break; case 4: if (uniform<=0.2) {selcoeff=gsl_ran_exponential(rgen,exp_mean);} if (uniform>0.2) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);} break; case 5: if (uniform<=0.5) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);} if (uniform>0.5) {selcoeff=gsl_ran_gamma (rgen, gamma2_beta, 1/gamma2_alpha);} break; case 6: if (uniform<=0.5) {selcoeff=gsl_ran_exponential(rgen, exp_mean);} if (uniform>0.5) {selcoeff=gsl_ran_exponential (rgen, exp_mean2);} break; case 7: if (uniform<=0.5) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);} if (uniform>0.5) {selcoeff=gsl_ran_exponential (rgen, exp_mean);} break; case 8: if (uniform<=0.8) {selcoeff=gsl_ran_exponential(rgen,exp_mean);} if (uniform>0.8) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);} break; case 9: selcoeff=gsl_ran_exponential(rgen,exp_mean); break; case 10: if (uniform<=0.5) {selcoeff=0.0;} if (uniform>0.5) {selcoeff=0.05;} break; case 11: if (uniform<=(0.3)) {selcoeff=0.0;} if (uniform>0.33&&uniform<=0.67) {selcoeff=0.05;} if (uniform>0.67) {selcoeff=0.5;} break; case 12: if (uniform<=0.3) {selcoeff=0;}//gsl_ran_gaussian (rgen,1e-5);} if (uniform>0.3&&uniform<=0.4) {selcoeff=-0.05;}//gsl_ran_gaussian (rgen,1e-5);selcoeff+=0.005;} if (uniform>0.4&&uniform<=0.6) {selcoeff=-0.5;}//gsl_ran_gaussian (rgen,1e-5);selcoeff+=0.05;} if (uniform>0.6) {selcoeff=-5;} //gsl_ran_gaussian (rgen,1e-5);selcoeff+=0.5;} break; case 13: selcoeff=uniform; break; case 14: if (uniform<=0.5) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);} if (uniform>0.5) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);} break; case 15: if (uniform<=0.2) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);} if (uniform>0.2) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);} break; case 16: if (uniform<=0.8) {selcoeff=gsl_ran_gamma (rgen, gamma_beta, 1/gamma_alpha);} if (uniform>0.8) {selcoeff=gsl_ran_beta (rgen, beta_alpha, beta_beta);} break; case 17: if (uniform<=(0.3)) {selcoeff=0.0;} if (uniform>0.33&&uniform<=0.67) {selcoeff=0.03;} if (uniform>0.67) {selcoeff=0.06;} break; case 18: if (uniform<=0.2) {selcoeff=sel_coeff1;} if (uniform>0.2&&uniform<=0.8) {selcoeff=sel_coeff2;} if (uniform>0.8) {selcoeff=sel_coeff3;} break; case 19: if (uniform<=0.3) {selcoeff=0;} if (uniform>0.3) {selcoeff=0.05;} break; case 20: if (uniform<=0.2) {selcoeff=0;} if (uniform>0.2&&uniform<=0.4) {selcoeff=0.05;} if (uniform>0.4) {selcoeff=0.5;} break; case 21: if (uniform<=0.2) {selcoeff=0;} if (uniform>0.2&&uniform<=0.4) {selcoeff=0.02;} if (uniform>0.4&&uniform<=0.6) {selcoeff=0.05;} if (uniform>0.6) {selcoeff=0.1;} break; case 22: selcoeff=exp_mean; break; case 23: selcoeff=gsl_ran_lognormal (rgen, gamma_alpha, gamma_beta); break; case 24: if (uniform<=0.2) {selcoeff=sel_coeff1;} if (uniform>0.2) {selcoeff=sel_coeff2;} break; case 25: if (uniform<=0.5) {selcoeff=sel_coeff1;} if (uniform>0.5) {selcoeff=sel_coeff2;} break; case 26: if (uniform<=prob1) {selcoeff=sel_coeff1;} if (uniform>prob1) {selcoeff=sel_coeff2;} break; case 27: if (uniform<=prob1) {selcoeff=sel_coeff1;} if (uniform>=prob1) {selcoeff=sel_coeff1;} if (uniform>prob1) {selcoeff=sel_coeff2;} break; }//end switch //monitorinput(); if(selcoeff>0){selcoeff=-selcoeff;} if (selcoeff<-100) {selcoeff=-100;}//free(FVS);continue;}//free(FVS);continue; //printf("%f\n",selcoeff); MEAN_S+=selcoeff; MEAN_S2+=-pow(selcoeff,2); MEAN_H+=1/selcoeff; if (selcoeff== 0) { fix_prob += 0.5/n_e; } else { fix_prob += kimura_fixation_prob(selcoeff, n_e); } /*calculate relative proportions*/ n_es=-n_e*selcoeff; if (n_es<=0.1){prop[0]++;} if (n_es<=1.0){prop[1]++;} if (n_es<=10.0){prop[2]++;} if (n_es<100.0){prop[3]++;} load_FV(N1,N2,t,selcoeff,f0,FVS); egf_scaling(N2,f0,FV0,FVS); gsl_ran_discrete_t *r= gsl_ran_discrete_preproc (n2d,FVS); double s1=gsl_ran_discrete (rgen, r); double prob=(double)(s1)/n2d; int success=gsl_ran_binomial(rgen,prob,nalleles); if (success==nalleles){discrete1[0]++;}else{ discrete1[success]++; } free(FVS); gsl_ran_discrete_free(r); }//end sampling MEAN_S/=sampleN; MEAN_S2/=sampleN; MEAN_H/=sampleN; MEAN_H=1/MEAN_H;//Reciprocal of the mean of the reciprocals fix_prob/=sampleN; fix_prob *=2*n_e; prop[3]=(prop[3]-prop[2])/sampleN; prop[2]=(prop[2]-prop[1])/sampleN; prop[1]=(prop[1]-prop[0])/sampleN; prop[0]=prop[0]/sampleN; egf_scaling(N2,f0,FV0,FV0); binomial_sampling(N2,nalleles,sampleS,FV0,discrete0);//neutral /*Print Output*/ printf("%f\t%f\t%f\n",MEAN_S,MEAN_S2,MEAN_H); //output_sfs_to_file_thanasis_format(nalleles,discrete0,discrete1,sfs_filename); output_sfs_to_file_peter_format2(nalleles,sampleS,sampleN,discrete1,discrete0,sfs_filename); FILE *file1= fopen(strcat(sfs_filename,".mean"), "w" ); fprintf(file1,"%0.16E %0.16E %0.16E ",MEAN_S,MEAN_S2,MEAN_H); for(i = 0; i <= 3; i++){ fprintf(file1,"%0.16E ",prop[i]); } fprintf(file1,"%0.16E ",fix_prob); fclose(file1); //////////////////////////////////////////////////////////////////////////////// free(FV0); gsl_rng_free (rgen); free(discrete0); free(discrete1); for(i = 1; i <= nspikes; i++){ free(FVSX[i]); } free(FVSX); return 0; }
{ "alphanum_fraction": 0.5971597763, "avg_line_length": 29.7035830619, "ext": "c", "hexsha": "5d9211fa95927de958d8d36386ee48eeb2cdda3c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kousathanas/simsfs_fast", "max_forks_repo_path": "Multi_DFE_gen_v1.8.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kousathanas/simsfs_fast", "max_issues_repo_path": "Multi_DFE_gen_v1.8.c", "max_line_length": 186, "max_stars_count": null, "max_stars_repo_head_hexsha": "0cb64ad4955eaa861a08233fcdd70e59ec15c350", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kousathanas/simsfs_fast", "max_stars_repo_path": "Multi_DFE_gen_v1.8.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5836, "size": 18238 }
///////////////////////////////////////////////////////////////////////////////// // // Levenberg - Marquardt non-linear minimization algorithm // Modified and simplified by Ted Laurence to use for MLE of Poisson-distributed data; Used only for // double precision, without constraints // Copyright (C) 2004 Manolis Lourakis (lourakis at ics forth gr) // Institute of Computer Science, Foundation for Research & Technology - Hellas // Heraklion, Crete, Greece. // // Modifications Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory. Written by Ted Laurence (laurence2@llnl.gov) // LLNL-CODE-424602 All rights reserved. // This file is part of dlevmar_mle_der // // Please also read Our Notice and GNU General Public License. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // ///////////////////////////////////////////////////////////////////////////////// #include <gsl/gsl_linalg.h> #include <gsl/gsl_vector.h> #include <math.h> #include "levmar_mle.h" #include "lm_mle_compiler.h" #define EPSILON 1E-12 #define ONE_THIRD 0.3333333334 /* 1.0/3.0 */ #define LM_REAL_MAX FLT_MAX #define LM_REAL_MIN -FLT_MAX double compute_chisq_measure(double *e, double *x, double *hx, int n, int fitType) { int i; double chisq=0.0; switch (fitType) { case LM_CHISQ_MLE: for (i=0; i<n; i++) { if ( hx[i] > 0) { if (x[i]==0) chisq += 2 * hx[i]; else chisq += 2 * (hx[i]-x[i]-x[i]*log(hx[i]/x[i])); e[i]=x[i]/hx[i]-1.0; } else e[i]=0.0; } break; case LM_CHISQ_NEYMAN: for (i=0; i<n; i++) { if (x[i]==0) { chisq += (x[i]-hx[i])*(x[i]-hx[i]); e[i]=x[i]-hx[i]; } else { chisq += (x[i]-hx[i])*(x[i]-hx[i])/x[i]; e[i]=(x[i]-hx[i])/x[i]; } } break; case LM_CHISQ_EQUAL_WT: for (i=0; i<n; i++) { e[i]=x[i]-hx[i]; chisq += e[i]*e[i]; } break; } return chisq; } /* * This function seeks the parameter vector p that best describes the measurements vector x. * More precisely, given a vector function func : R^m --> R^n with n>=m, * it finds p s.t. func(p) ~= x, i.e. the squared second order (i.e. L2) norm of * e=x-func(p) is minimized. * * This function requires an analytic Jacobian. * * Returns the number of iterations (>=0) if successful, LM_ERROR if failed * * For more details, see K. Madsen, H.B. Nielsen and O. Tingleff's lecture notes on * non-linear least squares at http://www.imm.dtu.dk/pubdb/views/edoc_download.php/3215/pdf/imm3215.pdf */ int dlevmar_mle_der( void (*func)(double *p, double *hx, int m, int n, void *adata), /* functional relation describing measurements. A p \in R^m yields a \hat{x} \in R^n */ void (*jacf)(double *p, double *j, int m, int n, void *adata), /* function to evaluate the Jacobian \part x / \part p */ double *p, /* I/O: initial parameter estimates. On output has the estimated solution */ double *x, /* I: measurement vector. NULL implies a zero vector */ int m, /* I: parameter vector dimension (i.e. #unknowns) */ int n, /* I: measurement vector dimension */ int itmax, /* I: maximum number of iterations */ double opts[5], /* I: minim. options [\mu, \epsilon1, \epsilon2, \epsilon3,\epsilon4]. Respectively the scale factor for initial \mu, * stopping thresholds for ||J^T e||_inf, ||Dp||_2, chisq, and delta_chisq. Set to NULL for defaults to be used */ double info[LM_INFO_SZ], /* O: information regarding the minimization. Set to NULL if don't care * info[0]= ||e||_2 at initial p. * info[1-4]=[ ||e||_2, ||J^T e||_inf, ||Dp||_2, mu/max[J^T J]_ii ], all computed at estimated p. * info[5]= # iterations, * info[6]=reason for terminating: 1 - stopped by small gradient J^T e * 2 - stopped by small Dp * 3 - stopped by itmax * 4 - singular matrix. Restart from current p with increased mu * 5 - no further error reduction is possible. Restart with increased mu * 6 - stopped by small ||e||_2 * 7 - stopped by invalid (i.e. NaN or Inf) "func" values. This is a user error * 8 - stopped by small change in chisq on successful iteration (dF<eps4) * info[7]= # function evaluations * info[8]= # Jacobian evaluations * info[9]= # linear systems solved, i.e. # attempts for reducing error */ double *work, /* working memory at least LM_DER_WORKSZ() reals large, allocated if NULL */ double *covar, /* O: Covariance matrix corresponding to LS solution; mxm. Set to NULL if not needed. */ void *adata, /* pointer to possibly additional data, passed uninterpreted to func & jacf. * Set to NULL if not needed */ int fitType) /* Which type of fit to perform * LM_CHISQ_MLE is MLE for Poisson distribution * LM_CHISQ_NEYMAN is least squares where sigma^2 is set to max(x,1) * LM_CHISQ_EQUAL_WT is least squares where sigma^2 is set to 1 */ { register int i, j, k, l; int worksz, freework=0, issolved; /* temp work arrays */ double *e, /* nx1 */ *e_test, /* nx1 */ *hx, /* \hat{x}_i, nx1 */ *jacTe, /* J^T e_i mx1 */ *jac, /* nxm */ *jacTjac, /* mxm */ *LUdecomp, /* mxm */ *Dp, /* mx1 */ *diag_jacTjac, /* diagonal of J^T J, mx1 */ *pDp; /* p + Dp, mx1 */ register double mu, /* damping constant */ tmp; /* mainly used in matrix & vector multiplications */ double p_chisq, jacTe_inf, pDp_chisq; /* ||e(p)||_2, ||J^T e||_inf, ||e(p+Dp)||_2 */ double p_L2, Dp_L2=LM_REAL_MAX, dF, dL; double tau, eps1, eps2, eps2_sq, eps3, eps4; double init_p_chisq; int nu=2, nu2, stop=0, nfev, njev=0, nlss=0; const int nm=n*m; gsl_matrix_view LUdecomp_view; gsl_vector_view jacTe_view, Dp_view; gsl_permutation * perm = gsl_permutation_alloc (m); int signum; mu=jacTe_inf=0.0; /* -Wall */ if(n<m){ fprintf(stderr, "(): cannot solve a problem with fewer measurements [%d] than unknowns [%d]\n", n, m); return LM_ERROR; } if(!jacf){ fprintf(stderr, "No function specified for computing the Jacobian"); return LM_ERROR; } if(opts){ tau=opts[0]; eps1=opts[1]; eps2=opts[2]; eps2_sq=opts[2]*opts[2]; eps3=opts[3]; eps4=opts[4]; } else{ // use default values tau=LM_INIT_MU; eps1=LM_STOP_THRESH; eps2=LM_STOP_THRESH; eps2_sq=LM_STOP_THRESH*LM_STOP_THRESH; eps3=LM_STOP_THRESH; eps4=LM_STOP_THRESH; } if(!work){ worksz=LM_MLE_WORKSZ(m, n); //2*n+4*m + n*m + m*m; work=(double *)malloc(worksz*sizeof(double)); /* allocate a big chunk in one step */ if(!work){ fprintf(stderr, "(): memory allocation request failed\n"); return LM_ERROR; } freework=1; } /* set up work arrays */ e=work; e_test=e + n; hx=e_test + n; jacTe=hx + n; jac=jacTe + m; jacTjac=jac + nm; LUdecomp=jacTjac + m*m; Dp=LUdecomp + m*m; diag_jacTjac=Dp + m; pDp=diag_jacTjac + m; LUdecomp_view=gsl_matrix_view_array(LUdecomp,m,m); jacTe_view=gsl_vector_view_array(jacTe,m); Dp_view=gsl_vector_view_array(Dp,m); /* compute e=x - f(p) and its chisq measure*/ (*func)(p, hx, m, n, adata); nfev=1; /* ### e=x-hx, p_eL2=||e|| */ p_chisq=compute_chisq_measure(e, x, hx, n, fitType); init_p_chisq=p_chisq; if(!LM_FINITE(p_chisq)) stop=7; for(k=0; k<itmax && !stop; ++k){ register int l, im; register double alpha, wt, *jaclm; /* Note that p and e have been updated at a previous iteration */ if(p_chisq<=eps3){ /* error is small */ stop=6; break; } /* Compute the Jacobian J at p, J^T J, J^T e, ||J^T e||_inf and ||p||^2. * Since J^T J is symmetric, its computation can be sped up by computing * only its upper triangular part and copying it to the lower part */ (*jacf)(p, jac, m, n, adata); ++njev; /* J^T J, J^T e */ for(i=m*m; i-->0; ) jacTjac[i]=0.0; for(i=m; i-->0; ) jacTe[i]=0.0; for(l=n; l-->0; ){ jaclm=jac+l*m; switch (fitType) { case LM_CHISQ_MLE: if (hx[l]>0) wt=x[l]/(hx[l]*hx[l]); else wt=0.0; break; case LM_CHISQ_NEYMAN: if (x[l]==0) wt=1.0; else wt=1.0/x[l]; break; case LM_CHISQ_EQUAL_WT: wt=1.0; break; } for(i=m; i-->0; ){ im=i*m; alpha=jaclm[i]; //jac[l*m+i]; for(j=i+1; j-->0; ) /* j<=i computes lower triangular part only */ jacTjac[im+j]+=jaclm[j]*alpha*wt; //jac[l*m+j] /* J^T e */ jacTe[i]+=alpha*e[l]; } } for(i=m; i-->0; ) /* copy to upper part */ for(j=i+1; j<m; ++j) jacTjac[i*m+j]=jacTjac[j*m+i]; /* Compute ||J^T e||_inf and ||p||^2 */ for(i=0, p_L2=jacTe_inf=0.0; i<m; ++i){ if(jacTe_inf < (tmp=FABS(jacTe[i]))) jacTe_inf=tmp; diag_jacTjac[i]=jacTjac[i*m+i]; /* save diagonal entries so that augmentation can be later canceled */ p_L2+=p[i]*p[i]; } /* check for convergence */ if((jacTe_inf <= eps1)){ Dp_L2=0.0; /* no increment for p in this case */ stop=1; break; } /* compute initial damping factor */ if(k==0){ for(i=0, tmp=LM_REAL_MIN; i<m; ++i) if(diag_jacTjac[i]>tmp) tmp=diag_jacTjac[i]; /* find max diagonal element */ mu=tau*tmp; } /* determine increment using adaptive damping */ while(1){ /* augment normal equations */ for(i=0; i<m; ++i) jacTjac[i*m+i]+=mu; /* solve augmented equations */ /* use the LU included with GSL*/ for (i=0; i<m*m; i++) LUdecomp[i]=jacTjac[i]; gsl_linalg_LU_decomp(&LUdecomp_view.matrix, perm, &signum); issolved = !gsl_linalg_LU_solve (&LUdecomp_view.matrix, perm, &jacTe_view.vector, &Dp_view.vector); if(issolved){ /* compute p's new estimate and ||Dp||^2 */ for(i=0, Dp_L2=0.0; i<m; ++i){ pDp[i]=p[i] + (tmp=Dp[i]); Dp_L2+=tmp*tmp; } //Dp_L2=sqrt(Dp_L2); if(Dp_L2<=eps2_sq*p_L2){ /* relative change in p is small, stop */ stop=2; break; } // if(Dp_L2>=(p_L2+eps2)/EPSILON*EPSILON){ /* almost singular */ // stop=4; // break; // } (*func)(pDp, hx, m, n, adata); ++nfev; /* evaluate function at p + Dp */ /* compute ||e(pDp)||_2 */ /* ### hx=x-hx, pDp_chisq=||hx|| */ pDp_chisq= compute_chisq_measure(e_test, x, hx, n, fitType); if(!LM_FINITE(pDp_chisq)){ /* chisq is not finite, most probably due to a user error. * This check makes sure that the inner loop does not run indefinitely. * Thanks to Steve Danauskas for reporting such cases */ stop=7; break; } for(i=0, dL=0.0; i<m; ++i) dL+=Dp[i]*(mu*Dp[i]+jacTe[i]); dF=p_chisq-pDp_chisq; if(dL>0.0 && dF>0.0){ /* reduction in error, increment is accepted */ tmp=(2.0*dF/dL-1.0); tmp=1.0-tmp*tmp*tmp; mu=mu*( (tmp>=ONE_THIRD)? tmp : ONE_THIRD ); nu=2; for(i=0 ; i<m; ++i) /* update p's estimate */ p[i]=pDp[i]; for(i=0; i<n; ++i) /* update e and ||e||_2 */ e[i]=e_test[i]; p_chisq=pDp_chisq; if (dF<eps4) stop = 8; break; } } /* if this point is reached, either the linear system could not be solved or * the error did not reduce; in any case, the increment must be rejected */ mu*=nu; nu2=nu<<1; // 2*nu; if(nu2<=nu){ /* nu has wrapped around (overflown). Thanks to Frank Jordan for spotting this case */ stop=5; break; } nu=nu2; for(i=0; i<m; ++i) /* restore diagonal J^T J entries */ jacTjac[i*m+i]=diag_jacTjac[i]; } /* inner loop */ } if(k>=itmax) stop=3; for(i=0; i<m; ++i) /* restore diagonal J^T J entries */ jacTjac[i*m+i]=diag_jacTjac[i]; if(info){ info[0]=init_p_chisq; info[1]=p_chisq; info[2]=jacTe_inf; info[3]=Dp_L2; for(i=0, tmp=LM_REAL_MIN; i<m; ++i) if(tmp<jacTjac[i*m+i]) tmp=jacTjac[i*m+i]; info[4]=mu/tmp; info[5]=(double)k; info[6]=(double)stop; info[7]=(double)nfev; info[8]=(double)njev; info[9]=(double)nlss; } if(freework) free(work); gsl_permutation_free(perm); return (stop!=4 && stop!=7)? k : LM_ERROR; }
{ "alphanum_fraction": 0.5604730735, "avg_line_length": 31.337995338, "ext": "c", "hexsha": "d443e8b9217edabcce85b25eb74e8d42ee1c629f", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2019-10-31T07:28:06.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-04T18:52:35.000Z", "max_forks_repo_head_hexsha": "f9f19ef5b0a00169562947c78a41c1f02e222a6a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "david-hoffman/dphtools", "max_forks_repo_path": "notebooks/nmeth0510-338-S2/lm_mle.c", "max_issues_count": 4, "max_issues_repo_head_hexsha": "d2156587cbeeb0433511811d49b69b2687b45fd6", "max_issues_repo_issues_event_max_datetime": "2022-02-09T06:49:58.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-18T18:15:39.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "david-hoffman/dphutils", "max_issues_repo_path": "notebooks/nmeth0510-338-S2/lm_mle.c", "max_line_length": 181, "max_stars_count": 2, "max_stars_repo_head_hexsha": "f9f19ef5b0a00169562947c78a41c1f02e222a6a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "david-hoffman/dphtools", "max_stars_repo_path": "notebooks/nmeth0510-338-S2/lm_mle.c", "max_stars_repo_stars_event_max_datetime": "2019-10-31T03:35:35.000Z", "max_stars_repo_stars_event_min_datetime": "2019-10-15T00:04:06.000Z", "num_tokens": 4243, "size": 13444 }
/*************************************************************************** misc.h - description ------------------- copyright : (C) 2005 by MOUSSA email : mmousa@liris.cnrs.fr ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef MISC_H #define MISC_H #include "config.h" #include <gsl/gsl_math.h> #include <gsl/gsl_monte.h> #include <gsl/gsl_monte_plain.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> ////////////////////////////////////////////////////////////////////////////// template<class T> void Add_vectors(T *vec1, T *vec2, T *result, int size); template<class T> void Add_vectors(T *vec1, T *vec2, T *result, int size){ for(int i=0; i<size; i++){ result[i] = vec1[i]+vec2[i]; } } ////////////////////////////////////////////////////////////////////////////// template<class T> void Mult_vector_const(T *vec, T c, T *result, int size); template<class T> void Mult_vector_const(T *vec, T c, T *result, int size){ for(int i=0; i<size; i++){ result[i] = vec[i]*c; } } ////////////////////////////////////////////////////////////////////////////// template<class T>void assign_value(T *vec, T c, int size); template<class T>void assign_value(T *vec, T c, int size){ for(int i = 0; i<size; i++) vec[i] = c; } ////////////////////////////////////////////////////////////////////////////// template<class T>void copy_vectors(T *src, T *dest, int size); template<class T>void copy_vectors(T *src, T *dest, int size){ for(int i = 0; i<size; i++){ dest[i] = src[i]; } } ////////////////////////////////////////////////////////////////////////////// template<class T> int is_overlaping(T *vec1, T *vec2, int size); template<class T> int is_overlaping(T *vec1, T *vec2, int size){ for(int i = 0; i<size; i++){ if((fabs(vec1[i])>1e-6)&&(fabs(vec2[i])>1e-6)) return true; } return false; } ////////////////////////////////////////////////////////////////////////////// template<class T> void print_vector(T *vec, int size); template<class T> void print_vector(T *vec, int size){ for(int i = 0; i<size; i++){ if(vec[i]>0.0) std::cout<<vec[i]<<std::endl; } } ////////////////////////////////////////////////////////////////////////////// template<class T> bool AllOnes(T *vec, int size); template<class T> bool AllOnes(T *vec, int size){ for(int i = 0; i < size; i++) if(fabs(vec[i]) < 1e-6) return false; return true; } ////////////////////////////////////////////////////////////////////////////// int gettoken(char[30], FILE *); bool FileName(char[30], char *); void theta_phi_bounds(Triangle_3 tr, double *mintheta, double *maxtheta, double *minphi, double *maxphi); void SphericalHarmonic(int, int, double, double, gsl_complex *); #endif
{ "alphanum_fraction": 0.4290229885, "avg_line_length": 41.4285714286, "ext": "h", "hexsha": "d0402ae1e9f917a8e4dfafc5b200a445f464e48b", "lang": "C", "max_forks_count": 77, "max_forks_repo_forks_event_max_datetime": "2022-03-24T01:03:54.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-24T22:36:29.000Z", "max_forks_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kyeonghopark/jgt-code", "max_forks_repo_path": "Volume_11/Number_2/Mousa2006/misc.h", "max_issues_count": 8, "max_issues_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_issues_repo_issues_event_max_datetime": "2021-05-27T01:49:50.000Z", "max_issues_repo_issues_event_min_datetime": "2016-01-15T13:23:16.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kyeonghopark/jgt-code", "max_issues_repo_path": "Volume_11/Number_2/Mousa2006/misc.h", "max_line_length": 105, "max_stars_count": 415, "max_stars_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kyeonghopark/jgt-code", "max_stars_repo_path": "Volume_11/Number_2/Mousa2006/misc.h", "max_stars_repo_stars_event_max_datetime": "2022-02-18T04:09:07.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-24T17:37:12.000Z", "num_tokens": 752, "size": 3480 }
#include <gsl/gsl_multiset.h> #include <gsl/gsl_errno.h> #include <stdio.h> int mgsl_multiset_fwrite(const char *filename, const gsl_multiset *p) { FILE *fp; if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED; if(gsl_multiset_fwrite(fp, p) != GSL_SUCCESS) return GSL_EFAILED; fclose(fp); return GSL_SUCCESS; } int mgsl_multiset_fread(const char *filename, gsl_multiset *p) { FILE *fp; if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED; if(gsl_multiset_fread(fp, p) != GSL_SUCCESS) return GSL_EFAILED; fclose(fp); return GSL_SUCCESS; } int mgsl_multiset_fprintf(const char *filename, const gsl_multiset *p, const char *format) { FILE *fp; if((fp = fopen(filename, "w")) == NULL) return GSL_EFAILED; if(gsl_multiset_fprintf(fp, p, format) != GSL_SUCCESS) return GSL_EFAILED; fclose(fp); return GSL_SUCCESS; } int mgsl_multiset_fscanf(const char *filename, gsl_multiset *p) { FILE *fp; if((fp = fopen(filename, "r")) == NULL) return GSL_EFAILED; if(gsl_multiset_fscanf(fp, p) != GSL_SUCCESS) return GSL_EFAILED; fclose(fp); return GSL_SUCCESS; }
{ "alphanum_fraction": 0.7128623188, "avg_line_length": 27.6, "ext": "c", "hexsha": "8f6f994ce3ecd821dfe503473c85fefbc70f0a5d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "44a0425fed0c8f4a7ce2548efd5b71375467772b", "max_forks_repo_licenses": [ "Artistic-2.0" ], "max_forks_repo_name": "frithnanth/raku-Math-Libgsl-Multiset", "max_forks_repo_path": "src/multiset.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "44a0425fed0c8f4a7ce2548efd5b71375467772b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Artistic-2.0" ], "max_issues_repo_name": "frithnanth/raku-Math-Libgsl-Multiset", "max_issues_repo_path": "src/multiset.c", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "44a0425fed0c8f4a7ce2548efd5b71375467772b", "max_stars_repo_licenses": [ "Artistic-2.0" ], "max_stars_repo_name": "frithnanth/raku-Math-Libgsl-Multiset", "max_stars_repo_path": "src/multiset.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 329, "size": 1104 }
//#include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_spline.h> #include <gsl/gsl_roots.h> #define NSPLINELD 1001 #define NSPLINEEZ 1001 #define NSPLINERR 10001 #define NSPLINEDF 10001 gsl_interp_accel *accLD, *accRed, *accEz, *accDF; gsl_spline *splineLD, *splineRed, *splineEz, *splineDF; #define MPC_IN_M 3.08567758e22 #define GPC_IN_M (1e3 * MPC_IN_M) #define C_LIGHT 2.99792458e8 #define HUBBLE0 (1e5 * 0.71 / MPC_IN_M) #define DH (C_LIGHT / HUBBLE0 / GPC_IN_M) #define DH3 (DH * DH * DH) void load_splines() { long int i; // Luminosity distribution accLD = gsl_interp_accel_alloc(); splineLD = gsl_spline_alloc(gsl_interp_cspline, NSPLINELD); double z1[NSPLINELD], ld[NSPLINELD]; FILE *fp1 = fopen("support_data/splines_LuminosityDistance.txt","r"); for ( i=0; i<NSPLINELD; i++ ) { fscanf(fp1, "%lf\t%lf\n", &z1[i], &ld[i]); } fclose(fp1); gsl_spline_init(splineLD, z1, ld, NSPLINELD); // Redshift distribution accRed = gsl_interp_accel_alloc(); splineRed = gsl_spline_alloc(gsl_interp_cspline, NSPLINERR); double z2[NSPLINERR], red[NSPLINERR]; FILE *fp2 = fopen("support_data/splines_RedshiftRate.txt","r"); for ( i=0; i<NSPLINERR; i++ ) { fscanf(fp2, "%lf\t%lf\n", &z2[i], &red[i]); } fclose(fp2); gsl_spline_init(splineRed, z2, red, NSPLINERR); // E(z) cosmology accEz = gsl_interp_accel_alloc(); splineEz = gsl_spline_alloc(gsl_interp_cspline, NSPLINEEZ); double z3[NSPLINEEZ], Ez[NSPLINEEZ], temp1, temp2; FILE *fp3 = fopen("support_data/splines_Ez.txt","r"); for ( i=0; i<NSPLINEEZ; i++ ) { fscanf(fp3, "%lf %lf %lf %lf\n", &z3[i], &temp1, &temp2, &Ez[i]); } fclose(fp3); gsl_spline_init(splineEz, z3, Ez, NSPLINEEZ); // detection fraction (w.r.t z) accDF = gsl_interp_accel_alloc(); splineDF = gsl_spline_alloc(gsl_interp_cspline, NSPLINEDF); double z4[NSPLINEDF], df[NSPLINEDF], temp3; FILE *fp4; if (runargs.method == NEURALNET) { fp4 = fopen("support_data/splines_detection_fraction_z.txt","r"); for ( i=0; i<NSPLINEDF; i++ ) { fscanf(fp4, "%lf %lf %lf\n", &z4[i], &df[i], &temp3); } fclose(fp4); } else if (runargs.method == RANDOMFOREST) { fp4 = fopen("support_data/splines_detection_fraction_z_RF.txt","r"); for ( i=0; i<NSPLINEDF; i++ ) { fscanf(fp4, "%lf %lf\n", &z4[i], &df[i]); } fclose(fp4); } else if (runargs.method == ADABOOST) { fp4 = fopen("support_data/splines_detection_fraction_z_AB.txt","r"); for ( i=0; i<NSPLINEDF; i++ ) { fscanf(fp4, "%lf %lf\n", &z4[i], &df[i]); } fclose(fp4); } else if (runargs.method == FLUXTHRESH) { fp4 = fopen("support_data/splines_detection_fraction_z_flux.txt","r"); for ( i=0; i<NSPLINEDF; i++ ) { fscanf(fp4, "%lf %lf\n", &z4[i], &df[i]); } fclose(fp4); } gsl_spline_init(splineDF, z4, df, NSPLINEDF); } void unload_splines() { gsl_spline_free(splineLD); gsl_interp_accel_free(accLD); gsl_spline_free(splineRed); gsl_interp_accel_free(accRed); gsl_spline_free(splineEz); gsl_interp_accel_free(accEz); gsl_spline_free(splineDF); gsl_interp_accel_free(accDF); } static inline double MAX(double v1, double v2) { return (((v1) > (v2)) ? (v1) : (v2)); } double log_sum_exp(double x, double y) { //convert to natural log x /= M_LOG10E; y /= M_LOG10E; double mx = MAX(x,y); double val = log(exp(x - mx) + exp(y - mx)) + mx; return val/M_LN10; } double log_subtract_exp(double x, double y) { // x >= y must be true! if (y>x) { fprintf(stderr, "%lf < %lf !\n", x, y); exit(-1); } //convert to natural log x /= M_LOG10E; y /= M_LOG10E; double val = x + log1p(-exp(y-x)); return val/M_LN10; } double lumdist_logpowint(double log_lum_min, double log_lum_max, double pwr) { double val; if ( pwr > -1.0 ) { val = -pwr * log_lum_star_global - log10(pwr+1.0) + log_subtract_exp((pwr+1.0)*log_lum_max, (pwr+1.0)*log_lum_min); } else { val = -pwr * log_lum_star_global - log10(-(pwr+1.0)) + log_subtract_exp((pwr+1.0)*log_lum_min, (pwr+1.0)*log_lum_max); } //fprintf(stderr, "%lf -> %lf : %lf\n", log_lum_min, log_lum_max, val); return val; } double lumdist_logpowinv(double prob, double log_lum_min, double log_lum_max, double pwr) { double temp = lumdist_logpowint(log_lum_min, log_lum_max, pwr) + log10(prob); temp += pwr * log_lum_star_global; if ( pwr > -1.0 ) { temp += log10(pwr+1.0); temp = log_sum_exp((pwr+1.0)*log_lum_min, temp); } else { temp += log10(-(pwr+1.0)); temp = log_subtract_exp((pwr+1.0)*log_lum_min, temp); } return temp/(pwr+1.0); } double luminosity_distr_fast(double prob, double log_lum_min, double log_lum_max) { //fprintf(stderr, "%lf, %lf, %lf, %lf, %lf, %lf\n", prob, log_lum_min, log_lum_max, log_lum_star_global, alpha1_global, beta1_global); double log_lum_int_lower = lumdist_logpowint(log_lum_min, log_lum_star_global, alpha1_global); double log_lum_int_upper = lumdist_logpowint(log_lum_star_global, log_lum_max, beta1_global); double log_lum_int_total = log_sum_exp(log_lum_int_lower, log_lum_int_upper); double lower_frac = pow(10.0, log_lum_int_lower - log_lum_int_total), upper_frac = 1.0 - lower_frac; //fprintf(stderr, "%lf, %lf, %lf, %lf, %lf\n", log_lum_int_lower, log_lum_int_upper, log_lum_int_total, lower_frac, upper_frac); if ( prob <= lower_frac ) { return lumdist_logpowinv(prob/lower_frac, log_lum_min, log_lum_star_global, alpha1_global); } else { return lumdist_logpowinv((prob - lower_frac)/upper_frac, log_lum_star_global, log_lum_max, beta1_global); } } double lum2flux_integrand(double E, void *params) { double *vals = (double *)params; double alpha = vals[0]; double beta = vals[1]; double E0 = vals[2]; double Ebreak = vals[3]; if ( E < Ebreak ) { return pow(E/100.0,alpha) * exp(-E/E0) * E; } else { return pow((alpha-beta)*E0/100.0,alpha-beta) * exp(beta-alpha) * pow(E/100.0,beta) * E; } } double lum2flux_integral_numeric(double alpha, double beta, double Epeak, double Emin, double Emax) { double E0 = Epeak / (2.0+alpha); double Ebreak = (alpha-beta)*E0; //gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000); double result, error; unsigned long int neval; double vals[4] = {alpha, beta, E0, Ebreak}; gsl_function F; F.function = &lum2flux_integrand; F.params = &vals[0]; gsl_set_error_handler_off(); //gsl_integration_qag(&F, Emin, Emax, 1e-7, 1e-6, 1000, 1, w, &result, &error); gsl_integration_qng(&F, Emin, Emax, 1e-7, 1e-6, &result, &error, &neval); //fprintf(stderr, "%d evaluations\t", neval); //gsl_integration_workspace_free (w); return result; } double Redshift_distribution_unnormalized(double z, double n1, double n2, double z1) { if (z <= z1) { return pow(1.0 + z, n1); } else { return pow(1.0 + z1, n1 - n2) * pow(1.0 + z, n2); } } double Redshift_distribution_normalized(double z, double n0, double n1, double n2, double z1) { return n0 * Redshift_distribution_unnormalized(z, n1, n2, z1); } double Redshift_rescaled(double z, void *params) { double *pars = (double *) params; double n0 = pars[0]; double n1 = pars[1]; double n2 = pars[2]; double z1 = pars[3]; double Rprime = Redshift_distribution_normalized(z, n0, n1, n2, z1) / (1.0 + z); Rprime *= DH3 * gsl_spline_eval(splineEz, z, accEz); return Rprime; } double Redshift_rejection_sampler(long int *seed, double n0, double n1, double n2, double z1) { double pars[4] = {n0, n1, n2, z1}; double Rzmax = Redshift_rescaled(z1, (void *) &pars[0]); double z = 0.0, p, x; for (;;) { z = ran2d(seed) * 10.0; p = Redshift_rescaled(z, (void *) &pars[0]) / Rzmax; x = ran2d(seed); if (x < p) break; } return z; } double GRBNumberIntegral(double n0, double n1, double n2, double z1) { double pars[4] = {n0, n1, n2, z1}; double result, error; unsigned long int neval; gsl_function F; F.function = &Redshift_rescaled; F.params = (void *) &pars[0]; gsl_set_error_handler_off(); gsl_integration_qng(&F, ZMIN, ZMAX, 1e-7, 1e-6, &result, &error, &neval); result *= 4.0 * M_PI; return result; } double GRBRate(double z, double n0, double n1, double n2, double z1) { double Rprime = Redshift_distribution_normalized(z, n0, n1, n2, z1) / (1.0 + z); Rprime *= DH3 * gsl_spline_eval(splineEz, z, accEz); Rprime *= 4.0 * M_PI * runargs.tobs * gsl_spline_eval(splineDF, z, accDF) / 6.0; return Rprime; } double GRBRateFunc(double z, void *params) { double *pars = (double *) params; double n0 = pars[0]; double n1 = pars[1]; double n2 = pars[2]; double z1 = pars[3]; return GRBRate(z, n0, n1, n2, z1); } double GRBRateIntegral(double n0, double n1, double n2, double z1) { double pars[4] = {n0, n1, n2, z1}; double result, error; unsigned long int neval; gsl_function F; F.function = &GRBRateFunc; F.params = (void *) &pars[0]; gsl_set_error_handler_off(); gsl_integration_qng(&F, ZMIN, ZMAX, 1e-7, 1e-6, &result, &error, &neval); return result; }
{ "alphanum_fraction": 0.675862069, "avg_line_length": 24.4959128065, "ext": "c", "hexsha": "b7f6782a938020d1feb6ded6f5a0c986de07d6a8", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-03-12T13:20:56.000Z", "max_forks_repo_forks_event_min_datetime": "2018-03-06T20:20:40.000Z", "max_forks_repo_head_hexsha": "6c8b88030446f594e7fb0963b4d0a3176b841d8e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "PBGraff/SwiftGRB_PEanalysis", "max_forks_repo_path": "src/poputils.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6c8b88030446f594e7fb0963b4d0a3176b841d8e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "PBGraff/SwiftGRB_PEanalysis", "max_issues_repo_path": "src/poputils.c", "max_line_length": 135, "max_stars_count": 5, "max_stars_repo_head_hexsha": "6c8b88030446f594e7fb0963b4d0a3176b841d8e", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "PBGraff/SwiftGRB_PEanalysis", "max_stars_repo_path": "src/poputils.c", "max_stars_repo_stars_event_max_datetime": "2021-04-19T12:24:14.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-04T18:20:32.000Z", "num_tokens": 3216, "size": 8990 }
/**************************************************************************** ** Copyright (c) 2021, Fougue Ltd. <http://www.fougue.pro> ** All rights reserved. ** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt ****************************************************************************/ #pragma once #include <gsl/span> namespace Mayo { template<typename T> using Span = gsl::span<T>; } // namespace Mayo
{ "alphanum_fraction": 0.4505747126, "avg_line_length": 27.1875, "ext": "h", "hexsha": "7fc492f398e4d9afd21f70deb5261b8e1f04c857", "lang": "C", "max_forks_count": 124, "max_forks_repo_forks_event_max_datetime": "2022-03-28T08:57:23.000Z", "max_forks_repo_forks_event_min_datetime": "2017-10-22T23:40:13.000Z", "max_forks_repo_head_hexsha": "881b81b2b6febe6fb88967e4eef6ef22882e1734", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "Unionfab/mayo", "max_forks_repo_path": "src/base/span.h", "max_issues_count": 102, "max_issues_repo_head_hexsha": "881b81b2b6febe6fb88967e4eef6ef22882e1734", "max_issues_repo_issues_event_max_datetime": "2022-03-24T15:24:28.000Z", "max_issues_repo_issues_event_min_datetime": "2017-05-18T09:36:26.000Z", "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "Unionfab/mayo", "max_issues_repo_path": "src/base/span.h", "max_line_length": 77, "max_stars_count": 382, "max_stars_repo_head_hexsha": "881b81b2b6febe6fb88967e4eef6ef22882e1734", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "Unionfab/mayo", "max_stars_repo_path": "src/base/span.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:08:24.000Z", "max_stars_repo_stars_event_min_datetime": "2018-02-24T23:46:02.000Z", "num_tokens": 77, "size": 435 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <time.h> #include <string.h> #include <gsl/gsl_rng.h> #include "dnestvars.h" /*! \file dnestpostprocess.c * \brief post process the sample generated by dnest. */ int cmp_sample(const void *pa, const void *pb); typedef struct { double logl, tiebreaker; int id; }SampleType; /* * This function calculates log(exp(x1) - exp(x2)). */ double logdiffexp(double x1, double x2) // x1 is larger { double biggest = x1; double xx1 = x1 - biggest, xx2 = x2 - biggest; return log(exp(xx1) - exp(xx2)) + biggest; } /* * This functions calculates log(exp(x1)+...+exp(xn)). */ double logsumexp(double *x, int n) { int j; double sum, max; max = x[0]; for(j = 0; j < n; j++) { max = fmax(max, x[j]); } sum = 0.0; for(j=0; j< n; j++) { sum += exp( x[j] - max); } return log(sum) + max; } void postprocess(double temperature) { printf("# Starts postprocess.\n"); FILE *fp, *fp_sample; double **levels_orig, **sample_info, *logl; int *sandwhich; double *psample; int i, j; int num_levels, num_samples; char buf[BUF_MAX_LENGTH]; int moreSample = 1; // read number of levels and samples fp = fopen(options.sampler_state_file, "r"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.sampler_state_file); exit(0); } fscanf(fp, "%d %d\n", &num_levels, &num_samples); fclose(fp); // allocate memory for levels levels_orig = malloc(num_levels * sizeof(double *)); for(i=0; i< num_levels; i++) { levels_orig[i] = malloc(3 * sizeof(double)); } // allocate memory for sample_info sample_info = malloc(num_samples * sizeof(double *)); for(i=0; i< num_samples; i++) { sample_info[i] = malloc(3 * sizeof(double)); } // allocate memory for samples logl = (void *)malloc(num_samples * sizeof(double)); sandwhich = malloc(num_samples * sizeof(int)); psample = (double *)malloc(dnest_size_of_modeltype); // read levels fp = fopen(options.levels_file, "r"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.levels_file); exit(0); } fgets(buf, BUF_MAX_LENGTH, fp); for(i=0; i < num_levels; i++) { if(feof(fp) != 0) { fprintf(stderr, "# Error: file %s ends at %d.\n", options.levels_file, i); exit(0); } fgets(buf, BUF_MAX_LENGTH, fp); if(sscanf(buf, "%lf %lf %lf", &levels_orig[i][0], &levels_orig[i][1], &levels_orig[i][2]) < 3) { fprintf(stderr, "# Error: Cannot read file %s.\n", options.levels_file); exit(0); } buf[0]='\0'; // clear up buf } fclose(fp); // read sample_info if(dnest_flag_sample_info == 0) //no need to recalculate { fp = fopen(options.sample_info_file, "r"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.sample_info_file); exit(0); } fgets(buf, BUF_MAX_LENGTH, fp); for(i=0; i < num_samples; i++) { if(feof(fp) != 0) { fprintf(stderr, "# Error: file %s ends at %d.\n", options.sample_info_file, i); exit(0); } fgets(buf, BUF_MAX_LENGTH, fp); if(sscanf(buf, "%lf %lf %lf", &sample_info[i][0], &sample_info[i][1], &sample_info[i][2]) < 3) { fprintf(stderr, "# Error: Cannot read file %s.\n", options.sample_info_file); exit(0); } buf[0]='\0'; // clear buf /* reset level assignment for levels larger than the maximum level numbers */ if(sample_info[i][0] > num_levels -1) sample_info[i][0] = num_levels - 1; } fclose(fp); } else //sample_info file doest not exist, need to recalculate. { fp = fopen(options.sample_info_file, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.sample_info_file); exit(0); } printf("# Dnest starts to recalculate the sample info.\n"); fprintf(fp, "# level assignment, log likelihood, tiebreaker, ID.\n"); //read sample fp_sample = fopen(options.sample_file, "r"); if(fp_sample == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.sample_file); exit(0); } fgets(buf, BUF_MAX_LENGTH, fp_sample); for(i=0; i < num_samples; i++) { read_particle(fp_sample, (void *)psample); sample_info[i][1] = log_likelihoods_cal_initial((void *)psample, dnest_arg); sample_info[i][2] = dnest_rand(); for(j=0; j<num_levels; j++) { if(sample_info[i][1] < levels_orig[j][1]) break; } /*j=num_levels-1; // find out the highest allowed level while( (sample_info[i][1] < levels_orig[j][1]) && (j>=0) ) { j--; }*/ sample_info[i][0] = (double)dnest_rand_int(j); // randomly assign a level [0, j-1] fprintf(fp, "%d %e %f %d\n", (int)sample_info[i][0], sample_info[i][1], sample_info[i][2], 1); } fclose(fp); fclose(fp_sample); } //tempering with a temperature for(i=0; i<num_samples; i++) logl[i] = sample_info[i][1] / temperature; // finding sandwhiching levels for each samples for(i=0; i<num_samples; i++) { sandwhich[i] = (int)sample_info[i][0]; for(j=sandwhich[i]; j < num_levels; j++) { if( sample_info[i][1] > levels_orig[j][1] ) sandwhich[i] = j; } //printf("%f %d\n", logl[i], sandwhich[i]); } double *logx_samples, *logp_samples, *logP_samples; double logx_min, logx_max, Umin, U; int num_samples_thisLevel; double *logx_samples_thisLevel; SampleType *logl_samples_thisLevel; double left, right; logx_samples = malloc(num_samples * sizeof(double)); logp_samples = malloc(num_samples * sizeof(double)); logP_samples = malloc(num_samples * sizeof(double)); logx_samples_thisLevel = malloc(num_samples * sizeof(double)); logl_samples_thisLevel = malloc(num_samples * sizeof(SampleType)); for(i=0; i<num_levels; i++) { logx_max = levels_orig[i][0]; if(i == num_levels - 1) logx_min = -1.0E300; else logx_min = levels_orig[i+1][0]; Umin = exp( logx_min - logx_max); // finding the samples sandwhiched by this levels num_samples_thisLevel = 0; for(j=0; j<num_samples; j++) if( sandwhich[j] == i ) { logl_samples_thisLevel[num_samples_thisLevel].logl = sample_info[j][1]; // logl logl_samples_thisLevel[num_samples_thisLevel].tiebreaker = sample_info[j][2]; // tiebreaker logl_samples_thisLevel[num_samples_thisLevel].id = j; // id num_samples_thisLevel++; } //printf("%d\n", num_samples_thisLevel); for(j=0; j<num_samples_thisLevel; j++) { U = Umin + (1.0 - Umin) * ( 1.0/(1.0 + num_samples_thisLevel) + ( 1.0 - 2.0/(1.0 + num_samples_thisLevel) ) * (num_samples_thisLevel-1 - j)/(num_samples_thisLevel - 1.0) ); logx_samples_thisLevel[j] = logx_max + log(U); } qsort(logl_samples_thisLevel, num_samples_thisLevel, sizeof(SampleType), cmp_sample); //printf("%f %f %d %f\n", logl_samples_thisLevel[0].logl, logl_samples_thisLevel[0].tiebreaker, logl_samples_thisLevel[0].id, logx_samples_thisLevel[0]); //printf("%f %f %d %f\n", logl_samples_thisLevel[1].logl, logl_samples_thisLevel[1].tiebreaker, logl_samples_thisLevel[1].id, logx_samples_thisLevel[1]); for(j = 0; j<num_samples_thisLevel; j++) { if(j != num_samples_thisLevel - 1) left = logx_samples_thisLevel[j+1]; else if (i == num_levels - 1) left = -1.0E300; else left = levels_orig[i+1][0]; if( j!= 0) right = logx_samples_thisLevel[j-1]; else right = levels_orig[i][0]; //printf("%e %e %e\n", right, left, logdiffexp(right, left)); logx_samples[logl_samples_thisLevel[j].id] = logx_samples_thisLevel[j]; logp_samples[logl_samples_thisLevel[j].id] = log(0.5) + logdiffexp(right, left); } } double sum, max, logz_estimates, H_estimates, ESS; sum = logsumexp(logp_samples, num_samples); for(j = 0; j < num_samples; j++) { logp_samples[j] -= sum; //logP_samples[j] = logp_samples[j] + sample_info[j][1]; logP_samples[j] = logp_samples[j] + logl[j]; } logz_estimates = logsumexp(logP_samples, num_samples); H_estimates = -logz_estimates; ESS = 0.0; for(j=0; j<num_samples; j++) { logP_samples[j] -= logz_estimates; //H_estimates += exp(logP_samples[j]) * sample_info[j][1]; H_estimates += exp(logP_samples[j]) * logl[j]; ESS += -logP_samples[j]*exp(logP_samples[j]); } ESS = exp(ESS); printf("log(Z) = %f\n", logz_estimates); printf("H = %f\n", H_estimates); printf("Effective sample size = %f\n", ESS); post_logz = logz_estimates; // resample to uniform weight int num_ps = moreSample*ESS; void *posterior_sample; double *posterior_sample_info; int *posterior_sample_idx; int which; const gsl_rng_type * dnest_post_gsl_T; gsl_rng * dnest_post_gsl_r; dnest_post_gsl_T = (gsl_rng_type *) gsl_rng_default; dnest_post_gsl_r = gsl_rng_alloc (dnest_post_gsl_T); #ifndef Debug gsl_rng_set(dnest_post_gsl_r, time(NULL)); #else gsl_rng_set(dnest_post_gsl_r, 8888); printf("# debugging, random seed %d\n", 8888); #endif posterior_sample = malloc(num_ps * dnest_size_of_modeltype); posterior_sample_info = malloc(num_ps * sizeof(double)); posterior_sample_idx = malloc(num_ps * sizeof(int)); // flag for which particle to save max = logP_samples[0]; for(j=0; j<num_samples; j++) max = fmax(logP_samples[j], max); for(j=0; j<num_samples; j++) logP_samples[j] -= max; for(j=0; j<num_ps; j++) { while(true) { which = gsl_rng_uniform_int(dnest_post_gsl_r, num_samples); if(log(gsl_rng_uniform(dnest_post_gsl_r)) < logP_samples[which]) { posterior_sample_info[j] = logl[which]; posterior_sample_idx[j] = which; // sample this particle break; } } } // read sample and pick out selected particles fp_sample = fopen(options.sample_file, "r"); if(fp_sample == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.sample_file); exit(0); } fgets(buf, BUF_MAX_LENGTH, fp_sample); for(i=0; i < num_samples; i++) { read_particle(fp_sample, (void *)psample); for(j=0; j < num_ps; j++) { if(posterior_sample_idx[j] == i) { memcpy(posterior_sample+j*dnest_size_of_modeltype, (void *)psample, dnest_size_of_modeltype); } } //printf("%f %f %f\n", sample[i].params[0], sample[i].params[1], sample[i].params[2]); } fclose(fp_sample); //save posterior sample fp = fopen(options.posterior_sample_file, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.posterior_sample_file); exit(0); } fprintf(fp, "# %d\n", num_ps); for(i=0; i<num_ps; i++) { print_particle(fp, posterior_sample + i*dnest_size_of_modeltype, dnest_arg); } fclose(fp); //save posterior sample information fp = fopen(options.posterior_sample_info_file, "w"); if(fp == NULL) { fprintf(stderr, "# Error: Cannot open file %s.\n", options.posterior_sample_info_file); exit(0); } fprintf(fp, "# %d\n", num_ps); for(i=0; i<num_ps; i++) { fprintf(fp, "%e\n", posterior_sample_info[i]); } fclose(fp); for(i=0; i<num_levels; i++) free(levels_orig[i]); free(levels_orig); for(i=0; i<num_samples; i++) free(sample_info[i]); free(sample_info); free(logl); free(logx_samples); free(logx_samples_thisLevel); free(logp_samples); free(logP_samples); free(logl_samples_thisLevel); free(sandwhich); free(psample); free(posterior_sample); free(posterior_sample_info); free(posterior_sample_idx); gsl_rng_free(dnest_post_gsl_r); printf("# Ends dnest postprocess.\n"); } int cmp_sample(const void *pa, const void *pb) { SampleType *a = (SampleType *)pa; SampleType *b = (SampleType *)pb; // in acesending order if(a->logl > b->logl) return true; if( a->logl == b->logl && a->tiebreaker > b->tiebreaker) return true; return false; }
{ "alphanum_fraction": 0.621226718, "avg_line_length": 26.9028077754, "ext": "c", "hexsha": "679934e06db28fb5048975237b2fe0455469db9c", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-06T11:26:06.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-05T02:01:57.000Z", "max_forks_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/pyCALI", "max_forks_repo_path": "src/pycali/cdnest/dnestpostprocess.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/pyCALI", "max_issues_repo_path": "src/pycali/cdnest/dnestpostprocess.c", "max_line_length": 157, "max_stars_count": 3, "max_stars_repo_head_hexsha": "e232531b5c6f7817b6e3bd34dbb31463807ae2b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/PyCALI", "max_stars_repo_path": "src/pycali/cdnest/dnestpostprocess.c", "max_stars_repo_stars_event_max_datetime": "2022-01-13T09:23:59.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-14T01:32:41.000Z", "num_tokens": 3737, "size": 12456 }
//===------------------------------------------------------------*- C++ -*-===// // // This file is distributed under MIT License. See LICENSE.txt for details. // //===----------------------------------------------------------------------===// // // Copyright (c) 2017 University of Kaiserslautern. // #pragma once #include <nlopt.h> namespace gosat { class OptConfig { public: OptConfig(); OptConfig(nlopt_algorithm global_alg, nlopt_algorithm local_alg); virtual ~OptConfig() = default; int MaxEvalCount; int MaxLocalEvalCount; double RelTolerance; double Bound; double StepSize; unsigned InitialPopulation; }; class NLoptOptimizer { public: NLoptOptimizer(); NLoptOptimizer(nlopt_algorithm global_alg, nlopt_algorithm local_alg = NLOPT_LN_BOBYQA); virtual ~NLoptOptimizer() = default; int optimize (nlopt_func func, unsigned dim, double* x, double* min) const noexcept; double eval (nlopt_func func, unsigned dim, const double* x) const noexcept; bool existsRoundingError (nlopt_func func, unsigned int dim, const double* x, const double* min) const noexcept; void fixRoundingErrorNearZero (nlopt_func const func, unsigned dim, double* x, double* min) const noexcept; int refineResult(nlopt_func func, unsigned dim, double* x, double* min); static bool isSupportedGlobalOptAlg(nlopt_algorithm opt_alg) noexcept; static bool isSupportedLocalOptAlg(nlopt_algorithm local_opt_alg) noexcept; static bool isRequireLocalOptAlg(nlopt_algorithm opt_alg) noexcept; static bool isRequirePopulation(nlopt_algorithm opt_alg) noexcept; private: const nlopt_algorithm m_global_opt_alg; const nlopt_algorithm m_local_opt_alg; public: OptConfig Config; }; }
{ "alphanum_fraction": 0.6263678999, "avg_line_length": 24.9220779221, "ext": "h", "hexsha": "b81deef4007325fd6c61375f40f95160d7a67c36", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-01-13T08:54:13.000Z", "max_forks_repo_forks_event_min_datetime": "2017-11-27T21:11:28.000Z", "max_forks_repo_head_hexsha": "dd4bd306119f2411dbda05514985ff94535f18ff", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "abenkhadra/gosat", "max_forks_repo_path": "src/Optimizer/NLoptOptimizer.h", "max_issues_count": 7, "max_issues_repo_head_hexsha": "dd4bd306119f2411dbda05514985ff94535f18ff", "max_issues_repo_issues_event_max_datetime": "2018-01-23T16:26:25.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-28T18:17:08.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "abenkhadra/gosat", "max_issues_repo_path": "src/Optimizer/NLoptOptimizer.h", "max_line_length": 80, "max_stars_count": 21, "max_stars_repo_head_hexsha": "dd4bd306119f2411dbda05514985ff94535f18ff", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "abenkhadra/gosat", "max_stars_repo_path": "src/Optimizer/NLoptOptimizer.h", "max_stars_repo_stars_event_max_datetime": "2022-02-15T20:28:18.000Z", "max_stars_repo_stars_event_min_datetime": "2017-10-13T06:48:53.000Z", "num_tokens": 424, "size": 1919 }
// ${_warning_in_the_generated_file_not_to_edit} #include <gsl/gsl_matrix.h> #include <gsl/gsl_errno.h> #include <math.h> #include "neqsys.h" // Global counters int NFEV = 0; int NJEV = 0; int NFJEV = 0; int func (const gsl_vector * x, void * params, gsl_vector * f) { /* Best is to name all parameters k[0] ... k[P] */ const double *k = (double *) params; const double * const y = (double *) x->data; /* Define variables for common subexpressions */ % for cse_token, cse_expr in func_cse_defs: const double ${cse_token} = ${cse_expr}; % endfor /* Calculate residuals */ % for i, expr in enumerate(func_new_code): gsl_vector_set(f, ${i}, ${expr}); % endfor NFEV++; return GSL_SUCCESS; } int jac (const gsl_vector * x, void *params, gsl_matrix * J) { const double *k = (double *) params; const double * const y = (double *) x->data; /* Define variables for common subexpressions */ % for cse_token, cse_expr in jac_cse_defs: const double ${cse_token} = ${cse_expr}; % endfor /* Populate the NY times NY Jacobian matrix */ % for i, expr in enumerate(jac_new_code): gsl_matrix_set (J, ${i // NX}, ${i % NX}, ${expr}); % endfor NJEV++; return GSL_SUCCESS; } int fdf (const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J) { const double * const k = (double *) params; const double * const y = (double *) x->data; /* Define variables for common subexpressions */ % for cse_token, cse_expr in fj_cse_defs: const double ${cse_token} = ${cse_expr}; % endfor /* Calculate residuals */ % for i, expr in enumerate(fj_func_new_code): gsl_vector_set(f, ${i}, ${expr}); % endfor /* Populate the NY times NY Jacobian matrix */ % for i, expr in enumerate(fj_jac_new_code): gsl_matrix_set (J, ${i // NX}, ${i % NX}, ${expr}); % endfor NFJEV++; return GSL_SUCCESS; }
{ "alphanum_fraction": 0.6393875396, "avg_line_length": 19.3265306122, "ext": "c", "hexsha": "adeb37743480c0d18367cea66119644b786526e9", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "677307d6b94e452262f7ffe944ec2bed6314d34b", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "bjodah/symneqsys", "max_forks_repo_path": "symneqsys/gsl/neqsys_template.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "677307d6b94e452262f7ffe944ec2bed6314d34b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "bjodah/symneqsys", "max_issues_repo_path": "symneqsys/gsl/neqsys_template.c", "max_line_length": 73, "max_stars_count": 1, "max_stars_repo_head_hexsha": "677307d6b94e452262f7ffe944ec2bed6314d34b", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "bjodah/symneqsys", "max_stars_repo_path": "symneqsys/gsl/neqsys_template.c", "max_stars_repo_stars_event_max_datetime": "2015-01-10T09:00:04.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-10T09:00:04.000Z", "num_tokens": 573, "size": 1894 }
#pragma once #include <gsl.h> #include "types/MT3_MathChar.h" #include "types/MT3_Radical.h" #include "types/MT3_Accent.h" #include "types/MT3_VCenter.h" #include "types/MT3_Overline.h" #include "types/MT3_Underline.h" #include "types/MT3_GenFraction.h" #include "types/MT3_LeftRight.h" #include "types/MT3_Script.h" #include "types/MT3_BigOp.h" #include "types/MT3_SubBox.h" #include "types/MT3_MList.h" #include "types/MT3_Kind.h" #include "types/MT3_MPen.h" #include "types/MT3_MSpace.h" #include "types/MT3_Style.h" #include "types/MT3_Choice.h"
{ "alphanum_fraction": 0.7644927536, "avg_line_length": 25.0909090909, "ext": "h", "hexsha": "1e19dabf72f39b7274e11879c070a7aead30ad19", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "robin33n/formulae-cxx", "max_forks_repo_path": "include/math/MathTypes.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_issues_repo_issues_event_max_datetime": "2019-09-26T11:32:00.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-25T11:10:39.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "robin33n/formulae-cxx", "max_issues_repo_path": "include/math/MathTypes.h", "max_line_length": 34, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4b691e515b30508fb5e29c68426bad51d9629e72", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "robin33n/formulae-cxx", "max_stars_repo_path": "include/math/MathTypes.h", "max_stars_repo_stars_event_max_datetime": "2019-11-25T04:00:03.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-25T04:00:03.000Z", "num_tokens": 186, "size": 552 }
#ifndef FORCE_H #define FORCE_H #include <functional> #include <gsl/gsl_integration.h> #include <gsl/gsl_errno.h> #include <vector> #include "jspec2/electron_beam.h" #include "jspec2/constants.h" using std::vector; enum class ForceFormula {PARKHOMCHUK, NONMAG_DERBENEV, NONMAG_MESHKOV, NONMAG_NUM1D, NONMAG_NUM3D, MESHKOV, DSM}; class FrictionForceSolver{ protected: double time_cooler; double mag_field = 0; static constexpr double k_f = -4*k_pi*k_c*k_c*k_ke*k_ke*k_e*k_e*k_e/(k_me*1e6); static constexpr double k_wp = 4*k_pi*k_c*k_c*k_e*k_ke/(k_me*1e6); static constexpr double k_rho_min = k_e*k_ke*k_c*k_c/(k_me*1e6); virtual void init(const ElectronBeam& ebeam){}; virtual void fin(){}; double max_impact_factor(double v_dlt, int charge_number,double density_e); public: void set_time_cooler(double t){time_cooler = t;} void set_mag_field(double x){mag_field = x;} double t_cooler() const {return time_cooler;} virtual void friction_force(int charge_number, int ion_number, const vector<double>& v_tr, const vector<double>& v_l, const vector<double>& density, const ElectronBeam& ebeam, vector<double>& force_tr, vector<double>& force_long) = 0; }; class ForcePark: public FrictionForceSolver { private: static constexpr double k_f = -4*k_c*k_c*k_ke*k_ke*k_e*k_e*k_e/(k_me*1e6); double t_eff = 0; //Effective temperature. double v_eff = 0; //Effective velocity. void rho_lamor_dlt2_eff_e(double v2_eff_e, double mag_field, const vector<double>& v_rms_l, const vector<double>& v_rms_t, ElectronBeam::Temperature tpr, int ion_number, vector<double>& dlt2_eff_e, vector<double>& rho_lamor); constexpr double dlt(ElectronBeam::Temperature tpr, double v2, const vector<double>& dlt2_eff_e, int i); constexpr double lc(ElectronBeam::Temperature tpr, double rho_max, double rho_min, const vector<double>& rho_lamor, int i); public: void set_t_eff(double x){t_eff = x; v_eff = sqrt(t_eff*k_c*k_c/(k_me*1e6));} void set_v_eff(double v){v_eff = v; t_eff = v_eff*v_eff*k_me*1e6/(k_c*k_c);} virtual void friction_force(int charge_number, int ion_number, const vector<double>& v_tr, const vector<double>& v_l, const vector<double>& density, const ElectronBeam& ebeam, vector<double>& force_tr, vector<double>& force_long) override; }; class ForceNonMag: public FrictionForceSolver { protected: bool smooth_rho_max = false; virtual double f_const(int charge_number) const {return charge_number*charge_number*k_f;} static constexpr double rho_min_const(int charge_number) {return charge_number*k_rho_min;} static constexpr double rho_max_1(int charge_number, double density_e){return pow(3*charge_number/density_e, 1.0/3);} double rho_max_2(double v) const {return v*time_cooler;} double rho_max(int charge_number, double v2, double ve2, double ne) const; virtual void force(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const,double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l) = 0; public: void set_smooth_rho_max(bool b){smooth_rho_max = b;} virtual void friction_force(int charge_number, int ion_number, const vector<double>& v_tr, const vector<double>& v_l, const vector<double>& density, const ElectronBeam& ebeam, vector<double>& force_tr, vector<double>& force_long) override; }; class ForceNonMagDerbenev: public ForceNonMag { private: constexpr double rho_max_ve_tr(double ve_tr, double ne); void force(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const, double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l) override; public: }; class ForceNonMagMeshkov: public ForceNonMag { private: void force(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const, double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l) override; public: }; class ForceNonMagNumeric1D: public ForceNonMag { private: double f_const(int charge_number) const override {return 0.28209479177387814*charge_number*charge_number*k_f;} //Coef - 1/sqrt(4*pi) static constexpr double k_f = 2*sqrt(2*k_pi)*k_pi*k_c*k_c*k_ke*k_ke*k_e*k_e*k_e/(k_me*1e6); size_t limit = 100; double espabs = 1e-6; double esprel = 1e-6; struct P{ double v_tr; double v_l; double ve_tr; double ve_l; int flag; //0: calculate B_tr; else: calculate B_l; }; #ifdef _OPENMP vector<gsl_integration_workspace*> gw; vector<P> p; #else gsl_integration_workspace *gw = nullptr; P p; #endif // _OPENMP double b(double q, void* params); void force(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const, double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l) override; public: void set_espabs(double x){espabs = x;} void set_esprel(double x){esprel = x;} ForceNonMagNumeric1D(int n=100); ~ForceNonMagNumeric1D(); }; // class ForceNonMagNumeric3D: public ForceNonMag { private: size_t limit = 100; double espabs = 1e-5; double esprel = 1e-3; struct P{ double v_tr; double v_l; double ve_tr; double ve_l; double vtr; double vl; double rho_max; int charge_number; int flag; //0: calculate B_tr; else: calculate B_l; }; bool use_gsl = false; bool use_mean_rho_min = false; #ifdef _OPENMP vector<gsl_integration_workspace*> giw; vector<gsl_integration_workspace*> gmw; vector<gsl_integration_workspace*> gow; vector<P> p; #else gsl_integration_workspace *giw = nullptr; gsl_integration_workspace *gmw = nullptr; gsl_integration_workspace *gow = nullptr; P p; #endif // _OPENMP #ifdef _OPENMP static double mean_rho_min; static double mean_lc; #pragma omp threadprivate(mean_rho_min, mean_lc) static bool first_run; static vector<vector<double>> exp_vtr; static vector<double> hlf_v2tr; static vector<double> hlf_v2l; static vector<vector<double>> vtr_cos; static vector<double> vl; static vector<double> vtr; static vector<vector<double>> v2tr_sin2; #pragma omp threadprivate(exp_vtr, hlf_v2tr, hlf_v2l, vtr_cos, vl, vtr, v2tr_sin2, first_run) #else double mean_rho_min = 0; double mean_lc = 0; vector<vector<double>> exp_vtr; vector<double> hlf_v2tr; vector<double> hlf_v2l; vector<vector<double>> vtr_cos; vector<double> vl; vector<double> vtr; vector<vector<double>> v2tr_sin2; bool first_run = true; #endif // _OPENMP bool const_tmpr = true; int n_tr = 20; int n_l = 10; int n_phi = 10; double d; double f_inv_norm; void pre_int(double sgm_vtr, double sgm_vl); void calc_exp_vtr(double sgm_vtr, double sgm_vl); void init(const ElectronBeam& ebeam) override; double inner_integrand(double phi, void* params); double middle_integrand(double vl, void* params); double outter_integrand(double vtr, void* params); double inner_norm_integrand(double vl, void* params); double outter_norm_integrand(double vtr, void* params); void force_grid(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const, double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l); void force_gsl(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const, double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l); void force(double v, double v_tr, double v_l, double v2, double ve_tr, double ve_l, double ve2, double f_const, double rho_min_const, int charge_number, double ne, double& force_tr, double& force_l) override; public: void set_espabs(double x){espabs = x;} void set_esprel(double x){esprel = x;} void set_gsl(bool b) {use_gsl = b;} void set_mean_rho_min(bool b) {use_mean_rho_min = b;} void set_grid(int ntr, int nl, int nphi){n_tr = ntr; n_l = nl; n_phi = nphi; first_run = true;} ForceNonMagNumeric3D(int n=100); ~ForceNonMagNumeric3D(); }; //gsl function wrapper for member functions in class. template< typename F > class gsl_function_pp : public gsl_function { public: gsl_function_pp(const F& func) : _func(func) { function = &gsl_function_pp::invoke; params=this; } private: const F& _func; static double invoke(double x, void *params) { return static_cast<gsl_function_pp*>(params)->_func(x); } }; class ForceMeshkov: public FrictionForceSolver { protected: //A fudge factor to smooth the friction force shape. Using the // "Classical" default definition here from the BETACOOL documentation double k = 2; void force(double ve_tr, double ve_l, double ve2_tr, double ve2_l, double v_tr, double v_l, double v2, double rho_min_const, int charge_number, double density, double f_const, double& force_tr,double& force_l); public: void set_smooth_factor(double x){k = x;} virtual void friction_force(int charge_number, int ion_number, const vector<double>& v_tr, const vector<double>& v_l, const vector<double>& density, const ElectronBeam& ebeam, vector<double>& force_tr, vector<double>& force_long) override; }; class ForceDSM: public FrictionForceSolver { //Derbenev-Skrinsky-Meshkov formula for magnetized cooling. bool mag_only = false; //A fudge factor to smooth the friction force shape. Using the // "Classical" default definition here from the BETACOOL documentation double k = 2; int n_a = 100; int n_ve = 100; bool const_tpr = true; #ifdef _OPENMP static bool first_run; static vector<double> a; static vector<double> cos_a; static vector<double> tan_a; static vector<double> t2; static vector<double> ve; static vector<double> exp_ve2; #pragma omp threadprivate(a, cos_a, tan_a, t2, ve, exp_ve2, first_run) #else bool first_run = true; vector<double> a; vector<double> cos_a; vector<double> tan_a; vector<double> t2; vector<double> ve; vector<double> exp_ve2; #endif // _OPENMP int n_tr = 20; int n_l = 10; int n_phi = 10; #ifdef _OPENMP static bool first_run_fa; static double f_inv_norm; static vector<vector<double>> exp_vtr; static vector<double> hlf_v2tr; static vector<double> hlf_v2l; static vector<vector<double>> vtr_cos; static vector<double> vl; static vector<double> vtr; static vector<vector<double>> v2tr_sin2; #pragma omp threadprivate(exp_vtr, hlf_v2tr, hlf_v2l, vtr_cos, vl, vtr, v2tr_sin2, first_run_fa, f_inv_norm) #else bool first_run_fa = true; double f_inv_norm; vector<vector<double>> exp_vtr; vector<double> hlf_v2tr; vector<double> hlf_v2l; vector<vector<double>> vtr_cos; vector<double> vl; vector<double> vtr; vector<vector<double>> v2tr_sin2; #endif // _OPENMP protected: void init(const ElectronBeam& ebeam) override; void pre_int(double sgm_vtr, double sgm_vl); void calc_exp_vtr(double sgm_vtr, double sgm_vl); void calc_alpha(); void calc_ve(); void calc_exp_ve2(double ve2_l, vector<double>& t2); void force(double ve_tr, double ve_l, double ve2_tr, double ve2_l, double v_tr, double v_l, double v2, double rho_min_const, int charge_number, double density, double f_const, double& force_tr,double& force_l); public: void set_smooth_factor(double x){k = x;} void set_steps(int i) {n_a = i; n_ve = i; first_run = true;} void set_grid(int ntr, int nl, int nphi){n_tr = ntr; n_l = nl; n_phi = nphi; first_run_fa = true;} void set_mag_only(bool b){mag_only = b;} virtual void friction_force(int charge_number, int ion_number, const vector<double>& v_tr, const vector<double>& v_l, const vector<double>& density, const ElectronBeam& ebeam, vector<double>& force_tr, vector<double>& force_long) override; }; #endif // FORCE_H
{ "alphanum_fraction": 0.6829382774, "avg_line_length": 39.946875, "ext": "h", "hexsha": "b995bc52d28147236ee66e0a797bab9fddb4b467", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "mbruker/jspec2-python", "max_forks_repo_path": "include/jspec2/force.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "mbruker/jspec2-python", "max_issues_repo_path": "include/jspec2/force.h", "max_line_length": 157, "max_stars_count": null, "max_stars_repo_head_hexsha": "c82b41cf0a314f15eb84ab15b0de96ac2992bf9c", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "mbruker/jspec2-python", "max_stars_repo_path": "include/jspec2/force.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3440, "size": 12783 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include <unordered_map> #include <mutex> #include <gsl/gsl> #include <typeindex> #include "arcana/containers/ticketed_collection.h" #include "arcana/string.h" #if NDEBUG #define FIRE_OBJECT_TRACE(...) #else #define OBJECT_TRACE_ENABLED #define FIRE_OBJECT_TRACE(channelName, instance, evt) \ ::mira::object_trace::fire(channelName, instance, evt) #endif namespace mira { /* Simple static analysis of data for exposing */ class object_trace final { using channel_callback = std::function<void(std::intptr_t, const void*)>; using global_callback = std::function<void(const char*, std::intptr_t, const void*)>; using channel_ticketed_collection = ticketed_collection<channel_callback, std::recursive_mutex>; using global_ticketed_collection = ticketed_collection<global_callback, std::recursive_mutex>; public: using channel_ticket = channel_ticketed_collection::ticket; using global_ticket = global_ticketed_collection::ticket; object_trace() = delete; /* Adds a listener to type T on the specified channel. The channel is useful to split data into logical streams. */ template<typename T> static auto listen(const char* channel, std::function<void(std::intptr_t, T&)> callback) { return add_listener(channel, std::type_index{ typeid(std::decay_t<T>) }, [callback = std::move(callback)](std::intptr_t instance, const void* data) { callback(instance, const_cast<T&>(*reinterpret_cast<const T*>(data))); }); } /* Adds a listener to type T to all channels. */ template<typename T> static auto listen(std::function<void(const char*, std::intptr_t, T&)> callback) { return add_listener(std::type_index{ typeid(std::decay_t<T>) }, [callback = std::move(callback)](const char* channel, std::intptr_t instance, const void* data) { callback(channel, instance, const_cast<T&>(*reinterpret_cast<const T*>(data))); }); } /* Fires an event in the specified channel. */ template<typename T> static void fire(const char* channel, const void* instance, const T& evt) { fire_event(channel, (std::intptr_t)instance, std::type_index{ typeid(std::decay_t<T>) }, &evt); } private: using channels = std::map<std::string, channel_ticketed_collection, string_compare>; struct listeners { channels ChannelListeners; global_ticketed_collection GlobalListeners; }; static channel_ticket add_listener(const char* channel, const std::type_index& type, channel_callback callback); static global_ticket add_listener(const std::type_index& type, global_callback callback); static void fire_event(const char* channel, std::intptr_t instance, const std::type_index& type, const void* data); static std::recursive_mutex m_mutex; static std::unordered_map<std::type_index, listeners> m_typemap; }; }
{ "alphanum_fraction": 0.6473988439, "avg_line_length": 34.9680851064, "ext": "h", "hexsha": "d250ec1baab267e9bb541eb9b966255236090925", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/object_trace.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/object_trace.h", "max_line_length": 159, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/analysis/object_trace.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 681, "size": 3287 }
#pragma once // View structures // STATUS: prototype, NSC #include <vector> #include <gsl.h> namespace duck { /* span<T> represents a reference to a segment of a T array. * Equivalent to a (T* base, int len). */ using gsl::span; /* string_view: Const reference (pointer) to a sequence of char. * Does not own the data, only points to it. * The char sequence may not be null terminated. * * std::string_view exists in C++17, but not before sadly. */ using string_view = gsl::cstring_span; using gsl::to_string; // Create new std::string from string_view bool is_prefix_of (string_view prefix, string_view str); bool is_prefix_of (char prefix, string_view str); // Split at separator. Does not remove empty parts, does not trim whitespace. std::vector<string_view> split (char separator, string_view text); } // namespace duck
{ "alphanum_fraction": 0.7285714286, "avg_line_length": 26.25, "ext": "h", "hexsha": "06e9eb56421d44de0a48fc6fce247e78471b9492", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "dc419c0ec496c1d7e809b6f1b473e03a709c75bd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lereldarion/duck", "max_forks_repo_path": "cpp/duck/view.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "dc419c0ec496c1d7e809b6f1b473e03a709c75bd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lereldarion/duck", "max_issues_repo_path": "cpp/duck/view.h", "max_line_length": 77, "max_stars_count": null, "max_stars_repo_head_hexsha": "dc419c0ec496c1d7e809b6f1b473e03a709c75bd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lereldarion/duck", "max_stars_repo_path": "cpp/duck/view.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 202, "size": 840 }
/* gsl_histogram2d_maxval.c * Copyright (C) 2000 Simone Piccardi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /*************************************************************** * * File gsl_histogram2d_maxval.c: * Routine to find maximum and minumum content of a 2D hisogram. * Need GSL library and header. * Contains the routines: * gsl_histogram2d_max_val find max content values * gsl_histogram2d_min_val find min content values * gsl_histogram2d_bin_max find coordinates of max contents bin * gsl_histogram2d_bin_min find coordinates of min contents bin * * Author: S. Piccardi * Jan. 2000 * ***************************************************************/ #include <config.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram2d.h> /* * Return the maximum contents value of a 2D histogram */ double gsl_histogram2d_max_val (const gsl_histogram2d * h) { const size_t nx = h->nx; const size_t ny = h->ny; size_t i; double max = h->bin[0 * ny + 0]; for (i = 0; i < nx * ny; i++) { if (h->bin[i] > max) { max = h->bin[i]; } } return max; } /* * Find the bin index for maximum value of a 2D histogram */ void gsl_histogram2d_max_bin (const gsl_histogram2d * h, size_t * imax_out, size_t * jmax_out) { const size_t nx = h->nx; const size_t ny = h->ny; size_t imax = 0, jmax = 0, i, j; double max = h->bin[0 * ny + 0]; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { double x = h->bin[i * ny + j]; if (x > max) { max = x; imax = i; jmax = j; } } } *imax_out = imax; *jmax_out = jmax; } /* * Return the minimum contents value of a 2D histogram */ double gsl_histogram2d_min_val (const gsl_histogram2d * h) { const size_t nx = h->nx; const size_t ny = h->ny; size_t i; double min = h->bin[0 * ny + 0]; for (i = 0; i < nx * ny; i++) { if (h->bin[i] < min) { min = h->bin[i]; } } return min; } /* * Find the bin index for minimum value of a 2D histogram */ void gsl_histogram2d_min_bin (const gsl_histogram2d * h, size_t * imin_out, size_t * jmin_out) { const size_t nx = h->nx; const size_t ny = h->ny; size_t imin = 0, jmin = 0, i, j; double min = h->bin[0 * ny + 0]; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { double x = h->bin[i * ny + j]; if (x < min) { min = x; imin = i; jmin = j; } } } *imin_out = imin; *jmin_out = jmin; }
{ "alphanum_fraction": 0.5970243748, "avg_line_length": 22.5642857143, "ext": "c", "hexsha": "163d69fec0675e450139bd2be0ac148f26660941", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/histogram/maxval2d.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/histogram/maxval2d.c", "max_line_length": 89, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/maxval2d.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 972, "size": 3159 }
#include <jni.h> #include <assert.h> #include <lapacke.h> extern void dtrmv_(char *uplo, char *trans, char *diag, int *n, double *A, int *lda, double *x, int *incx); #define jniRowMajor 101 #define jniColMajor 102 #define jniNoTrans 111 #define jniTrans 112 #define jniConjTrans 113 #define jniUpper 121 #define jniLower 122 #define jniNonUnit 131 #define jniUnit 132 #define jniLeft 141 #define jniRight 142 JNIEXPORT jint Java_JAMAJni_EigenvalueDecomposition_dgeev (JNIEnv *env, jclass klass, jint matrix_layout, jchar jobvl, jchar jobvr, jint n, jdoubleArray a, jint lda, jdoubleArray wr, jdoubleArray wi, jdoubleArray vl, jint ldvl, jdoubleArray vr, jint ldvr){ double *aElems, *wrElems, *wiElems, *vlElems, *vrElems; int info; aElems = (*env)-> GetDoubleArrayElements (env, a, NULL); wrElems = (*env)-> GetDoubleArrayElements (env, wr, NULL); wiElems = (*env)-> GetDoubleArrayElements (env, wi, NULL); vlElems = (*env)-> GetDoubleArrayElements (env, vl, NULL); vrElems = (*env)-> GetDoubleArrayElements (env, vr, NULL); assert(aElems && wrElems && wiElems && vlElems && vrElems); info = LAPACKE_dgeev((int) matrix_layout, (char) jobvl, (char) jobvr, (lapack_int) n, aElems, (lapack_int) lda, wrElems, wiElems, vlElems, (lapack_int) ldvl, vrElems, (lapack_int) ldvr); (*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0); (*env)-> ReleaseDoubleArrayElements (env, vl, vlElems, 0); (*env)-> ReleaseDoubleArrayElements (env, vr, vrElems, 0); (*env)-> ReleaseDoubleArrayElements (env, wr, wrElems, 0); (*env)-> ReleaseDoubleArrayElements (env, wi, wiElems, 0); return info; } JNIEXPORT void JNICALL Java_JAMAJni_EigenvalueDecomposition_dsyev (JNIEnv *env, jclass obj, jint layout, jchar jobz, jchar uplo, jint n, jdoubleArray ja, jint lda, jdoubleArray jw) { jdouble *a = (*env)-> GetDoubleArrayElements (env, ja, NULL); jdouble *w = (*env)-> GetDoubleArrayElements (env, jw, NULL); assert(a && w); LAPACKE_dsyev((int) layout, (char) jobz, (char) uplo, (lapack_int) n, a, (lapack_int) lda, w); (*env)-> ReleaseDoubleArrayElements (env, ja, a, 0); (*env)-> ReleaseDoubleArrayElements (env, jw, w, 0); } JNIEXPORT void JNICALL Java_JAMAJni_EigenvalueDecomposition_dtrsm (JNIEnv *env, jclass obj, jint layout, jchar jobz, jchar uplo, jint n, jdoubleArray ja, jint lda, jdoubleArray jw) { jdouble *a = (*env)-> GetDoubleArrayElements (env, ja, NULL); jdouble *w = (*env)-> GetDoubleArrayElements (env, jw, NULL); assert(a && w); LAPACKE_dsyev((int) layout, (char) jobz, (char) uplo, (lapack_int) n, a, (lapack_int) lda, w); (*env)-> ReleaseDoubleArrayElements (env, ja, a, 0); (*env)-> ReleaseDoubleArrayElements (env, jw, w, 0); }
{ "alphanum_fraction": 0.6707487754, "avg_line_length": 33.6235294118, "ext": "c", "hexsha": "241c8dfdb858299aa375c95ced92a5102a28779c", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_forks_repo_licenses": [ "AAL" ], "max_forks_repo_name": "dw6ja/JAMAJni", "max_forks_repo_path": "src/jni_lapacke/c/EigenvalueDecomposition.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "AAL" ], "max_issues_repo_name": "dw6ja/JAMAJni", "max_issues_repo_path": "src/jni_lapacke/c/EigenvalueDecomposition.c", "max_line_length": 190, "max_stars_count": null, "max_stars_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718", "max_stars_repo_licenses": [ "AAL" ], "max_stars_repo_name": "dw6ja/JAMAJni", "max_stars_repo_path": "src/jni_lapacke/c/EigenvalueDecomposition.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 934, "size": 2858 }
#ifndef NonLinearLSQ_h #define NonLinearLSQ_h /** * @file * $Revision: 4928 $ * $Date: 2012-12-21 10:44:12 -0700 (Fri, 21 Dec 2012) $ * $Id: NonLinearLSQ.h 4928 2012-12-21 17:44:12Z slambright@GS.DOI.NET $ * * Unless noted otherwise, the portions of Isis written by the USGS are * public domain. See individual third-party library and package descriptions * for intellectual property information, user agreements, and related * information. * * Although Isis has been used by the USGS, no warranty, expressed or * implied, is made by the USGS as to the accuracy and functioning of such * software and related material nor shall the fact of distribution * constitute any such warranty, and no responsibility is assumed by the * USGS in connection therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html * in a browser or see the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include <iostream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <QString> #include <tnt_array1d.h> #include <tnt_array1d_utils.h> #include <tnt_array2d.h> #include <tnt_array2d_utils.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlin.h> #include "IException.h" namespace Isis { /** * @brief NonLinearLSQ Computes a fit using a Levenberg-Marquardt algorithm * * This virtual base class uses the GSL toolkit to apply the * Levenberg-Marquardt algorithm to fit data to a non-linear equation using * least squares. * * @ingroup Utility * @author 2007-11-15 Kris Becker * * @internal */ class NonLinearLSQ { public: typedef TNT::Array1D<double> NLVector; typedef TNT::Array2D<double> NLMatrix; // Constructors and Destructor NonLinearLSQ() : _fitParms(), _uncert(), _nIters(0), _maxIters(50), _status(0), _userTerminated(false), _userMessage() {} /** Destructor */ virtual ~NonLinearLSQ() { } virtual int nSize() const = 0; virtual int nParms() const = 0; /** * @brief Sets the maximum number of iterations * * @param m User provides the maximum number iterations */ void setMaxIters(int m) { _maxIters = m; } /** * @brief Maximum number iterations for valid solution * * * @return int Maximum resolutions */ int maxIters() const { return (_maxIters); } virtual NLVector guess() = 0; virtual NLVector f_x(const NLVector &x) = 0; virtual NLMatrix df_x(const NLVector &x) = 0; virtual double absErr() const { return (1.0E-4); } virtual double relErr() const { return (1.0E-4); } int curvefit(); /** Return status of last fit processing */ inline int status() const { return (_status); } /** Determine success from last fit processing */ inline bool success() const { return (_status == GSL_SUCCESS); } /** Check status for success of the given condition */ inline bool success(int status) const { return (status == GSL_SUCCESS); } /** Return error message pertaining to last fit procesing */ inline QString statusstr() const { return (QString(gsl_strerror(_status))); } /** Return error message given status condition */ inline QString statusstr(int status) const { return (QString(gsl_strerror(status))); } /** Default interation test simply returns input status */ virtual int checkIteration(const int Iter, const NLVector &fitcoefs, const NLVector &uncerts, double cplxconj, int Istatus) { return (Istatus); } /** Return coefficients from last fit processing */ inline NLVector coefs() const { return (_fitParms); } /** Return uncertainties from last fit processing */ inline NLVector uncert() const { return (_uncert); } /** Return number of iterations from last fit processing */ inline int nIterations() const { return (_nIters); } protected: void Terminate(const QString &message = ""); void Abort(const QString &reason = ""); bool doContinue() const { return (!_userTerminated); } private: NLVector _fitParms; NLVector _uncert; int _nIters; int _maxIters; int _status; bool _userTerminated; QString _userMessage; struct _nlsqPointer { NonLinearLSQ *nlsq; }; static int f(const gsl_vector *x, void *params, gsl_vector *fx); static int df(const gsl_vector *x, void *params, gsl_matrix *J); static int fdf(const gsl_vector *x, void *params, gsl_vector *fx, gsl_matrix *J); NLVector gslToNlsq(const gsl_vector *v) const; NLMatrix gslToNlsq(const gsl_matrix *m) const; gsl_vector *NlsqTogsl(const NLVector &v, gsl_vector *gv = 0) const; gsl_matrix *NlsqTogsl(const NLMatrix &m, gsl_matrix *gm = 0) const; NLVector getUncertainty(const gsl_matrix *m) const; }; } // namespace Isis #endif
{ "alphanum_fraction": 0.5837546343, "avg_line_length": 36.6296296296, "ext": "h", "hexsha": "35356bd2560a0fab1a1647c2f8bb4e8f494ebb22", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "ihumphrey-usgs/ISIS3_old", "max_forks_repo_path": "isis/src/mro/apps/hical/NonLinearLSQ.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "ihumphrey-usgs/ISIS3_old", "max_issues_repo_path": "isis/src/mro/apps/hical/NonLinearLSQ.h", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "ihumphrey-usgs/ISIS3_old", "max_stars_repo_path": "isis/src/mro/apps/hical/NonLinearLSQ.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1381, "size": 5934 }
/****************************************************************************** (c) 2017 - 2019 Scientific Computation Research Center, Rensselaer Polytechnic Institute. All rights reserved. This work is open source software, licensed under the terms of the BSD license as described in the LICENSE file in the top-level directory. *******************************************************************************/ #ifndef MSI_PETSC_VERSION_H_ #define MSI_PETSC_VERSION_H_ #include <petscversion.h> #include <petsc.h> #include <utility> template <typename ... Args> auto PetscSetPCBackend(Args&&... args) -> decltype( #if PETSC_VERSION_GT(3,9,5) PCFactorSetMatSolverType(std::forward<Args>(args)...) #else PCFactorSetMatSolverPackage(std::forward<Args>(args)...) #endif ) { #if PETSC_VERSION_GT(3,9,5) return PCFactorSetMatSolverType(std::forward<Args>(args)...); #else return PCFactorSetMatSolverPackage(std::forward<Args>(args)...); #endif } #endif
{ "alphanum_fraction": 0.6273100616, "avg_line_length": 30.4375, "ext": "h", "hexsha": "272b1cb5f1527c54e0250d54b15509ac7f9aff34", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2018-04-19T18:31:27.000Z", "max_forks_repo_forks_event_min_datetime": "2018-01-09T19:00:36.000Z", "max_forks_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "SCOREC/msi", "max_forks_repo_path": "include/msi_petsc_version.h", "max_issues_count": 20, "max_issues_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197", "max_issues_repo_issues_event_max_datetime": "2019-11-21T16:38:35.000Z", "max_issues_repo_issues_event_min_datetime": "2018-04-18T19:33:33.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "SCOREC/msi", "max_issues_repo_path": "include/msi_petsc_version.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "SCOREC/msi", "max_stars_repo_path": "include/msi_petsc_version.h", "max_stars_repo_stars_event_max_datetime": "2020-10-10T11:50:23.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-10T11:50:23.000Z", "num_tokens": 222, "size": 974 }
/* * BRAINS * (B)LR (R)everberation-mapping (A)nalysis (I)n AGNs with (N)ested (S)ampling * Yan-Rong Li, liyanrong@ihep.ac.cn * Thu, Aug 4, 2016 */ #ifdef SpecAstro #include <math.h> #include <stddef.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <fftw3.h> #include "brains.h" /* * calculate SA phase and 2D TF */ void calculate_sa_transfun2d_from_blrmodel(const void *pm, double *transv, double *trans2d, int n_vel, int flag_save) { int i; double *sa_model, *rm_model; /* share all parameters */ if(parset.flag_sa_par_mutual == 0) { gen_cloud_sample(pm, 5, 0); transfun_2d_cal_with_sample(transv, trans2d, n_vel); calculate_sa_with_sample(pm); } /* share mass and inclination */ else if(parset.flag_sa_par_mutual == 1) { rm_model = (double *)pm; sa_model = rm_model + num_params_blr; sa_model[idx_sa_par_mutual[0]] = rm_model[idx_rm_par_mutual[0]]; //mbh sa_model[idx_sa_par_mutual[1]] = rm_model[idx_rm_par_mutual[1]]; //inc gen_cloud_sample(pm, 2, flag_save); transfun_2d_cal_with_sample(transv, trans2d, n_vel); gen_sa_cloud_sample((void *)sa_model, 3, flag_save); calculate_sa_with_sample(pm); } /* share inclination, opening angle and all dynamical parameters */ else { rm_model = (double *)pm; sa_model = rm_model + num_params_blr; sa_model[idx_sa_par_mutual[1]] = rm_model[idx_rm_par_mutual[1]]; //inc sa_model[idx_sa_par_mutual[2]] = rm_model[idx_rm_par_mutual[2]]; //opening angle /* dynamical parameters from mass on */ for(i=idx_sa_par_mutual[0]; i<num_params_sa_blr_model; i++) { sa_model[i] = rm_model[i]; /* note the BLR models are identical */ } gen_cloud_sample(pm, 2, flag_save); transfun_2d_cal_with_sample(transv, trans2d, n_vel); gen_sa_cloud_sample((void *)sa_model, 3, flag_save); calculate_sa_with_sample(pm); } } /* * calculate SA phase and 1D TF */ void calculate_sa_transfun_from_blrmodel(const void *pm, int flag_save) { double *sa_model, *rm_model; if(parset.flag_sa_par_mutual == 0) { gen_cloud_sample(pm, 4, flag_save); transfun_1d_cal_with_sample(); calculate_sa_with_sample(pm); } else { rm_model = (double *)pm; sa_model = rm_model + num_params_blr; sa_model[idx_sa_par_mutual[1]] = rm_model[idx_rm_par_mutual[1]]; // inc sa_model[idx_sa_par_mutual[2]] = rm_model[idx_rm_par_mutual[2]]; // opening angle gen_cloud_sample(pm, 1, flag_save); transfun_1d_cal_with_sample(); gen_sa_cloud_sample((void *)sa_model, 3, flag_save); calculate_sa_with_sample(pm); } } /* * calculate SA phase and line profile from cloud sample */ void calculate_sa_with_sample(const void *pm) { int i, j, k, idV; double V, V_offset, dV, y, z, alpha, beta, flux_norm, phase, *phase_norm, *alpha_cent, *beta_cent; double DA, PA, FA, CO, cos_PA, sin_PA; double *pmodel = (double *)pm; phase_norm = workspace_phase; alpha_cent = phase_norm + n_vel_sa_data; beta_cent = alpha_cent + n_vel_sa_data; /* angular size distance */ DA = exp(pmodel[num_params_blr + num_params_sa_blr_model]); /* position angle */ PA = pmodel[num_params_blr + num_params_sa_blr_model + 1]/180.0 * PI; /* line flux scaling factor */ FA = exp(pmodel[num_params_blr + num_params_sa_blr_model+2]); /* * line center offset: V+dV = (w-(w0+dw0))/(w0+dw0) ==> dV = - dw0/w0 * equivalent to redshift offset: dz = -(1+z) dw0/w0 */ CO = -pmodel[num_params_blr + num_params_sa_blr_model+3]/parset.sa_linecenter * C_Unit; /* North through East (E of N), 180 deg ambiguity */ cos_PA = cos(PA); sin_PA = sin(PA); dV = vel_sa_data[1] - vel_sa_data[0]; for(i=0; i<n_vel_sa_data; i++) { for(k=0; k<n_base_sa_data; k++) { phase_sa[k*n_vel_sa_data + i] = 0.0; } phase_norm[i] = 0.0; alpha_cent[i] = 0.0; beta_cent[i] = 0.0; } for(i=0; i<parset.n_cloud_per_task; i++) { y = clouds_alpha[i]; z = clouds_beta[i]; //alpha = y * cos_PA + z * sin_PA; //beta = -y * sin_PA + z * cos_PA; alpha = y; beta = z; for(j=0; j< parset.n_vel_per_cloud; j++) { V = clouds_vel[i*parset.n_vel_per_cloud + j] + CO; V_offset = V + bin_offset * dV; /* bin type: center or left edge */ if(V_offset<vel_sa_data[0] || V_offset >= vel_sa_data[n_vel_sa_data-1]+dV) continue; idV = (V_offset - vel_sa_data[0])/dV; phase_norm[idV] += clouds_weight[i]; alpha_cent[idV] += alpha * clouds_weight[i]; beta_cent[idV] += beta * clouds_weight[i]; } } /* normalize line spectrum */ flux_norm = 0.0; for(j=0; j<n_vel_sa_data; j++) { flux_norm += phase_norm[j]; } flux_norm /= (sa_flux_norm * n_vel_sa_data); for(j=0; j<n_vel_sa_data; j++) { Fline_sa[j] = FA * phase_norm[j]/(flux_norm + EPS); } for(j=0; j<n_vel_sa_data; j++) { y = alpha_cent[j]; z = beta_cent[j]; alpha_cent[j] = y * cos_PA + z * sin_PA; beta_cent[j] = -y * sin_PA + z * cos_PA; alpha_cent[j] = (alpha_cent[j]/(phase_norm[j]+EPS)) / DA; beta_cent[j] = (beta_cent[j]/(phase_norm[j]+EPS)) / DA; } /* phi = -2*pi * f_line * B/lambda * X/DA */ for(k=0; k<n_base_sa_data; k++) { for(j=0; j<n_vel_sa_data; j++) { phase = base_sa_data[k*2] * alpha_cent[j] + base_sa_data[k*2 + 1] * beta_cent[j]; phase_sa[k*n_vel_sa_data + j] = -Fline_sa[j]/(1.0+Fline_sa[j]) * phase; } } /* smooth */ sa_smooth_run(vel_sa_data, Fline_sa, n_vel_sa_data, phase_sa, n_base_sa_data); return; } /* * calculate SA phase and line profile from cloud sample at simulated mesh. */ void calculate_sa_sim_with_sample(const void *pm, double *vel_sa, int n_vel_sa, double *base_sa, int n_base_sa, double *p_sa, double *F_sa) { int i, j, k, idV; double V, V_offset, dV, y, z, alpha, beta, flux_norm, phase, *phase_norm, *alpha_cent, *beta_cent; double DA, PA, FA, CO, cos_PA, sin_PA; double *pmodel = (double *)pm; phase_norm = workspace_phase; alpha_cent = phase_norm + n_vel_sa; beta_cent = alpha_cent + n_vel_sa; /* angular size distance */ DA = exp(pmodel[num_params_blr + num_params_sa_blr_model]); /* position angle */ PA = pmodel[num_params_blr + num_params_sa_blr_model + 1]/180.0 * PI; /* line flux scaling factor */ FA = exp(pmodel[num_params_blr + num_params_sa_blr_model+2]); /* * line center offset: V+dV = (w-(w0+dw0))/(w0+dw0) ==> dV = - dw0/w0 * equivalent to redshift offset: dz = -(1+z) dw0/w0 */ CO = -pmodel[num_params_blr + num_params_sa_blr_model+3]/parset.sa_linecenter * C_Unit; /* North through East (E of N), 180 deg ambiguity */ cos_PA = cos(PA); sin_PA = sin(PA); dV = vel_sa[1] - vel_sa[0]; for(i=0; i<n_vel_sa; i++) { for(k=0; k<n_base_sa; k++) { p_sa[k*n_vel_sa + i] = 0.0; } phase_norm[i] = 0.0; alpha_cent[i] = 0.0; beta_cent[i] = 0.0; } for(i=0; i<parset.n_cloud_per_task; i++) { y = clouds_alpha[i]; z = clouds_beta[i]; //alpha = y * cos_PA + z * sin_PA; //beta = -y * sin_PA + z * cos_PA; alpha = y; beta = z; for(j=0; j< parset.n_vel_per_cloud; j++) { V = clouds_vel[i*parset.n_vel_per_cloud + j] + CO; V_offset = V + bin_offset * dV; /* bin type: center or left edge */ if(V_offset<vel_sa[0] || V_offset >= vel_sa[n_vel_sa-1]+dV) continue; idV = (V_offset - vel_sa[0])/dV; phase_norm[idV] += clouds_weight[i]; alpha_cent[idV] += alpha * clouds_weight[i]; beta_cent[idV] += beta * clouds_weight[i]; } } /* normalize line spectrum */ flux_norm = 0.0; for(j=0; j<n_vel_sa; j++) { flux_norm += phase_norm[j]; } flux_norm /= (sa_flux_norm * n_vel_sa); for(j=0; j<n_vel_sa; j++) { F_sa[j] = FA * phase_norm[j]/(flux_norm + EPS); } for(j=0; j<n_vel_sa; j++) { y = alpha_cent[j]; z = beta_cent[j]; alpha_cent[j] = y * cos_PA + z * sin_PA; beta_cent[j] = -y * sin_PA + z * cos_PA; alpha_cent[j] = (alpha_cent[j]/(phase_norm[j]+EPS)) / DA; beta_cent[j] = (beta_cent[j]/(phase_norm[j]+EPS)) / DA; } /* phi = -2*pi * f_line * B/lambda * X/DA */ for(k=0; k<n_base_sa; k++) { for(j=0; j<n_vel_sa; j++) { phase = base_sa[k*2] * alpha_cent[j] + base_sa[k*2 + 1] * beta_cent[j]; p_sa[k*n_vel_sa + j] = -F_sa[j]/(1.0+F_sa[j]) * phase; } } /* smooth */ sa_smooth_run(vel_sa, F_sa, n_vel_sa, p_sa, n_base_sa); return; } /* * calculate SA phase and line profile from a BLR model. */ void calculate_sa_from_blrmodel(const void *pm, int flag_save) { gen_sa_cloud_sample(pm, 3, 0); calculate_sa_with_sample(pm); return; } void set_sa_blr_model() { switch(parset.flag_sa_blrmodel) { case 0: num_params_sa_blr_model = num_params_MyBLRmodel2d; gen_sa_cloud_sample = gen_cloud_sample_mymodel; break; case 1: num_params_sa_blr_model = sizeof(BLRmodel1)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model1; break; case 2: num_params_sa_blr_model = sizeof(BLRmodel2)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model2; break; case 3: num_params_sa_blr_model = sizeof(BLRmodel3)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model3; break; case 4: num_params_sa_blr_model = sizeof(BLRmodel4)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model4; break; case 5: num_params_sa_blr_model = sizeof(BLRmodel5)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model5; break; case 6: num_params_sa_blr_model = sizeof(BLRmodel6)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model6; break; case 7: num_params_sa_blr_model = sizeof(BLRmodel7)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model7; break; case 8: num_params_sa_blr_model = sizeof(BLRmodel8)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model8; break; case 9: num_params_sa_blr_model = sizeof(BLRmodel9)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model9; break; default: num_params_sa_blr_model = sizeof(BLRmodel1)/sizeof(double); gen_sa_cloud_sample = gen_cloud_sample_model1; break; } return; } /* * set the index of mutual parameters (BH mass and inclination) in RM and SA BLR models. */ void set_idx_par_mutual() { switch(parset.flag_blrmodel) { case 0: idx_rm_par_mutual[0] = offsetof(MyBLRmodel, mbh); idx_rm_par_mutual[1] = offsetof(MyBLRmodel, inc); idx_rm_par_mutual[2] = offsetof(MyBLRmodel, opn); break; case 1: idx_rm_par_mutual[0] = offsetof(BLRmodel1, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel1, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel1, opn); break; case 2: idx_rm_par_mutual[0] = offsetof(BLRmodel2, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel2, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel2, opn); break; case 3: idx_rm_par_mutual[0] = offsetof(BLRmodel3, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel3, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel3, opn); break; case 4: idx_rm_par_mutual[0] = offsetof(BLRmodel4, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel4, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel4, opn); break; case 5: idx_rm_par_mutual[0] = offsetof(BLRmodel5, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel5, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel5, opn); break; case 6: idx_rm_par_mutual[0] = offsetof(BLRmodel6, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel6, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel6, opn); break; case 7: idx_rm_par_mutual[0] = offsetof(BLRmodel7, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel7, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel7, opn); break; case 8: idx_rm_par_mutual[0] = offsetof(BLRmodel8, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel8, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel8, theta_min); break; case 9: idx_rm_par_mutual[0] = offsetof(BLRmodel9, mbh); idx_rm_par_mutual[1] = offsetof(BLRmodel9, inc); idx_rm_par_mutual[2] = offsetof(BLRmodel9, opn); break; } switch(parset.flag_sa_blrmodel) { case 0: idx_sa_par_mutual[0] = offsetof(MyBLRmodel, mbh); idx_sa_par_mutual[1] = offsetof(MyBLRmodel, inc); idx_sa_par_mutual[2] = offsetof(MyBLRmodel, opn); break; case 1: idx_sa_par_mutual[0] = offsetof(SABLRmodel1, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel1, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel1, opn); break; case 2: idx_sa_par_mutual[0] = offsetof(SABLRmodel2, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel2, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel2, opn); break; case 3: idx_sa_par_mutual[0] = offsetof(SABLRmodel3, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel3, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel3, opn); break; case 4: idx_sa_par_mutual[0] = offsetof(SABLRmodel4, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel4, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel4, opn); break; case 5: idx_sa_par_mutual[0] = offsetof(SABLRmodel5, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel5, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel5, opn); break; case 6: idx_sa_par_mutual[0] = offsetof(SABLRmodel6, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel6, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel6, opn); break; case 7: idx_sa_par_mutual[0] = offsetof(SABLRmodel7, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel7, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel7, opn); break; case 8: idx_sa_par_mutual[0] = offsetof(SABLRmodel8, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel8, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel8, theta_min); break; case 9: idx_sa_par_mutual[0] = offsetof(SABLRmodel9, mbh); idx_sa_par_mutual[1] = offsetof(SABLRmodel9, inc); idx_sa_par_mutual[2] = offsetof(SABLRmodel9, opn); break; } idx_sa_par_mutual[0] /= sizeof(double); idx_sa_par_mutual[1] /= sizeof(double); idx_sa_par_mutual[2] /= sizeof(double); idx_rm_par_mutual[0] /= sizeof(double); idx_rm_par_mutual[1] /= sizeof(double); idx_rm_par_mutual[2] /= sizeof(double); return; } /* * setup SA BLR model parameter range. */ // model 1 void set_sa_blr_range_model1() { int i; i = 0; //mu sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //beta sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 2.0; //F sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 0.999; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in rad sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //lambda sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.5; //q sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //sa_blr_range_model[2][1] = fmin(sa_blr_range_model[2][1], log(rcloud_max_set)); return; } // model 2 void set_sa_blr_range_model2() { int i; i = 0; //mu sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //beta sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 2.0; //F sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 0.999; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in rad sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //sigr sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //sigtheta sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; return; } // model 3 void set_sa_blr_range_model3() { int i; i = 0; //Rin sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //F sa_blr_range_model[i][0] = log(1.0); sa_blr_range_model[i++][1] = log(1.0e2); //alpha sa_blr_range_model[i][0] = -3.0; sa_blr_range_model[i++][1] = 3.0; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in rad sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //xi sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //q sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //rcloud_max_set = fmax(rcloud_max_set, exp(sa_blr_range_model[3][1] + sa_blr_range_model[4][1])); return; } // model 4 void set_sa_blr_range_model4() { int i; i = 0; //Rin sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //F sa_blr_range_model[i][0] = log(1.0); sa_blr_range_model[i++][1] = log(1.0e2); //alpha sa_blr_range_model[i][0] = -3.0; sa_blr_range_model[i++][1] = 3.0; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in rad sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //xi sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = sqrt(2.0)/2.0; //q sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //rcloud_max_set = fmax(rcloud_max_set, exp(sa_blr_range_model[3][1] + sa_blr_range_model[4][1])); return; } // model 5 void set_sa_blr_range_model5() { int i; i = 0; //mu sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //Fin sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //Fout sa_blr_range_model[i][0] = log(1.0); sa_blr_range_model[i++][1] = log(10.0); //alpha sa_blr_range_model[i][0] = 1.0; sa_blr_range_model[i++][1] = 3.0; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in degree sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //beta sa_blr_range_model[i][0] = 1.0; sa_blr_range_model[i++][1] = 5.0; //xi sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //fellip sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //fflow sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //sigr_circ sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //sigthe_circ sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(1.0); //sigr_rad sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //sigthe_rad sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(1.0); //theta_rot sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 90.0; //sig_turb sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //rcloud_max_set = fmax(rcloud_max_set, exp(sa_blr_range_model[2][1] + sa_blr_range_model[4][1])); return; } // model 6 void set_sa_blr_range_model6() { int i; i = 0; //mu sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //beta sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 2.0; //F sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //inc sa_blr_range_model[i][0] = 0.0; //in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in rad sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //gamma sa_blr_range_model[i][0] = 1.0; sa_blr_range_model[i++][1] = 5.0; //xi sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //fellip sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //fflow sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //sigr_circ sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //sigthe_circ sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(1.0); //sigr_rad sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //sigthe_rad sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(1.0); //theta_rot sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 90.0; //sig_turb sa_blr_range_model[i][0] = log(0.0001); sa_blr_range_model[i++][1] = log(0.1); //rcloud_max_set = 44.85; //sa_blr_range_model[2][1] = fmin(sa_blr_range_model[2][1], log(rcloud_max_set)); return; } // model 7 void set_sa_blr_range_model7() { int i; i = 0; //mu sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //beta sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 2.0; //F sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in rad sa_blr_range_model[i++][1] = 90.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //gamma sa_blr_range_model[i][0] = 1.0; sa_blr_range_model[i++][1] = 5.0; //xi sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //fsh sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //mu_un sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //beta_un sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 2.0; //F_un sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //opn_un sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 90.0; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); //fellip sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //fflow sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //sigr_circ sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //sigthe_circ sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(1.0); //sigr_rad sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); //sigthe_rad sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(1.0); //theta_rot sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 90.0; //fellip_un sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //fflow_un sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //sig_turb sa_blr_range_model[i][0] = log(0.001); sa_blr_range_model[i++][1] = log(0.1); return; } // model 8 void set_sa_blr_range_model8() { int i; i = 0; //theta_min sa_blr_range_model[i][0] = 20.0; // in degree sa_blr_range_model[i++][1] = 90.0; //dtheta_max sa_blr_range_model[i][0] = 0.0; // in degree sa_blr_range_model[i++][1] = 90.0; //r_min sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.25); //fr_max sa_blr_range_model[i][0] = 1.0; // sa_blr_range_model[i++][1] = 10.0; //gamma sa_blr_range_model[i][0] = 0.0; // sa_blr_range_model[i++][1] = 3.0; //alpha sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 3.0; //lambda sa_blr_range_model[i][0] = -3.0; sa_blr_range_model[i++][1] = 0.0; //k sa_blr_range_model[i][0] = -0.5; sa_blr_range_model[i++][1] = 0.5; //xi sa_blr_range_model[i][0] = 0.0; sa_blr_range_model[i++][1] = 1.0; //Rv sa_blr_range_model[i][0] = log(10.0); sa_blr_range_model[i++][1] = log(50.0); //Rblr sa_blr_range_model[i][0] = log(10.0); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //inc sa_blr_range_model[i][0] = 0.0; // cos(inc) sa_blr_range_model[i++][1] = 1.0; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); return; } // model 9 void set_sa_blr_range_model9() { int i; i = 0; //mu sa_blr_range_model[i][0] = log(0.1); sa_blr_range_model[i++][1] = log(rcloud_max_set*0.5); //beta sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 2.0; //F sa_blr_range_model[i][0] = 0.001; sa_blr_range_model[i++][1] = 0.999; //inc sa_blr_range_model[i][0] = 0.0; // in cosine sa_blr_range_model[i++][1] = 1.0; //opn sa_blr_range_model[i][0] = 0.0; // in degree sa_blr_range_model[i++][1] = 90.0; //mbh sa_blr_range_model[i][0] = log(mass_range[0]); sa_blr_range_model[i++][1] = log(mass_range[1]); return; } /*! * This function copes with parameter fixing.\n * Only fix BLR model parameters. */ void set_par_fix_sa_blrmodel() { int i; char *pstr; npar_fix = 0; if(thistask == roottask) { pstr = parset.sa_str_par_fix_val; // set the default value if not provided. for(i=strlen(parset.sa_str_par_fix); i<num_params_sa_blr_model; i++) parset.sa_str_par_fix[i] = '0'; for(i=0; i<num_params_sa_blr_model; i++) { if(parset.sa_str_par_fix[i] == '0') { par_fix[num_params_blr + i] = 0; par_fix_val[num_params_blr + i] = -DBL_MAX; /* set to be the smallest value */ } else if(parset.sa_str_par_fix[i] == '1') { if(pstr == NULL) { printf("# %d-th SA BLR parameter value is not provided (counting from 0).\n", i); exit(0); } par_fix[num_params_blr + i] = 1; sscanf(pstr, "%lf", &par_fix_val[num_params_blr + i]); npar_fix++; printf("# %d-th SA BLR parameter fixed, value= %f.\n", i, par_fix_val[num_params_blr + i]); pstr = strchr(pstr, ':'); /* values are separated by ":" */ if(pstr!=NULL) { pstr++; } } else // default value { par_fix[num_params_blr + i] = 0; par_fix_val[num_params_blr + i] = -DBL_MAX; } } } MPI_Bcast(par_fix + num_params_blr, num_params_sa_blr_model, MPI_INT, roottask, MPI_COMM_WORLD); MPI_Bcast(par_fix_val + num_params_blr, num_params_sa_blr_model, MPI_DOUBLE, roottask, MPI_COMM_WORLD); return; } int nd_fft_sa, nd_fft_sa_cal, npad_sa; fftw_complex *sa_data_fft, *sa_resp_fft, *sa_conv_fft; fftw_plan sa_pdata, sa_presp, sa_pback; double *sa_real_data, *sa_real_resp, *sa_real_conv; /*! * This function initiates workspace for FFT. */ void sa_smooth_init(int n_v_sa, const double *v_sa, double sigV) { int i; double dV; npad_sa = fmin(n_v_sa * 0.1, 20); nd_fft_sa = n_v_sa+npad_sa*2; nd_fft_sa_cal = nd_fft_sa/2+1; sa_data_fft = (fftw_complex *) fftw_malloc((nd_fft_sa_cal) * sizeof(fftw_complex)); sa_resp_fft = (fftw_complex *) fftw_malloc((nd_fft_sa_cal) * sizeof(fftw_complex)); sa_conv_fft = (fftw_complex *) fftw_malloc((nd_fft_sa_cal) * sizeof(fftw_complex)); sa_real_data = (double *)fftw_malloc(nd_fft_sa * sizeof(double)); //real_resp = (double *)fftw_malloc(nd_fft_sa * sizeof(double)); sa_real_conv = (double *)fftw_malloc(nd_fft_sa * sizeof(double)); sa_pdata = fftw_plan_dft_r2c_1d(nd_fft_sa, sa_real_data, sa_data_fft, FFTW_PATIENT); //presp = fftw_plan_dft_r2c_1d(nd_fft_sa, sa_real_resp, sa_resp_fft, FFTW_PATIENT); sa_pback = fftw_plan_dft_c2r_1d(nd_fft_sa, sa_conv_fft, sa_real_conv, FFTW_PATIENT); dV = v_sa[1] - v_sa[0]; for(i=0; i<nd_fft_sa_cal; i++) { sa_resp_fft[i][0] = exp(-2.0 * PI*PI * sigV/dV*sigV/dV * i*i*1.0/nd_fft_sa/nd_fft_sa)/nd_fft_sa; sa_resp_fft[i][1] = 0.0; } return; } /*! * This function finalizes FFT. */ void sa_smooth_end() { fftw_destroy_plan(sa_pdata); fftw_destroy_plan(sa_pback); fftw_free(sa_data_fft); fftw_free(sa_resp_fft); fftw_free(sa_conv_fft); fftw_free(sa_real_data); //fftw_free(sa_real_resp); fftw_free(sa_real_conv); return; } void sa_smooth_run(double *v_sa, double *F_sa, int n_v_sa, double *p_sa, int n_base_sa) { int i, j; /* first profile */ memcpy(sa_real_data+npad_sa, F_sa, n_v_sa*sizeof(double)); for(i=0; i<npad_sa; i++) sa_real_data[i] = sa_real_data[nd_fft_sa-1-i] = 0.0; /* FFT of line */ fftw_execute(sa_pdata); /* complex multiply and inverse FFT * note that for FFT of real data, FFTW outputs n/2+1 complex numbers. * similarly, for complex to real transform, FFTW needs input of n/2+1 complex numbers. */ for(i=0; i<nd_fft_sa_cal; i++) { sa_conv_fft[i][0] = sa_data_fft[i][0]*sa_resp_fft[i][0] - sa_data_fft[i][1]*sa_resp_fft[i][1]; sa_conv_fft[i][1] = sa_data_fft[i][0]*sa_resp_fft[i][1] + sa_data_fft[i][1]*sa_resp_fft[i][0]; } fftw_execute(sa_pback); memcpy(F_sa, sa_real_conv+npad_sa, n_v_sa*sizeof(double)); /* then phase */ for(j=0; j<n_base_sa; j++) { memcpy(sa_real_data+npad_sa, &p_sa[j*n_v_sa], n_v_sa*sizeof(double)); for(i=0; i<npad_sa; i++) sa_real_data[i] = sa_real_data[nd_fft_sa-1-i] = 0.0; /* FFT of line */ fftw_execute(sa_pdata); /* complex multiply and inverse FFT * note that for FFT of real data, FFTW outputs n/2+1 complex numbers. * similarly, for complex to real transform, FFTW needs input of n/2+1 complex numbers. */ for(i=0; i<nd_fft_sa_cal; i++) { sa_conv_fft[i][0] = sa_data_fft[i][0]*sa_resp_fft[i][0] - sa_data_fft[i][1]*sa_resp_fft[i][1]; sa_conv_fft[i][1] = sa_data_fft[i][0]*sa_resp_fft[i][1] + sa_data_fft[i][1]*sa_resp_fft[i][0]; } fftw_execute(sa_pback); memcpy(&p_sa[j*n_v_sa], sa_real_conv+npad_sa, n_v_sa*sizeof(double)); } return; } #endif
{ "alphanum_fraction": 0.6361022364, "avg_line_length": 27.577092511, "ext": "c", "hexsha": "e0999f98927103963dcff9560eac0f6280291506", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z", "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z", "max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/BRAINS", "max_forks_repo_path": "src/specastro.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/BRAINS", "max_issues_repo_path": "src/specastro.c", "max_line_length": 117, "max_stars_count": 6, "max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/BRAINS", "max_stars_repo_path": "src/specastro.c", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z", "num_tokens": 11417, "size": 31300 }
/*#include <fftw.h>*/ #include <fftw3.h> #include <stdio.h> #include <stdlib.h> #define N 16 main() { int i; fftw_complex in[N], out[N]; float fact; fftw_plan p,p2; printf(" stuff in data\n"); for (i=0;i<N;i++) { /* in[i].re=(i*i); in[i].im=1; */ in[i][0]=(i*i); in[i][1]=1; } printf(" create plans\n"); p = (fftw_plan)fftw_plan_dft_1d(N,in,out,FFTW_FORWARD,FFTW_ESTIMATE); p2 = (fftw_plan)fftw_plan_dft_1d(N,out,in,FFTW_BACKWARD,FFTW_ESTIMATE); printf(" do it\n"); fftw_execute(p); for (i=0;i<N;i++) { /* printf("%12.4f %12.4f\n",out[i].re,out[i].im); */ printf("%12.4f %12.4f\n",out[i][0],out[i][1]); } printf(" \n"); printf(" undo it\n"); fftw_execute(p2); fact=1.0/(float)N; for (i=0;i<N;i++) { /* printf("%10.2f %10.2f\n",in[i].re*fact,in[i].im*fact); */ printf("%10.2f %10.2f\n",in[i][0]*fact,in[i][1]*fact); } printf(" clean up\n"); fftw_destroy_plan(p); fftw_destroy_plan(p2); }
{ "alphanum_fraction": 0.5487437186, "avg_line_length": 25.5128205128, "ext": "c", "hexsha": "4b99ac355e10423f8049907ee16851e767515224", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "timkphd/examples", "max_forks_repo_path": "oneday/libs/fft/test.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062", "max_issues_repo_issues_event_max_datetime": "2022-02-09T01:59:47.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-09T01:59:47.000Z", "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "timkphd/examples", "max_issues_repo_path": "oneday/libs/fft/test.c", "max_line_length": 76, "max_stars_count": 5, "max_stars_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "timkphd/examples", "max_stars_repo_path": "oneday/libs/fft/test.c", "max_stars_repo_stars_event_max_datetime": "2022-01-24T19:09:47.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-01T00:29:22.000Z", "num_tokens": 375, "size": 995 }
#include <viaio/Vlib.h> #include <viaio/VImage.h> #include <viaio/mu.h> #include <viaio/option.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_cblas.h> #include <gsl/gsl_blas.h> #include <stdio.h> #include <stdlib.h> #include <math.h> int DNorm(double *data,size_t n) { size_t j; double s1=0,s2=0,mean,sd,u,tiny=1.0e-6; double nx = (double)n; for (j=0; j<n; j++) { u = data[j]; s1 += u; s2 += u*u; } mean = s1/nx; sd = sqrt((s2 - nx * mean * mean) / (nx - 1.0)); if (sd < tiny) return -1; for (j=0; j<n; j++) { u = data[j]; data[j] = (u-mean)/sd; } return 1; } double DCorr(double *data1,double *data2,size_t n) { size_t j; double sum=0,nx=(double)n; for (j=0; j<n; j++) { sum += data1[j]*data2[j]; } return sum/nx; } void DMN(VImage map,float *A,size_t nvox) { size_t i,j,k; int b,r,c; fprintf(stderr," DMN...\n"); VAttrList list = VReadAttrList("dmn.v",0L,TRUE,FALSE); VImage dmn = VReadImage(list); if (dmn == NULL) VError(" no DMN found"); VImage dst = VCreateImageLike(dmn); VFillImage(dst,VAllBands,0); /* size_t i0=0; for (i=0; i<nvox; i++) { b = VPixel(map,0,0,i,VInteger); r = VPixel(map,0,1,i,VInteger); c = VPixel(map,0,2,i,VInteger); if (c==31 && r==25 && b==33) i0 = i; if (c==20 && r==18 && b==32) i0 = i; } i = i0; for (j=0; j<nvox; j++) { b = VPixel(map,0,0,j,VInteger); r = VPixel(map,0,1,j,VInteger); c = VPixel(map,0,2,j,VInteger); if (j < i) k = j+i*(i+1)/2; else k=i+j*(j+1)/2; VPixel(dst,b,r,c,VFloat) = A[k]; } */ double *data1 = (double *)VCalloc(nvox,sizeof(double)); double *data2 = (double *)VCalloc(nvox,sizeof(double)); for (j=0; j<nvox; j++) { b = VPixel(map,0,0,j,VInteger); r = VPixel(map,0,1,j,VInteger); c = VPixel(map,0,2,j,VInteger); data1[j] = VGetPixel(dmn,b,r,c); } DNorm(data1,nvox); for (i=0; i<nvox; i++) { if (i%100 == 0) fprintf(stderr," i: %7lu of %lu\r",i,nvox); k=0; for (j=0; j<nvox; j++) { b = VPixel(map,0,0,j,VInteger); r = VPixel(map,0,1,j,VInteger); c = VPixel(map,0,2,j,VInteger); if (j < i) k = j+i*(i+1)/2; else k=i+j*(j+1)/2; data2[j] = A[k]; } if (DNorm(data2,nvox) < 0) continue; b = VPixel(map,0,0,i,VInteger); r = VPixel(map,0,1,i,VInteger); c = VPixel(map,0,2,i,VInteger); VPixel(dst,b,r,c,VFloat) = DCorr(data1,data2,nvox); } VFree(data1); VFree(data2); VAttrList out_list = VCreateAttrList(); VAttrList geolist = VGetGeoInfo(list); VSetGeoInfo(geolist,out_list); VAppendAttr(out_list,"image",NULL,VImageRepn,dst); FILE *fp = fopen("dst.v","w"); VWriteFile (fp, out_list); fclose(fp); fprintf(stderr,"\n DMN, ok.\n"); }
{ "alphanum_fraction": 0.5633404105, "avg_line_length": 22.2519685039, "ext": "c", "hexsha": "bb5d5299d6079ac4977dabd748df72ad935f1067", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/nets/vecm/DMN.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/nets/vecm/DMN.c", "max_line_length": 64, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/nets/vecm/DMN.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 1098, "size": 2826 }
/////////////////////////////////////////////////////////////////////////////// // // File eigen_mm.h // // MIT License // Copyright (c) 2020 EigenMM // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Description: EigenMM library definitions // /////////////////////////////////////////////////////////////////////////////// #ifndef eigen_mm_H #define eigen_mm_H #include <petsc.h> #include <slepceps.h> #include <algorithm> #include <vector> #include <map> #include <string> #include <fstream> #include <iterator> #include <iostream> #include "mpi.h" #include "tinyxml.h" #define PI 3.141592653589793238462 class SolverOptions { private: // communicator options PetscInt _nodesperevaluator = 1; PetscInt _subproblemsperevaluator = 1; PetscInt _totalsubproblems = 1; PetscInt _nevaluators = 1; PetscInt _nevals = -1; PetscInt _taskspernode = 28; // eigenvalue partitioning options PetscInt _nk = 7; PetscInt _nb = 4; PetscInt _p = 0; PetscInt _nv = 10; PetscInt _splitmaxiters = 10; PetscInt _raditers = 10; PetscReal _splittol = 0.9; PetscReal _radtol = 1e-3; PetscReal _L = 0.01; PetscReal _R = -1.0; // save and print options bool _terse = false; bool _details = false; bool _debug = false; bool _save_operators = false; bool _save_correctness = false; bool _save_eigenvalues = false; bool _save_eigenbasis = false; char _operators_filename[2048]; char _correctness_filename[2048]; char _eigenvalues_filename[2048]; char _eigenbasis_filename[2048]; public: SolverOptions() {} // set communicator options void set_nodesperevaluator(PetscInt v) { _nodesperevaluator = v; } void set_subproblemsperevaluator(PetscInt v) { _subproblemsperevaluator = v; } void set_totalsubproblems(PetscInt v) { _totalsubproblems = v; } void set_nevaluators(PetscInt v) { _nevaluators = v; } void set_nevals(PetscInt v) { _nevals = v; } void set_taskspernode(PetscInt v) { _taskspernode = v; } // set eigenvalue partitioning options void set_nk(PetscInt v) { _nk = v; } void set_nb(PetscInt v) { _nb = v; } void set_p(PetscInt v) { _p = v; } void set_nv(PetscInt v) { _nv = v; } void set_splitmaxiters(PetscInt v) { _splitmaxiters = v; } void set_raditers(PetscInt v) { _raditers = v; } void set_splittol(PetscReal v) { _splittol = v; } void set_radtol(PetscReal v) { _radtol = v; } void set_L(PetscReal v) { _L = v; } void set_R(PetscReal v) { _R = v; } // set save and print options void set_terse(bool v) { _terse = v; } void set_details(bool v) { _details = v; } void set_debug(bool v) { _debug = v; } void set_save_operators(bool v, const char* filename) { _save_operators = v; sprintf(_operators_filename, "%s", filename); } void set_save_correctness(bool v, const char* filename) { _save_correctness = v; sprintf(_correctness_filename, "%s", filename); } void set_save_eigenvalues(bool v, const char* filename) { _save_eigenvalues = v; sprintf(_eigenvalues_filename, "%s", filename); } void set_save_eigenbasis(bool v, const char* filename) { _save_eigenbasis = v; sprintf(_eigenbasis_filename, "%s", filename); } // get communicator options PetscInt nodesperevaluator() { return _nodesperevaluator; } PetscInt subproblemsperevaluator() { return _subproblemsperevaluator; } PetscInt totalsubproblems() { return _totalsubproblems; } PetscInt nevaluators() { return _nevaluators; } PetscInt nevals() { return _nevals; } PetscInt taskspernode() { return _taskspernode; } // get eigenvalue partitioning options PetscInt nk() { return _nk; } PetscInt nb() { return _nb; } PetscInt p() { return _p; } PetscInt nv() { return _nv; } PetscInt splitmaxiters() { return _splitmaxiters; } PetscInt raditers() { return _raditers; } PetscReal splittol() { return _splittol; } PetscReal radtol() { return _radtol; } PetscReal L() { return _L; } PetscReal R() { return _R; } // get save and print options bool terse() { return _terse; } bool details() { return _details; } bool debug() { return _debug; } bool save_operators() { return _save_operators; } bool save_correctness() { return _save_correctness; } bool save_eigenvalues() { return _save_eigenvalues; } bool save_eigenbasis() { return _save_eigenbasis; } char* operators_filename() { return _operators_filename; } char* correctness_filename() { return _correctness_filename; } char* eigenvalues_filename() { return _eigenvalues_filename; } char* eigenbasis_filename() { return _eigenbasis_filename; } }; struct NodeInfo { // world PetscInt worldrank, worldsize; // evaluator PetscInt rank, size, id; MPI_Comm comm; // additional properties PetscInt nevaluators; const char* procname; PetscInt procid; // Results PetscInt neval; PetscInt neval0; }; class eigen_mm { private: EPS eps; SolverOptions opts; NodeInfo node; Mat K, M, V; Mat K_global, M_global; Vec lambda; std::vector<PetscReal> intervals; std::vector<PetscReal> residuals; void findUpperBound(); void rescaleInterval(); void formSubproblems(); PetscReal count_subintervals(PetscInt n, PetscReal Nhat, PetscInt Nbar, std::vector<PetscReal> x, std::vector<PetscInt> &RA, std::vector<PetscInt> &A); void merge_approximations(PetscReal Nhat, PetscInt Nbar, std::vector<PetscReal> &x, std::vector<PetscInt> &RA, std::vector<PetscReal> y, std::vector<PetscInt> RB, std::vector<PetscInt> &A); PetscInt solveSubproblems(); void formEigenbasis(PetscInt neval); PetscInt solveSubProblem(PetscReal *intervals, int job); void splitSubProblem(PetscReal a, PetscReal b, PetscReal *c, PetscInt *out_ec_left, PetscInt *out_ec_right); void global_refine(PetscInt n, std::vector<PetscReal> x, std::vector<PetscReal> &y, std::vector<PetscInt> C, PetscReal Nhat); void balance_intervals(PetscReal a, PetscReal b, PetscReal *c, PetscInt reva, PetscInt revb, PetscInt *revc, PetscInt *Cl, PetscInt *Cr); PetscInt computeDev_approximate(PetscReal a, PetscReal U, PetscBool rl); PetscInt computeDev_exact(PetscReal a, PetscBool rl); PetscReal computeRadius(Mat &A); void countInterval(PetscReal a, PetscReal b, PetscInt *count); public: eigen_mm(); ~eigen_mm(); int init(Mat &K_in, Mat &M_in, SolverOptions &opt); int solve(Mat *V_out, Vec *lambda_out); void exactEigenvalues_square_neumann(int Ne, std::vector<PetscReal> &lambda, std::vector<PetscReal> &eta1, std::vector<PetscReal> &eta2); void exactEigenvalues_cube_neumann(int Ne, std::vector<PetscReal> &lambda, std::vector<PetscReal> &eta1, std::vector<PetscReal> &eta2, std::vector<PetscReal> &eta3); }; #endif //eigen_mm_H
{ "alphanum_fraction": 0.6613156307, "avg_line_length": 33.4072580645, "ext": "h", "hexsha": "6005989cc5c776e95e59735732d1212b782e0fef", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5c94233524ae2758ebf47c3b3fdb6570a6cc4e59", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "paralab/EigenMM", "max_forks_repo_path": "include/eigenmm/eigen_mm.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c94233524ae2758ebf47c3b3fdb6570a6cc4e59", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "paralab/EigenMM", "max_issues_repo_path": "include/eigenmm/eigen_mm.h", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "5c94233524ae2758ebf47c3b3fdb6570a6cc4e59", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "paralab/EigenMM", "max_stars_repo_path": "include/eigenmm/eigen_mm.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2279, "size": 8285 }
/** Fit a set of points to a model that is subject to rotation and translation. * * The model is defined by a set of primitive faces such as plane, cylinder, sphere, etc. * The measured points are first translated by (xt, yt, zt), * then rotated about x-y-z axes by g, b, a angles in sequence, * * These 6 parameters are the output of the fit. * * Author: Yuan Mei */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multifit_nlinear.h> #ifdef LINE_MAX #undef LINE_MAX #define LINE_MAX 4096 #endif #ifndef LINE_MAX #define LINE_MAX 4096 #endif /** Check if the character is a field separator. */ #ifndef sepq #define sepq(a) ((a)==' ' || (a)=='\t') #endif #define NDIM 3 /**< number of dimensions */ enum { FACE_PLANE=1, FACE_CYLINDER=2, FACE_SPHERE=3, FACE_LINE=12, FACE_POINT=13 }; struct face { int ftype; /**< type of face: plane, cylinder etc... */ double x0; /**< origin */ double y0; double z0; double nx; /**< normal vector */ double ny; double nz; double r; /**< radius */ }; struct data { double pr; /**< probe radius */ const struct face *faces; size_t n; /**< number of measured data points */ size_t *fid; /**< idx of face in the registered faces */ double *x; /**< measured point */ double *y; double *z; double *w; /**< weights */ double *x1; /**< after transformation */ double *y1; double *z1; }; /** Distance from measured point to face. */ int dist_f(const gsl_vector *p, void *data, gsl_vector *f) { double pr = ((struct data *)data)->pr; const struct face *faces = ((struct data *)data)->faces; size_t n = ((struct data *)data)->n; size_t *fid = ((struct data *)data)->fid; double *x = ((struct data *)data)->x; double *y = ((struct data *)data)->y; double *z = ((struct data *)data)->z; double a = gsl_vector_get(p, 0), Ca = cos(a), Sa = sin(a); double b = gsl_vector_get(p, 1), Cb = cos(b), Sb = sin(b); double g = gsl_vector_get(p, 2), Cg = cos(g), Sg = sin(g); double xt = gsl_vector_get(p, 3); double yt = gsl_vector_get(p, 4); double zt = gsl_vector_get(p, 5); size_t i; for (i = 0; i < n; i++) { int ftype = faces[fid[i]].ftype; double x0 = faces[fid[i]].x0; double y0 = faces[fid[i]].y0; double z0 = faces[fid[i]].z0; double nx = faces[fid[i]].nx; double ny = faces[fid[i]].ny; double nz = faces[fid[i]].nz; double r = faces[fid[i]].r; double x1, y1, z1; x1 = Ca*Cb * (x[i]+xt) + (Ca*Sb*Sg-Sa*Cg) * (y[i]+yt) + (Ca*Sb*Cg+Sa*Sg) * (z[i]+zt); y1 = Sa*Cb * (x[i]+xt) + (Sa*Sb*Sg+Ca*Cg) * (y[i]+yt) + (Sa*Sb*Cg-Ca*Sg) * (z[i]+zt); z1 = - Sb * (x[i]+xt) + Cb*Sg * (y[i]+yt) + Cb*Cg * (z[i]+zt); ((struct data *)data)->x1[i] = x1; ((struct data *)data)->y1[i] = y1; ((struct data *)data)->z1[i] = z1; double d, dist=0.0; switch (ftype) { case FACE_PLANE: d = -(nx*x0 + ny*y0 + nz*z0); dist = fabs(nx*x1 + ny*y1 + nz*z1 + d) / sqrt(nx*nx + ny*ny + nz*nz); dist -= pr; break; case FACE_CYLINDER: case FACE_LINE: { double dx = x1 - x0, dy = y1 - y0, dz = z1 - z0; double s1 = dy * nz - dz * ny, s2 = dz*nx - dx*nz, s3 = dx*ny - dy*nx; dist = fabs(sqrt((s1*s1 + s2*s2 + s3*s3)/(nx*nx + ny*ny + nz*nz)) - r); if (ftype == FACE_CYLINDER) dist -= pr; } break; case FACE_SPHERE: case FACE_POINT: dist = fabs(sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0) + (z1-z0)*(z1-z0)) - r); if (ftype == FACE_SPHERE) dist -= pr; break; default: dist = 0.0; break; } gsl_vector_set(f, i, dist); } return GSL_SUCCESS; } void callback(const size_t iter, void *params, const gsl_multifit_nlinear_workspace *w) { gsl_vector *f = gsl_multifit_nlinear_residual(w); gsl_vector *x = gsl_multifit_nlinear_position(w); double rcond=0; /* compute reciprocal condition number of J(x) */ /* cond(J) = %8.4f, 1.0 / rcond */ gsl_multifit_nlinear_rcond(&rcond, w); fprintf(stderr, "iter %2zu: a = %7.4f, b = %7.4f, g = %7.4f, xt = %7.4f, yt = %7.4f, zt = %7.4f, |f(x)| = %.4f\n", iter, gsl_vector_get(x, 0), gsl_vector_get(x, 1), gsl_vector_get(x, 2), gsl_vector_get(x, 3), gsl_vector_get(x, 4), gsl_vector_get(x, 5), gsl_blas_dnrm2(f)); } /** Read a long line from file. * @param[inout] s string of the line, is allocated when s==NULL and n==0 and grown as needed. * @param[inout] n current size of s * @return s */ static char *file_read_long_line(char **s, size_t *n, FILE *fp) { const int bufsz = LINE_MAX; char *p; size_t cnt, sz; if ( *s == NULL && *n == 0 ) { *n = bufsz; if ( (*s = calloc(*n, sizeof(char))) == NULL ) exit(-1); } p = *s; sz = *n; while ( 1 ) { if ( fgets(p, sz, fp) == NULL ) return NULL; cnt = strlen(*s); if ( (*s)[cnt-1] == '\n' ) { break; } else { /* line too long, expand the buffer */ *n += bufsz; if ( (*s = realloc(*s, (*n)*sizeof(char))) == NULL ) exit(-1); p = *s + cnt; sz = bufsz; } } return *s; } /** Read face definition file. * * @param[inout] n number of faces read from file. If the given value * *n > 0, *n is interpreted as the number of elements in the faces * array and only up to *n faces will be read from file. However, if * the file contains less than *n faces, *n will be updated to reflect * the available number of elements. * * @param[inout] faces array of faces. If *faces != NULL, *faces will * be used rather than allocated. */ int read_faces(const char *fname, size_t *n, struct face **faces) { char *linebuf = NULL; size_t linen = 0; FILE *fp; if ((fp = fopen(fname, "r"))==NULL) { perror(fname); return -1; } struct face fc; int fid; size_t lid = 0; ssize_t nelem = -1; if (*faces == NULL) { /* get number of elements in the file */ while (file_read_long_line(&linebuf, &linen, fp)) { lid++; if (linebuf[0] == '#' || linebuf[0] == '\n') continue; int ret = sscanf(linebuf, "%d %d %lf %lf %lf %lf %lf %lf %lf", &fid, &fc.ftype, &fc.x0, &fc.y0, &fc.z0, &fc.nx, &fc.ny, &fc.nz, &fc.r); if (ret < 9 || fid < 0 || fc.ftype <= 0) { fprintf(stderr, "Malformatted face at line %zd\n", lid); } else { if (fid > nelem) nelem = fid; } } nelem++; if (nelem == 0) { fprintf(stderr, "No valid face in file.\n"); return -1; } else { fprintf(stderr, "%zd faces available in file.\n", nelem); } *n = nelem; if ((*faces = calloc(nelem, sizeof(struct face))) == NULL) { perror("calloc *faces"); return -1; } } rewind(fp); nelem = 0; lid = 0; while (file_read_long_line(&linebuf, &linen, fp) && (nelem < *n)) { lid++; if (linebuf[0] == '#' || linebuf[0] == '\n') continue; int ret = sscanf(linebuf, "%d %d %lf %lf %lf %lf %lf %lf %lf", &fid, &fc.ftype, &fc.x0, &fc.y0, &fc.z0, &fc.nx, &fc.ny, &fc.nz, &fc.r); if (ret < 9 || fid < 0 || fc.ftype <= 0) { fprintf(stderr, "Malformatted face at line %zd, skipped.\n", lid); } else { if (fid >= *n) break; struct face *fc1 = *faces; memcpy(&fc1[fid], &fc, sizeof(fc)); nelem++; } } fprintf(stderr, "%zd faces constructed.\n", nelem); free(linebuf); fclose(fp); return 0; } int read_points(const char *fname, size_t *n, struct data *data) { char *linebuf = NULL; size_t linen = 0; FILE *fp; if ((fp = fopen(fname, "r"))==NULL) { perror(fname); return -1; } int fidmax = -1; *n = 0; size_t lid = 0; while (file_read_long_line(&linebuf, &linen, fp)) { lid++; if (linebuf[0] == '#' || linebuf[0] == '\n') continue; int ret = 0; for (int i=0; i<linen; i++) { /* count number of ';' */ if (linebuf[i] == ';') ret++; } int fid; sscanf(linebuf, "%*d;%d", &fid); if (ret < 8 || fid < 0) { fprintf(stderr, "Malformatted point at line %zd\n", lid); } else { (*n)++; if (fid > fidmax) fidmax = fid; } } fprintf(stderr, "%zd points in file. fidmax = %d\n", *n, fidmax); data->n = *n; data->fid = calloc(data->n, sizeof(size_t)); data->x = calloc(data->n, sizeof(double)); data->y = calloc(data->n, sizeof(double)); data->z = calloc(data->n, sizeof(double)); data->w = calloc(data->n, sizeof(double)); data->x1 = calloc(data->n, sizeof(double)); data->y1 = calloc(data->n, sizeof(double)); data->z1 = calloc(data->n, sizeof(double)); rewind(fp); lid = 0; size_t idx = 0; while (file_read_long_line(&linebuf, &linen, fp)) { lid++; if (linebuf[0] == '#' || linebuf[0] == '\n') continue; int fid = 0, ret = 0; double x, y, z, s; // ret = sscanf(linebuf, "%*d;%d;%*s ;%*d;%lf;%lf;%lf;;%lf", &fid, &x, &y, &z, &s); char *buf = linebuf, *endptr; for (; *buf != ';' ; buf++){;} buf++; /* find the next character past a ';' */ fid = strtol(buf, &endptr, 0); if (endptr > buf) ret++; buf = endptr++; for (; *buf != ';' ; buf++){;} buf++; for (; *buf != ';' ; buf++){;} buf++; for (; *buf != ';' ; buf++){;} buf++; x = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++; for (; *buf != ';' ; buf++){;} buf++; y = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++; for (; *buf != ';' ; buf++){;} buf++; z = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++; for (; *buf != ';' ; buf++){;} buf++; for (; *buf != ';' ; buf++){;} buf++; s = strtod(buf, &endptr); if (endptr > buf) ret++; buf = endptr++; if (ret < 5 || fid < 0) { fprintf(stderr, "Malformatted point at line %zd, skipped.\n", lid); } else { data->fid[idx] = fid; data->x[idx] = x; data->y[idx] = y; data->z[idx] = z; data->w[idx] = (fabs(s)>1e-8) ? (1.0/(s*s)) : 1.0; idx++; } } fprintf(stderr, "%zd points read.\n", idx); free(linebuf); fclose(fp); return 0; } int main(int argc, char **argv) { if (argc != 10) { fprintf(stderr, "Usage: %s faces_file points_file pr a b g xt yt zt\n\n" " pr is the probe radius.\n" " The last 6 parameters are initial guesses.\n" " Points are first translated, then rotated about x(g), y(b), z(a).\n" " The 2nd column in points_file shall be faceid,\n" " which is the first column of faces_file.\n" " The last column in points_file shall be measurement sigma.\n", argv[0]); return EXIT_FAILURE; } size_t nfaces=0; struct face *faces=NULL; read_faces(argv[1], &nfaces, &faces); size_t nd=0; struct data data; read_points(argv[2], &nd, &data); data.faces = faces; data.pr = atof(argv[3]); #define np 6 double p_init[np] = {0}; /* starting values */ for (int i=0; i<np; i++) { p_init[i] = atof(argv[4+i]); } const gsl_multifit_nlinear_type *T = gsl_multifit_nlinear_trust; gsl_multifit_nlinear_workspace *w; gsl_multifit_nlinear_fdf fdf; gsl_multifit_nlinear_parameters fdf_params = gsl_multifit_nlinear_default_parameters(); gsl_vector *f; gsl_matrix *J; gsl_matrix *covar = gsl_matrix_alloc(np, np); gsl_vector_view params = gsl_vector_view_array(p_init, np); gsl_vector_view wts = gsl_vector_view_array(data.w, nd); gsl_rng *r; double chisq, chisq0; int status, info; const double xtol = 1e-8; const double gtol = 1e-8; const double ftol = 1e-8; gsl_rng_env_setup(); r = gsl_rng_alloc(gsl_rng_default); /* define the function to be minimized */ fdf.f = dist_f; fdf.df = NULL; /* set to NULL for finite-difference Jacobian */ fdf.fvv = NULL; /* not using geodesic acceleration */ fdf.n = nd; fdf.p = np; fdf.params = &data; /* `data' supplied to the penalty function */ /* allocate workspace with default parameters */ w = gsl_multifit_nlinear_alloc(T, &fdf_params, nd, np); /* initialize solver with starting point and weights */ gsl_multifit_nlinear_winit(&params.vector, &wts.vector, &fdf, w); /* compute initial cost function */ f = gsl_multifit_nlinear_residual(w); gsl_blas_ddot(f, f, &chisq0); /* solve the system with a maximum of 100 iterations */ status = gsl_multifit_nlinear_driver(100, xtol, gtol, ftol, callback, NULL, &info, w); /* compute covariance of best fit parameters */ J = gsl_multifit_nlinear_jac(w); gsl_multifit_nlinear_covar(J, 0.0, covar); /* compute final cost */ gsl_blas_ddot(f, f, &chisq); #define FIT(i) gsl_vector_get(w->x, i) #define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) fprintf(stderr, "summary from method '%s/%s'\n", gsl_multifit_nlinear_name(w), gsl_multifit_nlinear_trs_name(w)); fprintf(stderr, "number of iterations: %zu\n", gsl_multifit_nlinear_niter(w)); fprintf(stderr, "function evaluations: %zu\n", fdf.nevalf); fprintf(stderr, "Jacobian evaluations: %zu\n", fdf.nevaldf); fprintf(stderr, "reason for stopping: %s\n", (info == 1) ? "small step size" : "small gradient"); fprintf(stderr, "initial |f(x)| = %f\n", sqrt(chisq0)); fprintf(stderr, "final |f(x)| = %f\n", sqrt(chisq)); { double dof = nd - np; double c = GSL_MAX_DBL(1, sqrt(chisq / dof)); fprintf(stderr, "chisq/dof = %g\n", chisq / dof); fprintf(stderr, "a = %16g +/- %g\n", FIT(0), c*ERR(0)); fprintf(stderr, "b = %16g +/- %g\n", FIT(1), c*ERR(1)); fprintf(stderr, "g = %16g +/- %g\n", FIT(2), c*ERR(2)); fprintf(stderr, "xt = %16g +/- %g\n", FIT(3), c*ERR(3)); fprintf(stderr, "yt = %16g +/- %g\n", FIT(4), c*ERR(4)); fprintf(stderr, "zt = %16g +/- %g\n", FIT(5), c*ERR(5)); } fprintf(stderr, "status = %s\n", gsl_strerror(status)); /* compute residual of every point */ dist_f(w->x, &data, f); // pure distance, no weights. printf("# fid ftype distance x1 y1 z1\n"); for (int i=0; i<nd; i++) { printf("%8zd %7d %9.6f %11.5f %11.5f %11.5f\n", data.fid[i], faces[data.fid[i]].ftype, gsl_vector_get(f, i), data.x1[i], data.y1[i], data.z1[i]); } gsl_multifit_nlinear_free(w); gsl_matrix_free(covar); gsl_rng_free(r); free(faces); free(data.fid); free(data.x); free(data.y); free(data.z); free(data.w); free(data.x1); free(data.y1); free(data.z1); return EXIT_SUCCESS; }
{ "alphanum_fraction": 0.5238815375, "avg_line_length": 32.387755102, "ext": "c", "hexsha": "7b2df659d8fd84215b8ebcd4fc50438185fdd353", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7335344df2b58d8ab7f06e4fee8b71ec169a773a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ymei/BodyRotTransFit", "max_forks_repo_path": "RotTransFit.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "7335344df2b58d8ab7f06e4fee8b71ec169a773a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "ymei/BodyRotTransFit", "max_issues_repo_path": "RotTransFit.c", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "7335344df2b58d8ab7f06e4fee8b71ec169a773a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ymei/BodyRotTransFit", "max_stars_repo_path": "RotTransFit.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4865, "size": 15870 }
/* ----------------------------------------------------------------------------- * Copyright 2021 Jonathan Haigh * SPDX-License-Identifier: MIT * ---------------------------------------------------------------------------*/ #ifndef SQ_INCLUDE_GUARD_system_linux_SqParamSchemaImpl_h_ #define SQ_INCLUDE_GUARD_system_linux_SqParamSchemaImpl_h_ #include "core/typeutil.h" #include "system/SqParamSchema.gen.h" #include "system/schema.h" #include <gsl/gsl> namespace sq::system::linux { class SqParamSchemaImpl : public SqParamSchema<SqParamSchemaImpl> { public: explicit SqParamSchemaImpl(const ParamSchema &param_schema); SQ_ND Result get_name() const; SQ_ND Result get_doc() const; SQ_ND Result get_index() const; SQ_ND Result get_type() const; SQ_ND Result get_required() const; SQ_ND Result get_default_value() const; SQ_ND Result get_default_value_doc() const; SQ_ND Primitive to_primitive() const override; private: gsl::not_null<const ParamSchema *> param_schema_; }; } // namespace sq::system::linux #endif // SQ_INCLUDE_GUARD_system_linux_SqParamSchemaImpl_h_
{ "alphanum_fraction": 0.6742493176, "avg_line_length": 28.9210526316, "ext": "h", "hexsha": "43b7658b55b04afd61c11363cf78f80f17a4ac1b", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonathanhaigh/sq", "max_forks_repo_path": "src/system/include/system/linux/SqParamSchemaImpl.h", "max_issues_count": 44, "max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z", "max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonathanhaigh/sq", "max_issues_repo_path": "src/system/include/system/linux/SqParamSchemaImpl.h", "max_line_length": 80, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonathanhaigh/sq", "max_stars_repo_path": "src/system/include/system/linux/SqParamSchemaImpl.h", "max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z", "num_tokens": 242, "size": 1099 }
/* * Copyright (c) 2010-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2013 Inria. All rights reserved. * * @precisions normal z -> c d s * */ #include <lapacke.h> #include "dplasma.h" #include "dplasmatypes.h" #include "map2.h" static int dplasma_zlacpy_operator( parsec_execution_stream_t *es, const parsec_tiled_matrix_dc_t *descA, const parsec_tiled_matrix_dc_t *descB, const void *_A, void *_B, PLASMA_enum uplo, int m, int n, void *args ) { int tempmm, tempnn, ldam, ldbm; const parsec_complex64_t *A = (const parsec_complex64_t*)_A; parsec_complex64_t *B = (parsec_complex64_t*)_B; (void)es; (void)args; tempmm = ((m)==((descA->mt)-1)) ? ((descA->m)-(m*(descA->mb))) : (descA->mb); tempnn = ((n)==((descA->nt)-1)) ? ((descA->n)-(n*(descA->nb))) : (descA->nb); ldam = BLKLDD( descA, m ); ldbm = BLKLDD( descB, m ); LAPACKE_zlacpy_work( LAPACK_COL_MAJOR, lapack_const( uplo ), tempmm, tempnn, A, ldam, B, ldbm); return 0; } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zlacpy_New - Generates an taskpool that performs a copy of the matrix A * into the matrix B. * * See dplasma_map2_New() for further information. * * WARNING: The computations are not done by this call. * ******************************************************************************* * * @param[in] uplo * Specifies which part of matrix A is copied: * = PlasmaUpperLower: All matrix is referenced. * = PlasmaUpper: Only upper part is refrenced. * = PlasmaLower: Only lower part is referenced. * * @param[in] A * Descriptor of the distributed original matrix A. Any tiled matrix * descriptor can be used. However, if the data is stored in column * major, the tile distribution must match the one of the matrix B. * * @param[in,out] B * Descriptor of the distributed destination matrix B. Any tiled matrix * descriptor can be used, with no specific storage. * ******************************************************************************* * * @return * \retval NULL if incorrect parameters are given. * \retval The parsec taskpool describing the operation that can be * enqueued in the runtime with parsec_context_add_taskpool(). It, then, needs to be * destroy with dplasma_zlacpy_Destruct(); * ******************************************************************************* * * @sa dplasma_zlacpy * @sa dplasma_zlacpy_Destruct * @sa dplasma_clacpy_New * @sa dplasma_dlacpy_New * @sa dplasma_slacpy_New * ******************************************************************************/ parsec_taskpool_t* dplasma_zlacpy_New( PLASMA_enum uplo, const parsec_tiled_matrix_dc_t *A, parsec_tiled_matrix_dc_t *B) { parsec_taskpool_t* tp; tp = dplasma_map2_New(uplo, PlasmaNoTrans, A, B, dplasma_zlacpy_operator, NULL ); return tp; } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zlacpy_Destruct - Free the data structure associated to an taskpool * created with dplasma_zlacpy_New(). * ******************************************************************************* * * @param[in,out] taskpool * On entry, the taskpool to destroy. * On exit, the taskpool cannot be used anymore. * ******************************************************************************* * * @sa dplasma_zlacpy_New * @sa dplasma_zlacpy * ******************************************************************************/ void dplasma_zlacpy_Destruct( parsec_taskpool_t *tp ) { dplasma_map2_Destruct(tp); } /** ******************************************************************************* * * @ingroup dplasma_complex64 * * dplasma_zlacpy - Generates an taskpool that performs a copy of the matrix A * into the matrix B. * * See dplasma_map2() for further information. * ******************************************************************************* * * @param[in,out] parsec * The parsec context of the application that will run the operation. * * @param[in] uplo * Specifies which part of matrix A is copied: * = PlasmaUpperLower: All matrix is referenced. * = PlasmaUpper: Only upper part is refrenced. * = PlasmaLower: Only lower part is referenced. * * @param[in] A * Descriptor of the distributed original matrix A. Any tiled matrix * descriptor can be used. However, if the data is stored in column * major, the tile distribution must match the one of the matrix B. * * @param[in,out] B * Descriptor of the distributed destination matrix B. Any tiled matrix * descriptor can be used, with no specific storage. * ******************************************************************************* * * @return * \retval -i if the ith parameters is incorrect. * \retval 0 on success. * ******************************************************************************* * * @sa dplasma_zlacpy_New * @sa dplasma_zlacpy_Destruct * @sa dplasma_clacpy * @sa dplasma_dlacpy * @sa dplasma_slacpy * ******************************************************************************/ int dplasma_zlacpy( parsec_context_t *parsec, PLASMA_enum uplo, const parsec_tiled_matrix_dc_t *A, parsec_tiled_matrix_dc_t *B) { parsec_taskpool_t *parsec_zlacpy = NULL; if ((uplo != PlasmaUpperLower) && (uplo != PlasmaUpper) && (uplo != PlasmaLower)) { dplasma_error("dplasma_zlacpy", "illegal value of uplo"); return -2; } if ( (A->m > B->m) || (A->n > B->n) ) { dplasma_error("dplasma_zlacpy", "illegal matrix A (B is smaller than A)"); return -3; } parsec_zlacpy = dplasma_zlacpy_New(uplo, A, B); if ( parsec_zlacpy != NULL ) { parsec_context_add_taskpool(parsec, (parsec_taskpool_t*)parsec_zlacpy); dplasma_wait_until_completion(parsec); dplasma_zlacpy_Destruct( parsec_zlacpy ); } return 0; }
{ "alphanum_fraction": 0.5159005275, "avg_line_length": 32.5245098039, "ext": "c", "hexsha": "a1ffbff245743fc1eddb8ff5d3d3329619567484", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_path": "dplasma/lib/zlacpy_wrapper.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_path": "dplasma/lib/zlacpy_wrapper.c", "max_line_length": 93, "max_stars_count": 1, "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_path": "dplasma/lib/zlacpy_wrapper.c", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "num_tokens": 1551, "size": 6635 }
/* * C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer * * Yan-Rong Li, liyanrong@mail.ihep.ac.cn * Jun 30, 2016 * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <stdbool.h> #include <gsl/gsl_rng.h> #include "dnestvars.h" /* output files */ FILE *fsample, *fsample_info; /* random number generator */ const gsl_rng_type * dnest_gsl_T; gsl_rng * dnest_gsl_r; DNestOptions options; char options_file[STR_MAX_LENGTH]; // sampler bool save_to_disk; double compression; unsigned int regularisation; void *particles; int dnest_size_of_modeltype; int particle_offset_size, particle_offset_double; LikelihoodType *log_likelihoods; unsigned int *level_assignments; // number account of unaccepted times unsigned int *account_unaccepts; int size_levels, size_levels_combine; Level *levels; Level *copies_of_levels, *levels_combine; LikelihoodType *all_above; unsigned int count_saves, num_saves, num_saves_restart; int dnest_which_particle_update; // which particle to be updated int dnest_which_level_update; // which level to be updated; unsigned long long int count_mcmc_steps; LikelihoodType *above; unsigned int size_above, size_all_above; double post_logz; int dnest_num_params; char dnest_sample_postfix[STR_MAX_LENGTH], dnest_sample_tag[STR_MAX_LENGTH], dnest_sample_dir[STR_MAX_LENGTH]; double *dnest_param_range, *dnest_prior_info; int *dnest_prior_type; void *dnest_args; double *limits, *copies_of_limits; int dnest_thistask, dnest_totaltask; int *dnest_perturb_accept; int dnest_root; int dnest_flag_restart=0, dnest_flag_postprc=0, dnest_flag_sample_info=0, dnest_flag_limits=0; double dnest_post_temp=1.0; char file_restart[STR_MAX_LENGTH], file_save_restart[STR_MAX_LENGTH]; //*********************************************** /* functions */ double mod(double y, double x); void wrap_limit(double *x, double min, double max); int mod_int(int y, int x); int dnest_cmp(const void *pa, const void *pb); void options_load(char *optfile, DNestOptions *opts); void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params, double *param_range, int *prior_type, double *prior_info, char *sample_dir, char *optfile, DNestOptions *opts, void *args); void finalise(); void dnest_run(); void dnest_mcmc_run(); void update_particle(unsigned int which); void update_level_assignment(unsigned int which); double log_push(unsigned int which_level); bool enough_levels(Level *l, int size_l); void do_bookkeeping(); void save_levels(); void save_particle(); void save_limits(); void kill_lagging_particles(); void renormalise_visits(); void recalculate_log_X(); void dnest_postprocess(double temperature, char *optfile, DNestOptions *opts); void postprocess(double temperature); void initialize_output_file(); void close_output_file(); void dnest_save_restart(); void dnest_restart(); void dnest_restart_action(int iflag); void dnest_accept_action(); void dnest_kill_action(int i, int i_copy); void dnest_from_prior(void *model); double dnest_perturb(void *model); void dnest_print_particle(FILE *fp, const void *model); void dnest_read_particle(FILE *fp, void *model); /*=====================================================*/ // users responsible for following functions void (*print_particle)(FILE *fp, const void *model); void (*read_particle)(FILE *fp, void *model); void (*from_prior)(void *model); double (*log_likelihoods_cal)(const void *model); double (*log_likelihoods_cal_initial)(const void *model); double (*log_likelihoods_cal_restart)(const void *model); double (*perturb)(void *model); void (*restart_action)(int iflag); void (*accept_action)(); void (*kill_action)(int i, int i_copy); /*=====================================================*/
{ "alphanum_fraction": 0.7422490804, "avg_line_length": 31.1967213115, "ext": "c", "hexsha": "967369f9f266b0a10198cc7b9eaaa287470c8279", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LiyrAstroph/DNest_C", "max_forks_repo_path": "src/dnestvars.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LiyrAstroph/DNest_C", "max_issues_repo_path": "src/dnestvars.c", "max_line_length": 110, "max_stars_count": 6, "max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LiyrAstroph/CDNest", "max_stars_repo_path": "src/dnestvars.c", "max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z", "num_tokens": 929, "size": 3806 }
// get some values from a GNU scienctific library random number generator. // CK 2014 #include <stdio.h> #include <gsl/gsl_rng.h> void rantest(long seed,int N,double* out){ gsl_rng* rng = gsl_rng_alloc (gsl_rng_taus); // initialize a tausworthe rng gsl_rng_set(rng, seed); // seed it double number = -1; for(int i=0; i<N; i++){ number = gsl_rng_uniform(rng); // sample a number printf("%ld %f\n",seed,number); out[i] = number; } puts("---"); gsl_rng_free(rng); }
{ "alphanum_fraction": 0.6192307692, "avg_line_length": 24.7619047619, "ext": "c", "hexsha": "c2e73f77521c832616b56f9b484d07b7da4e399c", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-12-21T13:40:08.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-19T14:21:23.000Z", "max_forks_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cknd/synchrony", "max_forks_repo_path": "libHC/ekkesim/src/test_random_GSL.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cknd/synchrony", "max_issues_repo_path": "libHC/ekkesim/src/test_random_GSL.c", "max_line_length": 79, "max_stars_count": 5, "max_stars_repo_head_hexsha": "1478f602211ed4bc45331c8bd0124fe1d558aca9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cknd/synchrony", "max_stars_repo_path": "libHC/ekkesim/src/test_random_GSL.c", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:59:40.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-16T11:32:03.000Z", "num_tokens": 148, "size": 520 }
/* roots/test_funcs.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_math.h> #include <gsl/gsl_roots.h> #include "test.h" gsl_function create_function (double (*f)(double, void *)) { gsl_function F ; F.function = f; F.params = 0; return F ; } gsl_function_fdf create_fdf (double (*f)(double, void *), double (*df)(double, void *), void (*fdf)(double, void *, double *, double *)) { gsl_function_fdf FDF ; FDF.f = f ; FDF.df = df ; FDF.fdf = fdf ; FDF.params = 0 ; return FDF ; } /* f(x) = x^{20} - 1 */ /* f'(x) = 20x^{19} */ /* zero at x = 1 or -1 */ double func1 (double x, void *p) { return pow (x, 20.0) - 1; } double func1_df (double x, void * p) { return 20.0 * pow (x, 19.0); } void func1_fdf (double x, void * p, double *y, double *yprime) { *y = func1 (x, p); *yprime = 20.0 * pow (x, 19.0); } /* f(x) = sqrt(abs(x))*sgn(x) */ /* f'(x) = 1 / sqrt(abs(x) */ /* zero at x = 0 */ double func2 (double x, void * p) { double delta; if (x > 0) delta = 1.0; else if (x < 0) delta = -1.0; else delta = 0.0; return sqrt (fabs (x)) * delta; } double func2_df (double x, void * p) { return 1 / sqrt (fabs (x)); } void func2_fdf (double x, void * p, double *y, double *yprime) { *y = func2 (x, p); *yprime = 1 / sqrt (fabs (x)); } /* f(x) = x^2 - 1e-8 */ /* f'(x) = 2x */ /* zero at x = sqrt(1e-8) or -sqrt(1e-8) */ double func3 (double x, void * p) { return pow (x, 2.0) - 1e-8; } double func3_df (double x, void * p) { return 2 * x; } void func3_fdf (double x, void * p, double *y, double *yprime) { *y = func3 (x, p); *yprime = 2 * x; } /* f(x) = x exp(-x) */ /* f'(x) = exp(-x) - x exp(-x) */ /* zero at x = 0 */ double func4 (double x, void * p) { return x * exp (-x); } double func4_df (double x, void * p) { return exp (-x) - x * exp (-x); } void func4_fdf (double x, void * p, double *y, double *yprime) { *y = func4 (x, p); *yprime = exp (-x) - x * exp (-x); } /* f(x) = 1/(1+exp(x)) */ /* f'(x) = -exp(x) / (1 + exp(x))^2 */ /* no roots! */ double func5 (double x, void * p) { return 1 / (1 + exp (x)); } double func5_df (double x, void * p) { return -exp (x) / pow (1 + exp (x), 2.0); } void func5_fdf (double x, void * p, double *y, double *yprime) { *y = func5 (x, p); *yprime = -exp (x) / pow (1 + exp (x), 2.0); } /* f(x) = (x - 1)^7 */ /* f'(x) = 7 * (x - 1)^6 */ /* zero at x = 1 */ double func6 (double x, void * p) { return pow (x - 1, 7.0); } double func6_df (double x, void * p) { return 7.0 * pow (x - 1, 6.0); } void func6_fdf (double x, void * p, double *y, double *yprime) { *y = func6 (x, p); *yprime = 7.0 * pow (x - 1, 6.0); } /* sin(x) packaged up nicely. */ double sin_f (double x, void * p) { return sin (x); } double sin_df (double x, void * p) { return cos (x); } void sin_fdf (double x, void * p, double *y, double *yprime) { *y = sin (x); *yprime = cos (x); } /* cos(x) packaged up nicely. */ double cos_f (double x, void * p) { return cos (x); } double cos_df (double x, void * p) { return -sin (x); } void cos_fdf (double x, void * p, double *y, double *yprime) { *y = cos (x); *yprime = -sin (x); }
{ "alphanum_fraction": 0.5672888016, "avg_line_length": 17.7043478261, "ext": "c", "hexsha": "9b8f05e05e3eb9b3a8cfa248f72fe4329b8bd0a7", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/roots/test_funcs.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/roots/test_funcs.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "ruslankuzmin/julia", "max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/roots/test_funcs.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 1502, "size": 4072 }
/** * * @file core_zlantr.c * * PLASMA core_blas kernel * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.8.0 * @author Mathieu Faverge * @date 2010-11-15 * @precisions normal z -> c d s * **/ #include <lapacke.h> #include <math.h> #include "common.h" #define LAPACKE_CORRECT_DLANTR /***************************************************************************//** * * @ingroup dplasma_cores_complex64 * * CORE_zlantr returns the value * * zlantr = ( max(abs(A(i,j))), NORM = PlasmaMaxNorm * ( * ( norm1(A), NORM = PlasmaOneNorm * ( * ( normI(A), NORM = PlasmaInfNorm * ( * ( normF(A), NORM = PlasmaFrobeniusNorm * * where norm1 denotes the one norm of a matrix (maximum column sum), * normI denotes the infinity norm of a matrix (maximum row sum) and * normF denotes the Frobenius norm of a matrix (square root of sum * of squares). Note that max(abs(A(i,j))) is not a consistent matrix * norm. * ******************************************************************************* * * @param[in] norm * = PlasmaMaxNorm: Max norm * = PlasmaOneNorm: One norm * = PlasmaInfNorm: Infinity norm * = PlasmaFrobeniusNorm: Frobenius norm * * @param[in] uplo * Specifies whether the matrix A is upper triangular or lower triangular: * = PlasmaUpper: Upper triangle of A is stored; * = PlasmaLower: Lower triangle of A is stored. * * @param[in] diag * Specifies whether or not A is unit triangular: * = PlasmaNonUnit: A is non unit; * = PlasmaUnit: A us unit. * * @param[in] M * The number of rows of the matrix A. M >= 0. * If uplo == PlasmaUpper, M <= N. When M = 0, CORE_zlantr returns 0. * * @param[in] N * The number of columns of the matrix A. N >= 0. * If uplo == PlasmaLower, N <= M. When N = 0, CORE_zlantr returns 0. * * @param[in] A * The LDA-by-N matrix A. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,M). * * @param[in,out] work * Array of dimension (MAX(1,LWORK)), where LWORK >= M when norm = * PlasmaInfNorm, or LWORK >= N when norm = PlasmaOneNorm; otherwise, * work is not referenced. * * @param[out] normA * On exit, normA is the norm of matrix A. * ******************************************************************************/ #if defined(PLASMA_HAVE_WEAK) #pragma weak CORE_zlantr = PCORE_zlantr #define CORE_zlantr PCORE_zlantr #endif void CORE_zlantr(PLASMA_enum norm, PLASMA_enum uplo, PLASMA_enum diag, int M, int N, const PLASMA_Complex64_t *A, int LDA, double *work, double *normA) { #if defined(LAPACKE_CORRECT_DLANTR) *normA = LAPACKE_zlantr_work( LAPACK_COL_MAJOR, lapack_const(norm), lapack_const(uplo), lapack_const(diag), M, N, A, LDA, work); #else const PLASMA_Complex64_t *tmpA; double value; int i, j, imax; int idiag = (diag == PlasmaUnit) ? 1 : 0; if ( min(M, N) == 0 ) { *normA = 0; return; } switch ( norm ) { case PlasmaMaxNorm: if ( diag == PlasmaUnit ) { *normA = 1.; } else { *normA = 0.; } if ( uplo == PlasmaUpper ) { M = min(M, N); for (j = 0; j < N; j++) { tmpA = A+(j*LDA); imax = min(j+1-idiag, M); for (i = 0; i < imax; i++) { value = cabs( *tmpA ); *normA = ( value > *normA ) ? value : *normA; tmpA++; } } } else { N = min(M, N); for (j = 0; j < N; j++) { tmpA = A + j * (LDA+1) + idiag; for (i = j+idiag; i < M; i++) { value = cabs( *tmpA ); *normA = ( value > *normA ) ? value : *normA; tmpA++; } } } break; case PlasmaOneNorm: CORE_ztrasm( PlasmaColumnwise, uplo, diag, M, N, A, LDA, work ); if ( uplo == PlasmaLower ) N = min(M,N); *normA = 0; for (i = 0; i < N; i++) { *normA = ( work[i] > *normA ) ? work[i] : *normA; } break; case PlasmaInfNorm: CORE_ztrasm( PlasmaRowwise, uplo, diag, M, N, A, LDA, work ); if ( uplo == PlasmaUpper ) M = min(M,N); *normA = 0; for (i = 0; i < M; i++) { *normA = ( work[i] > *normA ) ? work[i] : *normA; } break; case PlasmaFrobeniusNorm: { double scale = 0.; double sumsq = 1.; CORE_ztrssq( uplo, diag, M, N, A, LDA, &scale, &sumsq ); *normA = scale * sqrt( sumsq ); } break; default: coreblas_error(1, "Illegal value of norm"); return; } #endif }
{ "alphanum_fraction": 0.474346748, "avg_line_length": 28.650273224, "ext": "c", "hexsha": "a0c4c056e0b1d18a3106040669716187ee5a5a7d", "lang": "C", "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "therault/dplasma", "max_forks_repo_path": "src/cores/core_zlantr.c", "max_issues_count": 5, "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "therault/dplasma", "max_issues_repo_path": "src/cores/core_zlantr.c", "max_line_length": 83, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "therault/dplasma", "max_stars_repo_path": "src/cores/core_zlantr.c", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "num_tokens": 1462, "size": 5243 }
/* * Copyright (c) 1997-1999 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /* This file was automatically generated --- DO NOT EDIT */ /* Generated on Mon Mar 8 17:44:40 EST 1999 */ #include <fftw-int.h> #include <fftw.h> /* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddle 9 */ /* * This function contains 80 FP additions, 40 FP multiplications, * (or, 60 additions, 20 multiplications, 20 fused multiply/add), * 30 stack variables, and 36 memory accesses */ static const fftw_real K939692620 = FFTW_KONST(+0.939692620785908384054109277324731469936208134); static const fftw_real K342020143 = FFTW_KONST(+0.342020143325668733044099614682259580763083368); static const fftw_real K984807753 = FFTW_KONST(+0.984807753012208059366743024589523013670643252); static const fftw_real K173648177 = FFTW_KONST(+0.173648177666930348851716626769314796000375677); static const fftw_real K642787609 = FFTW_KONST(+0.642787609686539326322643409907263432907559884); static const fftw_real K766044443 = FFTW_KONST(+0.766044443118978035202392650555416673935832457); static const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627); static const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000); /* * Generator Id's : * $Id: exprdag.ml,v 1.36 1999/02/19 17:22:11 athena Exp $ * $Id: fft.ml,v 1.41 1999/02/19 17:22:13 athena Exp $ * $Id: to_c.ml,v 1.24 1999/02/19 17:22:17 athena Exp $ */ void fftw_no_twiddle_9(const fftw_complex *input, fftw_complex *output, int istride, int ostride) { fftw_real tmp5; fftw_real tmp17; fftw_real tmp50; fftw_real tmp20; fftw_real tmp78; fftw_real tmp53; fftw_real tmp10; fftw_real tmp26; fftw_real tmp58; fftw_real tmp74; fftw_real tmp31; fftw_real tmp59; fftw_real tmp15; fftw_real tmp37; fftw_real tmp62; fftw_real tmp75; fftw_real tmp42; fftw_real tmp61; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp1; fftw_real tmp2; fftw_real tmp3; fftw_real tmp4; ASSERT_ALIGNED_DOUBLE(); tmp1 = c_re(input[0]); tmp2 = c_re(input[3 * istride]); tmp3 = c_re(input[6 * istride]); tmp4 = tmp2 + tmp3; tmp5 = tmp1 + tmp4; tmp17 = tmp1 - (K500000000 * tmp4); tmp50 = K866025403 * (tmp3 - tmp2); } { fftw_real tmp51; fftw_real tmp18; fftw_real tmp19; fftw_real tmp52; ASSERT_ALIGNED_DOUBLE(); tmp51 = c_im(input[0]); tmp18 = c_im(input[3 * istride]); tmp19 = c_im(input[6 * istride]); tmp52 = tmp18 + tmp19; tmp20 = K866025403 * (tmp18 - tmp19); tmp78 = tmp51 + tmp52; tmp53 = tmp51 - (K500000000 * tmp52); } { fftw_real tmp6; fftw_real tmp28; fftw_real tmp9; fftw_real tmp27; fftw_real tmp25; fftw_real tmp29; fftw_real tmp22; fftw_real tmp30; ASSERT_ALIGNED_DOUBLE(); tmp6 = c_re(input[istride]); tmp28 = c_im(input[istride]); { fftw_real tmp7; fftw_real tmp8; fftw_real tmp23; fftw_real tmp24; ASSERT_ALIGNED_DOUBLE(); tmp7 = c_re(input[4 * istride]); tmp8 = c_re(input[7 * istride]); tmp9 = tmp7 + tmp8; tmp27 = K866025403 * (tmp8 - tmp7); tmp23 = c_im(input[4 * istride]); tmp24 = c_im(input[7 * istride]); tmp25 = K866025403 * (tmp23 - tmp24); tmp29 = tmp23 + tmp24; } tmp10 = tmp6 + tmp9; tmp22 = tmp6 - (K500000000 * tmp9); tmp26 = tmp22 + tmp25; tmp58 = tmp22 - tmp25; tmp74 = tmp28 + tmp29; tmp30 = tmp28 - (K500000000 * tmp29); tmp31 = tmp27 + tmp30; tmp59 = tmp30 - tmp27; } { fftw_real tmp11; fftw_real tmp39; fftw_real tmp14; fftw_real tmp38; fftw_real tmp36; fftw_real tmp40; fftw_real tmp33; fftw_real tmp41; ASSERT_ALIGNED_DOUBLE(); tmp11 = c_re(input[2 * istride]); tmp39 = c_im(input[2 * istride]); { fftw_real tmp12; fftw_real tmp13; fftw_real tmp34; fftw_real tmp35; ASSERT_ALIGNED_DOUBLE(); tmp12 = c_re(input[5 * istride]); tmp13 = c_re(input[8 * istride]); tmp14 = tmp12 + tmp13; tmp38 = K866025403 * (tmp13 - tmp12); tmp34 = c_im(input[5 * istride]); tmp35 = c_im(input[8 * istride]); tmp36 = K866025403 * (tmp34 - tmp35); tmp40 = tmp34 + tmp35; } tmp15 = tmp11 + tmp14; tmp33 = tmp11 - (K500000000 * tmp14); tmp37 = tmp33 + tmp36; tmp62 = tmp33 - tmp36; tmp75 = tmp39 + tmp40; tmp41 = tmp39 - (K500000000 * tmp40); tmp42 = tmp38 + tmp41; tmp61 = tmp41 - tmp38; } { fftw_real tmp76; fftw_real tmp16; fftw_real tmp73; fftw_real tmp77; fftw_real tmp79; fftw_real tmp80; ASSERT_ALIGNED_DOUBLE(); tmp76 = K866025403 * (tmp74 - tmp75); tmp16 = tmp10 + tmp15; tmp73 = tmp5 - (K500000000 * tmp16); c_re(output[0]) = tmp5 + tmp16; c_re(output[3 * ostride]) = tmp73 + tmp76; c_re(output[6 * ostride]) = tmp73 - tmp76; tmp77 = K866025403 * (tmp15 - tmp10); tmp79 = tmp74 + tmp75; tmp80 = tmp78 - (K500000000 * tmp79); c_im(output[3 * ostride]) = tmp77 + tmp80; c_im(output[6 * ostride]) = tmp80 - tmp77; c_im(output[0]) = tmp78 + tmp79; } { fftw_real tmp21; fftw_real tmp54; fftw_real tmp44; fftw_real tmp49; fftw_real tmp48; fftw_real tmp55; fftw_real tmp45; fftw_real tmp56; ASSERT_ALIGNED_DOUBLE(); tmp21 = tmp17 + tmp20; tmp54 = tmp50 + tmp53; { fftw_real tmp32; fftw_real tmp43; fftw_real tmp46; fftw_real tmp47; ASSERT_ALIGNED_DOUBLE(); tmp32 = (K766044443 * tmp26) + (K642787609 * tmp31); tmp43 = (K173648177 * tmp37) + (K984807753 * tmp42); tmp44 = tmp32 + tmp43; tmp49 = K866025403 * (tmp43 - tmp32); tmp46 = (K766044443 * tmp31) - (K642787609 * tmp26); tmp47 = (K173648177 * tmp42) - (K984807753 * tmp37); tmp48 = K866025403 * (tmp46 - tmp47); tmp55 = tmp46 + tmp47; } c_re(output[ostride]) = tmp21 + tmp44; tmp45 = tmp21 - (K500000000 * tmp44); c_re(output[7 * ostride]) = tmp45 - tmp48; c_re(output[4 * ostride]) = tmp45 + tmp48; c_im(output[ostride]) = tmp54 + tmp55; tmp56 = tmp54 - (K500000000 * tmp55); c_im(output[4 * ostride]) = tmp49 + tmp56; c_im(output[7 * ostride]) = tmp56 - tmp49; } { fftw_real tmp57; fftw_real tmp69; fftw_real tmp72; fftw_real tmp66; fftw_real tmp64; fftw_real tmp65; fftw_real tmp71; fftw_real tmp70; ASSERT_ALIGNED_DOUBLE(); { fftw_real tmp67; fftw_real tmp68; fftw_real tmp60; fftw_real tmp63; ASSERT_ALIGNED_DOUBLE(); tmp57 = tmp17 - tmp20; tmp67 = (K173648177 * tmp59) - (K984807753 * tmp58); tmp68 = (K342020143 * tmp62) + (K939692620 * tmp61); tmp69 = tmp67 - tmp68; tmp72 = K866025403 * (tmp67 + tmp68); tmp66 = tmp53 - tmp50; tmp60 = (K173648177 * tmp58) + (K984807753 * tmp59); tmp63 = (K342020143 * tmp61) - (K939692620 * tmp62); tmp64 = tmp60 + tmp63; tmp65 = K866025403 * (tmp63 - tmp60); } c_re(output[2 * ostride]) = tmp57 + tmp64; tmp71 = tmp57 - (K500000000 * tmp64); c_re(output[8 * ostride]) = tmp71 - tmp72; c_re(output[5 * ostride]) = tmp71 + tmp72; c_im(output[2 * ostride]) = tmp66 + tmp69; tmp70 = tmp66 - (K500000000 * tmp69); c_im(output[5 * ostride]) = tmp65 + tmp70; c_im(output[8 * ostride]) = tmp70 - tmp65; } } fftw_codelet_desc fftw_no_twiddle_9_desc = { "fftw_no_twiddle_9", (void (*)()) fftw_no_twiddle_9, 9, FFTW_FORWARD, FFTW_NOTW, 145, 0, (const int *) 0, };
{ "alphanum_fraction": 0.6391039174, "avg_line_length": 30.8913043478, "ext": "c", "hexsha": "b7c1374b81aa3329f83fb046c5d81f8ecd0e9d9e", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_path": "jlp_numeric/old/fftw2_src/fn_9.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_path": "jlp_numeric/old/fftw2_src/fn_9.c", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/fn_9.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2841, "size": 8526 }
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "compearth.h" #ifdef COMPEARTH_USE_MKL #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wstrict-prototypes" #endif #include <mkl_cblas.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #else #include <cblas.h> #endif static double compearth_norm64f(const int n, const double *__restrict__ x, const enum ceNormType_enum norm, const double p, int *ierr); /*! * @brief Computes the matrix (Frobenius) norm for a matrix * * @param[in] n number of matrices * @param[in] M 3 x 3 input matrix as a length 9 array [9*n] * @param[in] Lnorm matrix norm * TWO_NORM (2) * ONE_NORM (1) * P_NORM (in this case must set p) * INFINITY_NORM * NEGATIVE_INFINITY_NORM * @param[in] p if using a p-norm this is the value for p (> 0) * * @param[out] mnorm matrix norms for each matrix * * @result 0 indicates success * */ int compearth_normMat(const int n, const double *__restrict__ M, const enum ceNormType_enum Lnorm, const double p, double *__restrict__ mnorm) { int i, ierr; ierr = 0; for (i=0; i<n; i++) { mnorm[i] = compearth_norm64f(9, &M[9*i], Lnorm, p, &ierr); if (ierr != 0) { fprintf(stderr, "%s: Error computing matrix norm!\n", __func__); mnorm[i] = 0.0; break; } } return ierr; } /*! * @brief Computes the norm of a vector. This is from ISTI's ISCL. * * @param[in] n Length of array x. * @param[in] x Array of dimension [n] of which to compute norm. * @param[in] norm Type of norm to compute. * @param[in] p If performing a P norm then this must be defined to * a real number greater than or equal to 1. Otherwise, * it will not be accessed. * * @param[out] ierr 0 indicates success * * @result P-norm of array x. * * @author Ben Baker * * @date August 2017 - redefined variables so that this may exist in * compearth without collisions with ISCL. * */ static double compearth_norm64f(const int n, const double *__restrict__ x, const enum ceNormType_enum norm, const double p, int *ierr) { double xnorm; int i; *ierr = 0; xnorm = 0.0; if (n < 1 || x == NULL) { if (n < 1){fprintf(stderr, "%s: Error no data\n", __func__);} if (x == NULL){fprintf(stderr, "%s: Error x is NULL\n", __func__);} *ierr = 1; return xnorm; } // 2 norm if (norm == CE_TWO_NORM) { xnorm = cblas_dnrm2(n, x, 1); // 1 norm } else if (norm == CE_ONE_NORM) { xnorm = cblas_dasum(n, x, 1); } // p norm else if (norm == CE_P_NORM) { if (p <= 0.0) { fprintf(stderr, "%s: Invalid p value %f\n", __func__, p); *ierr = 1; return xnorm; } #pragma omp simd reduction(+:xnorm) for (i=0; i<n; i++) { xnorm = xnorm + pow(fabs(x[i]), p); } xnorm = pow(xnorm, 1./p); } // infinity norm else if (norm == CE_INFINITY_NORM) { xnorm = fabs(x[cblas_idamax(n, x, 1)]); } // negative infinity norm else if (norm == CE_NEGATIVE_INFINITY_NORM) { xnorm = fabs(x[0]); #pragma omp simd reduction(min:xnorm) for (i=1; i<n; i++) { xnorm = fmin(fabs(x[i]), xnorm); } } // not sure - default to 2-norm else { fprintf(stderr, "%s: Defaulting to 2-norm\n", __func__); xnorm = cblas_dnrm2(n, x, 1); } return xnorm; }
{ "alphanum_fraction": 0.5300573709, "avg_line_length": 27.6482758621, "ext": "c", "hexsha": "3ddeaabd04e0dc6da3ae98631b3ffbc6277ae08b", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z", "max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z", "max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carltape/mtbeach", "max_forks_repo_path": "c_src/normMat.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "carltape/mtbeach", "max_issues_repo_path": "c_src/normMat.c", "max_line_length": 76, "max_stars_count": 9, "max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OUCyf/mtbeach", "max_stars_repo_path": "c_src/normMat.c", "max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z", "num_tokens": 1111, "size": 4009 }
#ifndef H_EASY_GSL #define H_EASY_GSL #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #ifdef __cplusplus extern "C" { #endif struct egsl_val { gsl_matrix * gslm; int cid : 16; int index : 16; }; typedef struct egsl_val val; /* Core functions */ /* Push a new context. */ void egsl_push(); void egsl_push_named(const char*name); /* Pops a context */ void egsl_pop(); void egsl_pop_named(const char*name); void egsl_free(void); double* egsl_atmp(val v, size_t i, size_t j); val egsl_alloc(size_t rows, size_t columns); val egsl_alloc_in_context(int cid, size_t rows, size_t cols); gsl_matrix * egsl_gslm(val v); /** Creates a copy of v in the previous context.*/ val egsl_promote(val v); /** Operations among values */ val egsl_scale(double, val); val egsl_sum(val, val); val egsl_sum3(val, val, val); val egsl_mult(val, val); val egsl_transpose(val); val egsl_inverse(val); val egsl_sub(val,val); val egsl_sum(val v1,val v2); val egsl_compose_col(val v1, val v2); val egsl_compose_row(val v1, val v2); void egsl_add_to(val v1, val v2); void egsl_add_to_col(val v1, size_t j, val v2); double egsl_norm(val); void egsl_symm_eig(val v, double* eigenvalues, val* eigenvectors); double egsl_atv(val, size_t i); double egsl_atm(val, size_t i, size_t j); /* File: egsl_conversions.c Conversions */ val egsl_vFa(size_t rows, const double*); val egsl_vFda(size_t rows, size_t columns, const double*); /** Copies a VECTOR value into array */ void egsl_v2a(val, double*); /** Copies a MATRIX value into array (row1 .. rown) */ void egsl_v2da(val, double*); /** Copies a vector value into a gsl_vector */ void egsl_v2vec(val, gsl_vector*); val egsl_vFgslv(const gsl_vector*); val egsl_vFgslm(const gsl_matrix*); gsl_matrix* egsl_v2gslm(val); /*/ File: egsl_misc.c Miscellaneous useful matrixes. */ val egsl_zeros(size_t rows, size_t columns); val egsl_ones(size_t rows, size_t columns); val egsl_vers(double theta); val egsl_rot(double theta); /* Misc */ void egsl_print(const char*str, val); /** Prints eigenvalues and eigenvectors of a symmetric matrix */ void egsl_print_spectrum(const char*s, val v); void egsl_print_stats(void); /** Private implementations things */ void egsl_expect_size(val v, size_t rows, size_t cols); void egsl_error(void); #ifdef __cplusplus } #endif #endif
{ "alphanum_fraction": 0.7364106989, "avg_line_length": 22.7254901961, "ext": "h", "hexsha": "0b8c17cd77f2c66fcd93fcd00d6d0906e82e7782", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-12-06T12:39:31.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-24T20:11:24.000Z", "max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "alecone/ROS_project", "max_forks_repo_path": "src/csm/sm/lib/egsl/egsl.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "alecone/ROS_project", "max_issues_repo_path": "src/csm/sm/lib/egsl/egsl.h", "max_line_length": 66, "max_stars_count": 4, "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_path": "src/csm/sm/lib/egsl/egsl.h", "max_stars_repo_stars_event_max_datetime": "2021-12-27T02:53:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-21T00:38:17.000Z", "num_tokens": 670, "size": 2318 }
#pragma once #include <gsl.h> #include <ImmutableRanges.h> #include <qobject.h> #include <mitkBaseData.h> #include <FaceIdentifier.h> class QWidget; namespace crimson { class QtPropertyStorage; /*! \brief An interface for data associated with model faces. * * This includes boundary conditions and materials. */ class FaceData : public mitk::BaseData { public: mitkClassMacro(FaceData, BaseData); /*! * \brief Gets the FaceData object name. */ virtual gsl::cstring_span<> getName() const = 0; /*! * \brief Gets the list of face types (as defined by FaceIdentifer::FaceType) that the face * data can be applied to. */ virtual ImmutableRefRange<FaceIdentifier::FaceType> applicableFaceTypes() = 0; ///@{ /*! * \brief Sets the identifiers of the faces the FaceData is applied to. */ virtual void setFaces(ImmutableRefRange<FaceIdentifier> faces) = 0; /*! * \brief Gets the identifiers of the faces the FaceData is applied to. */ virtual ImmutableRefRange<FaceIdentifier> getFaces() const = 0; ///@} /*! * \brief Creates custom editor widget which should be added to the UI. */ virtual QWidget* createCustomEditorWidget() { return nullptr; } /*! * \brief Gets property storage for the FaceData properties. */ virtual gsl::not_null<QtPropertyStorage*> getPropertyStorage() = 0; /*! * \brief stores a pointer to C++ owned data object. For use in python-based boundary conditions that have the logic implemented in C++ */ virtual void setDataObject(QVariantList data){}; virtual void setDataUID(std::string dataUID){}; virtual std::string getDataUID(){ return std::string{}; }; protected: FaceData() { mitk::BaseData::InitializeTimeGeometry(1); } virtual ~FaceData() {} FaceData(const Self&) = default; void SetRequestedRegion(const itk::DataObject*) override {} void SetRequestedRegionToLargestPossibleRegion() override {} bool RequestedRegionIsOutsideOfTheBufferedRegion() override { return true; } bool VerifyRequestedRegion() override { return true; } }; } // end namespace crimson
{ "alphanum_fraction": 0.6848623853, "avg_line_length": 26.265060241, "ext": "h", "hexsha": "93c288e2a9be706fb883a0664ca092096b327179", "lang": "C", "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-07-26T17:39:57.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-19T09:02:21.000Z", "max_forks_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "carthurs/CRIMSONGUI", "max_forks_repo_path": "Modules/SolverSetupService/include/FaceData.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "carthurs/CRIMSONGUI", "max_issues_repo_path": "Modules/SolverSetupService/include/FaceData.h", "max_line_length": 117, "max_stars_count": 10, "max_stars_repo_head_hexsha": "1464df9c4d04cf3ba131ca90b91988a06845c68e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "carthurs/CRIMSONGUI", "max_stars_repo_path": "Modules/SolverSetupService/include/FaceData.h", "max_stars_repo_stars_event_max_datetime": "2022-02-23T02:52:38.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-17T18:55:31.000Z", "num_tokens": 520, "size": 2180 }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "arcana/utils/serialization/base_stream.h" #include "arcana/utils/serialization/serializable.h" #include "arcana/analysis/determinator.h" #include "Proxies/Proxy.h" #include "arcana/analysis/binary_iterator.h" #include "Mapping/MapPointKeyframeAssociations.h" #include "BundleAdjustment/BundleAdjust.h" #include "Proxies/KeyframeFields.h" #include "Tracking/PoseEstimator.h" #include "Utils/cv.h" #include <type_traits> #include <memory> #include <gsl/gsl> namespace mage { class MapPoint; class Keyframe; template<typename IterT> inline void binary_iterate(const Id<MapPoint>& id, mira::binary_iterator<IterT>& iterator) { iterator.iterate(reinterpret_cast<const IdT&>(id)); } template<typename IterT> inline void binary_iterate(const Id<Keyframe>& id, mira::binary_iterator<IterT>& iterator) { iterator.iterate(reinterpret_cast<const IdT&>(id)); } /* Serialize only the proxy properties that support serialization */ template<typename IterT, typename T, typename ...Props> inline void binary_iterate(const Proxy<T, Props...>& proxy, mira::binary_iterator<IterT>& iterator) { iterator.iterate(static_cast<const proxy::Id<T>&>(proxy)); int unused[] = { 0, // in case it's just a Proxy<MapPoint>, we can't declare an empty c-style array (iterator.iterate(static_cast<const Props&>(proxy)) , 0)... }; (void)unused; }; template<typename IterT> inline void binary_iterate(const KeyframeReprojection& data, mira::binary_iterator<IterT>& itr) { itr.iterate(reinterpret_cast<const IdT&>(data.KeyframeId)); itr.iterate(data.Pose); for (auto& point : data.Points) { itr.iterate(point.As<Proxy<MapPoint, proxy::Position, proxy::UpdateStatistics, proxy::ViewingData>>()); itr.iterate(*point.GetRepresentativeDescriptor()); } } template<typename IterT> inline void binary_iterate(const MapPointAssociation& data, mira::binary_iterator<IterT>& itr) { itr.iterate(&data, sizeof(MapPointAssociation)); } template<typename IterT> inline void binary_iterate(const HistoricalFrame& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.UpdatedPose); itr.iterate(data.Keyframe); } template<typename IterT> inline void binary_iterate(const AdjustableData& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.Keyframes); itr.iterate(data.ExternallyTetheredKeyframes); itr.iterate(data.MapPointAssociations); itr.iterate(data.MapPoints); } template<typename IterT> inline void binary_iterate(const typename MapPointAssociations<MapPointTrackingProxy>::Association& assoc, mira::binary_iterator<IterT>& itr) { itr.iterate_all(assoc.MapPoint, assoc.Index); } template<typename IterT> inline void binary_iterate(const MapPointKeyframeAssociations& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.MapPoint); itr.iterate(data.Keyframes); } template<typename IterT> inline void binary_iterate(const KeyframeAssociation& data, mira::binary_iterator<IterT>& itr) { itr.iterate_all(data.KeyframeId, data.KeypointDescriptorIndex); } template<typename IterT> inline void binary_iterate(const FrameId& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.CorrelationId); itr.iterate(data.Camera); } template<typename IterT> inline void binary_iterate(const AnalyzedImage& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.GetFrameId()); itr.iterate(data.GetTimeStamp().time_since_epoch()); itr.iterate(data.GetImageData()); itr.iterate(data.GetDistortedCalibration()); itr.iterate(data.GetUndistortedCalibration()); itr.iterate(data.GetKeyPoints()); } template<typename IterT, typename T> inline void binary_iterate(const Tether<T>& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.Type()); itr.iterate(data.Weight()); itr.iterate(data.OriginId()); if (data.Type() == TetherType::DISTANCE) { itr.iterate(data.Distance()); } if(data.Type() == TetherType::SIX_DOF || data.Type() == TetherType::EXTRINSIC) { itr.iterate(data.Position()); } if (data.Type() == TetherType::THREE_DOF || data.Type() == TetherType::SIX_DOF || data.Type() == TetherType::EXTRINSIC) { itr.iterate(data.Rotation()); } } namespace proxy { // no-ops that we don't check for determinism inline void binary_iterate(const Image&, mira::binary_iterator<mira::determinator::iterator_callback>&) {} inline void binary_iterate(const Associations<MapPointTrackingProxy>&, mira::binary_iterator<mira::determinator::iterator_callback>&) {} inline void binary_iterate(const UnAssociatedMask& data, mira::binary_iterator<mira::determinator::iterator_callback>& itr) { itr.iterate(data.GetUnassociatedKeypointCount()); itr.iterate(data.GetUnassociatedKeypointMask()); } template<typename IterT> inline void binary_iterate(const PoseConstraints& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.IsImmortal()); itr.iterate(data.IsFixed()); itr.iterate(data.GetTethers()); } template<typename IterT> inline void binary_iterate(const Descriptor& data, mira::binary_iterator<IterT>& itr) { // proxy::Descriptor is just a pointer to the descriptor itr.iterate(data.GetRepresentativeDescriptor()->Data(), mage::ORBDescriptor::DESCRIPTOR_SIZE_BYTES); } template<typename IterT> inline void binary_iterate(const Associations<mage::MapPointTrackingProxy>& data, mira::binary_iterator<IterT>& itr) { // not the real size as we don't account for the bimap overhead std::vector<mage::MapPointAssociations<mage::MapPointTrackingProxy>::Association> assocs; data.GetAssociations(assocs); itr.iterate(assocs); } } } namespace cv { template<typename IterT> inline void binary_iterate(const cv::KeyPoint& data, mira::binary_iterator<IterT>& itr) { itr.iterate(&data, sizeof(data)); } template<typename IterT> inline void binary_iterate(const cv::Vec3f& data, mira::binary_iterator<IterT>& itr) { itr.iterate(&data, sizeof(data)); } } namespace Eigen { template<typename IterT, typename T> inline void binary_iterate(const Quaternion<T>& data, mira::binary_iterator<IterT>& itr) { itr.iterate(data.coeffs().data(), data.coeffs().size()*sizeof(T)); } }
{ "alphanum_fraction": 0.6646833829, "avg_line_length": 33.4549763033, "ext": "h", "hexsha": "50b4e1ccb984455858a0860faf33b7c5fb941c4e", "lang": "C", "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_path": "Core/MAGESLAM/Source/Analysis/binary_iterators.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_path": "Core/MAGESLAM/Source/Analysis/binary_iterators.h", "max_line_length": 145, "max_stars_count": 70, "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_path": "Core/MAGESLAM/Source/Analysis/binary_iterators.h", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "num_tokens": 1653, "size": 7059 }
#ifndef MSHADOW_TENSOR_BASE_H #define MSHADOW_TENSOR_BASE_H /*! * \file tensor_base.h * \brief definitions of base types, macros functions * * \author Bing Xu, Tianqi Chen */ #include <cmath> #include <cstdio> #include <cfloat> #include <climits> #include <algorithm> // macro defintiions /*!\brief if this macro is define to be 1, mshadow should compile without any of other libs */ #ifndef MSHADOW_STAND_ALONE #define MSHADOW_STAND_ALONE 0 #endif /*! \brief whether do padding during allocation */ #ifndef MSHADOW_ALLOC_PAD #define MSHADOW_ALLOC_PAD true #endif /*! * \brief x dimension of data must be bigger pad_size * ratio to be alloced padded memory, otherwise use tide allocation * for example, if pad_ratio=2, GPU memory alignement size is 32, then we will only allocate padded memory if x dimension > 64 * set it to 0 then we will always allocate padded memory */ #ifndef MSHADOW_MIN_PAD_RATIO #define MSHADOW_MIN_PAD_RATIO 2 #endif #if MSHADOW_STAND_ALONE #define MSHADOW_USE_CBLAS 0 #define MSHADOW_USE_MKL 0 #define MSHADOW_USE_CUDA 0 #endif /*! \brief use CBLAS for CBLAS */ #ifndef MSHADOW_USE_CBLAS #define MSHADOW_USE_CBLAS 0 #endif /*! \brief use MKL for BLAS */ #ifndef MSHADOW_USE_MKL #define MSHADOW_USE_MKL 1 #endif /*! \brief use CUDA support, must ensure that the cuda include path is correct, or directly compile using nvcc */ #ifndef MSHADOW_USE_CUDA #define MSHADOW_USE_CUDA 1 #endif /*! \brief use single precition float */ #ifndef MSHADOW_SINGLE_PRECISION #define MSHADOW_SINGLE_PRECISION 1 #endif /*! \brief whether use SSE */ #ifndef MSHADOW_USE_SSE #define MSHADOW_USE_SSE 1 #endif /*! \brief whether use NVML to get dynamic info */ #ifndef MSHADOW_USE_NVML #define MSHADOW_USE_NVML 0 #endif // SSE is conflict with cudacc #ifdef __CUDACC__ #undef MSHADOW_USE_SSE #define MSHADOW_USE_SSE 0 #endif #if MSHADOW_USE_CBLAS extern "C"{ #include <cblas.h> } #elif MSHADOW_USE_MKL #include <mkl.h> #include <mkl_cblas.h> #include <mkl_vsl.h> #include <mkl_vsl_functions.h> #endif #if MSHADOW_USE_CUDA #include <cublas.h> #include <curand.h> #endif #if MSHADOW_USE_NVML #include <nvml.h> #endif // -------------------------------- // MSHADOW_XINLINE is used for inlining template code for both CUDA and CPU code. #ifdef MSHADOW_XINLINE #error "MSHADOW_XINLINE must not be defined" #endif #ifdef __CUDACC__ #define MSHADOW_XINLINE inline __attribute__((always_inline)) __device__ __host__ #else #define MSHADOW_XINLINE inline __attribute__((always_inline)) #endif /*! \brief cpu force inline */ #define MSHADOW_CINLINE inline __attribute__((always_inline)) #if defined(__GXX_EXPERIMENTAL_CXX0X) || defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L #define MSHADOW_CONSTEXPR constexpr #else #define MSHADOW_CONSTEXPR const #endif /*! \brief namespace for mshadow */ namespace mshadow { /*! \brief buffer size for each random number generator */ const unsigned kRandBufferSize = 1000000; /*! \brief pi */ const float kPi = 3.1415926f; #if MSHADOW_SINGLE_PRECISION /*! \brief type that will be used for content */ typedef float real_t; #else typedef double real_t; #endif /*! \brief type that will be used for index */ typedef unsigned index_t; }; // namespace mshadow namespace mshadow { /*! \brief namespace for operators */ namespace op { // binary operator /*! \brief mul operator */ struct mul{ /*! \brief map a, b to result using defined operation */ MSHADOW_XINLINE static real_t Map(real_t a, real_t b) { return a * b; } }; /*! \brief plus operator */ struct plus { /*! \brief map a, b to result using defined operation */ MSHADOW_XINLINE static real_t Map(real_t a, real_t b) { return a + b; } }; /*! \brief minus operator */ struct minus { /*! \brief map a, b to result using defined operation */ MSHADOW_XINLINE static real_t Map(real_t a, real_t b) { return a - b; } }; /*! \brief divide operator */ struct div { /*! \brief map a, b to result using defined operation */ MSHADOW_XINLINE static real_t Map(real_t a, real_t b) { return a / b; } }; /*! \brief get rhs */ struct right { /*! \brief map a, b to result using defined operation */ MSHADOW_XINLINE static real_t Map(real_t a, real_t b) { return b; } }; }; // namespace op /*! \brief namespace for savers */ namespace sv { /*! \brief save to saver: = */ struct saveto { /*! \brief save b to a using save method */ MSHADOW_XINLINE static void Save(real_t& a, real_t b) { a = b; } /*! \brief helper constant to use BLAS, alpha */ MSHADOW_CONSTEXPR static real_t kAlphaBLAS = 1.0f; /*! \brief helper constant to use BLAS, beta */ MSHADOW_CONSTEXPR static real_t kBetaBLAS = 0.0f; /*! \brief corresponding binary operator type */ typedef op::right OPType; }; /*! \brief save to saver: += */ struct plusto { /*! \brief save b to a using save method */ MSHADOW_XINLINE static void Save(real_t& a, real_t b) { a += b; } /*! \brief helper constant to use BLAS, alpha */ MSHADOW_CONSTEXPR static real_t kAlphaBLAS = 1.0f; /*! \brief helper constant to use BLAS, beta */ MSHADOW_CONSTEXPR static real_t kBetaBLAS = 1.0f; /*! \brief corresponding binary operator type */ typedef op::plus OPType; }; /*! \brief minus to saver: -= */ struct minusto { /*! \brief save b to a using save method */ MSHADOW_XINLINE static void Save(real_t& a, real_t b) { a -= b; } /*! \brief helper constant to use BLAS, alpha */ MSHADOW_CONSTEXPR static real_t kAlphaBLAS = -1.0f; /*! \brief helper constant to use BLAS, beta */ MSHADOW_CONSTEXPR static real_t kBetaBLAS = 1.0f; /*! \brief corresponding binary operator type */ typedef op::minus OPType; }; /*! \brief multiply to saver: *= */ struct multo { /*! \brief save b to a using save method */ MSHADOW_XINLINE static void Save(real_t& a, real_t b) { a *= b; } /*! \brief corresponding binary operator type */ typedef op::mul OPType; }; /*! \brief divide to saver: /= */ struct divto { /*! \brief save b to a using save method */ MSHADOW_XINLINE static void Save(real_t& a, real_t b) { a /= b; } /*! \brief corresponding binary operator type */ typedef op::div OPType; }; }; // namespace sv namespace op { // unary operator/ function: example // these operators can be defined by user, in the same style as binary and unary operator // to use, simply write F<op::identity>( src ) /*! \brief identity function that maps a real number to it self */ struct identity{ /*! \brief map a to result using defined operation */ MSHADOW_XINLINE static real_t Map(real_t a) { return a; } }; }; // namespace op /*! \brief namespace for potential reducer operations */ namespace red { /*! \brief sum reducer */ struct sum { /*! \brief do reduction into dst */ MSHADOW_XINLINE static void Reduce( volatile real_t& dst, volatile real_t src ) { dst += src; } /*! \brief calculate gradient of redres with respect to redsrc, redres: reduced result, redsrc: one of reduction element */ MSHADOW_XINLINE static real_t PartialGrad( real_t redres, real_t redsrc ) { return 1.0f; } /*! \brief an intial value of reducer */ MSHADOW_CONSTEXPR static real_t kInitV = 0.0f; }; /*! \brief maximum reducer */ struct maximum { /*! \brief do reduction into dst */ MSHADOW_XINLINE static void Reduce( volatile real_t& dst, volatile real_t src ) { using namespace std; dst = max( dst, src ); } /*! \brief calculate gradient of redres with respect to redsrc, redres: reduced result, redsrc: one of reduction element */ MSHADOW_XINLINE static real_t PartialGrad( real_t redres, real_t redsrc ) { return redres == redsrc ? 1.0f: 0.0f; } /*! \brief an intial value of reducer */ #if MSHADOW_SINGLE_PRECISION MSHADOW_CONSTEXPR static real_t kInitV = -FLT_MAX; #else MSHADOW_CONSTEXPR static real_t kInitV = -DBL_MAX; #endif }; }; /*! \brief namespace for helper utils of the project */ namespace utils{ /*! \brief send error message then exit */ inline void Error( const char *msg ){ fprintf( stderr, "Error:%s\n",msg ); exit( -1 ); } /*! \brief assert a expression is true */ inline void Assert( bool exp ){ if( !exp ) Error( "AssertError" ); } /*! \brief assert a expression is true */ inline void Assert( bool exp, const char *msg ){ if( !exp ) Error( msg ); } /*! \brief warning */ inline void Warning( const char *msg ){ fprintf( stderr, "warning:%s\n",msg ); } }; // namespace utils }; // namespace mshadow #endif // TENSOR_BASE_H
{ "alphanum_fraction": 0.5945919077, "avg_line_length": 33.6421404682, "ext": "h", "hexsha": "b251cbadf4fc705161901ca45d2808bdc205f3fb", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7d39f8813d057565224402e230afacb98c8c366b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "kaiping/RNNLM_PARAM_SHARING", "max_forks_repo_path": "include/mshadow/tensor_base.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7d39f8813d057565224402e230afacb98c8c366b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "kaiping/RNNLM_PARAM_SHARING", "max_issues_repo_path": "include/mshadow/tensor_base.h", "max_line_length": 136, "max_stars_count": 3, "max_stars_repo_head_hexsha": "7d39f8813d057565224402e230afacb98c8c366b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "kaiping/RNNLM_PARAM_SHARING", "max_stars_repo_path": "include/mshadow/tensor_base.h", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:03:31.000Z", "max_stars_repo_stars_event_min_datetime": "2016-10-29T09:40:46.000Z", "num_tokens": 2468, "size": 10059 }
/* * read_parameters.h * Spike * parse simple name/value pairs * * Created by Ben Evans on 28/11/2008. * Copyright 2008 University of Oxford. All rights reserved. * */ #ifndef _READ_PARAMETERS_H #define _READ_PARAMETERS_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <assert.h> #include "globals.h" #include "parameters.h" #include "utils.h" #include <gsl/gsl_sf_gamma.h> // N choose M funcion #define MAXLEN 256 #define BUFFER 512 // Make larger for comments or break up comments #define VECBUFF 4 char * trim(char * string); int parse_string(PARAMS * params, char * string); int read_parameters(PARAMS * params, char * paramfile); int parseIntVector(char * string, int ** array); int parseFloatVector(char * string, float ** array); int printParameters(PARAMS * mp, char * paramfile); void printIntArray(FILE * fp, char * name, int * array, int len); void printFloatArray(FILE * fp, char * name, float * array, int len); #endif
{ "alphanum_fraction": 0.7185332012, "avg_line_length": 24.6097560976, "ext": "h", "hexsha": "ab17ba2a5bfacca0803f048a14379fd99afa9274", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_forks_repo_path": "source/read_parameters.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_issues_repo_path": "source/read_parameters.h", "max_line_length": 69, "max_stars_count": null, "max_stars_repo_head_hexsha": "23f537bfa3605a5d1100b51eea7160d92d43be58", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "wincle626/SpikingNeuralNetworkSimulatorXOS", "max_stars_repo_path": "source/read_parameters.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 256, "size": 1009 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #pragma once #define NOMINMAX #pragma warning(disable : 6221) // Disable implicit cast warning for C++/WinRT headers (tracked by Bug 17528784: C++/WinRT headers trigger C6221 comparing e.code() to int-typed things) // Disable factory caching in CppWinRT as the global COM pointers that are released during dll/process // unload are not safe. Setting this makes CppWinRT just call get_activation_factory directly every time. #define WINRT_DISABLE_FACTORY_CACHE 1 #include "targetver.h" #include "BuildMacros.h" #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <wrl\implements.h> #include <wrl\module.h> #include <wrl\event.h> #define MUX_ASSERT(X) _ASSERT(X) #define MUX_ASSERT_MSG(X, MSG) _ASSERT_EXPR(X, MSG) #define MUX_ASSERT_NOASSUME(X) _ASSERT(X) #define MUX_FAIL_FAST() RaiseFailFastException(nullptr, nullptr, 0); #define MUX_FAIL_FAST_MSG(MSG) RaiseFailFastException(nullptr, nullptr, 0); #ifdef BUILD_WINDOWS #include <gsl/gsl_util> #else #include <gsl_util.h> #endif // windows.ui.xaml.h accesses LoadLibrary in its inline declaration of CreateXamlUiPresenter // Accessing LoadLibrary is not always allowed (e.g. on phone), so we need to suppress that. // We can do so by making this define prior to including the header. #define CREATE_XAML_UI_PRESENTER_API #include <Windows.UI.Xaml.Hosting.ReferenceTracker.h> #include <WindowsNumerics.h> #include <strsafe.h> #include <robuffer.h> // STL #include <vector> #include <map> #include <functional> #define _USE_MATH_DEFINES #include <math.h> #ifdef BUILD_WINDOWS #include <staging.h> #include <featurestaging-xaml.h> #undef CATCH_RETURN // See our implementation in ErrorHandling.h #else #define WI_IS_FEATURE_PRESENT(FeatureName) 1 #endif #undef GetCurrentTime #include "CppWinRTIncludes.h"
{ "alphanum_fraction": 0.7546523017, "avg_line_length": 28.3611111111, "ext": "h", "hexsha": "e99222be962ad5590773d25d6186393834af0eff", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-28T10:29:11.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-28T10:29:11.000Z", "max_forks_repo_head_hexsha": "7f0068704a279afd1fb38fd3f576a21980e355b0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "DotNetUX/microsoft-ui-xaml", "max_forks_repo_path": "dev/dll/pch.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "cd29bf314a888d18e7702fc857b193e2cb96302e", "max_issues_repo_issues_event_max_datetime": "2018-12-07T16:50:00.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-07T16:49:26.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "agneszitte-nventive/microsoft-ui-xaml", "max_issues_repo_path": "dev/dll/pch.h", "max_line_length": 185, "max_stars_count": 3, "max_stars_repo_head_hexsha": "7f0068704a279afd1fb38fd3f576a21980e355b0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "DotNetUX/microsoft-ui-xaml", "max_stars_repo_path": "dev/dll/pch.h", "max_stars_repo_stars_event_max_datetime": "2020-03-24T13:23:27.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-06T08:02:41.000Z", "num_tokens": 483, "size": 2042 }
/* specfunc/bessel_sequence.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: G. Jungman */ #include <config.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_sf_bessel.h> #define DYDX_p(p,u,x) (-(p)/(x) + (((nu)*(nu))/((x)*(x))-1.0)*(u)) #define DYDX_u(p,u,x) (p) static int rk_step(double nu, double x, double dx, double * Jp, double * J) { double p_0 = *Jp; double u_0 = *J; double p_1 = dx * DYDX_p(p_0, u_0, x); double u_1 = dx * DYDX_u(p_0, u_0, x); double p_2 = dx * DYDX_p(p_0 + 0.5*p_1, u_0 + 0.5*u_1, x + 0.5*dx); double u_2 = dx * DYDX_u(p_0 + 0.5*p_1, u_0 + 0.5*u_1, x + 0.5*dx); double p_3 = dx * DYDX_p(p_0 + 0.5*p_2, u_0 + 0.5*u_2, x + 0.5*dx); double u_3 = dx * DYDX_u(p_0 + 0.5*p_2, u_0 + 0.5*u_2, x + 0.5*dx); double p_4 = dx * DYDX_p(p_0 + p_3, u_0 + u_3, x + dx); double u_4 = dx * DYDX_u(p_0 + p_3, u_0 + u_3, x + dx); *Jp = p_0 + p_1/6.0 + p_2/3.0 + p_3/3.0 + p_4/6.0; *J = u_0 + u_1/6.0 + u_2/3.0 + u_3/3.0 + u_4/6.0; return GSL_SUCCESS; } int gsl_sf_bessel_sequence_Jnu_e(double nu, gsl_mode_t mode, size_t size, double * v) { /* CHECK_POINTER(v) */ if(nu < 0.0) { GSL_ERROR ("domain error", GSL_EDOM); } else if(size == 0) { GSL_ERROR ("error", GSL_EINVAL); } else { const gsl_prec_t goal = GSL_MODE_PREC(mode); const double dx_array[] = { 0.001, 0.03, 0.1 }; /* double, single, approx */ const double dx_nominal = dx_array[goal]; const int cnu = (int) ceil(nu); const double nu13 = pow(nu,1.0/3.0); const double smalls[] = { 0.01, 0.02, 0.4, 0.7, 1.3, 2.0, 2.5, 3.2, 3.5, 4.5, 6.0 }; const double x_small = ( nu >= 10.0 ? nu - nu13 : smalls[cnu] ); gsl_sf_result J0, J1; double Jp, J; double x; size_t i = 0; /* Calculate the first point. */ x = v[0]; gsl_sf_bessel_Jnu_e(nu, x, &J0); v[0] = J0.val; ++i; /* Step over the idiot case where the * first point was actually zero. */ if(x == 0.0) { if(v[1] <= x) { /* Strict ordering failure. */ GSL_ERROR ("error", GSL_EFAILED); } x = v[1]; gsl_sf_bessel_Jnu_e(nu, x, &J0); v[1] = J0.val; ++i; } /* Calculate directly as long as the argument * is small. This is necessary because the * integration is not very good there. */ while(v[i] < x_small && i < size) { if(v[i] <= x) { /* Strict ordering failure. */ GSL_ERROR ("error", GSL_EFAILED); } x = v[i]; gsl_sf_bessel_Jnu_e(nu, x, &J0); v[i] = J0.val; ++i; } /* At this point we are ready to integrate. * The value of x is the last calculated * point, which has the value J0; v[i] is * the next point we need to calculate. We * calculate nu+1 at x as well to get * the derivative, then we go forward. */ gsl_sf_bessel_Jnu_e(nu+1.0, x, &J1); J = J0.val; Jp = -J1.val + nu/x * J0.val; while(i < size) { const double dv = v[i] - x; const int Nd = (int) ceil(dv/dx_nominal); const double dx = dv / Nd; double xj; int j; if(v[i] <= x) { /* Strict ordering failure. */ GSL_ERROR ("error", GSL_EFAILED); } /* Integrate over interval up to next sample point. */ for(j=0, xj=x; j<Nd; j++, xj += dx) { rk_step(nu, xj, dx, &Jp, &J); } /* Go to next interval. */ x = v[i]; v[i] = J; ++i; } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5742690058, "avg_line_length": 27.5806451613, "ext": "c", "hexsha": "c816a33ce53a6754f34d52cf00c65adb9bf8799a", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_sequence.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_sequence.c", "max_line_length": 88, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_sequence.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 1533, "size": 4275 }
#include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #include "qdm.h" #define TAU_RESET_L_SIZE 11 #define TAU_RESET_M_SIZE 8 #define TAU_RESET_H_SIZE 11 #define TAU_RESET_SIZE (TAU_RESET_L_SIZE + TAU_RESET_M_SIZE + TAU_RESET_H_SIZE) #define TAU_RESET_STEP 0.0001 #define TAU_RESET_GAP 0.001 #define TAU_TABLE_SIZE 1048576 #define TAU_INITIAL_GUESS 0.5 #define TAU_EPS 0.001 #define TAU_ITERATION_MAX 1000 static void qdm_tau_reset_setup( qdm_tau *t ) { t->reset = gsl_vector_alloc(TAU_RESET_SIZE); size_t offset = 0; gsl_vector_view view; view = gsl_vector_subvector(t->reset, offset, TAU_RESET_L_SIZE); qdm_vector_set_seq(&view.vector, t->low, t->low + (TAU_RESET_L_SIZE - 1) * TAU_RESET_STEP); offset += TAU_RESET_L_SIZE; view = gsl_vector_subvector(t->reset, offset, TAU_RESET_M_SIZE); qdm_vector_set_seq(&view.vector, t->low + TAU_RESET_GAP, t->high - TAU_RESET_GAP); offset += TAU_RESET_M_SIZE; view = gsl_vector_subvector(t->reset, offset, TAU_RESET_H_SIZE); qdm_vector_set_seq(&view.vector, t->high - (TAU_RESET_H_SIZE - 1) * TAU_RESET_STEP, t->high); offset += TAU_RESET_H_SIZE; } static void qdm_tau_table_setup( qdm_tau *t ) { if (!t->use_table) { t->ispline_table = NULL; t->mspline_table = NULL; return; } t->ispline_table = gsl_matrix_alloc(TAU_TABLE_SIZE, (t->knots->size - t->spline_df) + 1); t->mspline_table = gsl_matrix_alloc(TAU_TABLE_SIZE, (t->knots->size - t->spline_df) + 1); double tau = 0; gsl_vector_view row; for (size_t i = 0; i < TAU_TABLE_SIZE; i++) { tau = (double)(i) / TAU_TABLE_SIZE; row = gsl_matrix_row(t->ispline_table, i); qdm_ispline_vector( &row.vector, tau, t->spline_df, t->knots ); row = gsl_matrix_row(t->mspline_table, i); qdm_mspline_vector( &row.vector, tau, t->spline_df, t->knots ); } } qdm_tau * qdm_tau_alloc( int use_table, double low, double high, size_t spline_df, const gsl_vector *knots ) { qdm_tau *t = malloc(sizeof(qdm_tau)); if (use_table == 1) { t->use_table = true; } else { t->use_table = false; } t->low = low; t->high = high; t->spline_df = spline_df; t->knots = qdm_vector_copy(knots); qdm_tau_reset_setup(t); qdm_tau_table_setup(t); return t; } void qdm_tau_free( qdm_tau *t ) { if (t == NULL) { return; } t->use_table = 0; t->low = 0; t->high = 0; t->spline_df = 0; t->knots = NULL; gsl_vector_free(t->reset); t->reset = NULL; gsl_matrix_free(t->ispline_table); t->ispline_table = NULL; gsl_matrix_free(t->mspline_table); t->mspline_table = NULL; free(t); } double qdm_tau_ispline_mmm( const qdm_tau *t, const double value, const gsl_vector *mmm ) { double result = 0; if (t->use_table) { size_t i = (size_t)fmin(floor(value * TAU_TABLE_SIZE), TAU_TABLE_SIZE - 1); gsl_vector_view ispline = gsl_matrix_row(t->ispline_table, i); gsl_blas_ddot(&ispline.vector, mmm, &result); } else { size_t m = (t->knots->size - t->spline_df) + 1; double ispline_data[m]; gsl_vector_view ispline = gsl_vector_view_array(ispline_data, m); qdm_ispline_vector(&ispline.vector, value, t->spline_df, t->knots); gsl_blas_ddot(&ispline.vector, mmm, &result); } return result; } double qdm_tau_mspline_mmm( const qdm_tau *t, const double value, const gsl_vector *mmm ) { double result = 0; if (t->use_table) { size_t i = (size_t)fmin(floor(value * TAU_TABLE_SIZE), TAU_TABLE_SIZE - 1); gsl_vector_view mspline = gsl_matrix_row(t->mspline_table, i); gsl_blas_ddot(&mspline.vector, mmm, &result); } else { size_t m = (t->knots->size - t->spline_df) + 1; double mspline_data[m]; gsl_vector_view mspline = gsl_vector_view_array(mspline_data, m); qdm_mspline_vector(&mspline.vector, value, t->spline_df, t->knots); gsl_blas_ddot(&mspline.vector, mmm, &result); } return result; } double qdm_tau_find( const qdm_tau *t, const double v, const gsl_vector *mmm ) { double tau = TAU_INITIAL_GUESS; double qi_u = 0; double qm_u = 0; size_t reset_i = 0; for (size_t i = 0; i < TAU_ITERATION_MAX; i++) { if (reset_i >= t->reset->size) { tau = TAU_INITIAL_GUESS; break; } /* Calculate position... */ qi_u = qdm_tau_ispline_mmm(t, tau, mmm); /* Calculate slope... */ qm_u = qdm_tau_mspline_mmm(t, tau, mmm); /* Check if the update is within our desired interval [0, 1]. */ double update = tau - (qi_u - v) / qm_u; if (update < 0 || update > 1) { tau = gsl_vector_get(t->reset, reset_i); reset_i++; continue; } else { tau = update; } if (fabs(qi_u - v) <= TAU_EPS) { break; } } return tau; }
{ "alphanum_fraction": 0.6499590835, "avg_line_length": 20.1983471074, "ext": "c", "hexsha": "509c910cee385e795d77e375cf5234b41310b31d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "calebcase/qdm", "max_forks_repo_path": "src/tau.c", "max_issues_count": 3, "max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "calebcase/qdm", "max_issues_repo_path": "src/tau.c", "max_line_length": 95, "max_stars_count": null, "max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "calebcase/qdm", "max_stars_repo_path": "src/tau.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1608, "size": 4888 }
#include <gsl/gsl_linalg.h> int main (void) { double a_data[] = { 0.18, 0.60, 0.57, 0.96, 0.41, 0.24, 0.99, 0.58, 0.14, 0.30, 0.97, 0.66, 0.51, 0.13, 0.19, 0.85 } ; double b_data[] = { 1.0, 2.0, 3.0, 4.0 }; gsl_matrix_view m = gsl_matrix_view_array(a_data, 4, 4); gsl_vector_view b = gsl_vector_view_array(b_data, 4); gsl_vector *x = gsl_vector_alloc (4); int s; gsl_permutation * p = gsl_permutation_alloc (4); gsl_linalg_LU_decomp (&m.matrix, p, &s); gsl_linalg_LU_solve (&m.matrix, p, &b.vector, x); gsl_vector_fprintf(stdout, x, "%g"); gsl_permutation_free (p); }
{ "alphanum_fraction": 0.5634218289, "avg_line_length": 20.5454545455, "ext": "c", "hexsha": "c49ab2ef6ae45fd7fd100ad9f7f7b01e5d9770be", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/demo.c", "max_line_length": 51, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 262, "size": 678 }
// Copyright 2021 atframework // Created by owent #pragma once #include <config/atframe_utils_build_feature.h> #include <config/compiler_features.h> #include <design_pattern/nomovable.h> #include <design_pattern/noncopyable.h> #include <time/time_utility.h> #include <gsl/select-gsl.h> #include <list> #include <vector> #if defined(LIBATFRAME_UTILS_ENABLE_UNORDERED_MAP_SET) && LIBATFRAME_UTILS_ENABLE_UNORDERED_MAP_SET # include <unordered_map> # include <unordered_set> #else # include <map> # include <set> #endif #include "atframe/atapp_conf.h" #include "atframe/etcdcli/etcd_discovery.h" namespace atapp { class app; class atapp_connection_handle; class atapp_endpoint; class atapp_connector_impl; struct atapp_endpoint_bind_helper { // This API is used by inner system and will not be exported, do not call it directly static LIBATAPP_MACRO_API_SYMBOL_HIDDEN void unbind(atapp_connection_handle &handle, atapp_endpoint &connect); // This API is used by inner system and will not be exported, do not call it directly static LIBATAPP_MACRO_API_SYMBOL_HIDDEN void bind(atapp_connection_handle &handle, atapp_endpoint &connect); }; class atapp_endpoint { public: using handle_set_t = std::unordered_set<atapp_connection_handle *>; using handle_set_iterator = handle_set_t::iterator; using handle_set_const_iterator = handle_set_t::const_iterator; using ptr_t = std::shared_ptr<atapp_endpoint>; using weak_ptr_t = std::weak_ptr<atapp_endpoint>; struct pending_message_t { util::time::time_utility::raw_time_t expired_timepoint; int32_t type; uint64_t message_sequence; std::vector<unsigned char> data; std::unique_ptr<atapp::protocol::atapp_metadata> metadata; }; UTIL_DESIGN_PATTERN_NOCOPYABLE(atapp_endpoint) UTIL_DESIGN_PATTERN_NOMOVABLE(atapp_endpoint) private: struct construct_helper_t {}; public: LIBATAPP_MACRO_API atapp_endpoint(app &owner, construct_helper_t &helper); static LIBATAPP_MACRO_API ptr_t create(app &owner); LIBATAPP_MACRO_API ~atapp_endpoint(); LIBATAPP_MACRO_API uint64_t get_id() const noexcept; LIBATAPP_MACRO_API gsl::string_view get_name() const noexcept; UTIL_FORCEINLINE bool has_connection_handle() const noexcept { return !refer_connections_.empty(); } LIBATAPP_MACRO_API const etcd_discovery_node::ptr_t &get_discovery() const noexcept; LIBATAPP_MACRO_API void update_discovery(const etcd_discovery_node::ptr_t &discovery) noexcept; LIBATAPP_MACRO_API void add_connection_handle(atapp_connection_handle &handle); LIBATAPP_MACRO_API void remove_connection_handle(atapp_connection_handle &handle); LIBATAPP_MACRO_API atapp_connection_handle *get_ready_connection_handle() const noexcept; LIBATAPP_MACRO_API int32_t push_forward_message(int32_t type, uint64_t &msg_sequence, const void *data, size_t data_size, const atapp::protocol::atapp_metadata *metadata); LIBATAPP_MACRO_API int32_t retry_pending_messages(const util::time::time_utility::raw_time_t &tick_time, int32_t max_count = 0); LIBATAPP_MACRO_API void add_waker(util::time::time_utility::raw_time_t wakeup_time); UTIL_FORCEINLINE app *get_owner() const noexcept { return owner_; } LIBATAPP_MACRO_API size_t get_pending_message_count() const noexcept; LIBATAPP_MACRO_API size_t get_pending_message_size() const noexcept; private: void reset(); void cancel_pending_messages(); void trigger_on_receive_forward_response(atapp_connector_impl *connector, atapp_connection_handle *handle, int32_t type, uint64_t sequence, int32_t error_code, const void *data, size_t data_size, const atapp::protocol::atapp_metadata *metadata); private: bool closing_; app *owner_; util::time::time_utility::raw_time_t nearest_waker_; weak_ptr_t watcher_; handle_set_t refer_connections_; etcd_discovery_node::ptr_t discovery_; std::list<pending_message_t> pending_message_; size_t pending_message_size_; #if defined(LIBATAPP_ENABLE_CUSTOM_COUNT_FOR_STD_LIST) && LIBATAPP_ENABLE_CUSTOM_COUNT_FOR_STD_LIST size_t pending_message_count_; #endif friend struct atapp_endpoint_bind_helper; }; } // namespace atapp
{ "alphanum_fraction": 0.7738868275, "avg_line_length": 36.5423728814, "ext": "h", "hexsha": "6147e48b35453820eb9f63b599c5c9065a5cd0ce", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z", "max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z", "max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "atframework/libatapp", "max_forks_repo_path": "include/atframe/connectors/atapp_endpoint.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "atframework/libatapp", "max_issues_repo_path": "include/atframe/connectors/atapp_endpoint.h", "max_line_length": 117, "max_stars_count": 16, "max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "atframework/libatapp", "max_stars_repo_path": "include/atframe/connectors/atapp_endpoint.h", "max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z", "num_tokens": 1004, "size": 4312 }
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root // for more information. #ifndef NOVELRT_EXPERIMENTAL_GRAPHICS_H #define NOVELRT_EXPERIMENTAL_GRAPHICS_H // Graphics dependencies #include "../../Graphics/RGBAColour.h" #include "../../Maths/Maths.h" #include "../../Utilities/Event.h" #include "../../Utilities/Misc.h" #include "../EngineConfig.h" #include "../Threading/Threading.h" #include <chrono> #include <cstdint> #include <filesystem> #include <gsl/span> #include <list> #include <memory> #include <mutex> #include <optional> #include <string> #include <typeindex> #include <utility> #include <vector> /** * @brief The experimental Graphics plugin API. Comes with built-in support for the ECS. */ namespace NovelRT::Experimental::Graphics { enum class ShaderProgramKind : uint32_t; class GraphicsDeviceObject; enum class GraphicsResourceAccess : uint32_t; enum class GraphicsSurfaceKind : uint32_t; class IGraphicsSurface; class GraphicsAdapter; class GraphicsDevice; class GraphicsResource; class GraphicsBuffer; class GraphicsTexture; class ShaderProgram; class GraphicsPipeline; class GraphicsPipelineSignature; class GraphicsPipelineInput; class GraphicsPipelineResource; class GraphicsPipelineInputElement; enum class GraphicsPipelineInputElementKind : uint32_t; enum class GraphicsPipelineResourceKind : uint32_t; enum class ShaderProgramVisibility : uint32_t; class GraphicsContext; class GraphicsFence; class GraphicsPrimitive; class GraphicsProvider; class GraphicsMemoryAllocator; struct GraphicsMemoryAllocatorSettings; enum class GraphicsTextureKind : uint32_t; class IGraphicsAdapterSelector; enum class GraphicsMemoryRegionAllocationFlags : uint32_t; class GraphicsMemoryBlockCollection; class GraphicsMemoryBlock; enum class GraphicsMemoryRegionAllocationFlags : uint32_t; class GraphicsMemoryBudget; enum class GraphicsBufferKind : uint32_t; enum class TexelFormat : uint32_t; class GraphicsSurfaceContext; } // Graphics types // clang-format off #include "ShaderProgramKind.h" #include "EcsDefaultRenderingComponentTypes.h" #include "EcsDefaultRenderingSystem.h" #include "GraphicsAdapter.h" #include "GraphicsDeviceObject.h" #include "GraphicsContext.h" #include "GraphicsFence.h" #include "GraphicsMemoryAllocatorSettings.h" #include "GraphicsMemoryRegion.h" #include "IGraphicsMemoryRegionCollection.h" #include "GraphicsMemoryRegionAllocationFlags.h" #include "TexelFormat.h" #include "GraphicsMemoryAllocator.h" #include "GraphicsMemoryBlockCollection.h" #include "GraphicsMemoryBudget.h" #include "GraphicsMemoryBlock.h" #include "GraphicsResourceAccess.h" #include "GraphicsSurfaceKind.h" #include "GraphicsTextureKind.h" #include "IGraphicsSurface.h" #include "GraphicsSurfaceContext.h" #include "GraphicsDevice.h" #include "GraphicsResource.h" #include "GraphicsBufferKind.h" #include "GraphicsBuffer.h" #include "GraphicsTexture.h" #include "IGraphicsAdapterSelector.h" #include "ShaderProgram.h" #include "GraphicsPipeline.h" #include "GraphicsPipelineSignature.h" #include "GraphicsPrimitive.h" #include "GraphicsProvider.h" #include "GraphicsPipelineInput.h" #include "GraphicsPipelineInputElement.h" #include "GraphicsPipelineInputElementKind.h" #include "GraphicsPipelineResource.h" #include "GraphicsPipelineResourceKind.h" #include "ShaderProgramVisibility.h" // clang-format on #endif // !NOVELRT_EXPERIMENTAL_GRAPHICS_H
{ "alphanum_fraction": 0.7870499581, "avg_line_length": 31.4298245614, "ext": "h", "hexsha": "1727869d4a1930926ed0fb66369e492925481c2f", "lang": "C", "max_forks_count": 56, "max_forks_repo_forks_event_max_datetime": "2022-03-03T19:52:18.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-22T15:57:00.000Z", "max_forks_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "BanalityOfSeeking/NovelRT", "max_forks_repo_path": "include/NovelRT/Experimental/Graphics/Graphics.h", "max_issues_count": 270, "max_issues_repo_head_hexsha": "bbbe54f719acdc2fcee4604ee90fb43ff975aee9", "max_issues_repo_issues_event_max_datetime": "2022-03-08T02:28:20.000Z", "max_issues_repo_issues_event_min_datetime": "2019-02-14T20:33:05.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "BanalityOfSeeking/NovelRT", "max_issues_repo_path": "include/NovelRT/Experimental/Graphics/Graphics.h", "max_line_length": 119, "max_stars_count": 167, "max_stars_repo_head_hexsha": "82000a25fd53157b26a6e6d6c71cbee0ebaa241b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Exadon/NovelRT", "max_stars_repo_path": "include/NovelRT/Experimental/Graphics/Graphics.h", "max_stars_repo_stars_event_max_datetime": "2022-03-25T17:14:24.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-12T14:12:04.000Z", "num_tokens": 748, "size": 3583 }
#include <gsl/gsl_test.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_math.h> #include "gsl_cblas.h" #include "tests.h" void test_hpmv (void) { const double flteps = 1e-4, dbleps = 1e-6; { int order = 101; int uplo = 121; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0627557f, -0.839323f, -0.0877262f, -0.169208f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1118) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1118) imag"); }; }; }; { int order = 101; int uplo = 121; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0627557f, -0.839323f, -0.0877262f, -0.169208f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1119) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1119) imag"); }; }; }; { int order = 101; int uplo = 122; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0037603f, -0.816761f, -0.0392456f, -0.121154f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1120) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1120) imag"); }; }; }; { int order = 101; int uplo = 122; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0037603f, -0.816761f, -0.0392456f, -0.121154f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1121) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1121) imag"); }; }; }; { int order = 102; int uplo = 121; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0627557f, -0.839323f, -0.0877262f, -0.169208f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1122) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1122) imag"); }; }; }; { int order = 102; int uplo = 121; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0627557f, -0.839323f, -0.0877262f, -0.169208f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1123) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1123) imag"); }; }; }; { int order = 102; int uplo = 122; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0037603f, -0.816761f, -0.0392456f, -0.121154f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1124) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1124) imag"); }; }; }; { int order = 102; int uplo = 122; float alpha[2] = {-0.3f, 0.1f}; float beta[2] = {0.0f, 1.0f}; int N = 2; float A[] = { 0.339f, -0.102f, 0.908f, 0.097f, -0.808f, 0.236f }; float X[] = { 0.993f, -0.502f, -0.653f, 0.796f }; int incX = -1; float Y[] = { -0.35f, 0.339f, -0.269f, -0.122f }; int incY = -1; float y_expected[] = { -0.0037603f, -0.816761f, -0.0392456f, -0.121154f }; cblas_chpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], flteps, "chpmv(case 1125) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], flteps, "chpmv(case 1125) imag"); }; }; }; { int order = 101; int uplo = 121; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.745218, -0.60699, -0.37301, -0.983688 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1126) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1126) imag"); }; }; }; { int order = 101; int uplo = 121; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.745218, -0.60699, -0.37301, -0.983688 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1127) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1127) imag"); }; }; }; { int order = 101; int uplo = 122; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.646956, -0.542012, -0.282168, -0.912668 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1128) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1128) imag"); }; }; }; { int order = 101; int uplo = 122; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.646956, -0.542012, -0.282168, -0.912668 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1129) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1129) imag"); }; }; }; { int order = 102; int uplo = 121; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.745218, -0.60699, -0.37301, -0.983688 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1130) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1130) imag"); }; }; }; { int order = 102; int uplo = 121; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.745218, -0.60699, -0.37301, -0.983688 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1131) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1131) imag"); }; }; }; { int order = 102; int uplo = 122; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.646956, -0.542012, -0.282168, -0.912668 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1132) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1132) imag"); }; }; }; { int order = 102; int uplo = 122; double alpha[2] = {1, 0}; double beta[2] = {0, 1}; int N = 2; double A[] = { 0.543, -0.737, 0.281, -0.053, -0.098, -0.826 }; double X[] = { 0.67, -0.857, -0.613, -0.927 }; int incX = -1; double Y[] = { -0.398, -0.934, -0.204, 0.183 }; int incY = -1; double y_expected[] = { 0.646956, -0.542012, -0.282168, -0.912668 }; cblas_zhpmv(order, uplo, N, alpha, A, X, incX, beta, Y, incY); { int i; for (i = 0; i < 2; i++) { gsl_test_rel(Y[2*i], y_expected[2*i], dbleps, "zhpmv(case 1133) real"); gsl_test_rel(Y[2*i+1], y_expected[2*i+1], dbleps, "zhpmv(case 1133) imag"); }; }; }; }
{ "alphanum_fraction": 0.5113066432, "avg_line_length": 29.9078947368, "ext": "c", "hexsha": "9dd11c92cafd936b3986c9ce8a7b2d72644388ed", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z", "max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ICML14MoMCompare/spectral-learn", "max_forks_repo_path": "code/em/treba/gsl-1.0/cblas/test_hpmv.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "ICML14MoMCompare/spectral-learn", "max_issues_repo_path": "code/em/treba/gsl-1.0/cblas/test_hpmv.c", "max_line_length": 82, "max_stars_count": 14, "max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ICML14MoMCompare/spectral-learn", "max_stars_repo_path": "code/em/treba/gsl-1.0/cblas/test_hpmv.c", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "num_tokens": 5235, "size": 11365 }
/* WidiPadi is a motif discovery tool for DNA sequences */ /* Copyright (C) 2006 Bioinformatics Centre */ /* Author: Eivind Valen and Ole Winther */ /* This program is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU General Public License */ /* as published by the Free Software Foundation; either version 2 */ /* of the License, or (at your option) any later version. */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> #include <stdio.h> #include <getopt.h> #include <gsl/gsl_sf_gamma.h> #include "error.h" #include "sesa.h" #define USAGE "Usage: widipadi [OPTIONS] SEQUENCES" enum bool {false, true}; /* FUNCTION PROTOTYPES */ PSSM hits_to_count_matrix(SESA sesa, struct HitTable *hits, const double threshold, int length, int alphabetSize); int compare_hit_scores(const void *hit1, const void *hit2); int parse_options(int argc, char **argv); void print_help(); /* Acceptance */ int accept_all(SESA sesa, struct HitTable *hits); int acceptIf_over_300_hits(SESA sesa, struct HitTable *hits); int acceptIf_required_presence(SESA sesa, struct HitTable *hits); /* DEFAULTS */ unsigned int length = 8; unsigned int alphabetSize = 4; unsigned int mismatches = 1; int (*acceptanceFunc)(SESA, struct HitTable *) = acceptIf_required_presence; double required_presence = 0.7; unsigned int exhaustive = false; /** * Prints a help message to stdout. */ void print_help() { printf(USAGE); printf("\nOptions:\n"); /* printf(" -a Size of alphabet\n"); */ printf(" -h Prints this help and exits\n"); printf(" -l LENGTH Length of WM\n"); printf(" -m MISMATCHES Number of mismatches\n"); printf(" -r RATIO Sets the ratio of sequences where the PSSM must match\n"); printf(" -x Do exhaustive search\n"); printf("\n"); } /** * Parses command line options */ int parse_options(int argc, char **argv) { int count = 1; int c; while ((c = getopt(argc, argv, "hl:m:r:x")) != -1) { count++; switch (c) { case 'h': print_help(); exit(EXIT_SUCCESS); case 'l': length = (unsigned int) strtol(optarg, (char **) NULL, 0); count++; break; case 'm': mismatches = (unsigned int) strtol(optarg, (char **) NULL, 0); count++; break; case 'r': acceptanceFunc = acceptIf_required_presence; required_presence = strtod(optarg, (char **) NULL); count++; break; case 'x': exhaustive = true; break; default: fprintf(stderr, USAGE); exit(EXIT_FAILURE); } } return count; } /* * Converts all hits above scoring threshold to a count matrix * * Only 0th order */ PSSM hits_to_count_matrix(SESA sesa, struct HitTable *hits, const double threshold, int length, int alphabetSize) { PSSM pssm = initMatrix(0, length, alphabetSize); ESA esa = sesa->esa; struct HitEntry *hit; int i, j; i = pssm->offsets[pssm->length]; while (i--) pssm->counts[i] = 0; for (i = 0; i < hits->nScores; i++) { hit = &hits->pScores[i]; if (hit->score < threshold) break; for (j = 0; j < length; j++) { int ltr = esa->pStr[hit->position + j]; /* fprintf(stderr, "%c", ind2chr(ltr)); */ pssm->counts[ pssm->offsets[j] + ltr ]++; } /* fprintf(stderr, " (%f)\n", hit->score); */ } return pssm; } /** * Comparing function for sort. Sorts on scores from low to high. */ int compare_hit_scores(const void *hit1, const void *hit2) { return ((struct HitEntry *)hit2)->score - ((struct HitEntry *)hit1)->score; } /** * Accepts all PSSMs (for testing) */ int accept_all(SESA sesa, struct HitTable *hits) { return true; } /** * Accepts PSSMs with more than 300 hits (for testing) */ int acceptIf_over_300_hits(SESA sesa, struct HitTable *hits) { return (hits->nScores > 300 ? true : false); } /** * Accepts PSSMs with hits present in at least "required_presence" of * the sequences */ int acceptIf_required_presence(SESA sesa, struct HitTable *hits) { int present[sesa->nSeq]; int i, j; i = sesa->nSeq; while(i--) present[i] = 0; i = hits->nScores; while (i--) present[ sesa->seq[ hits->pScores[i].position ] ]++; j = 0; i = sesa->nSeq; while (i--) if (present[i]) j++; return ( ((double) j / (double) sesa->nSeq) > required_presence ? true : false); } /* * Log likelihood scoring */ double log_likelihood(ESA esa, PSSM pssm, int *count_bg_all, double *pcount, double *pcount_bg) { int pcount_tot = 0, pcount_bg_tot = 0, count_tot = 0, count_bg_tot = 0; int alphlen = pssm->alphabetSize; int count_bg[alphlen]; int ccount, ltr, pos, ord, i; double ll = 0.0; i = alphlen; while (i--) count_bg[i] = count_bg_all[i]; pos = pssm->length; while (pos--) { ltr = alphlen; while(ltr--) { ccount = pssm->counts[pos * alphlen + ltr]; count_bg[ltr] -= ccount ; ll += gsl_sf_lngamma( ccount + pcount[ltr] ); } } ltr = alphlen; while (ltr--) { pcount_tot += pcount[ltr]; pcount_bg_tot += pcount_bg[ltr]; count_tot += pssm->counts[ltr]; count_bg_tot += count_bg[ltr]; ll += gsl_sf_lngamma( count_bg[ltr] + pcount_bg[ltr] ); } ll -= alphlen * gsl_sf_lngamma( count_tot + pcount_tot ) + gsl_sf_lngamma(count_bg_tot + pcount_bg_tot ); return ll; } /* * Log likelihood scoring */ double higher_log_likelihood(ESA esa, PSSM pssm, double *pcount, double *pcount_bg) { int pos, lcpi, skip, curSuf, i, j, p; int numSufs = getSize(esa); int curEsaIndex = 0; int order = 2; int wcount[order+1]; i = order+1; while (i--) wcount[i] = 0; /* Iterate all suffixes */ while(curEsaIndex < numSufs){ lcpi = getLcp(esa, curEsaIndex); curSuf = getSuf(esa, curEsaIndex); skip = getSkip(esa, curEsaIndex); /* We can skip if the lcp is longer than the order */ if (lcpi > order) { /* FIX: HACK */ if (skip == 0) { curEsaIndex++; continue; } /* Count all the skipped words */ i = order+1; while (i--) wcount[i] += skip - curEsaIndex; curEsaIndex = skip; continue; } else { pos = pssm->length; while (pos--) { } /* Print the hits */ p = 1; for (j = 0; j <= order; j++) if (ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+j]) == '-') p = 0; if (p) { for (i = 0; i <= order; i++) fprintf(stderr, "%c", ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+i])); fprintf(stderr, ": %5i\n", wcount[2]); } wcount[order] = 1; /* For higher order models the first columns have fewer letters */ i = order; while (i--) { if (i >= lcpi) { p = 1; for (j = 0; j <= i; j++) if (ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+j]) == '-') p = 0; if (p) { for (j = 0; j <= i; j++) fprintf(stderr, "%c", ind2chr(esa->pStr[getSuf(esa, curEsaIndex-1)+j])); for (j = i; j < order; j++) fprintf(stderr, " "); fprintf(stderr, ": %5i\n", wcount[i]); } wcount[i] = 1; } } curEsaIndex++; } } exit(0); } void print_esa (ESA esa) { int numSufs = getSize(esa); int i,j; for (i = 0; i < numSufs; i++) { fprintf(stderr, "%4i: SUF(%3i) LCP(%3i) SKIP(%4i) ", i, getSuf(esa, i), getLcp(esa, i), getSkip(esa, i)); for (j = 0; j < 8; j++) { fprintf(stderr, "%c", ind2chr(esa->pStr[getSuf(esa, i)+j])); } fprintf(stderr, "\n"); } } int main(int argc, char **argv) { PSSMScoreTable results; struct HitTable *hits = NULL; PSSM pssm, count; SESA sesa; unsigned int arg_count, j; int i; arg_count = parse_options(argc, argv); printf("Reading file: %s (%i)\n", argv[arg_count], argc - arg_count); if (!argv[arg_count]) { fprintf(stderr, "Need an input file\n"); exit(EXIT_FAILURE); } sesa = build_SESA(argc - arg_count, &argv[arg_count], "ACGT", "N", 0); if (!sesa) { fprintf(stderr, "%s\n", getError()); exit(EXIT_FAILURE); } printf("Searching %s for motifs of length %i with %i mismatch%s\n", (exhaustive ? "exhaustively" : "exclusively"), length, mismatches, (mismatches > 1 ? "es" : "")); if (exhaustive) { /* Exhaustive search searches for all words og length n. */ results = SESA_exhaustive_search(sesa, length, mismatches, alphabetSize, acceptanceFunc); } else { /* Exclusive search only searches for PSSMs representing words present in the sequence. */ results = SESA_exclusive_search(sesa, length, mismatches, alphabetSize, acceptanceFunc); } /** * Both the above methods return a list of integers that uniquely * identifies pssms. We do not return the hits of the PSSMs even * though we have searched with them since this might be very(!) * memory demanding, depending on criteria used for acceptance. * * If we know the criteria is strict we might considering altering * this to avoid re-searching and thus speed up the process. */ pssm = initMatrix(0, length, alphabetSize); for (i = 0; i < results->nPssm; i++) { /* Sets the pssm to the values corresponding to the ID*/ set_mismatch_scores(pssm, results->pssmNr[i]); calcAndSetThresholds(pssm, -((double)mismatches)-0.5); /* Search with the PSSM again */ init_hittable(); /* Creates a hittable */ hits = SESA_search(sesa, pssm); /* Searches again */ /* Sort the hits */ qsort((void*)hits->pScores, hits->nScores, sizeof(struct HitEntry), compare_hit_scores); printf("\n\n"); print_pssm(pssm); for (j = 0; j <= mismatches; j++) { printf("Count matrix for %i mismatches\n", j); count = hits_to_count_matrix(sesa, hits, -((double)j)-0.5, pssm->length, pssm->alphabetSize); double ost1[] = {1.0, 1.0, 1.0, 1.0}; double ost2[] = {1.0, 1.0, 1.0, 1.0}; /* double foo = log_likelihood(count, sesa->bg, ost1, ost2); */ double foo = higher_log_likelihood(sesa->esa, count, ost1, ost2); /* fprintf(stderr, "LL: %g\n", foo); */ /* print_counts(count); */ printf("\n\n"); } release_hits(hits); /* Frees the allocated hittable*/ } exit(EXIT_SUCCESS); }
{ "alphanum_fraction": 0.603535586, "avg_line_length": 26.9503722084, "ext": "c", "hexsha": "a0ca57bdbffa564c2fc93f260eff9a5ecec34ff2", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kipkurui/gimmemotifs", "max_forks_repo_path": "src/MoAn/widipadi.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kipkurui/gimmemotifs", "max_issues_repo_path": "src/MoAn/widipadi.c", "max_line_length": 167, "max_stars_count": 1, "max_stars_repo_head_hexsha": "51bd0c6700877f79179f08e5bab7de70fc2eab94", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kipkurui/gimmemotifs", "max_stars_repo_path": "src/MoAn/widipadi.c", "max_stars_repo_stars_event_max_datetime": "2019-07-14T08:28:25.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-14T08:28:25.000Z", "num_tokens": 3241, "size": 10861 }
/* vector/gsl_vector_double.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_VECTOR_DOUBLE_H__ #define __GSL_VECTOR_DOUBLE_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_block_double.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size; size_t stride; double *data; gsl_block *block; int owner; } gsl_vector; typedef struct { gsl_vector vector; } _gsl_vector_view; typedef _gsl_vector_view gsl_vector_view; typedef struct { gsl_vector vector; } _gsl_vector_const_view; typedef const _gsl_vector_const_view gsl_vector_const_view; /* Allocation */ GSL_FUN gsl_vector *gsl_vector_alloc (const size_t n); GSL_FUN gsl_vector *gsl_vector_calloc (const size_t n); GSL_FUN gsl_vector *gsl_vector_alloc_from_block (gsl_block * b, const size_t offset, const size_t n, const size_t stride); GSL_FUN gsl_vector *gsl_vector_alloc_from_vector (gsl_vector * v, const size_t offset, const size_t n, const size_t stride); GSL_FUN void gsl_vector_free (gsl_vector * v); /* Views */ GSL_FUN _gsl_vector_view gsl_vector_view_array (double *v, size_t n); GSL_FUN _gsl_vector_view gsl_vector_view_array_with_stride (double *base, size_t stride, size_t n); GSL_FUN _gsl_vector_const_view gsl_vector_const_view_array (const double *v, size_t n); GSL_FUN _gsl_vector_const_view gsl_vector_const_view_array_with_stride (const double *base, size_t stride, size_t n); GSL_FUN _gsl_vector_view gsl_vector_subvector (gsl_vector *v, size_t i, size_t n); GSL_FUN _gsl_vector_view gsl_vector_subvector_with_stride (gsl_vector *v, size_t i, size_t stride, size_t n); GSL_FUN _gsl_vector_const_view gsl_vector_const_subvector (const gsl_vector *v, size_t i, size_t n); GSL_FUN _gsl_vector_const_view gsl_vector_const_subvector_with_stride (const gsl_vector *v, size_t i, size_t stride, size_t n); /* Operations */ GSL_FUN void gsl_vector_set_zero (gsl_vector * v); GSL_FUN void gsl_vector_set_all (gsl_vector * v, double x); GSL_FUN int gsl_vector_set_basis (gsl_vector * v, size_t i); GSL_FUN int gsl_vector_fread (FILE * stream, gsl_vector * v); GSL_FUN int gsl_vector_fwrite (FILE * stream, const gsl_vector * v); GSL_FUN int gsl_vector_fscanf (FILE * stream, gsl_vector * v); GSL_FUN int gsl_vector_fprintf (FILE * stream, const gsl_vector * v, const char *format); GSL_FUN int gsl_vector_memcpy (gsl_vector * dest, const gsl_vector * src); GSL_FUN int gsl_vector_reverse (gsl_vector * v); GSL_FUN int gsl_vector_swap (gsl_vector * v, gsl_vector * w); GSL_FUN int gsl_vector_swap_elements (gsl_vector * v, const size_t i, const size_t j); GSL_FUN double gsl_vector_max (const gsl_vector * v); GSL_FUN double gsl_vector_min (const gsl_vector * v); GSL_FUN void gsl_vector_minmax (const gsl_vector * v, double * min_out, double * max_out); GSL_FUN size_t gsl_vector_max_index (const gsl_vector * v); GSL_FUN size_t gsl_vector_min_index (const gsl_vector * v); GSL_FUN void gsl_vector_minmax_index (const gsl_vector * v, size_t * imin, size_t * imax); GSL_FUN int gsl_vector_add (gsl_vector * a, const gsl_vector * b); GSL_FUN int gsl_vector_sub (gsl_vector * a, const gsl_vector * b); GSL_FUN int gsl_vector_mul (gsl_vector * a, const gsl_vector * b); GSL_FUN int gsl_vector_div (gsl_vector * a, const gsl_vector * b); GSL_FUN int gsl_vector_scale (gsl_vector * a, const double x); GSL_FUN int gsl_vector_add_constant (gsl_vector * a, const double x); GSL_FUN int gsl_vector_axpby (const double alpha, const gsl_vector * x, const double beta, gsl_vector * y); GSL_FUN double gsl_vector_sum (const gsl_vector * a); GSL_FUN int gsl_vector_equal (const gsl_vector * u, const gsl_vector * v); GSL_FUN int gsl_vector_isnull (const gsl_vector * v); GSL_FUN int gsl_vector_ispos (const gsl_vector * v); GSL_FUN int gsl_vector_isneg (const gsl_vector * v); GSL_FUN int gsl_vector_isnonneg (const gsl_vector * v); GSL_FUN INLINE_DECL double gsl_vector_get (const gsl_vector * v, const size_t i); GSL_FUN INLINE_DECL void gsl_vector_set (gsl_vector * v, const size_t i, double x); GSL_FUN INLINE_DECL double * gsl_vector_ptr (gsl_vector * v, const size_t i); GSL_FUN INLINE_DECL const double * gsl_vector_const_ptr (const gsl_vector * v, const size_t i); #ifdef HAVE_INLINE INLINE_FUN double gsl_vector_get (const gsl_vector * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0); } #endif return v->data[i * v->stride]; } INLINE_FUN void gsl_vector_set (gsl_vector * v, const size_t i, double x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_VOID ("index out of range", GSL_EINVAL); } #endif v->data[i * v->stride] = x; } INLINE_FUN double * gsl_vector_ptr (gsl_vector * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (double *) (v->data + i * v->stride); } INLINE_FUN const double * gsl_vector_const_ptr (const gsl_vector * v, const size_t i) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(i >= v->size)) { GSL_ERROR_NULL ("index out of range", GSL_EINVAL); } #endif return (const double *) (v->data + i * v->stride); } #endif /* HAVE_INLINE */ __END_DECLS #endif /* __GSL_VECTOR_DOUBLE_H__ */
{ "alphanum_fraction": 0.6403441192, "avg_line_length": 32.049382716, "ext": "h", "hexsha": "82b3aad35a6bf4a85532e98e6d6bbc2a0a38c5bc", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_double.h", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_double.h", "max_line_length": 108, "max_stars_count": 2, "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_double.h", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "num_tokens": 1878, "size": 7788 }
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" void cblas_dger (const enum CBLAS_ORDER order, const int M, const int N, const double alpha, const double *X, const int incX, const double *Y, const int incY, double *A, const int lda) { #define BASE double #include "source_ger.h" #undef BASE }
{ "alphanum_fraction": 0.6842105263, "avg_line_length": 24.4285714286, "ext": "c", "hexsha": "d9596ae52bd4f550f344f64d57e25d414c94a255", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/cblas/dger.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/cblas/dger.c", "max_line_length": 70, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/cblas/dger.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 98, "size": 342 }
/* * Subroutines that deal with the aXe configuration file. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_vector.h> #include "aper_conf.h" #include "disp_conf.h" #include "aXe_grism.h" #include "spc_cfg.h" #include "disp_conf.h" #include "aXe_utils.h" #define MAX(x,y) (((x)>(y))?(x):(y)) /** * Function: get_aperture_descriptor * Read a configuration file and populate an aperture_conf structure * containing a description of the optical set up. * This function populates the geometrical description of all the beams in * all the apertures listed in the configuration file. * * Parameters: * @param actinfo - the header structure with the column names * @param filename - the complete filename to the axe configuration file * * Returns: * @return config - the configuration structure created */ aperture_conf * get_aperture_descriptor (char *filename) { char beam[MAXCHAR] = "\0"; aperture_conf *config; int i, ix; gsl_vector *v; struct CfgStrings AperConfig[] = { {"INSTRUMENT", NULL}, {"CAMERA", NULL}, {"SCIENCE_EXT", NULL}, {"ERRORS_EXT", NULL}, {"DQ_EXT",NULL}, {"DQMASK",NULL}, {"EXPTIME",NULL}, {"GAIN",NULL}, {"OPTKEY1",NULL}, {"OPTVAL1",NULL}, {"FFNAME",NULL}, {"REFX",NULL}, {"REFY",NULL}, /* aXe1.4:*/ {"DRZRESOLA",NULL}, {"DRZSCALE",NULL}, {"DRZLAMB0",NULL}, {"DRZXINI",NULL}, {"DRZPFRAC",NULL}, {"DRZKERNEL",NULL}, /* aXe1.5: */ {"PSFCOEFFS",NULL}, {"PSFRANGE",NULL}, {"RDNOISE",NULL}, /* NICMOS HLA */ {"IPIXFUNCTION",NULL}, {"POBJSIZE",NULL}, {"SMFACTOR",NULL}, {NULL, NULL}, {NULL, NULL} /* array terminator. REQUIRED !!! */ }; struct CfgStrings BeamConfig[] = { {NULL, NULL}, {NULL, NULL} }; AperConfig[25].name = beam; BeamConfig[0].name = beam; config = malloc (sizeof (aperture_conf)); if (config == NULL) { aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Could not allocate memory for aperture configuration"); } CfgRead (filename, AperConfig); /* Initialize optional keywords to default values*/ sprintf(config->instrument,"None"); sprintf(config->camera,"None"); sprintf(config->science_ext,"None"); sprintf(config->errors_ext,"None"); sprintf(config->dq_ext,"None"); sprintf(config->exptimekey,"None"); sprintf(config->gainkey,"None"); config->dqmask=0; sprintf(config->optkey1,"None"); sprintf(config->optval1,"None"); sprintf(config->FFname,"None"); sprintf(config->IPIXfunc,"None"); sprintf(config->drz_kernel,"square"); config->refx = 0; config->refy = 0; config->drz_resol = 0.0; config->drz_scale = 0.0; config->drz_lamb0 = 0.0; config->drz_xstart = 15.0; config->drz_pfrac = 1.0; config->psfcoeffs = NULL; config->psfrange = NULL; config->rdnoise = 0.0; config->pobjsize = -1.0; config->smfactor = -1.0; for (ix = 0; ix < 26; ix++) { /* Name of the instrument */ if (!strcmp (AperConfig[ix].name, "INSTRUMENT")) { if (AperConfig[ix].data == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "INSTRUMENT tag was not read from %s\n", filename); sprintf (config->instrument, "%s", AperConfig[ix].data); } /* Name of the camera */ if (!strcmp (AperConfig[ix].name, "CAMERA")) { if (AperConfig[ix].data == NULL) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "camera tag was not read from %s\n", filename); sprintf (config->camera, "%s", AperConfig[ix].data); } /* Name of the Science data extension */ if (!strcmp (AperConfig[ix].name, "SCIENCE_EXT")) { if (AperConfig[ix].data != NULL) sprintf (config->science_ext, "%s", AperConfig[ix].data); } /* Name of the optional Error FITS extension */ if (!strcmp (AperConfig[ix].name, "ERRORS_EXT")) { if (AperConfig[ix].data != NULL) { sprintf (config->errors_ext, "%s", AperConfig[ix].data); } } /* Name of the optional Data Quality FITS extension */ if (!strcmp (AperConfig[ix].name, "DQ_EXT")) { if (AperConfig[ix].data != NULL) { sprintf (config->dq_ext, "%s", AperConfig[ix].data); } } /* Name of the optional EXPTIME FITS keyword */ if (!strcmp (AperConfig[ix].name, "EXPTIME")) { if (AperConfig[ix].data != NULL) { sprintf (config->exptimekey, "%s", AperConfig[ix].data); } } /* Red in the readout noise */ if (!strcmp (AperConfig[ix].name, "RDNOISE")) { if (AperConfig[ix].data != NULL) { config->rdnoise = atof(AperConfig[ix].data); } } /* Name of the optional GAIN FITS keyword */ if (!strcmp (AperConfig[ix].name, "GAIN")) { if (AperConfig[ix].data != NULL) { sprintf (config->gainkey, "%s", AperConfig[ix].data); } } /* Gett the Data Quality Mask */ if (!strcmp (AperConfig[ix].name, "DQMASK")) { if (AperConfig[ix].data != NULL) { config->dqmask = atoi(AperConfig[ix].data); } } /* Optional OPTional 1st FITS keyword selection */ if (!strcmp (AperConfig[ix].name, "OPTKEY1")) { if (AperConfig[ix].data != NULL) { sprintf (config->optkey1, "%s", AperConfig[ix].data); } } /* Optional OPTional 1st FITS keyword value */ if (!strcmp (AperConfig[ix].name, "OPTVAL1")) { if (AperConfig[ix].data != NULL) { sprintf (config->optval1, "%s", AperConfig[ix].data); } } /* Optional FFname keyword value */ if (!strcmp (AperConfig[ix].name, "FFNAME")) { if (AperConfig[ix].data != NULL) { sprintf (config->FFname, "%s", AperConfig[ix].data); } } /* Optional intra pixel correction keyword value */ if (!strcmp (AperConfig[ix].name, "IPIXFUNCTION")) { if (AperConfig[ix].data != NULL) { sprintf (config->IPIXfunc, "%s", AperConfig[ix].data); } } /* Optional REFX keyword value */ if (!strcmp (AperConfig[ix].name, "REFX")) { if (AperConfig[ix].data != NULL) { config->refx = atoi(AperConfig[ix].data); } } /* Optional REFY keyword value */ if (!strcmp (AperConfig[ix].name, "REFY")) { if (AperConfig[ix].data != NULL) { config->refy = atoi(AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "DRZRESOLA")) { if (AperConfig[ix].data != NULL) { config->drz_resol = atof(AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "DRZSCALE")) { if (AperConfig[ix].data != NULL) { config->drz_scale = atof(AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "DRZLAMB0")) { if (AperConfig[ix].data != NULL) { config->drz_lamb0 = atof(AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "DRZXINI")) { if (AperConfig[ix].data != NULL) { config->drz_xstart = atof(AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "DRZPFRAC")) { if (AperConfig[ix].data != NULL) { config->drz_pfrac = atof(AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "DRZKERNEL")) { if (AperConfig[ix].data != NULL) { sprintf (config->drz_kernel, "%s", AperConfig[ix].data); } } if (!strcmp (AperConfig[ix].name, "PSFCOEFFS")) { if (AperConfig[ix].data != NULL) { // sprintf (config->drz_kernel, "%s", AperConfig[ix].data); v = string_to_gsl_array (AperConfig[ix].data); config->psfcoeffs = v; } } if (!strcmp (AperConfig[ix].name, "PSFRANGE")) { if (AperConfig[ix].data != NULL) { v = string_to_gsl_array (AperConfig[ix].data); if (v->size != 2) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "configuration file: two items for PSFRANGE, lambda_min and lambda_max must be given, not %i\n", v->size); config->psfrange = v; } } // read in the size of point-like objects if (!strcmp (AperConfig[ix].name, "POBJSIZE")) { if (AperConfig[ix].data != NULL) { config->pobjsize = atof(AperConfig[ix].data); } } // read in the adjustment for smoothed flux conversion if (!strcmp (AperConfig[ix].name, "SMFACTOR")) { if (AperConfig[ix].data != NULL) { config->smfactor = atof(AperConfig[ix].data); } } } // release memory i=0; while(AperConfig[i].name!=NULL) free(AperConfig[i++].data); /* Looking for up to MAX_BEAMS beams */ config->nbeams = 0; for (i = 0; i < MAX_BEAMS; i++) { sprintf (beam, "BEAM%c", BEAM (i)); CfgRead (filename, BeamConfig); if (BeamConfig[0].data != NULL) { v = string_to_gsl_array (BeamConfig[0].data); if (v->size != 2) { aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "tag %s does not have the proper format in file %s.\n" "Should be of the form %s [integer] [integer]\n", BeamConfig[0].data, filename,beam); // beam, filename,beam); } (config->beam[config->nbeams]).offset.dx0 = (int) gsl_vector_get (v, 0); (config->beam[config->nbeams]).offset.dx1 = (int) gsl_vector_get (v, 1); // release the memory gsl_vector_free(v); (config->beam[config->nbeams]).ID = i; // release memory ix=0; while(BeamConfig[ix].name!=NULL) free(BeamConfig[ix++].data); BeamConfig[0].data = NULL; (config->beam[config->nbeams]).mmag_extract = get_beam_mmag_extract (filename, i); (config->beam[config->nbeams]).mmag_mark = get_beam_mmag_mark (filename, i); sprintf (beam, "PSF_OFFSET_%c", BEAM (i)); CfgRead (filename, BeamConfig); if (BeamConfig[0].data != NULL) { (config->beam[config->nbeams]).psf_offset = atof(BeamConfig[0].data); } else { (config->beam[config->nbeams]).psf_offset = 0.0; } // release memory ix=0; while(BeamConfig[ix].name!=NULL) free(BeamConfig[ix++].data); BeamConfig[0].data = NULL; config->nbeams = config->nbeams + 1; } } if (config->nbeams == 0) { aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "No beam was found in %s. At least one beam must be found.\n", filename); } return config; } /** * Function: aperture_conf_fprintf * Function to output the content of an aperture_conf structure. * * Parameters: * @param file - a pointer to an output stream or file * @param conf - a pointer to an existing aperture_conf structure */ void aperture_conf_fprintf (FILE * file, aperture_conf * conf) { int i = 0, id; fprintf (file, "Aperture_conf: INSTRUMENT: %s\n", conf->instrument); fprintf (file, "Aperture_conf: NBEAMS: %d\n", conf->nbeams); for (i = 0; i < conf->nbeams; i++) { id = conf->beam[i].ID; fprintf (file, "Aperture_conf: BEAM%c: %d %d\n", BEAM (id), conf->beam[i].offset.dx0, conf->beam[i].offset.dx1); } fprintf (file, "FITS SCI extension name: %s, number: %d\n", conf->science_ext, conf->science_numext); fprintf (file, "FITS ERR extension name: %s, number: %d\n", conf->errors_ext, conf->errors_numext); fprintf (file, "FITS DQ extension name: %s, number: %d\n", conf->dq_ext, conf->dq_numext); fprintf (file, "DQ mask: %d\n",conf->dqmask); fprintf (file, "FF filename: %s\n",conf->FFname); fprintf (file, "Refx: %d\n",conf->refx); fprintf (file, "Refy: %d\n",conf->refy); fprintf (file, "DRZRESO: %10.3f\n",conf->drz_resol); fprintf (file, "DRZSCALE: %10.3f\n",conf->drz_scale); fprintf (file, "DRZLAMB0: %10.3f\n",conf->drz_lamb0); fprintf (file, "DRZXINI: %10.3f\n",conf->drz_xstart); fprintf (file, "DRZPFRAC: %10.3f\n",conf->drz_pfrac); fprintf (file, "DRZKERNEL: %s\n",conf->drz_kernel); } /** * Function: get_extension_numbers * This function assigns HDU numbers to an aperture_conf * structues after looking for the location of named * extension in a given FITS file. Optional values not * found are set to -1. * * Parameters: * @param filename - a pointer to a string containing the name * of an existing FITS file * @param conf - a pointer to a populated aperture_conf structure * @param keyword - a pointer to a string containing the name of * an optional keyword to read * @param keyval - a pointer to a string containing the value of * the optional keyword to look for */ void get_extension_numbers(char filename[], aperture_conf * conf, char keyword[],char keyval[]) { int extver = -1; conf->science_numext = get_hdunum_from_hduname(filename, conf->science_ext,keyword ,keyval,extver); if (conf->science_numext > -1) extver = (int)get_float_from_keyword(filename, conf->science_numext, "EXTVER"); if (strcmp(conf->errors_ext,"None")) { conf->errors_numext = get_hdunum_from_hduname(filename, conf->errors_ext,keyword, keyval,extver); } else { conf->errors_numext = -1; } if (strcmp(conf->dq_ext,"None")) { conf->dq_numext = get_hdunum_from_hduname(filename,conf->dq_ext, keyword,keyval,extver); } else { conf->dq_numext = -1; } } /** * Function: free_aperture_conf * The function releases all memory allocated * in a configuration structure. * * Parameters: * @param conf - the configuration structure */ void free_aperture_conf(aperture_conf * conf) { if (conf->psfcoeffs) gsl_vector_free(conf->psfcoeffs); if (conf->psfrange) gsl_vector_free(conf->psfrange); free(conf); conf = NULL; } /** * Function: get_psf_offset * The function extracts and returns the psf-offset * stored in a given configuration structure and * a given beam * * Parameters: * @param conf - the configuration structure * @param beam - the beam * * Returns: * @return psf_offset - the psf-offset for the beam */ double get_psf_offset(aperture_conf * conf, const beam actbeam) { // initialize the offset double psf_offset=0.0; int i=0; // go over all beams in the configuration structure for (i = 0; i < conf->nbeams; i++) { // check whether the current beam is the // right one if (conf->beam[i].ID == actbeam.ID) // return the offset return conf->beam[i].psf_offset; } // return the default offset return psf_offset; } /** * Function: get_psf_offset * The function extracts and returns the psf-offset * stored in a given configuration structure and * a given beam * * Parameters: * @param conf - the configuration structure * @param beam - the beam * * Returns: * @return psf_offset - the psf-offset for the beam */ double get_max_offset(aperture_conf * conf) { // initialize the offset double max_offset=0.0; int i=0; // go over all beams in the configuration structure for (i = 0; i < conf->nbeams; i++) { // check whether the current beam is the // right one max_offset = MAX(conf->beam[i].psf_offset, max_offset); } // return the default offset return max_offset; } /** * Function: extend_config_beams * The function extends the size of the beams in a * configuration structure. * * Parameters: * @param conf - the configuration structure */ void extend_config_beams(aperture_conf *conf) { int index; // go over all beams in the configuration structure for (index=0; index < conf->nbeams; index++) { // lower the left border conf->beam[index].offset.dx0 -= BCK_BEAM_EXT; // enhance the right border conf->beam[index].offset.dx1 += BCK_BEAM_EXT; } }
{ "alphanum_fraction": 0.5481941438, "avg_line_length": 28.6830065359, "ext": "c", "hexsha": "c5e740373e38f8ca929b02d00bc78ca65aa1d063", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/aper_conf.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/aper_conf.c", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/aper_conf.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4710, "size": 17554 }
#pragma once #include <gsl/gsl_multifit_nlinear.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_cdf.h> #include <QVector> #include <algorithm> #include <tuple> class Gaussian2DFit { struct data { double* x; double* y; size_t n; double* z; size_t width; size_t height; }; enum { numOfPara = 7 }; /* model function: A *exp(-a*(x-x0)^2 - 2*b*(x-x0)*(y-y0) - c*(y-y0)^2) + d, see more detail https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function*/ private: gsl_vector* p0; /* initial fitting parameters:amplitude,center(x0,y0),width(a,b,c),offset*/ gsl_vector* p; /* fitting parameters */ gsl_vector* f; /* residual yi-y(xi) */ gsl_matrix* covar; /*covariance matrix, not yet multiplied by sigma, so is not variance-covariance matrix*/ gsl_multifit_nlinear_fdf fdf; gsl_multifit_nlinear_parameters fdf_params; gsl_multifit_nlinear_workspace* work; data fit_data; size_t max_iter; double ptol; /* tolerance on fitting parameter p */ double gtol; /* tolerance on gradient */ double ftol; int info;/*fiting stop reason, for debug*/ double rss; /*mean of sum of residual square, dof corrected*/ gsl_vector* confid95; gsl_vector* jacEllipseMajorABC; gsl_vector* jacEllipseMinorABC; double ellipseMajor95; double ellipseMinor95; public: Gaussian2DFit() {}; Gaussian2DFit(size_t n, size_t width, size_t height, double* datax, double* datay, double* dataz, double A0, double x00, double y00, double a0, double b0, double c0, double D0, size_t max_iter = 200, double ptol = 1.0e-8, double gtol = 1.0e-8, double ftol = 1.0e-8); ~Gaussian2DFit(); void solve_system(); void set_data(double* datay); void set_data(size_t n, size_t width, size_t height, double* datax, double* datay, double* dataz, bool free = true); void set_initialP(double A0, double x00, double y00, double a0, double b0, double c0, double D0); int getInfo() const { return info; } static double gaussian2d(const double A, const double x0, const double y0, const double a, const double b, const double c, const double D, const double tx, const double ty); QVector<double> calcFittedGaussian(); const QVector<double> fittedPara() const; const QVector<double> confidence95Interval() const; const std::pair<double, double> MajorMinor95() const; private: static int func_f(const gsl_vector* p, void* datafit, gsl_vector* f); static int func_df(const gsl_vector* p, void* datafit, gsl_matrix* J); static int func_fvv(const gsl_vector* p, const gsl_vector* v, void* datafit, gsl_vector* fvv); void inline errorPropaABC(double a, double b, double c, gsl_vector* ellipseJac, bool Major = true);/*for calculating jac of the transformed gaussian arg, now is a classical form of ellipse*/ };
{ "alphanum_fraction": 0.6131097561, "avg_line_length": 36.8539325843, "ext": "h", "hexsha": "9401b03c36f5582b00ac8c97de8ee51f868b542e", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_path": "VimbaCam/Source/Gaussian2DFit.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_path": "VimbaCam/Source/Gaussian2DFit.h", "max_line_length": 120, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/VimbaCamJILA", "max_stars_repo_path": "VimbaCam/Source/Gaussian2DFit.h", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 837, "size": 3280 }
#ifndef OPENDSS_H #define OPENDSS_H #include <petsc.h> #include <complex.h> extern PetscErrorCode OpenDSSRunCommand(const char*); extern PetscErrorCode OpenDSSVsourcesSetPU(PetscScalar); extern PetscErrorCode OpenDSSVsourcesSetAngleDeg(PetscScalar); extern PetscErrorCode OpenDSSSolutionGetSolve(PetscInt*); extern PetscErrorCode OpenDSSCircuitGetTotalPower(double complex**); #endif
{ "alphanum_fraction": 0.8541666667, "avg_line_length": 34.9090909091, "ext": "h", "hexsha": "5ae71ffc6aeb3d1d9e510129f57cf52dcaa3a778", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z", "max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "GMLC-TDC/Use-Cases", "max_forks_repo_path": "ANL-TD-Iterative-Pflow/include/opendss.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "GMLC-TDC/Use-Cases", "max_issues_repo_path": "ANL-TD-Iterative-Pflow/include/opendss.h", "max_line_length": 68, "max_stars_count": 1, "max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "GMLC-TDC/Use-Cases", "max_stars_repo_path": "ANL-TD-Iterative-Pflow/include/opendss.h", "max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z", "max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z", "num_tokens": 97, "size": 384 }
#include <petsc.h> int main(int argc, char **argv) { PetscErrorCode ierr; PetscMPIInt rank; PetscInt i; PetscReal localval, globalsum, x; ierr = PetscInitialize(&argc,&argv,NULL, "Compute exp in parallel with PETSc.\n\n"); if (ierr) return ierr; ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank); CHKERRQ(ierr); PetscOptionsBegin(PETSC_COMM_WORLD, "", "options for expx", ""); PetscOptionsReal("-x", "input to exp(x) function", "expx.c", x, &x, PETSC_NULL); PetscOptionsEnd(); // compute exp(x) where n = (rank of process) + 1 localval = 1.0; for (i = 2; i < rank+1; i++) localval /= i; localval *= PetscPowReal(x, rank); // sum the contributions over all processes ierr = MPI_Allreduce(&localval,&globalsum,1,MPIU_REAL,MPIU_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr); // output estimate of e and report on work from each process ierr = PetscPrintf(PETSC_COMM_WORLD, "exp(%f) is about %17.15f\n", x, globalsum); CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_SELF, "rank %d did %d flops\n", rank, (rank > 0) ? rank-1 : 0); CHKERRQ(ierr); return PetscFinalize(); }
{ "alphanum_fraction": 0.6550522648, "avg_line_length": 32.8, "ext": "c", "hexsha": "14733056fa5bfd53fac6af32257cbce545b4b138", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "thw1021/p4pdes", "max_forks_repo_path": "c/ch1/exercises/expx.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "thw1021/p4pdes", "max_issues_repo_path": "c/ch1/exercises/expx.c", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "thw1021/p4pdes", "max_stars_repo_path": "c/ch1/exercises/expx.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 352, "size": 1148 }
/** @file */ #ifndef __CCL_F1D_H_INCLUDED__ #define __CCL_F1D_H_INCLUDED__ #include <gsl/gsl_spline.h> CCL_BEGIN_DECLS typedef enum ccl_f1d_extrap_t { ccl_f1d_extrap_0 = 0, // No extrapolation ccl_f1d_extrap_const = 410, // Constant extrapolation ccl_f1d_extrap_linx_liny = 411, // Linear x, linear y ccl_f1d_extrap_linx_logy = 412, // Linear x, log y ccl_f1d_extrap_logx_liny = 413, // Log x, linear y ccl_f1d_extrap_logx_logy = 414, // Log x, log y } ccl_f1d_extrap_t; /* * Spline wrapper * Used to take care of evaluations outside the supported range */ typedef struct { gsl_spline *spline; double y0,yf; //Constant values to use beyond interpolation limit ccl_f1d_extrap_t extrap_lo_type; ccl_f1d_extrap_t extrap_hi_type; double x_ini, x_end; //Interpolation limits double y_ini, y_end; double der_lo; double der_hi; } ccl_f1d_t; ccl_f1d_t *ccl_f1d_t_new(int n,double *x,double *y,double y0,double yf, ccl_f1d_extrap_t extrap_lo_type, ccl_f1d_extrap_t extrap_hi_type, int *status); double ccl_f1d_t_eval(ccl_f1d_t *spl,double x); void ccl_f1d_t_free(ccl_f1d_t *spl); CCL_END_DECLS #endif
{ "alphanum_fraction": 0.7556521739, "avg_line_length": 23.9583333333, "ext": "h", "hexsha": "d1d15a457e0cb8cef8f37e75aebd5da5f88aa76b", "lang": "C", "max_forks_count": 54, "max_forks_repo_forks_event_max_datetime": "2022-02-06T13:12:10.000Z", "max_forks_repo_forks_event_min_datetime": "2017-07-12T13:08:25.000Z", "max_forks_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Jappenn/CCL", "max_forks_repo_path": "include/ccl_f1d.h", "max_issues_count": 703, "max_issues_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_issues_repo_issues_event_max_datetime": "2022-03-30T14:40:10.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-07T16:27:17.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Jappenn/CCL", "max_issues_repo_path": "include/ccl_f1d.h", "max_line_length": 71, "max_stars_count": 91, "max_stars_repo_head_hexsha": "a37cad61f060f3928fa5d47b1e2670db3e9bce6f", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Jappenn/CCL", "max_stars_repo_path": "include/ccl_f1d.h", "max_stars_repo_stars_event_max_datetime": "2022-03-28T08:55:54.000Z", "max_stars_repo_stars_event_min_datetime": "2017-07-14T02:45:59.000Z", "num_tokens": 412, "size": 1150 }
#ifndef AFS_H #define AFS_H #include <gsl/gsl_matrix.h> #include <glib.h> //afsObject represents a two population coalescent typedef struct afsObject { int npops,nalleles; int aCounts[2]; //this keeps track of popn specific allele counts gsl_matrix_int **popMats; char *matString; } afsObject; typedef struct afsStateSpace { int nstates; afsObject **states; //below are only to hasten the process of state //space enumeration //int **nstateArray; //afsObject ****tmpStorage; GHashTable *stateHash; } afsStateSpace; //for use in programs like cmc_island_mle struct island_lik_params{ int snpNumber, maxSampleSize,nstates,n1,n2, hStates,nParams; gsl_vector *weights, *sampleSizeVector,*rates; //paramVector for HMM == [N2,thetaState1,thetaState2,...,thetaStaten, m1State1,m2State1,m1State2,m2State2,...,m1Staten,m2Staten] <n is number of hmm states>; gsl_vector *paramVector,*paramCIUpper,*paramCILower, *mlParams; //For straight MLE the paramVector takes the form [N1,N2,m1,m2] gsl_matrix *log_afs, *posts, *transMat,*topol,*expAFS, *visitMat; gsl_matrix_int *moveType; afsStateSpace *stateSpace; struct site *data; double *cs_work; int *dim1, *dim2; //these pointers ease the construction of sparse matrices int nzCount; double maxLik; int optimized; }island_lik_params; #define MAXSTATES 100000000 #define MAXSIZE 20 afsObject *afsObjectNew(int n1, int n2); void afsObjectFree(afsObject *v); void afsObjectInit(afsObject *v,int n1, int n2); void afsObjectPrint(afsObject *v); afsObject *afsObjectNewFrom(afsObject *v); afsObject *afsObjectDelta(afsObject *a, afsObject *b); void afsObjectDeltaPre(afsObject *a, afsObject *b,afsObject *tmp); int afsObjectCount(afsObject *a); afsStateSpace *afsStateSpaceNew(); void afsStateSpaceFree(afsStateSpace *a); int afsStateSpaceContainsState(afsStateSpace *S, afsObject *aState); void afsStateSpaceRemoveAbsorbing(afsStateSpace *S); int afsStateSpaceContainsStateTmpStorage(afsStateSpace *S, afsObject *aState); void afsStateSpaceMapPopn(afsStateSpace *S, int *map); void afsStateSpaceMapAndReducePopn(afsStateSpace *S, int *map, afsStateSpace *reducedSpace, int *reverseMap); void afsStateSpaceRemovePopulation(afsStateSpace *S, int popn); afsStateSpace *afsStateSpaceCopy(afsStateSpace *S); void mcMatsImportFromFile(const char *fileName,int *nnz,double *topol, int *moveA, int *dim1, int *dim2); int nDescPop1(afsObject *v); int nDescPop2(afsObject *v); int compatibleAfsGivenInitial(afsObject *v, int n1, int n2); int afsObjectsEqual(afsObject *a, afsObject *b); void acceptOrRejectProposedState(afsStateSpace *S, afsObject *child, int n1, int n2); int afsObjectQsortCompare(const void *p1, const void *p2); afsStateSpace *afsStateSpaceImportFromFile(const char *fileName); void nonZeroEntries(gsl_matrix_int *m, int **coords, int *count); void entriesGreaterThan(gsl_matrix_int *m, int **coords, int *count, int cut); void entriesLessThan(gsl_matrix_int *m, int **coords, int *count, int cut); int countNegativeEntries(gsl_matrix_int *m); double xchoosey(int n, int k); int matrixAllGTZ(gsl_matrix_int *m); int matrixSum(gsl_matrix_int *m); void gsl_matrix_prettyPrint(gsl_matrix *m); double matrixSumDouble(gsl_matrix *m); void preorderEvolveState(afsStateSpace *S, afsObject *aState, int n1, int n2); void coalMarkovChainTopologyMatrix(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int n1, int n2); int coalMarkovChainTopologyMatrix_2(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int *dim1, int *dim2); int coalMarkovChainTopologyMatrix_sparse(afsStateSpace *S,double *topol, int *moveType, int *dim1, int *dim2); void readTopolFile(const char *fileName, double *topA, int *moveA, int *dim1, int *dim2); void fillTransitionMatrix(afsStateSpace *S, gsl_matrix *topol, gsl_matrix_int *moveType, gsl_matrix *transMat, gsl_vector *rates, double theta1, double theta2, double mig1, double mig2); struct cs_di_sparse *fillTransitionMatrix_2(afsStateSpace *S, gsl_matrix *topol, gsl_matrix_int *moveType, gsl_vector *rates, int nzCount, int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2); void fillExpectedAFS(afsStateSpace *S, gsl_matrix *transMat,gsl_vector *rates, gsl_matrix *expAFS, int n1, int n2); void fillExpectedAFS_visits(afsStateSpace *S, gsl_matrix *visitMat,gsl_vector *rates, gsl_matrix *expAFS); void fillExpectedAFS_visits_2(afsStateSpace *S, double *visitMat,gsl_vector *rates, gsl_matrix *expAFS); void overlayPopnSplitting(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int n1, int n2); void maximize_island_lik_const(double *lik, void * p); void maximize_island_lik_hmm_const(double *lik, void * p); void maximize_island_lik_CILower(double *lik, void * p); void maximize_island_lik_CIUpper(double *lik, void * p); void island_lik_constraint_CI(size_t n, const double *pGuess, void * p, double *result); void island_lik_constraint(size_t n, const double *pGuess, void * p, double *result); void island_lik_constraint_hmm(size_t n, const double *pGuess, void * p, double *result); void fillLogAFS_ptr_sp(void * p); void fillLogAFS_ptr_sp2(void * p); void fillLogAFS_ptr_sp_hmm(int state,void * p); void itoa(int n, char s[]); void reverse(char s[]); void NumericalGradient_island_lik(size_t n, const double *v, void *params, double *df); void island_lik_fdf(const size_t n, const double *x,void *fparams,double *fval,double *grad); #endif
{ "alphanum_fraction": 0.7824252431, "avg_line_length": 36.8310810811, "ext": "h", "hexsha": "157eef99546a53b836894c30a59fd87210f1d92d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e1643d7489106d5e040329bd0b7db75d80ce21d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/im_clam", "max_forks_repo_path": "AFS.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z", "max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dortegadelv/IMaDNA", "max_issues_repo_path": "AFS.h", "max_line_length": 158, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dortegadelv/IMaDNA", "max_stars_repo_path": "AFS.h", "max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z", "max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z", "num_tokens": 1619, "size": 5451 }
/* gsl_multilarge.h * * Copyright (C) 2015 Patrick Alken * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MULTILARGE_H__ #define __GSL_MULTILARGE_H__ #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_types.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS /* iteration solver type */ typedef struct { const char *name; void * (*alloc) (const size_t p); int (*reset) (void *); int (*accumulate) (gsl_matrix * X, gsl_vector * y, void *); int (*solve) (const double lambda, gsl_vector * c, double * rnorm, double * snorm, void *); int (*rcond) (double * rcond, void *); int (*lcurve) (gsl_vector * reg_param, gsl_vector * rho, gsl_vector * eta, void *); void (*free) (void *); } gsl_multilarge_linear_type; typedef struct { const gsl_multilarge_linear_type * type; void * state; size_t p; } gsl_multilarge_linear_workspace; /* available types */ GSL_VAR const gsl_multilarge_linear_type * gsl_multilarge_linear_normal; GSL_VAR const gsl_multilarge_linear_type * gsl_multilarge_linear_tsqr; /* * Prototypes */ gsl_multilarge_linear_workspace * gsl_multilarge_linear_alloc(const gsl_multilarge_linear_type * T, const size_t p); void gsl_multilarge_linear_free(gsl_multilarge_linear_workspace * w); const char *gsl_multilarge_linear_name(const gsl_multilarge_linear_workspace * w); int gsl_multilarge_linear_reset(gsl_multilarge_linear_workspace * w); int gsl_multilarge_linear_accumulate(gsl_matrix * X, gsl_vector * y, gsl_multilarge_linear_workspace * w); int gsl_multilarge_linear_solve(const double lambda, gsl_vector * c, double * rnorm, double * snorm, gsl_multilarge_linear_workspace * w); int gsl_multilarge_linear_rcond(double *rcond, gsl_multilarge_linear_workspace * w); int gsl_multilarge_linear_lcurve(gsl_vector * reg_param, gsl_vector * rho, gsl_vector * eta, gsl_multilarge_linear_workspace * w); int gsl_multilarge_linear_wstdform1 (const gsl_vector * L, const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_matrix * Xs, gsl_vector * ys, gsl_multilarge_linear_workspace * work); int gsl_multilarge_linear_stdform1 (const gsl_vector * L, const gsl_matrix * X, const gsl_vector * y, gsl_matrix * Xs, gsl_vector * ys, gsl_multilarge_linear_workspace * work); int gsl_multilarge_linear_L_decomp (gsl_matrix * L, gsl_vector * tau); int gsl_multilarge_linear_wstdform2 (const gsl_matrix * LQR, const gsl_vector * Ltau, const gsl_matrix * X, const gsl_vector * w, const gsl_vector * y, gsl_matrix * Xs, gsl_vector * ys, gsl_multilarge_linear_workspace * work); int gsl_multilarge_linear_stdform2 (const gsl_matrix * LQR, const gsl_vector * Ltau, const gsl_matrix * X, const gsl_vector * y, gsl_matrix * Xs, gsl_vector * ys, gsl_multilarge_linear_workspace * work); int gsl_multilarge_linear_genform1 (const gsl_vector * L, const gsl_vector * cs, gsl_vector * c, gsl_multilarge_linear_workspace * work); int gsl_multilarge_linear_genform2 (const gsl_matrix * LQR, const gsl_vector * Ltau, const gsl_vector * cs, gsl_vector * c, gsl_multilarge_linear_workspace * work); __END_DECLS #endif /* __GSL_MULTILARGE_H__ */
{ "alphanum_fraction": 0.569026058, "avg_line_length": 38.1056338028, "ext": "h", "hexsha": "e99c1e1c02f6a072b9ac720bf5cb09491b5bd673", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2019-06-13T05:31:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-20T16:50:58.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge/gsl_multilarge.h", "max_issues_count": 11, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2022-02-07T08:59:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-29T16:26:06.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multilarge/gsl_multilarge.h", "max_line_length": 84, "max_stars_count": 7, "max_stars_repo_head_hexsha": "3eb0cf4b8fcfa2c36e133e4df2b2a3e6d2d3e589", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "shi-bash-cmd/qtTest", "max_stars_repo_path": "315/gsltest/gsl/include/gsl/gsl_multilarge.h", "max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z", "num_tokens": 1095, "size": 5411 }
#include <float.h> #include <inttypes.h> #include <limits.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include <valgrind/callgrind.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_statistics.h> #include "betree.h" #include "debug.h" #include "hashmap.h" #include "helper.h" #include "printer.h" #include "tree.h" #include "utils.h" #define MAX_EXPRS 10000 #define MAX_EVENTS 5000 #define DEFAULT_SEARCH_COUNT 10 // wc -L filename #define MAX_EVENT_CHARACTERS 20000 #define MAX_EXPR_CHARACTERS 17000 #define MAX_CONSTANT_CHARACTERS 20 const char* EXPRS_FILE = "data/betree_exprs"; const char* CONSTANTS_FILE = "data/betree_constants"; const char* EVENTS_FILE = "data/betree_events"; struct betree_events { size_t count; char** events; }; void add_event(char* event, struct betree_events* events) { if(events->count == 0) { events->events = calloc(1, sizeof(*events->events)); if(events == NULL) { fprintf(stderr, "%s calloc failed", __func__); abort(); } } else { char** new_events = realloc(events->events, sizeof(*new_events) * ((events->count) + 1)); if(new_events == NULL) { fprintf(stderr, "%s realloc failed", __func__); abort(); } events->events = new_events; } events->events[events->count] = strdup(event); events->count++; } char* strip_chars(const char* string, const char* chars) { char* new_string = malloc(strlen(string) + 1); int counter = 0; for(; *string; string++) { if(!strchr(chars, *string)) { new_string[counter] = *string; ++counter; } } new_string[counter] = 0; return new_string; } int event_parse(const char* text, struct betree_event** event); size_t read_betree_events(struct betree_events* events) { FILE* f = fopen(EVENTS_FILE, "r"); size_t count = 0; char line[MAX_EVENT_CHARACTERS]; // Arbitrary from what I've seen while(fgets(line, sizeof(line), f)) { if(MAX_EVENTS != 0 && events->count == MAX_EVENTS) { break; } add_event(line, events); count++; } fclose(f); return count; } size_t read_betree_exprs(struct betree* tree) { FILE* f = fopen(EXPRS_FILE, "r"); FILE* constants_f = fopen(CONSTANTS_FILE, "r"); //char* lines[MAX_EXPRS]; char line[MAX_EXPR_CHARACTERS]; // Arbitrary from what I've seen char constants_line[MAX_CONSTANT_CHARACTERS]; size_t count = 0; const struct betree_sub* subs[MAX_EXPRS]; enum e { constant_count = 3 }; while(fgets(line, sizeof(line), f)) { char* ignore = fgets(constants_line, sizeof(constants_line), constants_f); (void)ignore; char* copy = strdup(constants_line); char* rest = copy; int64_t campaign_id = strtoll(strtok_r(rest, ",", &rest), NULL, 10); int64_t advertiser_id = strtoll(strtok_r(rest, ",", &rest), NULL, 10); int64_t flight_id = strtoll(strtok_r(rest, "\n", &rest), NULL, 10); const struct betree_constant* constants[constant_count] = { betree_make_integer_constant("campaign_id", campaign_id), betree_make_integer_constant("advertiser_id", advertiser_id), betree_make_integer_constant("flight_id", flight_id), }; const struct betree_sub* sub = betree_make_sub(tree, count, constant_count, constants, line); subs[count] = sub; count++; betree_free_constants(constant_count, (struct betree_constant**) constants); free(copy); if(MAX_EXPRS != 0 && count == MAX_EXPRS) { break; } } /*for(size_t i = 0; i < tree->config->attr_domain_count; i++) {*/ /*const struct attr_domain* attr_domain = tree->config->attr_domains[i];*/ /*print_attr_domain(attr_domain);*/ /*}*/ fclose(f); fclose(constants_f); for(size_t i = 0; i < count; i++) { const struct betree_sub* sub = subs[i]; if(!betree_insert_sub(tree, sub)) { printf("Can't insert expr %zu\n", i); abort(); } } return count; } void read_betree_defs(struct betree* tree) { FILE* f = fopen("data/betree_defs", "r"); char line[LINE_MAX]; while(fgets(line, sizeof(line), f)) { add_variable_from_string(tree, line); } fclose(f); } int compare_int( const void* a, const void* b ) { if( *(int*)a == *(int*)b ) return 0; return *(int*)a < *(int*)b ? -1 : 1; } int main(int argc, char** argv) { size_t search_count = DEFAULT_SEARCH_COUNT; if(argc > 1) { search_count = atoi(argv[1]); } if(access("data/betree_defs", F_OK) == -1 || access("data/betree_events", F_OK) == -1 || access("data/betree_exprs", F_OK) == -1 || access("data/betree_constants", F_OK) == -1) { fprintf(stderr, "Missing files, skipping the tests"); return 0; } struct timespec start, insert_done, gen_event_done, search_done; // Init struct betree* tree = betree_make(); read_betree_defs(tree); clock_gettime(CLOCK_MONOTONIC_RAW, &start); // Insert size_t expr_count = read_betree_exprs(tree); clock_gettime(CLOCK_MONOTONIC_RAW, &insert_done); uint64_t insert_us = (insert_done.tv_sec - start.tv_sec) * 1000000 + (insert_done.tv_nsec - start.tv_nsec) / 1000; printf(" Insert took %" PRIu64 "\n", insert_us); struct betree_events events = { .count = 0, .events = NULL }; size_t event_count = read_betree_events(&events); uint64_t evaluated_sum = 0; uint64_t matched_sum = 0; uint64_t memoized_sum = 0; uint64_t shorted_sum = 0; const size_t search_us_count = search_count * events.count; double search_us_data[search_us_count]; CALLGRIND_START_INSTRUMENTATION; size_t search_us_i = 0; for(size_t j = 0; j < search_count; j++) { for(size_t i = 0; i < events.count; i++) { clock_gettime(CLOCK_MONOTONIC_RAW, &gen_event_done); char* event = events.events[i]; struct report* report = make_report(); if(betree_search(tree, event, report) == false) { fprintf(stderr, "Failed to search with event\n"); abort(); } clock_gettime(CLOCK_MONOTONIC_RAW, &search_done); uint64_t search_us = (search_done.tv_sec - gen_event_done.tv_sec) * 1000000 + (search_done.tv_nsec - gen_event_done.tv_nsec) / 1000; search_us_data[search_us_i] = (double)search_us; evaluated_sum += report->evaluated; matched_sum += report->matched; memoized_sum += report->memoized; shorted_sum += report->shorted; free_report(report); search_us_i++; } printf("Finished run %zu/%zu\n", j, search_count); } CALLGRIND_STOP_INSTRUMENTATION; CALLGRIND_DUMP_STATS; for(size_t i = 0; i < events.count; i++) { free(events.events[i]); } double evaluated_average = (double)evaluated_sum / (double)MAX_EVENTS; double matched_average = (double)matched_sum / (double)MAX_EVENTS; double memoized_average = (double)memoized_sum / (double)MAX_EVENTS; double shorted_average = (double)shorted_sum / (double)MAX_EVENTS; printf("%zu searches, %zu expressions, %zu events, %zu preds, %zu memoize preds. Evaluated %.2f, matched %.2f, memoized %.2f, shorted %.2f\n", search_us_count, expr_count, event_count, tree->config->pred_map->pred_count, tree->config->pred_map->memoize_count, evaluated_average / search_count, matched_average / search_count, memoized_average / search_count, shorted_average / search_count); double search_us_min = gsl_stats_min(search_us_data, 1, search_us_count); double search_us_max = gsl_stats_max(search_us_data, 1, search_us_count); double search_us_mean = gsl_stats_mean(search_us_data, 1, search_us_count); gsl_sort(search_us_data, 1, search_us_count); double search_us_90 = gsl_stats_quantile_from_sorted_data(search_us_data, 1, search_us_count, 0.90); double search_us_95 = gsl_stats_quantile_from_sorted_data(search_us_data, 1, search_us_count, 0.95); double search_us_99 = gsl_stats_quantile_from_sorted_data(search_us_data, 1, search_us_count, 0.99); printf("Min: %.1f, Mean: %.1f, Max: %.1f, 90: %.1f, 95: %.1f, 99: %.1f\n", search_us_min, search_us_mean, search_us_max, search_us_90, search_us_95, search_us_99); printf("| %lu | %.1f | %.1f | %.1f | %.1f | %.1f | %.1f | |\n", insert_us, search_us_min, search_us_mean, search_us_max, search_us_90, search_us_95, search_us_99); // DEBUG write_dot_file(tree); // DEBUG free(events.events); betree_free(tree); return 0; }
{ "alphanum_fraction": 0.6361913257, "avg_line_length": 31.804964539, "ext": "c", "hexsha": "de69b1900a8decfc8ddd89c450633ef5fe8ae829", "lang": "C", "max_forks_count": 11, "max_forks_repo_forks_event_max_datetime": "2020-10-02T14:17:50.000Z", "max_forks_repo_forks_event_min_datetime": "2018-04-06T14:57:18.000Z", "max_forks_repo_head_hexsha": "51d7474cce329b6ea392ac873100e3963c23b471", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jonahharris/be-tree", "max_forks_repo_path": "tests/real_tests.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "51d7474cce329b6ea392ac873100e3963c23b471", "max_issues_repo_issues_event_max_datetime": "2021-08-03T01:49:39.000Z", "max_issues_repo_issues_event_min_datetime": "2018-04-05T22:00:50.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jonahharris/be-tree", "max_issues_repo_path": "tests/real_tests.c", "max_line_length": 167, "max_stars_count": 29, "max_stars_repo_head_hexsha": "51d7474cce329b6ea392ac873100e3963c23b471", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jonahharris/be-tree", "max_stars_repo_path": "tests/real_tests.c", "max_stars_repo_stars_event_max_datetime": "2022-03-11T03:55:44.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-28T13:42:04.000Z", "num_tokens": 2377, "size": 8969 }
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <math.h> #include <gsl/gsl_errno.h> #include "ccl.h" // Error handling policy: whether to exit on error (C default) or continue // (Python or other binding default) static CCLErrorPolicy _ccl_error_policy = CCL_ERROR_POLICY_EXIT; // Debug mode policy: whether to print error messages as they are raised. This // is useful for the Python wrapper, which normally allows errors to be // overwritten by the C code until control returns to Python. If debug mode is // switched on, the errors are always printed by the C code when they occur. // Setting the debug mode to warning allows ccl_raise_warning to print warnings // but keeps the behavior of ccl_raise_exception as if debug mode is set to off. static CCLDebugModePolicy _ccl_debug_mode_policy = CCL_DEBUG_MODE_WARNING; // Set error policy void ccl_set_error_policy(CCLErrorPolicy error_policy) { _ccl_error_policy = error_policy; } // Set debug mode policy void ccl_set_debug_policy(CCLDebugModePolicy debug_policy) { _ccl_debug_mode_policy = debug_policy; } // Convenience function to raise exceptions in an appropriate way void ccl_raise_exception(int err, const char* msg, ...) { char message[256]; va_list va; va_start(va, msg); vsnprintf(message, 250, msg, va); va_end(va); // Print error message and exit if fatal errors are enabled if ((_ccl_error_policy == CCL_ERROR_POLICY_EXIT) && (err)) { fprintf(stderr, "ERROR %d: %s\n", err, message); exit(1); } // Print error message and exit if debug output is enabled else if ((_ccl_debug_mode_policy == CCL_DEBUG_MODE_ON) && (err)){ fprintf(stderr, "ERROR %d: %s\n", err, message); } } // Convenience function to handle warnings void ccl_raise_warning(int err, const char* msg, ...) { char message[256]; va_list va; va_start(va, msg); vsnprintf(message, 250, msg, va); va_end(va); // For now just print warning to stderr if debug is enabled. // TODO: Implement some kind of error stack that can be passed on to, e.g., // the python binding. if( (_ccl_debug_mode_policy == CCL_DEBUG_MODE_ON) || (_ccl_debug_mode_policy == CCL_DEBUG_MODE_WARNING) ) { fprintf(stderr, "WARNING: %s\n", message); } } // Convenience function to handle warnings void ccl_raise_gsl_warning(int gslstatus, const char* msg, ...) { char message[256]; va_list va; va_start(va, msg); vsnprintf(message, 250, msg, va); va_end(va); ccl_raise_warning(gslstatus, "%s GSL error: %s", message, gsl_strerror(gslstatus)); return; } void ccl_check_status(ccl_cosmology *cosmo, int * status) { switch (*status) { case 0: // all good, nothing to do return; case CCL_ERROR_LINSPACE: // spacing allocation error, always terminate ccl_raise_exception(*status, cosmo->status_message); case CCL_ERROR_SPLINE: // spline allocation error, always terminate ccl_raise_exception(*status, cosmo->status_message); case CCL_ERROR_COMPUTECHI: // compute_chi error //RH ccl_raise_exception(*status, cosmo->status_message); case CCL_ERROR_HMF_INTERP: // terminate if hmf definition not supported ccl_raise_exception(*status, cosmo->status_message); case CCL_ERROR_NU_INT: // error in getting the neutrino integral spline: exit. No status_message in cosmo because can't pass cosmology to the function. ccl_raise_exception(*status, "Error, in ccl_neutrinos.c. ccl_calculate_nu_phasespace_spline(): Error in setting neutrino phasespace spline."); case CCL_ERROR_NU_SOLVE: // error in converting Omeganuh2-> Mnu: exit. No status_message in cosmo because can't pass cosmology to the function. ccl_raise_exception(*status, "Error, in ccl_neutrinos.c. Omeganuh2_to_Mnu(): Root finding did not converge."); // TODO: Implement softer error handling, e.g. for integral convergence here default: ccl_raise_exception(*status, cosmo->status_message); } } /* ------- ROUTINE: ccl_check_status_nocosmo ------ INPUTS: pointer to a status integer TASK: Perform a check on status for the case where it is not possible to have a cosmology object where the status check is required. */ void ccl_check_status_nocosmo(int * status) { switch (*status) { case 0: // Nothing to do return; case CCL_ERROR_LINSPACE: // Spacing allocation error, always terminate ccl_raise_exception(*status, "CCL_ERROR_LINSPACE: Spacing allocation error."); case CCL_ERROR_SPLINE: // Spline allocation error, always terminate ccl_raise_exception(*status, "CCL_ERROR_SPLINE: Spline allocation error."); case CCL_ERROR_COMPUTECHI: // Compute_chi error ccl_raise_exception(*status, "CCL_ERROR_COMPUTECHI: Comoving distance chi computation failed."); case CCL_ERROR_HMF_INTERP: // Terminate if hmf definition not supported ccl_raise_exception(*status, "CCL_ERROR_HMF_INTERP: Halo mass function definition not supported."); case CCL_ERROR_NU_INT: // Error in getting the neutrino integral spline: exit. No status_message // in cosmo because can't pass cosmology to the function. ccl_raise_exception(*status, "CCL_ERROR_NU_INT: Error getting the neutrino phase-space integral spline."); case CCL_ERROR_NU_SOLVE: // Error in converting Omeganuh2-> Mnu: exit. No status_message in cosmo // because can't pass cosmology to the function. ccl_raise_exception(*status, "CCL_ERROR_NU_SOLVE: Error converting Omeganuh2 -> Mnu."); case CCL_ERROR_MNU_UNPHYSICAL: // Error in the sum of mnu or Omeganu passed for the hierarchy requested. ccl_raise_exception(*status, "CCL_ERROR_MNU_UNPHYSICAL: Sum of neutrinos masses for this Omeganu value is incompatible with the requested mass hierarchy."); case CCL_ERROR_NOT_IMPLEMENTED: ccl_raise_exception(*status, "CCL_ERROR_NOT_IMPLEMENTED: the type of m_nu specified is not supported."); default: ccl_raise_exception(*status, "Unrecognized error code (see gsl_errno.h for error codes 1-32)."); } }
{ "alphanum_fraction": 0.7346972447, "avg_line_length": 38.6050955414, "ext": "c", "hexsha": "e83167c2feec4367b86d32c61d1cd19ed6d48cbf", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Russell-Jones-OxPhys/CCL", "max_forks_repo_path": "src/ccl_error.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Russell-Jones-OxPhys/CCL", "max_issues_repo_path": "src/ccl_error.c", "max_line_length": 153, "max_stars_count": null, "max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Russell-Jones-OxPhys/CCL", "max_stars_repo_path": "src/ccl_error.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1570, "size": 6061 }
#ifndef __GSL_STATISTICS_H__ #define __GSL_STATISTICS_H__ #include <gsl/gsl_statistics_long_double.h> #include <gsl/gsl_statistics_double.h> #include <gsl/gsl_statistics_float.h> #include <gsl/gsl_statistics_ulong.h> #include <gsl/gsl_statistics_long.h> #include <gsl/gsl_statistics_uint.h> #include <gsl/gsl_statistics_int.h> #include <gsl/gsl_statistics_ushort.h> #include <gsl/gsl_statistics_short.h> #include <gsl/gsl_statistics_uchar.h> #include <gsl/gsl_statistics_char.h> #endif /* __GSL_STATISTICS_H__ */
{ "alphanum_fraction": 0.8111753372, "avg_line_length": 24.7142857143, "ext": "h", "hexsha": "ac175638f3dc1aeb3dbdffc453e1158d6135176a", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z", "max_forks_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ielomariala/Hex-Game", "max_forks_repo_path": "gsl-2.6/gsl/gsl_statistics.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ielomariala/Hex-Game", "max_issues_repo_path": "gsl-2.6/gsl/gsl_statistics.h", "max_line_length": 43, "max_stars_count": null, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/gsl/gsl_statistics.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 139, "size": 519 }
#pragma once #include <stdio.h> #include <stdbool.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #define SIM_SUCCESS 0 #define SIM_FAILURE -1 #define SIM_INFO(...) do {fprintf(stdout,##__VA_ARGS__);} while(0) #define SIM_ERROR(...) do {fprintf(stdout,##__VA_ARGS__);} while(0) #define SHUTDOWN_MESSAGE "shutdown\n" typedef struct { gsl_vector *yd; gsl_vector *y; } VehicleState; typedef struct { gsl_vector *(*feedback) (gsl_vector *yd, gsl_vector *y); } Controller;
{ "alphanum_fraction": 0.716904277, "avg_line_length": 20.4583333333, "ext": "h", "hexsha": "0ada760a937c6a1f1877ac9e1d892099f9efa6a3", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "umd-agrc/SimpleControlSim", "max_forks_repo_path": "defines.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "umd-agrc/SimpleControlSim", "max_issues_repo_path": "defines.h", "max_line_length": 67, "max_stars_count": null, "max_stars_repo_head_hexsha": "d04a8fa496ec414e2cffdc70ee0beda85e0d7cb4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "umd-agrc/SimpleControlSim", "max_stars_repo_path": "defines.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 132, "size": 491 }
/* randist/cauchy.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> /* The Cauchy probability distribution is p(x) dx = (1/(pi a)) (1 + (x/a)^2)^(-1) dx It is also known as the Lorentzian probability distribution */ double gsl_ran_cauchy (const gsl_rng * r, const double a) { double u; do { u = gsl_rng_uniform (r); } while (u == 0.5); return a * tan (M_PI * u); } double gsl_ran_cauchy_pdf (const double x, const double a) { double u = x / a; double p = (1 / (M_PI * a)) / (1 + u * u); return p; }
{ "alphanum_fraction": 0.6836158192, "avg_line_length": 27.2307692308, "ext": "c", "hexsha": "7fffd6826f0fba5a4ec8c26c4467b313666c99c8", "lang": "C", "max_forks_count": 40, "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_path": "pkgs/libs/gsl/src/randist/cauchy.c", "max_issues_count": 12, "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_path": "pkgs/libs/gsl/src/randist/cauchy.c", "max_line_length": 81, "max_stars_count": 64, "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_path": "pkgs/libs/gsl/src/randist/cauchy.c", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "num_tokens": 413, "size": 1416 }
#ifndef BRATU3D_H #define BRATU3D_H #include <petsc.h> typedef struct Params { double lambda_; } Params; PetscErrorCode FormInitGuess(DM da, Vec x, Params *p); PetscErrorCode FormFunction(DM da, Vec x, Vec F, Params *p); PetscErrorCode FormJacobian(DM da, Vec x, Mat J, Params *p); #endif/*BRATU3D_H*/
{ "alphanum_fraction": 0.737012987, "avg_line_length": 20.5333333333, "ext": "h", "hexsha": "10709d04e5e73aabed0ea9dfbaadfb99f70c2004", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "underworldcode/petsc4py", "max_forks_repo_path": "demo/wrap-swig/Bratu3D.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "underworldcode/petsc4py", "max_issues_repo_path": "demo/wrap-swig/Bratu3D.h", "max_line_length": 60, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fdfdd79be39b8cbe95cf57010f29a6cb2ef463a6", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "underworldcode/petsc4py", "max_stars_repo_path": "demo/wrap-swig/Bratu3D.h", "max_stars_repo_stars_event_max_datetime": "2018-11-11T05:00:53.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-11T05:00:53.000Z", "num_tokens": 98, "size": 308 }
/** * Subroutines used in the "aXe_AF2PET.c" for the task aXe_AF2PET */ #include <stdarg.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_nan.h> #include <gsl/gsl_sys.h> #include "spc_wl_calib.h" #include "aXe_grism.h" #include "aXe_errors.h" #include "disp_conf.h" /** * The function performs a wavelength calibration on an allready * existing ap_pixel table. It fills in the lambda and dlambda fields. * * @param ap_p - the ap_pixel table to work on, with the pathlength field * filled out * @param calib - the calibration function */ void wl_calib (ap_pixel * ap_p, const calib_function * const calib) { double l1,l2; while (ap_p->p_x != -1) { ap_p->lambda = calib->func (ap_p->xi, calib->order, calib->coeffs); l1 = calib->func (ap_p->xi - .5, calib->order, calib->coeffs); l2 = calib->func (ap_p->xi + .5, calib->order, calib->coeffs); ap_p->dlambda = fabs(l2-l1); ap_p++; } } /* * Function: pwise_wl_calib * Make for every PET pixel an individual wavelength * calibration. The function was developed for FORS2 MXU spectra * and makes especially sense for long spectra and/or fast * variations of the 2D calibration solution. */ void pwise_wl_calib(const global_disp *gdisp, const d_point pixel, const beam actbeam, const int for_grism, ap_pixel *ap_p, const calib_function *old_calib) { calib_function *calib; d_point actpix; double l1,l2; double tmp; int i=0; while (ap_p[i].p_x != -1) { // get the current xy-position of the pixel actpix.x = pixel.x + ap_p[i].dist*cos(actbeam.orient); actpix.y = pixel.y + ap_p[i].dist*sin(actbeam.orient); // create a calibration for that position calib = create_calib_from_gsl_vector(for_grism, get_calvector_from_gdisp(gdisp, actpix)); // determine the wavelength value ap_p[i].lambda = calib->func (ap_p[i].xi, calib->order, calib->coeffs); // determine the dlambda value l1 = calib->func (ap_p[i].xi - .5, calib->order, calib->coeffs); l2 = calib->func (ap_p[i].xi + .5, calib->order, calib->coeffs); ap_p[i].dlambda = fabs(l2-l1); // determine the trace length tmp = old_calib->func (ap_p[i].xi, old_calib->order, old_calib->coeffs); ap_p[i].xi = ap_p[i].xi + (ap_p[i].lambda - tmp) / ap_p[i].dlambda; // free the calibration // structure free_calib(calib); // enhance the counter i++; } } /** * The function trims down an ap_pixel table to only allowed values * for the trace path length or trace distance. The input ap_pixel * is only changed. Valid entries are moved to the front side, * and a new endmark is set after all valid entries * * @param ap_pixel the input ap_pixel table * @param prange the valid trace range * @param wl_calibration the calibration structure, needed to get the * first dispersion coefficient * * @return ret ap_pixel table output */ ap_pixel * prange_cut(ap_pixel * in_p, const gsl_vector * prange, const calib_function * wl_calibration) { //long nelem; ap_pixel * ret, *cur_ap, *ap_p; double prel; double trmin=1.0E+06, trmax=-1.0E6; // set all PET list pointers // to the beginning of the array ret = in_p; cur_ap = in_p; ap_p = in_p; while (ap_p->p_x != -1) { // search for new minimum // and amximum in tracelength if (ap_p->xi > trmax) trmax = ap_p->xi; if (ap_p->xi < trmin) trmin = ap_p->xi; // compute the tracelength with // respect to the zeropoint prel = ap_p->xi - wl_calibration->coeffs[0]; // check whether the realitive zeropoint is within the allowed range if (prel > gsl_vector_get(prange,0) && prel < gsl_vector_get(prange,1)) { // transfer the properties // of the good pixel to the next // PET element in the list of good PET's cur_ap->p_x = ap_p->p_x; cur_ap->p_y = ap_p->p_y; cur_ap->x = ap_p->x; cur_ap->y = ap_p->y; cur_ap->dist = ap_p->dist; cur_ap->xs = ap_p->xs; cur_ap->ys = ap_p->ys; cur_ap->dxs = ap_p->dxs; cur_ap->xi = ap_p->xi; cur_ap->count = ap_p->count; cur_ap->error = ap_p->error; cur_ap->weight = ap_p->weight; cur_ap->contam = ap_p->contam; cur_ap->dq = ap_p->dq; // forward the pointer // of good pixels cur_ap++; } // always forward the // general pointer ap_p++; } // make a new endmark cur_ap->p_x = -1; cur_ap->p_y = -1; cur_ap->count = -1; // return the pointer return ret; } /** * Calibration function for the grism: simple polynomial * * @param xi the path length of the sample point * @param order the order of the polynomial, i.e. the number of coefficients * minus one * @param coeffs a pointer to order+1 doubles, starting with the zeroth * coefficent * * @return res wavelength at xi */ static double grism_calib_func (const double xi, const int order, const double *const coeffs) { int i; double res = 0; for (i = 0; i <= order; i++) { res += coeffs[i] * pow(xi,i*1.0); } return res; } /** * Calibration function for the prism: reciprocal polynomial in the * form: lambda = a1 + a2/(xi-a0) + a3/(xi-a0)**2 + a4/(xi-a0)**3 * * @param xi the path length of the sample point * @param order the order of the polynomial, i.e. the number of coefficients * minus one * @param coeffs a pointer to order+1 doubles, starting with the zeroth * coefficent * @return res wavelength at xi */ static double prism_calib_func (const double xi, const int order, const double *const coeffs) { int i; double res = 0; if (xi==0.) return GSL_NAN; for (i = 0; i <= order-1; i++) { // res += coeffs[i] / pow(xi,i*1.0); res += coeffs[i+1] / pow((xi-coeffs[0]),i*1.0); } return res; } /** * Create a prism or grism calibration function, i.e. a function of one of * the forms "sum(a_i 1/x^i, i=0..order)" or "sum(a_i x^i, i=0..order)" * for transforming pathlength along the trace to lambda. * *@param for_grism if true, a the second form of the calibration function * is used (normal polynom), otherwise the first one. *@param order order of the polynom *@param a a GSL vector of length n containing the n coefficients * describing the wavelength calibration polynomial. *@return calib an allocated structure containing an allocated array * for the coefficients. Free using calib_free. */ calib_function * create_calib_from_gsl_vector (const int for_grism, const gsl_vector * a) { calib_function *calib; int i, order; // set the polynomial order order = a->size - 1; // allocate memory calib = malloc(sizeof (calib_function)); // complain if memory // allocation failed if (!calib) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Out of memory"); // store the order of the // calibration calib->order = order; // transfer the calibration functions if (for_grism) calib->func = &grism_calib_func; else calib->func = &prism_calib_func; // allocate memory; complain if problems occur calib->coeffs = malloc ((order + 1) * sizeof (double)); if (!calib->coeffs) aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Out of memory"); // transfer the coefficients calib->coeffs[0] = gsl_vector_get (a, 0); for (i = 1; i <= order; i++) calib->coeffs[i] = gsl_vector_get (a, i); // set the allowed range for // the trace lengths to NULL calib->pr_range = NULL; // return the calibration // structure return calib; } /** * Function: free_calib * Free a calibration function and its assoicated data. * * @param calib the calibration structure to be freed * */ void free_calib(calib_function * calib) { free (calib->coeffs); calib->coeffs = NULL; if (calib->pr_range != NULL) { gsl_vector_free(calib->pr_range); calib->pr_range = NULL; } free (calib); calib = NULL; }
{ "alphanum_fraction": 0.6211775992, "avg_line_length": 27.0746753247, "ext": "c", "hexsha": "ec6ddbb89000adfb0d55faf275f0d009cdd1d555", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_path": "cextern/src/spc_wl_calib.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_path": "cextern/src/spc_wl_calib.c", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_path": "cextern/src/spc_wl_calib.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2432, "size": 8339 }
/* interpolation/steffen.c * * Copyright (C) 2014 Jean-François Caron * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* Author: J.-F. Caron * * This interpolation method is taken from * M.Steffen, "A simple method for monotonic interpolation in one dimension", * Astron. Astrophys. 239, 443-450 (1990). * * This interpolation method guarantees monotonic interpolation functions between * the given data points. A consequence of this is that extremal values can only * occur at the data points. The interpolating function and its first derivative * are guaranteed to be continuous, but the second derivative is not. * * The implementation is modelled on the existing Akima interpolation method * previously included in GSL by Gerard Jungman. */ #include <config.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_math.h> #include <gsl/gsl_errno.h> #include "integ_eval.h" #include <gsl/gsl_interp.h> typedef struct { double * a; /* eqs 2-5 of paper */ double * b; double * c; double * d; double * y_prime; /* eq 11 of paper */ } steffen_state_t; static void steffen_free (void * vstate); static double steffen_copysign(const double x, const double y); static void * steffen_alloc (size_t size) { steffen_state_t *state; state = (steffen_state_t *) calloc (1, sizeof (steffen_state_t)); if (state == NULL) { GSL_ERROR_NULL("failed to allocate space for state", GSL_ENOMEM); } state->a = (double *) malloc (size * sizeof (double)); if (state->a == NULL) { steffen_free(state); GSL_ERROR_NULL("failed to allocate space for a", GSL_ENOMEM); } state->b = (double *) malloc (size * sizeof (double)); if (state->b == NULL) { steffen_free(state); GSL_ERROR_NULL("failed to allocate space for b", GSL_ENOMEM); } state->c = (double *) malloc (size * sizeof (double)); if (state->c == NULL) { steffen_free(state); GSL_ERROR_NULL("failed to allocate space for c", GSL_ENOMEM); } state->d = (double *) malloc (size * sizeof (double)); if (state->d == NULL) { steffen_free(state); GSL_ERROR_NULL("failed to allocate space for d", GSL_ENOMEM); } state->y_prime = (double *) malloc (size * sizeof (double)); if (state->y_prime == NULL) { steffen_free(state); GSL_ERROR_NULL("failed to allocate space for y_prime", GSL_ENOMEM); } return state; } static int steffen_init (void * vstate, const double x_array[], const double y_array[], size_t size) { steffen_state_t *state = (steffen_state_t *) vstate; size_t i; double *a = state->a; double *b = state->b; double *c = state->c; double *d = state->d; double *y_prime = state->y_prime; /* * first assign the interval and slopes for the left boundary. * We use the "simplest possibility" method described in the paper * in section 2.2 */ double h0 = (x_array[1] - x_array[0]); double s0 = (y_array[1] - y_array[0]) / h0; y_prime[0] = s0; /* Now we calculate all the necessary s, h, p, and y' variables from 1 to N-2 (0 to size - 2 inclusive) */ for (i = 1; i < (size - 1); i++) { double pi; /* equation 6 in the paper */ double hi = (x_array[i+1] - x_array[i]); double him1 = (x_array[i] - x_array[i - 1]); /* equation 7 in the paper */ double si = (y_array[i+1] - y_array[i]) / hi; double sim1 = (y_array[i] - y_array[i - 1]) / him1; /* equation 8 in the paper */ pi = (sim1*hi + si*him1) / (him1 + hi); /* This is a C equivalent of the FORTRAN statement below eqn 11 */ y_prime[i] = (steffen_copysign(1.0,sim1) + steffen_copysign(1.0,si)) * GSL_MIN(fabs(sim1), GSL_MIN(fabs(si), 0.5*fabs(pi))); } /* * we also need y' for the rightmost boundary; we use the * "simplest possibility" method described in the paper in * section 2.2 * * y' = s_{n-1} */ y_prime[size-1] = (y_array[size - 1] - y_array[size - 2]) / (x_array[size - 1] - x_array[size - 2]); /* Now we can calculate all the coefficients for the whole range. */ for (i = 0; i < (size - 1); i++) { double hi = (x_array[i+1] - x_array[i]); double si = (y_array[i+1] - y_array[i]) / hi; /* These are from equations 2-5 in the paper. */ a[i] = (y_prime[i] + y_prime[i+1] - 2*si) / hi / hi; b[i] = (3*si - 2*y_prime[i] - y_prime[i+1]) / hi; c[i] = y_prime[i]; d[i] = y_array[i]; } return GSL_SUCCESS; } static void steffen_free (void * vstate) { steffen_state_t *state = (steffen_state_t *) vstate; RETURN_IF_NULL(state); if (state->a) free (state->a); if (state->b) free (state->b); if (state->c) free (state->c); if (state->d) free (state->d); if (state->y_prime) free (state->y_prime); free (state); } static int steffen_eval (const void * vstate, const double x_array[], const double y_array[], size_t size, double x, gsl_interp_accel * a, double *y) { const steffen_state_t *state = (const steffen_state_t *) vstate; size_t index; if (a != 0) { index = gsl_interp_accel_find (a, x_array, size, x); } else { index = gsl_interp_bsearch (x_array, x, 0, size - 1); } /* evaluate */ { const double x_lo = x_array[index]; const double delx = x - x_lo; const double a = state->a[index]; const double b = state->b[index]; const double c = state->c[index]; const double d = state->d[index]; /* Use Horner's scheme for efficient evaluation of polynomials. */ /* *y = a*delx*delx*delx + b*delx*delx + c*delx + d; */ *y = d + delx*(c + delx*(b + delx*a)); return GSL_SUCCESS; } } static int steffen_eval_deriv (const void * vstate, const double x_array[], const double y_array[], size_t size, double x, gsl_interp_accel * a, double *dydx) { const steffen_state_t *state = (const steffen_state_t *) vstate; size_t index; /* DISCARD_POINTER(y_array); /\* prevent warning about unused parameter *\/ */ if (a != 0) { index = gsl_interp_accel_find (a, x_array, size, x); } else { index = gsl_interp_bsearch (x_array, x, 0, size - 1); } /* evaluate */ { double x_lo = x_array[index]; double delx = x - x_lo; double a = state->a[index]; double b = state->b[index]; double c = state->c[index]; /*double d = state->d[index];*/ /* *dydx = 3*a*delx*delx*delx + 2*b*delx + c; */ *dydx = c + delx*(2*b + delx*3*a); return GSL_SUCCESS; } } static int steffen_eval_deriv2 (const void * vstate, const double x_array[], const double y_array[], size_t size, double x, gsl_interp_accel * a, double *y_pp) { const steffen_state_t *state = (const steffen_state_t *) vstate; size_t index; /* DISCARD_POINTER(y_array); /\* prevent warning about unused parameter *\/ */ if (a != 0) { index = gsl_interp_accel_find (a, x_array, size, x); } else { index = gsl_interp_bsearch (x_array, x, 0, size - 1); } /* evaluate */ { const double x_lo = x_array[index]; const double delx = x - x_lo; const double a = state->a[index]; const double b = state->b[index]; *y_pp = 6*a*delx + 2*b; return GSL_SUCCESS; } } static int steffen_eval_integ (const void * vstate, const double x_array[], const double y_array[], size_t size, gsl_interp_accel * acc, double a, double b, double * result) { /* a and b are the boundaries of the integration. */ const steffen_state_t *state = (const steffen_state_t *) vstate; size_t i, index_a, index_b; /* Find the data points in the x_array that are nearest to the desired */ /* a and b integration boundaries. */ if (acc != 0) { index_a = gsl_interp_accel_find (acc, x_array, size, a); index_b = gsl_interp_accel_find (acc, x_array, size, b); } else { index_a = gsl_interp_bsearch (x_array, a, 0, size - 1); index_b = gsl_interp_bsearch (x_array, b, 0, size - 1); } *result = 0.0; /* Iterate over all the segments between data points and sum the */ /* contributions into result. */ for(i=index_a; i<=index_b; i++) { const double x_hi = x_array[i + 1]; const double x_lo = x_array[i]; const double dx = x_hi - x_lo; if(dx != 0.0) { /* * check if we are at a boundary point, so take the * a and b parameters instead of the data points. */ double x1 = (i == index_a) ? a-x_lo : 0.0; double x2 = (i == index_b) ? b-x_lo : x_hi-x_lo; *result += (1.0/4.0)*state->a[i]*(x2*x2*x2*x2 - x1*x1*x1*x1) +(1.0/3.0)*state->b[i]*(x2*x2*x2 - x1*x1*x1) +(1.0/2.0)*state->c[i]*(x2*x2 - x1*x1) +state->d[i]*(x2-x1); } else /* if the interval was zero, i.e. consecutive x values in data. */ { *result = 0.0; return GSL_EINVAL; } } return GSL_SUCCESS; } static double steffen_copysign(const double x, const double y) { if ((x < 0 && y > 0) || (x > 0 && y < 0)) return -x; return x; } static const gsl_interp_type steffen_type = { "steffen", 3, &steffen_alloc, &steffen_init, &steffen_eval, &steffen_eval_deriv, &steffen_eval_deriv2, &steffen_eval_integ, &steffen_free }; const gsl_interp_type * gsl_interp_steffen = &steffen_type;
{ "alphanum_fraction": 0.6018108264, "avg_line_length": 26.826873385, "ext": "c", "hexsha": "1c9ce1046c0d21cf9778dba690c3824e4da8d8b2", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/steffen.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/steffen.c", "max_line_length": 81, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/interpolation/steffen.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 3053, "size": 10382 }
#include <Python.h> #include <numpy/arrayobject.h> #include <gsl/gsl_linalg.h> #include <sys/time.h> #define ARRAYD(p) ((double *) (((PyArrayObject *)p)->data)) /* * [INITIALIZATION] * ------------------ PROTOTYPES FOR FUNCTIONS AND EXTERNAL VARIABLES ----------------------- * */ int CheckAperture(double* center, int len_rows, int len_cen, double S, int CentralAperture); double Polyval(double x,double* coeffs, int len_coeffs); double** MakeArray(int rows, int columns); /* Function that makes/allocates an array of pointers */ double* MakeVector(int nelements); /* Function that makes/allocates a pointer in memory */ double* RangeDetector(double *v,double C,double S,int len_v,int K,int len_rows,int len_cols,int range); /* Detects the range of the calculations */ double* SimpleRangeDetector(double *v,double Length,int len_v,int len_rows,int len_cols,int range); void FreeArray(double** theArray,int rows); /* Function that frees an array of pointers from memory */ void PixelResampling(double** A,double* pmin,double* pmax,int len_cols); /* Algorithm for pixel resampling */ void BPixelResampling(double** A,double** B,double* pmin,double* pmax,int len_cols); /* Algorithm for pixel resampling */ void SimplePixelResampling(double** A,double* pmin,double* pmax,int len_cols); void LinearSolver(double** A,double* b,double* x,int length); /* Linear-algebra system solver (returns the solution in the x vector) */ double** getQ(double *v,double C,double S,int len_v,int K,int len_cols,int range,double* pmin,double* pmax,int mode); /* Function that gets the Q values (returns a matrix) */ void getJ(double** J,int N,int len_cols); /* Function that calculates the powers of j, the columns */ void getC(double** A,double** Q,double** VarE,double** C_qp,double** J,double* pmin,double* pmax,int K,int N,int len_cols); /* Function that gets the C values (For the L.S.) */ void getX(double** A,double** Q,double** E,double** VarE,double* X,double** J,double* pmin,double* pmax,int K,int N,int len_cols); /* Function that gets the X values */ void getP(double* B,double** Q,double** P,double** J,double* pmin,double* pmax,int K,int N,int len_rows,int len_cols,int mode); /* Computes the light fraction matrix (matrix) */ void getRowSum(double** A,double* RS,double *v,double* pmin,double* pmax,int len_cols,int len_v); /* Computes the sum of the vertical elements in a row */ void getE(double** A,double* RS,double** E,double* pmin,double* pmax,double *v,int len_rows,int len_cols); /* Computes the light fraction estimates E_{ij} */ void getVarRowSum(double** A,double** V,double* VarRS,double* pmin,double* pmax,double RON,double GAIN,int len_cols); /* Same as RowSum but for variances */ void getVarE(double** A,double** E,double* RS,double* VarRS,double** VarE,double** V,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols); /* Same as E for Var(E) */ double CalculateQ(double *v,int k,int i,int j,double C,double S,int len_v,int range); /* Calculates the value of Q for given parameters */ double CalculateC(double** A,double** Q,double** VarE,int m, int l, int n, int k,double** J,double* pmin,double* pmax,int len_cols); /* Same as above for C */ double CalculateX(double** A,double** Q,double** E,double** VarE,int n, int k,double** J,double* pmin,double* pmax,int len_cols); /* Same as above for X */ double Trace(int x,double *v,int len_v,int range); /* Computes the trace for a given value of x */ void getMinMax(double* pmin,double* pmax,double *v,double C, double S,int K,int len_v,int len_cols,int range); void getSimpleMinMax(double* pmin,double* pmax,double *v,int len_v,int len_cols,int range,double Length); double** MarshIteration(double** M,double** VarImage,double* pmin,double* pmax,double *v,double C,double S,double RON,double GAIN,int len_v,int len_rows,int len_cols,int N,int K,int mode,int range,int debug,double NSigma,int isvarimage); /* Function that iterates the whole Marsh's algorithm */ double** Transpose(double** O,int rowsIN, int colsIN); /* Function that obtains the tranpose of a matrix */ void Renormalize(double** P,double* pmin,double* pmax,int len_rows,int len_cols); void VarRevision(double** A,double** VarImage,double** V,double* RS,double** P,double* pmin,double* pmax,int len_cols,double RON,double GAIN,int isvarimage); /* Function that revise the variance estimates */ int OutlierRejection(double** A,double** V,double** P,double** E,double** VarE,double* RS,double* pmin,double* pmax,double NSigma,int len_cols,int debug); /* Out. Rej. algorithm */ double** getSpectrum(double** A,double** VarImage,double** P,double *v,int len_v,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols,double CosmicSigma,int debug,int isvarimage); /* Function that returns the 1-D spectrum matrix given P. The first row of the matrix are the pixel values in matrix coordinates (lambda), the second row is F_{lambda} and the third is var(F_{lambda}) */ double** BgetSpectrum(double** A,double** B,double** P,double *v,int len_v,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols,double CosmicSigma,int debug); /* Function that returns the 1-D spectrum matrix given P. The first row of the matrix are the pixel values in matrix coordinates (lambda), the second row is F_{lambda} and the third is var(F_{lambda}) */ void getImageVariances(double** A,double** V,double** VarImage,double* pmin,double* pmax,double RON,double GAIN,int len_cols,int isvarimage); /* Function that returns a matrix with the values of the initial variances in each pixel */ void getRowSumW(double** A,double** V,double** P,double* pmin,double* pmax,double* RSW,int len_cols); /* Function that returns the denominator in eq. (4) of Marsh (1989) */ void getW(double** A,double** P,double** V,double* RSW,double** W,double* pmin,double* pmax,int len_cols); /* Function that returns the weigths for the weighted averaged spectra */ void getF(double** W,double** A,double* F,double* pmin,double* pmax,int len_cols); /* Vector containing the fluxes calculated from the weighted average */ void getBF(double** W,double** B,double* BF,double* pmin,double* pmax,int len_cols); /* Vector containing the fluxes calculated from the weighted average */ void getVarF(double** A,double** W,double** V,double* VarF,double* pmin,double* pmax,int len_cols); /* Vector containing the variances of fluxes calculated from the weighted average */ int CosmicRayRejection(double** A,double** V,double** P,double* F,double* VarF,double CosmicSigma,double* pmin,double* pmax,int len_cols,int debug); /* Cosmic Rays rejection algorithm */ int BCosmicRayRejection(double** A,double** B,double** V,double** P,double* F,double* VarF,double CosmicSigma,double* pmin,double* pmax,int len_cols,int debug); /* Cosmic Rays rejection algorithm */ /* [INITIALIZATION OF A METHOD] *------------------------THE OBTAINP METHOD----------------------------- * PyObject initialization: We define a PyObject which defines a Method * for the Marsh module: The ObtainP method which returns the P[i][j] spatial * light fractions back to Python. BE CAREFUL WITH THE INDEXES, remember * that i=rows, j=columns. According to Marsh's (1989) variables, j=X and * i=Y. *---------------------------------------------------------------------- */ static PyObject *Marsh_ObtainP(PyObject *self, PyObject *args){ struct timeval tim; gettimeofday(&tim, NULL); double t1=tim.tv_sec+(tim.tv_usec/1000000.0); double *m,dvalue=0; double *v,*pmin,*pmax; // pmin,pmax: FREED (on the MarshIteration function) double C,S,Length,RON,GAIN,NSigma; int len_v,K,N,len_cols,len_rows,mode,range=-1,debug,isvarimage=0; int i,j,real_cols,real_rows,col_min,col_max; PyObject *marray, *varray; /* *--------------------------------THE DATA--------------------------------------- * After initialization of the PyObject pointers, we wish to recover the following inputs: * * marray: Vector of the flattened-matrix of the Echelle Spectra data. * * varray: Vector containing the coefficients of the trace of the spectrum. * * len_rows: Length of the rows of the flattened-matrix. * * len_cols: Length of the columns of the flattened-matrix. * * len_v: Length of the coefficient-vector. * * Length: Given that the trace is centered on the spectrum, Length gives the length, * in pixels from the center, where we'll consider the spectrum. * * RON: The Read Out Noise of our measurements in electrons. * * GAIN: The Gain of the detector, in electrons/ADU. * * mode: Set this to 0 to apply Marsh's Algorithm (curved trace) to the data. * Set this to 1 to apply Horne's Algorithm (trace paralell to the rows) to the data. * * ------------------------------------------------------------------------------ */ PyArg_ParseTuple(args,"OOiiidddddiiii",&marray,&varray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&NSigma,&S,&N,&mode,&col_min,&col_max); if(col_min!=0){ col_min=col_min+1; } if(col_max!=0){ col_max=col_max-1; } debug=0; m = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */ v = ARRAYD(varray); real_cols=len_cols; real_rows=len_rows; if(mode!=0) S=1.0; /* If Horne's algorithm is used, the spacing between polynomials is 1 */ Length = CheckAperture(v, len_rows, len_v, S, Length); K=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S polynomials, rounding the decimal number, from the center. Then we multiply this number by 2 (to get the total number of polynomials up and down the center) and add 1 to get the middle polynomial (the one corresponding to the center). */ if(debug!=0){ printf("Number of polynomial to fit: %d \n",K); } C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number is the polynomial number of the center. */ double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting and final column pixels that "swims in" and "out" of the image, respectively (FREED here, later). */ if(debug!=0){ printf("Range[0]: %f\n",Range[0]); printf("Range[1]: %f\n",Range[1]); printf("len_cols=%d, len_rows=%d \n",len_cols,len_rows); } range=Range[0]; if(Range[0]!=-1){ if(col_min==0 && col_max==0){ len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a cutted image */ } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ if(Range[0]>=col_min && Range[1]<=col_max){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]<=col_max){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]>col_max){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(Range[0]>=col_min && Range[1]>col_max){ Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } } else if(col_min!=0 && col_max==0){ if(Range[0]>=col_min){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } } } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(col_min!=0 && col_max==0){ range=col_min; Range[0]=col_min; Range[1]=len_cols-1; len_cols=Range[1]-Range[0]+1; } double** M = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (FREED on MarshIt.) */ double** DummyM = MakeArray(len_rows,len_cols); /* This is just a dummy array to be consistent with the variance image */ if(Range[0]==-1){ for(i=0;i<len_rows;i++){ /* If the column doesn't present problems, proceed as usual */ for(j=0;j<len_cols;j++){ M[i][j]=m[i*real_cols+j]-dvalue; DummyM[i][j]=m[i*real_cols+j]-dvalue; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ M[i][j-range]=m[i*real_cols+j]-dvalue; DummyM[i][j-range]=m[i*real_cols+j]-dvalue; } } } /* Start of the Marsh's Algorithm iteration: */ pmin=MakeVector(len_cols); pmax=MakeVector(len_cols); getMinMax(pmin,pmax,v,C,S,K,len_v,len_cols,range); double** PF = MarshIteration(Transpose(M,len_rows,len_cols),Transpose(DummyM,len_rows,len_cols),pmin,pmax,v,C,S,RON,GAIN,len_v,len_rows,len_cols,N,K,mode,range,debug,NSigma,isvarimage); // FREED (here, later). double** PFinal = MakeArray(real_rows,real_cols); // FREED (here, later). if(Range[0]==-1){ for(i=0;i<len_rows;i++){ for(j=0;j<len_cols;j++){ PFinal[i][j]=PF[i][j]; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ PFinal[i][j]=PF[i][j-range]; } } len_cols=real_cols; } FreeArray(PF,len_rows); gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); if(debug!=0){ printf("%2.2lf seconds elapsed\n", t2-t1); } // /* End of the Marsh's Algorithm iteration! */ // // /* Start of the matrix-to-vector conversion part of the code */ double* theArray; // FREED (here, later). theArray = (double*) malloc((len_cols*len_rows)*sizeof(double)); for(i=0;i<len_rows;i++){ for(j=0;j<len_cols;j++){ theArray[i*len_cols+j]=PFinal[i][j]; if(PFinal[i][j]>1){ theArray[i*len_cols+j]=0; } } } FreeArray(PFinal,len_rows); free(Range); /* End of the matrix-to-vector conversion part of the code. Everything's ok up to here...now I have my theArray[i][j] array (matrix) ready to be called...*/ /* Finally, we create a Python "Object" List that contains the P coefficients and return it back to Python */ PyObject *lst = PyList_New(len_rows*len_cols); PyObject *num; if (!lst) return NULL; for (i = 0; i < len_rows*len_cols; i++) { num=PyFloat_FromDouble(theArray[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); } free(theArray); PyObject *MyResult = Py_BuildValue("O",lst); Py_DECREF(lst); return MyResult; } /* [INITIALIZATION OF A METHOD] * ------------------------THE OBTAINSpectrum METHOD----------------------------- */ static PyObject *Marsh_ObtainSpectrum(PyObject *self, PyObject *args){ struct timeval tim; gettimeofday(&tim, NULL); int i,j,real_cols,real_rows,col_min,col_max; double t1=tim.tv_sec+(tim.tv_usec/1000000.0),dvalue=0; double *mflat,*pflat; double *v,*pmin,*pmax; // (pmin,pmax) freed here, later. double Length,RON,GAIN,CosmicSigma,S,C; int len_v,len_cols,len_rows,K,range=-1,debug,isvarimage=0; PyObject *parray, *marray,*varray; /* *--------------------------------THE DATA--------------------------------------- * After initialization of the PyObject pointers, we wish to recover the following inputs: * * marray: Vector of the flattened-matrix of the Echelle Spectra data. * * varray: Vector containing the coefficients of the trace of the spectrum. * * parray: Vector of the flattened-matrix of the Echelle Spectra P_{ij} coefficents. * * len_rows: Length of the rows of the flattened-matrix. * * len_cols: Length of the columns of the flattened-matrix. * * len_v: Length of the coefficient-vector. * * Length: Aperture to be used in the obtention of the spectrum. * * RON: The Read Out Noise of our measurements. * * GAIN: The Gain of the detector, in electrons/ADU. * * S: Spacing of the polynomials obtained in the ObtainP function. * * CosmicSigma: Number of times sigma is multiplied by to reject Cosmic Rays. * * ------------------------------------------------------------------------------ */ PyArg_ParseTuple(args,"OOOiiidddddii",&marray,&varray,&parray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&S,&CosmicSigma,&col_min,&col_max); if(col_min!=0){ col_min=col_min+1; } if(col_max!=0){ col_max=col_max-1; } debug=0; pflat = ARRAYD(parray); /* We convert our PyObject struct pointers to C-vector array */ mflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */ v = ARRAYD(varray); real_cols=len_cols; real_rows=len_rows; Length = CheckAperture(v, len_rows, len_v, S, Length); /* Start of the algorithm for the spectrum obtention (faster with the transpose!): */ K=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S polynomials, rounding the decimal number, from the center. Then we multiply this number by 2 (to get the total number of polynomials up and down the center) and add 1 to get the middle polynomial (the one corresponding to the center). */ C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number is the polynomial number of the center. */ range=0; double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting and final column pixels that "swims in" and "out" of the image, respectively (FREED here) */ range=Range[0]; if(debug!=0){ printf("Range[0]: %f\n",Range[0]); printf("Range[1]: %f\n",Range[1]); dvalue=1018.0; } if(Range[0]!=-1){ if(col_min==0 && col_max==0){ len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a cutted image */ } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ if(Range[0]>=col_min && Range[1]<=col_max){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]<=col_max){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]>col_max){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(Range[0]>=col_min && Range[1]>col_max){ Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } } else if(col_min!=0 && col_max==0){ if(Range[0]>=col_min){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } } } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(col_min!=0 && col_max==0){ range=col_min; Range[0]=col_min; Range[1]=len_cols-1; len_cols=Range[1]-Range[0]+1; } double** M = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (FREED on getSpectrum) */ double** P = MakeArray(len_rows,len_cols); /* Create a matrix array for our P's (FREED on getSpectrum) */ double** DummyM = MakeArray(len_rows,len_cols); if(Range[0]==-1){ for(i=0;i<len_rows;i++){ /* If the column doesn't present problems, proceed as usual */ for(j=0;j<len_cols;j++){ M[i][j]=mflat[i*real_cols+j]-dvalue; DummyM[i][j]=mflat[i*real_cols+j]-dvalue; P[i][j]=pflat[i*real_cols+j]; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ M[i][j-range]=mflat[i*real_cols+j]-dvalue; DummyM[i][j-range]=mflat[i*real_cols+j]-dvalue; P[i][j-range]=pflat[i*real_cols+j]; } } } pmin=MakeVector(len_cols); pmax=MakeVector(len_cols); getMinMax(pmin,pmax,v,C,S,K,len_v,len_cols,range); double** Spectrum=getSpectrum(Transpose(M,len_rows,len_cols),Transpose(DummyM,len_rows,len_cols),Transpose(P,len_rows,len_cols),v,len_v,pmin,pmax,RON,GAIN,len_rows,len_cols,CosmicSigma,debug,isvarimage); // FREED (here, later) gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); if(debug!=0){ printf("%2.2lf seconds elapsed\n", t2-t1); } /* End of the algorithm */ double* theArray; // FREED (here, later) theArray = (double*) malloc((real_cols*3)*sizeof(double)); for(i=0;i<3;i++){ for(j=0;j<real_cols;j++){ if(range==-1){ theArray[i*real_cols+j]=Spectrum[i][j]; } else if(range!=-1 && i==0){ theArray[i*real_cols+j]=j; } else if(range!=-1 && i!=0){ if(j<Range[0] || j>Range[1]) theArray[i*real_cols+j]=0; else theArray[i*real_cols+j]=Spectrum[i][j-range]; } } } FreeArray(Spectrum,3); free(Range); /* Finally, we create a Python "Object" List that contains the P coefficients and return it back to Python */ PyObject *lst = PyList_New(real_cols*3); if (!lst) return NULL; for (i = 0; i < 3*real_cols; i++) { PyObject *num = PyFloat_FromDouble(theArray[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); } free(theArray); free(pmin); free(pmax); PyObject *MyResult = Py_BuildValue("Oi",lst,real_cols); Py_DECREF(lst); return MyResult; } /* [INITIALIZATION OF A METHOD] *------------------------THE SOBTAINP METHOD----------------------------- * PyObject initialization: We define a PyObject which defines a Method * for the Marsh module: The ObtainP method which returns the P[i][j] spatial * light fractions back to Python. BE CAREFUL WITH THE INDEXES, remember * that i=rows, j=columns. According to Marsh's (1989) variables, j=X and * i=Y. *---------------------------------------------------------------------- */ static PyObject *Marsh_SObtainP(PyObject *self, PyObject *args){ struct timeval tim; gettimeofday(&tim, NULL); double t1=tim.tv_sec+(tim.tv_usec/1000000.0); double *m,*varianceimage,*bimage,dvalue=0; double *v,*pmin,*pmax; // pmin,pmax: FREED (on the MarshIteration function) double C,S,Length,RON,GAIN,NSigma; int len_v,K,N,len_cols,len_rows,mode,range=-1,debug,isvarimage=1; int i,j,real_cols,real_rows,col_min,col_max; PyObject *marray, *varray,*vararray,*barray; /* *--------------------------------THE DATA--------------------------------------- * After initialization of the PyObject pointers, we wish to recover the following inputs: * * marray: Vector of the flattened-matrix of the Echelle Spectra data. * * varray: Vector containing the coefficients of the trace of the spectrum. * * len_rows: Length of the rows of the flattened-matrix. * * len_cols: Length of the columns of the flattened-matrix. * * len_v: Length of the coefficient-vector. * * Length: Given that the trace is centered on the spectrum, Length gives the length, * in pixels from the center, where we'll consider the spectrum. * * RON: The Read Out Noise of our measurements in electrons. * * GAIN: The Gain of the detector, in electrons/ADU. * * mode: Set this to 0 to apply Marsh's Algorithm (curved trace) to the data. * Set this to 1 to apply Horne's Algorithm (trace paralell to the rows) to the data. * * ------------------------------------------------------------------------------ */ PyArg_ParseTuple(args,"OOOOiiidddddiiii",&marray,&barray,&vararray,&varray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&NSigma,&S,&N,&mode,&col_min,&col_max); if(col_min!=0){ col_min=col_min+1; } if(col_max!=0){ col_max=col_max-1; } debug=0; m = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */ v = ARRAYD(varray); varianceimage = ARRAYD(vararray); bimage = ARRAYD(barray); real_cols=len_cols; real_rows=len_rows; if(mode!=0) S=1.0; /* If Horne's algorithm is used, the spacing between polynomials is 1 */ Length = CheckAperture(v, len_rows, len_v, S, Length); K=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S polynomials, rounding the decimal number, from the center. Then we multiply this number by 2 (to get the total number of polynomials up and down the center) and add 1 to get the middle polynomial (the one corresponding to the center). */ if(debug!=0){ printf("Number of polynomial to fit: %d \n",K); dvalue=1018.0; } C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number is the polynomial number of the center. */ double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting and final column pixels that "swims in" and "out" of the image, respectively (FREED here, later). */ if(debug!=0){ printf("Range[0]: %f\n",Range[0]); printf("Range[1]: %f\n",Range[1]); printf("len_cols=%d, len_rows=%d \n",len_cols,len_rows); } range=Range[0]; if(Range[0]!=-1){ if(col_min==0 && col_max==0){ len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a cutted image */ } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ if(Range[0]>=col_min && Range[1]<=col_max){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]<=col_max){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]>col_max){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(Range[0]>=col_min && Range[1]>col_max){ Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } } else if(col_min!=0 && col_max==0){ if(Range[0]>=col_min){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } } } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(col_min!=0 && col_max==0){ range=col_min; Range[0]=col_min; Range[1]=len_cols-1; len_cols=Range[1]-Range[0]+1; } double** M = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (FREED on MarshIt.) */ double** Var = MakeArray(len_rows,len_cols); if(Range[0]==-1){ for(i=0;i<len_rows;i++){ /* If the column doesn't present problems, proceed as usual */ for(j=0;j<len_cols;j++){ if(bimage[i*real_cols+j]==1){ M[i][j]=m[i*real_cols+j]-dvalue; } else{ M[i][j]=-9999; } Var[i][j]=varianceimage[i*real_cols+j]; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ if(bimage[i*real_cols+j]==1){ M[i][j-range]=m[i*real_cols+j]-dvalue; } else{ M[i][j-range]=-9999; } Var[i][j-range]=varianceimage[i*real_cols+j]; } } } /* Start of the Marsh's Algorithm iteration: */ pmin=MakeVector(len_cols); pmax=MakeVector(len_cols); getMinMax(pmin,pmax,v,C,S,K,len_v,len_cols,range); double** PF = MarshIteration(Transpose(M,len_rows,len_cols),Transpose(Var,len_rows,len_cols),pmin,pmax,v,C,S,RON,GAIN,len_v,len_rows,len_cols,N,K,mode,range,debug,NSigma,isvarimage); // FREED (here, later). double** PFinal = MakeArray(real_rows,real_cols); // FREED (here, later). if(Range[0]==-1){ for(i=0;i<len_rows;i++){ for(j=0;j<len_cols;j++){ PFinal[i][j]=PF[i][j]; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ PFinal[i][j]=PF[i][j-range]; } } len_cols=real_cols; } FreeArray(PF,len_rows); gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); if(debug!=0){ printf("%2.2lf seconds elapsed\n", t2-t1); } // /* End of the Marsh's Algorithm iteration! */ // // /* Start of the matrix-to-vector conversion part of the code */ double* theArray; // FREED (here, later). theArray = (double*) malloc((len_cols*len_rows)*sizeof(double)); for(i=0;i<len_rows;i++){ for(j=0;j<len_cols;j++){ theArray[i*len_cols+j]=PFinal[i][j]; if(PFinal[i][j]>1){ theArray[i*len_cols+j]=0; } } } FreeArray(PFinal,len_rows); free(Range); /* End of the matrix-to-vector conversion part of the code. Everything's ok up to here...now I have my theArray[i][j] array (matrix) ready to be called...*/ /* Finally, we create a Python "Object" List that contains the P coefficients and return it back to Python */ PyObject *lst = PyList_New(len_rows*len_cols); PyObject *num; if (!lst) return NULL; for (i = 0; i < len_rows*len_cols; i++) { num=PyFloat_FromDouble(theArray[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); } free(theArray); PyObject *MyResult = Py_BuildValue("O",lst); Py_DECREF(lst); return MyResult; } /* [INITIALIZATION OF A METHOD] * ------------------------THE SOBTAINSpectrum METHOD----------------------------- */ static PyObject *Marsh_SObtainSpectrum(PyObject *self, PyObject *args){ struct timeval tim; gettimeofday(&tim, NULL); int i,j,real_cols,real_rows,col_min,col_max; double t1=tim.tv_sec+(tim.tv_usec/1000000.0),dvalue=0; double *mflat,*varflat,*pflat,*bflat; double *v,*pmin,*pmax; // (pmin,pmax) freed here, later. double Length,RON,GAIN,CosmicSigma,S,C; int len_v,len_cols,len_rows,K,range=-1,debug,isvarimage=1; PyObject *parray, *marray,*varray,*vararray,*barray; /* *--------------------------------THE DATA--------------------------------------- * After initialization of the PyObject pointers, we wish to recover the following inputs: * * marray: Vector of the flattened-matrix of the Echelle Spectra data. * * varray: Vector containing the coefficients of the trace of the spectrum. * * parray: Vector of the flattened-matrix of the Echelle Spectra P_{ij} coefficents. * * len_rows: Length of the rows of the flattened-matrix. * * len_cols: Length of the columns of the flattened-matrix. * * len_v: Length of the coefficient-vector. * * Length: Aperture to be used in the obtention of the spectrum. * * RON: The Read Out Noise of our measurements. * * GAIN: The Gain of the detector, in electrons/ADU. * * S: Spacing of the polynomials obtained in the ObtainP function. * * CosmicSigma: Number of times sigma is multiplied by to reject Cosmic Rays. * * ------------------------------------------------------------------------------ */ PyArg_ParseTuple(args,"OOOOOiiidddddii",&marray,&barray,&vararray,&varray,&parray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&S,&CosmicSigma,&col_min,&col_max); if(col_min!=0){ col_min=col_min+1; } if(col_max!=0){ col_max=col_max-1; } debug=0; pflat = ARRAYD(parray); /* We convert our PyObject struct pointers to C-vector array */ mflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */ varflat = ARRAYD(vararray); bflat = ARRAYD(barray); v = ARRAYD(varray); real_cols=len_cols; real_rows=len_rows; Length = CheckAperture(v, len_rows, len_v, S, Length); /* Start of the algorithm for the spectrum obtention (faster with the transpose!): */ K=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S polynomials, rounding the decimal number, from the center. Then we multiply this number by 2 (to get the total number of polynomials up and down the center) and add 1 to get the middle polynomial (the one corresponding to the center). */ C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number is the polynomial number of the center. */ range=0; double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting and final column pixels that "swims in" and "out" of the image, respectively (FREED here) */ range=Range[0]; if(debug!=0){ printf("Range[0]: %f\n",Range[0]); printf("Range[1]: %f\n",Range[1]); dvalue=1018.0; } if(Range[0]!=-1){ if(col_min==0 && col_max==0){ len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a cutted image */ } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ if(Range[0]>=col_min && Range[1]<=col_max){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]<=col_max){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]>col_max){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(Range[0]>=col_min && Range[1]>col_max){ Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } } else if(col_min!=0 && col_max==0){ if(Range[0]>=col_min){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } } } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(col_min!=0 && col_max==0){ range=col_min; Range[0]=col_min; Range[1]=len_cols-1; len_cols=Range[1]-Range[0]+1; } double** M = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (FREED on getSpectrum) */ double** P = MakeArray(len_rows,len_cols); /* Create a matrix array for our P's (FREED on getSpectrum) */ double** Var = MakeArray(len_rows,len_cols); if(Range[0]==-1){ for(i=0;i<len_rows;i++){ /* If the column doesn't present problems, proceed as usual */ for(j=0;j<len_cols;j++){ if(bflat[i*real_cols+j]==1){ M[i][j]=mflat[i*real_cols+j]-dvalue; } else{ M[i][j]=-9999; } P[i][j]=pflat[i*real_cols+j]; Var[i][j]=varflat[i*real_cols+j]; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ if(bflat[i*real_cols+j]==1){ M[i][j-range]=mflat[i*real_cols+j]-dvalue; } else{ M[i][j-range]=-9999; } P[i][j-range]=pflat[i*real_cols+j]; Var[i][j-range]=varflat[i*real_cols+j]; } } } pmin=MakeVector(len_cols); pmax=MakeVector(len_cols); getMinMax(pmin,pmax,v,C,S,K,len_v,len_cols,range); double** Spectrum=getSpectrum(Transpose(M,len_rows,len_cols),Transpose(Var,len_rows,len_cols),Transpose(P,len_rows,len_cols),v,len_v,pmin,pmax,RON,GAIN,len_rows,len_cols,CosmicSigma,debug,isvarimage); // FREED (here, later) gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); if(debug!=0){ printf("%2.2lf seconds elapsed\n", t2-t1); } /* End of the algorithm */ double* theArray; // FREED (here, later) theArray = (double*) malloc((real_cols*3)*sizeof(double)); for(i=0;i<3;i++){ for(j=0;j<real_cols;j++){ if(range==-1){ theArray[i*real_cols+j]=Spectrum[i][j]; } else if(range!=-1 && i==0){ theArray[i*real_cols+j]=j; } else if(range!=-1 && i!=0){ if(j<Range[0] || j>Range[1]) theArray[i*real_cols+j]=0; else theArray[i*real_cols+j]=Spectrum[i][j-range]; } } } FreeArray(Spectrum,3); free(Range); /* Finally, we create a Python "Object" List that contains the P coefficients and return it back to Python */ PyObject *lst = PyList_New(real_cols*3); if (!lst) return NULL; for (i = 0; i < 3*real_cols; i++) { PyObject *num = PyFloat_FromDouble(theArray[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); } free(theArray); free(pmin); free(pmax); PyObject *MyResult = Py_BuildValue("Oi",lst,real_cols); Py_DECREF(lst); return MyResult; } static PyObject *Marsh_BObtainSpectrum(PyObject *self, PyObject *args){ struct timeval tim; gettimeofday(&tim, NULL); int i,j,real_cols,real_rows,col_min,col_max; double t1=tim.tv_sec+(tim.tv_usec/1000000.0),dvalue=0; double *mflat,*pflat,*bflat; double *v,*pmin,*pmax; // (pmin,pmax) freed here, later. double Length,RON,GAIN,CosmicSigma,S,C; int len_v,len_cols,len_rows,K,range=-1,debug; PyObject *parray, *marray,*varray,*barray; /* *--------------------------------THE DATA--------------------------------------- * After initialization of the PyObject pointers, we wish to recover the following inputs: * * marray: Vector of the flattened-matrix of the Echelle Spectra data. * * varray: Vector containing the coefficients of the trace of the spectrum. * * parray: Vector of the flattened-matrix of the Echelle Spectra P_{ij} coefficents. * * len_rows: Length of the rows of the flattened-matrix. * * len_cols: Length of the columns of the flattened-matrix. * * len_v: Length of the coefficient-vector. * * Length: Aperture to be used in the obtention of the spectrum. * * RON: The Read Out Noise of our measurements. * * GAIN: The Gain of the detector, in electrons/ADU. * * S: Spacing of the polynomials obtained in the ObtainP function. * * CosmicSigma: Number of times sigma is multiplied by to reject Cosmic Rays. * * ------------------------------------------------------------------------------ */ PyArg_ParseTuple(args,"OOOOiiidddddii",&marray,&varray,&parray,&barray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&S,&CosmicSigma,&col_min,&col_max); if(col_min!=0){ col_min=col_min+1; } if(col_max!=0){ col_max=col_max-1; } debug=0; pflat = ARRAYD(parray); /* We convert our PyObject struct pointers to C-vector array */ mflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */ bflat = ARRAYD(barray); /* We convert our PyObject struct pointers to C-vector array */ v = ARRAYD(varray); real_cols=len_cols; real_rows=len_rows; Length = CheckAperture(v, len_rows, len_v, S, Length); /* Start of the algorithm for the spectrum obtention (faster with the transpose!): */ K=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S polynomials, rounding the decimal number, from the center. Then we multiply this number by 2 (to get the total number of polynomials up and down the center) and add 1 to get the middle polynomial (the one corresponding to the center). */ C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number is the polynomial number of the center. */ range=0; double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting and final column pixels that "swims in" and "out" of the image, respectively (FREED here) */ range=Range[0]; if(debug!=0){ printf("Range[0]: %f\n",Range[0]); printf("Range[1]: %f\n",Range[1]); dvalue=0.0; } if(Range[0]!=-1){ if(col_min==0 && col_max==0){ len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a cutted image */ } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ if(Range[0]>=col_min && Range[1]<=col_max){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]<=col_max){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]>col_max){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(Range[0]>=col_min && Range[1]>col_max){ Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } } else if(col_min!=0 && col_max==0){ if(Range[0]>=col_min){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } } } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(col_min!=0 && col_max==0){ range=col_min; Range[0]=col_min; Range[1]=len_cols-1; len_cols=Range[1]-Range[0]+1; } double** M = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (FREED on getSpectrum) */ double** B = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (FREED on getSpectrum) */ double** P = MakeArray(len_rows,len_cols); /* Create a matrix array for our P's (FREED on getSpectrum) */ if(Range[0]==-1){ for(i=0;i<len_rows;i++){ /* If the column doesn't present problems, proceed as usual */ for(j=0;j<len_cols;j++){ M[i][j]=mflat[i*real_cols+j]-dvalue; B[i][j]=bflat[i*real_cols+j]; P[i][j]=pflat[i*real_cols+j]; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ M[i][j-range]=mflat[i*real_cols+j]-dvalue; B[i][j-range]=bflat[i*real_cols+j]; P[i][j-range]=pflat[i*real_cols+j]; } } } pmin=MakeVector(len_cols); pmax=MakeVector(len_cols); getMinMax(pmin,pmax,v,C,S,K,len_v,len_cols,range); double** Spectrum=BgetSpectrum(Transpose(M,len_rows,len_cols),Transpose(B,len_rows,len_cols),Transpose(P,len_rows,len_cols),v,len_v,pmin,pmax,RON,GAIN,len_rows,len_cols,CosmicSigma,debug); // FREED (here, later) gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); if(debug!=0){ printf("%2.2lf seconds elapsed\n", t2-t1); } /* End of the algorithm */ double* theArray; // FREED (here, later) theArray = (double*) malloc((real_cols*4)*sizeof(double)); for(i=0;i<4;i++){ for(j=0;j<real_cols;j++){ if(range==-1){ theArray[i*real_cols+j]=Spectrum[i][j]; } else if(range!=-1 && i==0){ theArray[i*real_cols+j]=j; } else if(range!=-1 && i!=0){ if(j<Range[0] || j>Range[1]) theArray[i*real_cols+j]=0; else theArray[i*real_cols+j]=Spectrum[i][j-range]; } } } FreeArray(Spectrum,4); free(Range); /* Finally, we create a Python "Object" List that contains the P coefficients and return it back to Python */ PyObject *lst = PyList_New(real_cols*4); if (!lst) return NULL; for (i = 0; i < 4*real_cols; i++) { PyObject *num = PyFloat_FromDouble(theArray[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); } free(theArray); free(pmin); free(pmax); PyObject *MyResult = Py_BuildValue("Oi",lst,real_cols); Py_DECREF(lst); return MyResult; } static PyObject *Marsh_SimpleExtraction(PyObject *self, PyObject *args){ struct timeval tim; gettimeofday(&tim, NULL); int i,j,real_cols,debug=0,col_min,col_max; double t1=tim.tv_sec+(tim.tv_usec/1000000.0),vMin,vMax,dvalue=0; double *mflat; double *v; double Length,C,S; int len_v,len_cols,len_rows,K,range; PyObject *marray,*varray; /* *--------------------------------THE DATA--------------------------------------- * After initialization of the PyObject pointers, we wish to recover the following inputs: * * marray: Vector of the flattened-matrix of the Echelle Spectra data. * * varray: Vector containing the coefficients of the trace of the spectrum. * * len_rows: Length of the rows of the flattened-matrix. * * len_cols: Length of the columns of the flattened-matrix. * * len_v: Length of the coefficient-vector. * * Length: Aperture (in pixels) to be taken from the center to cover the entire spectrum. * * ------------------------------------------------------------------------------ */ PyArg_ParseTuple(args,"OOiiidii",&marray,&varray,&len_rows,&len_cols,&len_v,&Length,&col_min,&col_max); if(col_min!=0){ col_min=col_min+1; } if(col_max!=0){ col_max=col_max-1; } range=0; mflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */ v = ARRAYD(varray); real_cols=len_cols; S=1.0; Length = CheckAperture(v, len_rows, len_v, S, Length); K=(int)(2*(int)((Length/S))+1); C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number is the polynomial number of the center. */ double* Range = SimpleRangeDetector(v,Length,len_v,len_rows,len_cols,range); /* This vector containts the detected starting and final column pixels that "swims in" and "out" of the image, respectively (F) */ range=Range[0]; if(debug!=0){ printf("Range[0]: %f\n",Range[0]); printf("Range[1]: %f\n",Range[1]); dvalue=1018.0; } if(Range[0]!=-1){ if(col_min==0 && col_max==0){ len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a cutted image */ } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ if(Range[0]>=col_min && Range[1]<=col_max){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]<=col_max){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min && Range[1]>col_max){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(Range[0]>=col_min && Range[1]>col_max){ Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } } else if(col_min!=0 && col_max==0){ if(Range[0]>=col_min){ len_cols=Range[1]-Range[0]+1; } else if(Range[0]<col_min){ range=col_min; Range[0]=col_min; len_cols=Range[1]-Range[0]+1; } } } else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){ range=col_min; Range[0]=col_min; Range[1]=col_max; len_cols=Range[1]-Range[0]+1; } else if(col_min!=0 && col_max==0){ range=col_min; Range[0]=col_min; Range[1]=len_cols-1; len_cols=Range[1]-Range[0]+1; } double** M = MakeArray(len_rows,len_cols); /* Create a matrix array for our image (F) */ if(Range[0]==-1){ for(i=0;i<len_rows;i++){ /* If the column doesn't present problems, proceed as usual */ for(j=0;j<len_cols;j++){ M[i][j]=mflat[i*real_cols+j]-dvalue; } } } else{ for(i=0;i<len_rows;i++){ /* If it does, we fill our cutted image */ for(j=range;j<Range[1]+1;j++){ M[i][j-range]=mflat[i*real_cols+j]-dvalue; } } } double* pmin=MakeVector(len_cols); // (F) double* pmax=MakeVector(len_cols); // (F) getSimpleMinMax(pmin,pmax,v,len_v,len_cols,range,Length); SimplePixelResampling(M,pmin,pmax,len_cols); // C=C-0.5; // getMinMax(); /* Start of the algorithm for the Simple Extraction Algorithm */ double* FSpectrum=MakeVector(len_cols); // (F) double Sum; for(i=0;i<len_cols;i++){ Sum=0; vMin=pmin[i]; vMax=pmax[i]; for(j=vMin;j<vMax;j++){ Sum=M[j][i]+Sum; } FSpectrum[i]=Sum; } FreeArray(M,len_rows); free(pmin); free(pmax); double* Spectrum=MakeVector(real_cols); // (F) if(range!=-1){ for(i=0;i<real_cols;i++){ if(i>=range && i<Range[1]+1){ Spectrum[i]=FSpectrum[i-range]; } else{ Spectrum[i]=0.0; } } } else{ for(i=0;i<real_cols;i++){ Spectrum[i]=FSpectrum[i]; } } free(FSpectrum); len_cols=real_cols; gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); if(debug!=0){ printf("%2.2lf seconds elapsed\n", t2-t1); } /* End of the algorithm */ /* Finally, we create a Python "Object" List that contains the P coefficients and return it back to Python */ PyObject *lst = PyList_New(len_cols); if (!lst) return NULL; for (i = 0; i < len_cols; i++) { PyObject *num = PyFloat_FromDouble(Spectrum[i]); if (!num) { Py_DECREF(lst); return NULL; } PyList_SET_ITEM(lst, i, num); } free(Spectrum); free(Range); PyObject *MyResult = Py_BuildValue("O",lst); Py_DECREF(lst); return MyResult; } static PyMethodDef MarshMethods[] = { {"ObtainP", Marsh_ObtainP, METH_VARARGS, "First step in the Method for optimum spectra obtention from Echelle Spectrographs: The obtention of the light fractions P."}, {"SObtainP", Marsh_ObtainP, METH_VARARGS, "Special function same as ObtainP, but for the case when we have a variance image."}, {"BObtainSpectrum", Marsh_BObtainSpectrum, METH_VARARGS, "Final step in the Method for optimum spectra obtention from Echelle Spectrographs: The obtention of the spectrum."}, {"ObtainSpectrum", Marsh_ObtainSpectrum, METH_VARARGS, "Final step in the Method for optimum spectra obtention from Echelle Spectrographs: The obtention of the spectrum."}, {"SimpleExtraction", Marsh_SimpleExtraction,METH_VARARGS, "Function that performs a simple extraction for comparison with the Optimal Extraction algorithm."}, {"SObtainSpectrum", Marsh_ObtainSpectrum, METH_VARARGS, "Special function, same as ObtainSpectrum but when we have a variance image."}, {"SSimpleExtraction", Marsh_SimpleExtraction,METH_VARARGS, "Special function, same as SObtainSpectrum, but when we have a variance image."}, {NULL, NULL, 0, NULL} }; void initMarsh(void){ (void) Py_InitModule("Marsh", MarshMethods); } /********************************************************************* * [START OF THE FUNCTIONS OF THE MARSH ALGORITHM] * ********************************************************************* */ double** Transpose(double **O,int rowsIN,int colsIN){ int i,j; double **OT=MakeArray(colsIN,rowsIN); for(i=0;i<rowsIN;i++){ for(j=0;j<colsIN;j++){ OT[j][i]=O[i][j]; } } FreeArray(O,rowsIN); return OT; } // Must GENERALIZE this void PixelResampling(double** A,double* pmin,double* pmax,int len_cols){ int j; double MinFluxFraction,MaxFluxFraction=0; for(j=0;j<len_cols;j++){ if(A[j][(int)pmin[j]]!=-9999){ MinFluxFraction=1.0-(pmin[j]-(double)((int)pmin[j])); // The fraction is 1-(RealPixel+0.5-(int)pmin[j]) MaxFluxFraction=pmax[j]-(double)((int)pmax[j]); // The fraction is RealPixel+0.5-(int)pmax[j] A[j][(int)pmin[j]]=MinFluxFraction*A[j][(int)pmin[j]]; A[j][(int)pmax[j]]=MaxFluxFraction*A[j][(int)pmax[j]]; } } } void BPixelResampling(double** A,double** B,double* pmin,double* pmax,int len_cols){ int j; double MinFluxFraction,MaxFluxFraction=0; for(j=0;j<len_cols;j++){ MinFluxFraction=1.0-(pmin[j]-(double)((int)pmin[j])); // The fraction is 1-(RealPixel+0.5-(int)pmin[j]) MaxFluxFraction=pmax[j]-(double)((int)pmax[j]); // The fraction is RealPixel+0.5-(int)pmax[j] A[j][(int)pmin[j]]=MinFluxFraction*A[j][(int)pmin[j]]; A[j][(int)pmax[j]]=MaxFluxFraction*A[j][(int)pmax[j]]; B[j][(int)pmin[j]]=MinFluxFraction*B[j][(int)pmin[j]]; B[j][(int)pmax[j]]=MaxFluxFraction*B[j][(int)pmax[j]]; } } void SimplePixelResampling(double** A,double* pmin,double* pmax,int len_cols){ int j; double MinFluxFraction,MaxFluxFraction=0; for(j=0;j<len_cols;j++){ MinFluxFraction=1.0-(pmin[j]-(double)((int)pmin[j])); // The fraction is 1-(RealPixel+0.5-(int)pmin[j]) MaxFluxFraction=pmax[j]-(double)((int)pmax[j]); // The fraction is RealPixel+0.5-(int)pmax[j] A[(int)pmin[j]][j]=MinFluxFraction*A[(int)pmin[j]][j]; A[(int)pmax[j]][j]=MaxFluxFraction*A[(int)pmax[j]][j]; } } /* [FUNCTION] * --------------------------------LINEAR SYSTEM SOLVER-------------------------------- * This function recieves a GSL vector b, a matrix A and returns the solution to the * system Ax=b. Here, length is the number of equations of the linear system. * ------------------------------------------------------------------------------------ */ void LinearSolver(double** A,double* b,double* x,int length){ int i,j; gsl_matrix *AGSL = gsl_matrix_alloc(length,length); /* We allocate memory for our GSL matrices and vectors */ gsl_vector *xGSL = gsl_vector_alloc(length); gsl_vector *bGSL = gsl_vector_alloc(length); for(i=0;i<length;i++){ for(j=0;j<length;j++){ gsl_matrix_set(AGSL,i,j,A[i][j]); /* Set the obtained values of the C_qp matrix to "A" */ } gsl_vector_set(bGSL,i,b[i]); /* Set the obtained values of the X_q vector to "b" */ } // gsl_linalg_HH_solve(AGSL,bGSL,xGSL); /* Solve the system... */ gsl_vector *tau = gsl_vector_alloc(length); gsl_linalg_QR_decomp(AGSL,tau); gsl_linalg_QR_solve(AGSL,tau,bGSL,xGSL); for(i=0;i<length;i++){ x[i]=gsl_vector_get(xGSL,i); /* Set the solution in each B_q vector term */ } } /* [FUNCTION] * ------------------------------------TRACE VALUE-------------------------------------- * Function that returns the value of the position of the trace at a given X (given in * Matrix Coordiantes). * ------------------------------------------------------------------------------------- */ double Trace(int x,double *v,int len_v,int range){ // int i; double Sum=0; if(range==-1){ Sum=v[x]; // for(i=0;i<len_v;i++) // Sum=v[(len_v-1)-i]*pow(x,(double)i)+Sum; } else{ Sum=v[x+range]; // for(i=0;i<len_v;i++) // Sum=v[(len_v-1)-i]*pow(x+range,(double)i)+Sum; } return Sum; } /* [FUNCTION] * ----------------------------Sum of the rows ------------------------------------ * Here we compute the sum of the row values for each column. This is the "standard * spectrum", i.e., the spectrum one would extract with unitary weigths. * -------------------------------------------------------------------------------- */ void getRowSum(double** A,double* RS,double *v,double* pmin,double* pmax,int len_cols,int len_v){ double Sum,c; int i,j,vMin,vMax; for(j=0;j<len_cols;j++){ Sum=0; vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ c=A[j][i]; if(c!=-9999){ Sum=c+Sum; } } RS[j]=Sum; /* We save the sum of the row (column) of the untransposed (transposed) matrix. */ } } /* [FUNCTION] * --------------------E (P Estimators)--------------------------------------- * Here we compute the light fractions estimators E and save it on our matrix. * --------------------------------------------------------------------------- */ void getE(double** A,double* RS,double** E,double* pmin,double* pmax,double *v,int len_rows,int len_cols){ double c; int i,j,vMin,vMax; for(j=0;j<len_cols;j++){ vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ c=A[j][i]; if(c!=-9999){ E[j][i]=c/RS[j]; /* Our estimations are the pixel value divided by the row sum (column sum of the untransposed (transposed) matrix: E_{ji}=A_{ji}/RS_{j} */ } } } } /* [FUNCTION] * --------------------Sum of the rows (Var(E) Estimators)--------------------------- * Here we compute the sum of the row values of the variances for each column. * ---------------------------------------------------------------------------------- */ void getVarRowSum(double** A,double** V,double* VarRS,double* pmin,double* pmax,double RON,double GAIN,int len_cols){ int i,j,vMin,vMax; double SumVar; for(j=0;j<len_cols;j++){ SumVar=0; vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999) SumVar=V[j][i]+SumVar; /* Each variance is taken as Poisson Noise+RON**2 (see the getImageVariances() and VarRevision() functions).*/ } VarRS[j]=SumVar; } } /* [FUNCTION] * --------------------Var(E) (P Estimators)--------------------------------------- * Here we compute the light fraction's variance for the estimators E and return * them as a matrix. Commented is the delta method. * --------------------------------------------------------------------------- */ void getVarE(double** A,double** E,double* RS,double* VarRS,double** VarE,double** V,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols){ int i,j,vMin,vMax; double a1=0,a2=0,c; // double c; for(j=0;j<len_cols;j++){ vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ c=A[j][i]; if(c!=-9999){ a1=((1.0/pow(RS[j],2.0))-(2.0*c/pow(RS[j],3.0)))*(V[j][i]); a2=(pow(E[j][i]/RS[j],2.0))*VarRS[j]; VarE[j][i]=a1+a2; // VarE[j][i]=V[j][i]/pow(RS[j],2.0); } } } } /* [FUNCTION] * --------------------Q Coefficients------------------------------------------ * Here we compute the Q coefficients for our light fractions using the linear * interpolation method proposed by Marsh (1989). * --------------------------------------------------------------------------- */ double CalculateQ(double *v,int k,int i,int j,double C,double S,int len_v,int range){ double d,x=Trace(j,v,len_v,range)+(S*(double)k)+C; // We compute the position of the center of the polynomial. d=fabs(x-(double)i); if(d>= 0.5+S) return 0.0; else if(d+S <= 0.5) return S; else if(d <= 0.5){ return ((S/2.0)+(0.5-d)-(pow(0.5-d,2.0)/(2.0*S))); } else if(d > 0.5){ return ((0.5-d)+(pow(0.5-d,2.0)/(2.0*S))+S/2); } else return -999; } double** getQ(double *v,double C,double S,int len_v,int K,int len_cols,int range,double* pmin,double* pmax,int mode){ int i,j,vMin,vMax,contador,k; contador=0; for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ contador+=1; } } double** Q=MakeArray(K,contador); for(k=0;k<=(K-1);k++){ contador=0; for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ if(mode==0){ Q[k][contador]=CalculateQ(v,k+1,i,j,C,S,len_v,range); } else{ Q[k][contador]=1.0; } contador+=1; } } } return Q; } /* [FUNCTION] * --------------------C Coefficients------------------------------------------ * Here we compute the C coefficients for the obtention of the C_p matrix * proposed by Marsh (1989). * --------------------------------------------------------------------------- */ double CalculateC(double** A,double** Q,double** VarE,int m, int l, int n, int k,double** J,double* pmin,double* pmax,int len_cols){ int i,j,vMin,vMax,contador; double TotalSum,Qk,Ql,Power; TotalSum=0,Qk=0,Ql=0; contador=0; for(j=0;j<len_cols;j++){ vMin=pmin[j]; vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. Power=J[n+m-2][j]; for(i=vMin;i<=vMax;i++){ Qk=Q[k-1][contador]; Ql=Q[l-1][contador]; /* We save computation time if either of Q is 0: */ if((Qk!=0.0) && (Ql!=0.0) && (A[j][i]!=-9999)){ /* If it isn't, we continue the calculation of our sum. */ TotalSum=((Qk*Ql*Power)/(VarE[j][i]))+TotalSum; } contador+=1; } } return TotalSum; } void getC(double** A,double** Q,double** VarE,double** C_qp,double** J,double* pmin,double* pmax,int K,int N,int len_cols){ int p,q,m,l,n,k,dummyq; double value=0; p=0,q=0,dummyq=1; for(k=1;k<=K;k++){ for(n=1;n<=N;n++){ for(l=1;l<=K;l++){ for(m=1;m<=N;m++){ p=N*(l-1)+m; q=N*(k-1)+n; if(dummyq<q){ // When we change of "q", we go to p=q, because the matrix is symmetric m=n; // and therefore all values can be obtained from the upper ones. l=k; p=N*(l-1)+m; q=N*(k-1)+n; } value=CalculateC(A,Q,VarE,m,l,n,k,J,pmin,pmax,len_cols); C_qp[p-1][q-1]=value; C_qp[q-1][p-1]=value; dummyq=q; } } } } } /* [FUNCTION] * --------------------X Coefficients------------------------------------------ * Here we compute the X coefficients for the obtention of the X_q vector * proposed by Marsh (1989). * --------------------------------------------------------------------------- */ double CalculateX(double** A,double** Q,double** E,double** VarE,int n, int k,double** J,double* pmin,double* pmax,int len_cols){ int i,j,vMin,vMax,contador; double TotalSum,Qk,Power; TotalSum=0,Qk=0; contador=0; for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. Power=J[n-1][j]; for(i=vMin;i<=vMax;i++){ Qk=Q[k-1][contador]; if(Qk!=0.0 && (A[j][i]!=-9999)){ // We save computation time if either of Q is 0. TotalSum=((E[j][i]*Qk*Power)/(VarE[j][i]))+TotalSum; } contador+=1; } } return TotalSum; } void getX(double** A,double** Q,double** E,double** VarE,double* X,double** J,double* pmin,double* pmax,int K,int N,int len_cols){ int q,n,k; q=0; for(k=1;k<=K;k++){ for(n=1;n<=N;n++){ q=N*(k-1)+n; X[q-1]=CalculateX(A,Q,E,VarE,n,k,J,pmin,pmax,len_cols); } } } /* [FUNCTION] * --------------------P Coefficients------------------------------------------ * Here we compute the light fractions P and return them as a matrix * --------------------------------------------------------------------------- */ void getP(double* B,double** Q,double** P,double** J,double* pmin,double* pmax,int K,int N,int len_rows,int len_cols,int mode){ double Sum,Gkj; int i,j,vMin,vMax,contador,n,k,q; contador=0,Sum=0,Gkj=0; if(mode==0){ for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ for(k=1;k<=K;k++){ for(n=1;n<=N;n++){ q=N*(k-1)+n; Gkj=(B[q-1]*J[n-1][j])+Gkj; /* We obtain the G_{kj} coefficient for a given k and j.*/ } Sum=(Q[k-1][contador]*Gkj)+Sum; /* Therms for the P_{ij} sum (eq (6), Marsh, 1989). */ Gkj=0; } P[j][i]=Sum; contador+=1; Sum=0; } } } else{ for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. k=1; for(i=vMin;i<=vMax;i++){ for(n=1;n<=N;n++){ q=N*(k-1)+n; Gkj=(B[q-1]*J[n-1][j])+Gkj; /* We obtain the G_{kj} coefficient for a given k and j.*/ } P[j][i]=Gkj; Gkj=0; k++; } } } } void VarRevision(double** A,double** VarImage,double** V,double* RS,double** P,double* pmin,double* pmax,int len_cols,double RON,double GAIN,int isvarimage){ int i,j,vMin,vMax; double c; for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ c=A[j][i]; if(c!=-9999){ if(isvarimage==0){ V[j][i]=pow(RON/GAIN,2.0)+fabs(RS[j]*P[j][i])/GAIN; } else{ V[j][i]=VarImage[j][i]; } } } } } int OutlierRejection(double** A,double** V,double** P,double** E,double** VarE,double* RS,double* pmin,double* pmax,double NSigma,int len_cols,int debug){ int i,j,vMin,vMax,counter=0; double TotalSum=0,SigmaSquared,Ratio; SigmaSquared=pow(NSigma,2.0); for(j=0;j<len_cols;j++){ vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999){ Ratio=pow(A[j][i]-RS[j]*P[j][i],2.0)/V[j][i]; TotalSum=(pow(P[j][i]-E[j][i],2.0)/VarE[j][i])+TotalSum; if(Ratio>=SigmaSquared){ A[j][i]=-9999; counter++; } } } } if(debug!=0){ printf("Number of outliers found: %d \n",counter); printf("Chi-squared of the fit: %f \n",TotalSum); } if(counter==0){ return 0; } return 1; } /* [FUNCTION] * ------------------------ Marsh's algorithm---------------------------------- * Here we obtain images (analogous to the image of pixel count values, M) for * the following: * * E_ij: Matrix image (same ij coordiantes as M) containing the estimated light * fractions (recall this is an estimate of P_ij, the model of this light * fraction. * * Var(E_ij): Matrix image (same ij coordiantes as M) containing the estimated light * fraction's variances. * * P_ij: Matrix image (same ij coordiantes as M) containing the modeled light * fractions. * --------------------------------------------------------------------------- */ double** MarshIteration(double** M,double** VarImage,double* pmin,double* pmax,double *v,double C,double S,double RON,double GAIN,int len_v,int len_rows,int len_cols,int N,int K,int mode,int range,int debug,double NSigma, int isvarimage){ int Iteration=1,IterNum=0; double** P=MakeArray(len_cols,len_rows); // FREED on Transpose. double** V=MakeArray(len_cols,len_rows); // FREED here, later. double** E=MakeArray(len_cols,len_rows); // FREED here, later. double** VarE=MakeArray(len_cols,len_rows); // FREED here, later. double** C_qp=MakeArray(N*K,N*K); /* Matrix that contains the coefficients for the linear system (FREED here, later) */ double** J=MakeArray(2*(N-1)+1,len_cols); // FREED here, later. // All from here to the end, FREED, later. double* B=MakeVector(N*K); /* Vector with the solutions to the linear system. */ double* X=MakeVector(N*K); /* Vector with the coefficients for the linear system. Given these elements, we wish to solve the C_qp B_q=X_q system */ double* RS=MakeVector(len_cols); /* Vector that saves the sum of pixel values of the rows (columns) of the transposed (untransposed) M matrix. */ double* VarRS=MakeVector(len_cols); /* Vector that saves the sum of pixel values variances of the rows (columns) of the transposed (untransposed) M matrix */ PixelResampling(M,pmin,pmax,len_cols); double** Q=getQ(v,C,S,len_v,K,len_cols,range,pmin,pmax,mode); /* First we obtain the Q matrix (note: independant of fit) */ getJ(J,N,len_cols); getImageVariances(M,V,VarImage,pmin,pmax,RON,GAIN,len_cols,isvarimage); getRowSum(M,RS,v,pmin,pmax,len_cols,len_v); getE(M,RS,E,pmin,pmax,v,len_rows,len_cols); getVarRowSum(M,V,VarRS,pmin,pmax,RON,GAIN,len_cols); getVarE(M,E,RS,VarRS,VarE,V,pmin,pmax,RON,GAIN,len_rows,len_cols); while(Iteration != 0){ /* If Iteration=1, we continue iterating! */ IterNum+=1; if(debug!=0){ printf("------------------- \n"); printf("Iteration number %d \n",IterNum); printf("------------------- \n"); printf("Obtaining the profiles...\n"); /* We obtain Var(E_ij), the variances of E_ij on each pixel */ } getC(M,Q,VarE,C_qp,J,pmin,pmax,K,N,len_cols); /* We obtain C_qp, the matrix with the C coefficients for the fit */ getX(M,Q,E,VarE,X,J,pmin,pmax,K,N,len_cols); /* We obtain X_q, the vector with the coefficients for the fit */ LinearSolver(C_qp,X,B,N*K); /* Solve the linear system C_qp*B_q=X_q, obtaining the B_q vector */ getP(B,Q,P,J,pmin,pmax,K,N,len_rows,len_cols,mode); /* We obtain P, the model light fractions on each pixel */ Renormalize(P,pmin,pmax,len_rows,len_cols); VarRevision(M,VarImage,V,RS,P,pmin,pmax,len_cols,RON,GAIN,isvarimage); getVarRowSum(M,V,VarRS,pmin,pmax,RON,GAIN,len_cols); getVarE(M,E,RS,VarRS,VarE,V,pmin,pmax,RON,GAIN,len_rows,len_cols); if(IterNum!=1) Iteration=OutlierRejection(M,V,P,E,VarE,RS,pmin,pmax,NSigma,len_cols,debug); } FreeArray(E,len_cols); /* Free our vectors and matrices */ FreeArray(VarE,len_cols); FreeArray(C_qp,N*K); FreeArray(Q,K); FreeArray(J,2*(N-1)+1); FreeArray(M,len_cols); FreeArray(VarImage,len_cols); FreeArray(V,len_cols); free(B); free(X); free(RS); free(VarRS); free(pmin); free(pmax); if(debug!=0){ printf("Going out of MarshIteration...\n"); } return Transpose(P,len_cols,len_rows); } void Renormalize(double** P,double* pmin,double* pmax,int len_rows,int len_cols){ int vMin,vMax,j,i; double PartialSum; for(j=0;j<len_cols;j++){ PartialSum=0; vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ if(P[j][i]<0) P[j][i]=0; PartialSum=P[j][i]+PartialSum; } for(i=vMin;i<=vMax;i++){ P[j][i]=P[j][i]/PartialSum; } } } double** getSpectrum(double** A,double** VarImage,double** P,double *v,int len_v,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols,double CosmicSigma,int debug,int isvarimage){ int j; int Iteration=1,IterNum=0; double** W=MakeArray(len_cols,len_rows); // FREED, later double** V=MakeArray(len_cols,len_rows); // FREED, later double* F=MakeVector(len_cols); // FREED, later double* VarF=MakeVector(len_cols); // FREED, later double* RSW=MakeVector(len_cols); // FREED, later PixelResampling(A,pmin,pmax,len_cols); getRowSum(A,F,v,pmin,pmax,len_cols,len_v); while(Iteration == 1){ VarRevision(A,VarImage,V,F,P,pmin,pmax,len_cols,RON,GAIN,isvarimage); IterNum+=1; if(debug!=0){ printf("------------------- \n"); printf("Iteration number %d \n",IterNum); printf("------------------- \n"); printf("Obtaining the spectrum...\n"); } getRowSumW(A,V,P,pmin,pmax,RSW,len_cols); /* We obtain the denominator for the W_i (see Marsh (1989), eq. (4)) */ getW(A,P,V,RSW,W,pmin,pmax,len_cols); /* We obtain the weights to estimate the fluxes. */ getF(W,A,F,pmin,pmax,len_cols); getVarF(A,W,V,VarF,pmin,pmax,len_cols); if(CosmicSigma==0) Iteration=0; else Iteration=CosmicRayRejection(A,V,P,F,VarF,CosmicSigma,pmin,pmax,len_cols,debug); } double** Spectrum=MakeArray(3,len_cols); // FREED, on the main code for(j=0;j<len_cols;j++){ Spectrum[0][j]=(double)j; Spectrum[1][j]=F[j]; Spectrum[2][j]=(double)1/(VarF[j]); } FreeArray(W,len_cols); FreeArray(V,len_cols); FreeArray(P,len_cols); FreeArray(A,len_cols); FreeArray(VarImage,len_cols); free(F); free(VarF); // free(OutlierDetector); free(RSW); return Spectrum; } double** BgetSpectrum(double** A,double** B,double** P,double *v,int len_v,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols,double CosmicSigma,int debug){ int j; int Iteration=1,IterNum=0,isvarimage=0; double** W=MakeArray(len_cols,len_rows); // FREED, later double** V=MakeArray(len_cols,len_rows); // FREED, later double* F=MakeVector(len_cols); // FREED, later double* BF=MakeVector(len_cols); // REED double* VarF=MakeVector(len_cols); // FREED, later double* RSW=MakeVector(len_cols); // FREED, later BPixelResampling(A,B,pmin,pmax,len_cols); getRowSum(A,F,v,pmin,pmax,len_cols,len_v); while(Iteration == 1){ VarRevision(A,A,V,F,P,pmin,pmax,len_cols,RON,GAIN,isvarimage); IterNum+=1; if(debug!=0){ printf("------------------- \n"); printf("Iteration number %d \n",IterNum); printf("------------------- \n"); printf("Obtaining the spectrum...\n"); } getRowSumW(A,V,P,pmin,pmax,RSW,len_cols); /* We obtain the denominator for the W_i (see Marsh (1989), eq. (4)) */ getW(A,P,V,RSW,W,pmin,pmax,len_cols); /* We obtain the weights to estimate the fluxes. */ getF(W,A,F,pmin,pmax,len_cols); getVarF(A,W,V,VarF,pmin,pmax,len_cols); if(CosmicSigma==0) Iteration=0; else Iteration=BCosmicRayRejection(A,B,V,P,F,VarF,CosmicSigma,pmin,pmax,len_cols,debug); } getBF(W,B,BF,pmin,pmax,len_cols); double** Spectrum=MakeArray(4,len_cols); // FREED, on the main code for(j=0;j<len_cols;j++){ Spectrum[0][j]=(double)j; Spectrum[1][j]=F[j]; Spectrum[2][j]=(double)1/(VarF[j]); Spectrum[3][j]=BF[j]; } FreeArray(W,len_cols); FreeArray(V,len_cols); FreeArray(P,len_cols); FreeArray(A,len_cols); FreeArray(B,len_cols); free(F); free(BF); free(VarF); // free(OutlierDetector); free(RSW); return Spectrum; } int CosmicRayRejection(double** A,double** V,double** P,double* F,double* VarF,double CosmicSigma,double* pmin,double* pmax,int len_cols,int debug){ int i,j,vMin,vMax,ii=0,jj=0,counter=0,detection=0; double Ratio,DummyRatio=0,count,fluxcount,countsigma,fluxcountsigma; for(j=0;j<len_cols;j++){ vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999){ count=A[j][i]; countsigma=sqrt(V[j][i]); fluxcount=F[j]*P[j][i]; fluxcountsigma=sqrt(VarF[j])*P[j][i]; if(count>=fluxcount){ Ratio=(count-CosmicSigma*countsigma)-(fluxcount+CosmicSigma*fluxcountsigma); if(Ratio>0){ detection=1; } } else{ Ratio=(fluxcount-CosmicSigma*fluxcountsigma)-(count+CosmicSigma*countsigma); if(Ratio>0){ detection=1; } } if(detection==1){ if(DummyRatio<Ratio){ ii=i; jj=j; DummyRatio=Ratio; counter=1; detection=0; } } } } } if(counter==0){ return 0; } else{ if(debug!=0){ printf("Cosmic ray found at column %d row %d \n",jj,ii); printf("Counts=%f, Light fraction (P)=%f , Total flux in column=%f (var=%f) , Variance=%f \n",A[jj][ii],P[jj][ii],F[jj],VarF[jj],V[jj][ii]); } A[jj][ii]=-9999; return 1; } } int BCosmicRayRejection(double** A,double** B,double** V,double** P,double* F,double* VarF,double CosmicSigma,double* pmin,double* pmax,int len_cols,int debug){ int i,j,vMin,vMax,ii=0,jj=0,counter=0,detection=0; double Ratio,DummyRatio=0,count,fluxcount,countsigma,fluxcountsigma; for(j=0;j<len_cols;j++){ vMin=pmin[j]; vMax=pmax[j]; for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999){ count=A[j][i]; countsigma=sqrt(V[j][i]); fluxcount=F[j]*P[j][i]; fluxcountsigma=sqrt(VarF[j])*P[j][i]; if(count>=fluxcount){ Ratio=(count-CosmicSigma*countsigma)-(fluxcount+CosmicSigma*fluxcountsigma); if(Ratio>0){ detection=1; } } else{ Ratio=(fluxcount-CosmicSigma*fluxcountsigma)-(count+CosmicSigma*countsigma); if(Ratio>0){ detection=1; } } if(detection==1){ if(DummyRatio<Ratio){ ii=i; jj=j; DummyRatio=Ratio; counter=1; detection=0; } } } } } if(counter==0){ return 0; } else{ if(debug!=0){ printf("Cosmic ray found at column %d row %d \n",jj,ii); printf("Counts=%f, Light fraction (P)=%f , Total flux in column=%f (var=%f) , Variance=%f \n",A[jj][ii],P[jj][ii],F[jj],VarF[jj],V[jj][ii]); } A[jj][ii]=-9999; B[jj][ii]=-9999; return 1; } } void getImageVariances(double** A,double** V,double** VarImage,double* pmin,double* pmax,double RON,double GAIN,int len_cols,int isvarimage){ int vMin,vMax,j,i; for(j=0;j<len_cols;j++){ vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ // V[j][i]=fabs(A[j][i]/GAIN)+pow(RON/GAIN,2.0); if(isvarimage==0){ V[j][i]=1.0; } else{ if(A[j][i]!=-9999){ V[j][i]=VarImage[j][i]; } } } } } void getRowSumW(double** A,double** V,double** P,double* pmin,double* pmax,double* RSW,int len_cols){ int i,j,vMin,vMax; double Sum; for(j=0;j<len_cols;j++){ Sum=0; vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999) Sum=(pow(P[j][i],2.0)/V[j][i])+Sum; } RSW[j]=Sum; } } void getW(double** A,double** P,double** V,double* RSW,double** W,double* pmin,double* pmax,int len_cols){ int vMin,vMax,j,i; double PartialSum; for(j=0;j<len_cols;j++){ PartialSum=0; vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999) W[j][i]=(P[j][i]/V[j][i])/RSW[j]; } } } void getF(double** W,double** A,double* F,double* pmin,double* pmax,int len_cols){ int vMin,vMax,j,i; double PartialSum; for(j=0;j<len_cols;j++){ PartialSum=0; vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999) PartialSum=(W[j][i]*A[j][i])+PartialSum; } F[j]=PartialSum; } } void getBF(double** W,double** B,double* BF,double* pmin,double* pmax,int len_cols){ int vMin,vMax,j,i; double PartialSum; for(j=0;j<len_cols;j++){ PartialSum=0; vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ if(B[j][i]!=-9999) PartialSum=(W[j][i]*B[j][i])+PartialSum; } BF[j]=PartialSum; } } void getVarF(double** A,double** W,double** V,double* VarF,double* pmin,double* pmax,int len_cols){ int vMin,vMax,j,i; double PartialSum; for(j=0;j<len_cols;j++){ PartialSum=0; vMin=pmin[j]; // If the value extends to a lower pixel, we take it into account. vMax=pmax[j]; // If the value extends to a higher pixel, we take it into account. for(i=vMin;i<=vMax;i++){ if(A[j][i]!=-9999) PartialSum=(pow(W[j][i],2.0)*V[j][i])+PartialSum; } VarF[j]=PartialSum; } } void getMinMax(double* pmin,double* pmax,double *v,double C, double S,int K,int len_v,int len_cols,int range){ int j; for(j=0;j<len_cols;j++){ pmin[j]=((Trace(j,v,len_v,range)+C)+S)+0.5; pmax[j]=((Trace(j,v,len_v,range)+C)+(double)(K)*S)+0.5; } } void getSimpleMinMax(double* pmin,double* pmax,double *v,int len_v,int len_cols,int range,double Length){ int j; for(j=0;j<len_cols;j++){ pmin[j]=Trace(j,v,len_v,range)-Length+0.5; pmax[j]=Trace(j,v,len_v,range)+Length+0.5; } } void getJ(double** J,int N,int len_cols){ int ulimit=2*(N-1)+1,power; int j; for(power=0;power<ulimit;power++){ for(j=0;j<len_cols;j++){ J[power][j]=pow((double)j,power); } } } double** MakeArray(int rows, int columns){ int i,j; double** theArray; theArray = (double**) malloc(rows*sizeof(double*)); for(i=0;i<rows;i++) theArray[i] = (double*) malloc(columns*sizeof(double)); /* Fill the array with zeroes (i.e. we clean it) */ for(i=0;i<rows;i++){ for(j=0;j<columns;j++){ theArray[i][j]=0.0; } } return theArray; } int CheckAperture(double* center, int len_rows, int len_cen, double S, int CentralAperture){ int uprow,lowrow; int K = (int)((int)((CentralAperture/S)+0.5)); // This is the number of polynomials at each side of the central aperture int i; int InitialAperture = CentralAperture; for(i=0;i<len_cen;i++){ uprow = (int)(center[i]+S*(K+1.0)+0.5); lowrow = (int)(center[i]-S*(K+1.0)-0.5); if(uprow>=len_rows){ CentralAperture = CentralAperture - 1; K = (int)((int)((CentralAperture/S)+0.5)); lowrow = (int)(center[i]-S*(K+1.0)-0.5); i = i-1; } if(lowrow<0 && uprow>=len_rows){ CentralAperture = CentralAperture - 1; } if(lowrow<0 && uprow<len_rows){ CentralAperture = CentralAperture - 1; K = (int)((int)((CentralAperture/S)+0.5)); i = i-1; } // If the aperture doesn't stabilize to a value above 1, // then it can't be stabilized and we trust the user input value: if(CentralAperture<1){ CentralAperture = InitialAperture; break; } } if(CentralAperture != InitialAperture){ printf("MARSH CODE: Changed central aperture to %d\n",CentralAperture); } return CentralAperture; } double* MakeVector(int nelements){ double* Vector; int j; Vector = (double*) malloc(nelements*sizeof(double)); for(j=0;j<nelements;j++){ Vector[j]=0.0; } return Vector; } void FreeArray(double** theArray,int rows){ int i; for(i=0;i<rows;i++){ free(theArray[i]); } free(theArray); } double* RangeDetector(double *v,double C,double S,int len_v,int K,int len_rows,int len_cols,int range){ int j,s=0,uplim=0,downlim=0; double* ReturningVector = MakeVector(2); ReturningVector[1]=len_cols; if(Trace(0,v,len_v,range)>Trace(len_cols/2,v,len_v,range) && ((int)(((Trace(0,v,len_v,range)+C)+(double)(K)*S)+0.5)>=len_rows || (int)(((Trace(len_cols-1,v,len_v,range)+C)+(double)(K)*S)+0.5)>=len_rows)){ // The problem is on an upper trace for(j=0;j<len_cols;j++){ uplim=((Trace(j,v,len_v,range)+C)+(double)(K)*S)+0.5; if( uplim<len_rows && s==0 ){ s++; ReturningVector[0]=j; } else if( uplim==len_rows && s>0 ){ ReturningVector[1]=j-1; break; } } } else if(Trace(0,v,len_v,range)<Trace(len_cols/2,v,len_v,range) && ((int)(((Trace(0,v,len_v,range)+C)+S)+0.5)<0 || (int)(((Trace(len_cols-1,v,len_v,range)+C)+S)+0.5)<0)){ // The problem is on an lower trace for(j=0;j<len_cols;j++){ downlim=((Trace(j,v,len_v,range)+C)+S)+0.5; if( downlim==0 && s==0 ){ s++; ReturningVector[0]=j; } else if( downlim<0 && s>0 ){ ReturningVector[1]=j-1; break; } } } else{ ReturningVector[0]=-1; } return ReturningVector; } double* SimpleRangeDetector(double *v,double Length,int len_v,int len_rows,int len_cols,int range){ int j,s=0,uplim=0,downlim=0; double* ReturningVector = MakeVector(2); ReturningVector[1]=len_cols; if(Trace(0,v,len_v,range)>Trace(len_cols/2,v,len_v,range) && ((int)((Trace(0,v,len_v,range)+Length)+0.5)>=len_rows || (int)((Trace(len_cols-1,v,len_v,range)+Length)+0.5)>=len_rows)){ // The problem is on an upper trace for(j=0;j<len_cols;j++){ uplim=(Trace(j,v,len_v,range)+Length)+0.5; if( uplim<len_rows && s==0 ){ s++; ReturningVector[0]=j; } else if( uplim==len_rows && s>0 ){ ReturningVector[1]=j-1; break; } } } else if(Trace(0,v,len_v,range)<Trace(len_cols/2,v,len_v,range) && ((int)((Trace(0,v,len_v,range)-Length)+0.5)<0 || (int)((Trace(len_cols-1,v,len_v,range)-Length)+0.5)<0)){ // The problem is on an lower trace for(j=0;j<len_cols;j++){ downlim=(Trace(j,v,len_v,range)-Length)+0.5; if( downlim==0 && s==0 ){ s++; ReturningVector[0]=j; } else if( downlim<0 && s>0 ){ ReturningVector[1]=j-1; break; } } } else{ ReturningVector[0]=-1; } return ReturningVector; }
{ "alphanum_fraction": 0.5253341559, "avg_line_length": 41.1944091487, "ext": "c", "hexsha": "02796a1f2b004152e0bb53d5d1eee78c0cf74626", "lang": "C", "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:50:35.000Z", "max_forks_repo_forks_event_min_datetime": "2016-09-09T23:58:15.000Z", "max_forks_repo_head_hexsha": "e55150c587782cbecfd45c21ba0ce0023e54c3a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "afeinstein20/ceres", "max_forks_repo_path": "utils/OptExtract/Marsh.c", "max_issues_count": 29, "max_issues_repo_head_hexsha": "e55150c587782cbecfd45c21ba0ce0023e54c3a9", "max_issues_repo_issues_event_max_datetime": "2021-06-02T14:55:53.000Z", "max_issues_repo_issues_event_min_datetime": "2016-09-10T15:30:29.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "afeinstein20/ceres", "max_issues_repo_path": "utils/OptExtract/Marsh.c", "max_line_length": 329, "max_stars_count": 35, "max_stars_repo_head_hexsha": "e55150c587782cbecfd45c21ba0ce0023e54c3a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "afeinstein20/ceres", "max_stars_repo_path": "utils/OptExtract/Marsh.c", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:25:49.000Z", "max_stars_repo_stars_event_min_datetime": "2016-09-09T04:08:45.000Z", "num_tokens": 24848, "size": 97260 }
// // her.h // Linear Algebra Template Library // // Created by Rodney James on 12/23/11. // Copyright (c) 2011 University of Colorado Denver. All rights reserved. // #ifndef _her_h #define _her_h /// @file her.h Performs complex vector outer product. #include <cctype> #include "latl.h" namespace LATL { /// @brief Performs a vector outer product of a complex vector with itself. /// /// For a complex Hermitian matrix A, complex vector x and real scalar alpha, /// /// A := alpha * x * x' + A /// /// is computed. The result is Hermitian and is stored as either upper or lower triangular in A. /// @return 0 if success. /// @return -i if the ith argument is invalid. /// @tparam real_t Floating point type. /// @param uplo Specifies whether A is stored as upper or lower triangular. /// /// if uplo = 'U' or 'u' then A is upper triangular /// if uplo = 'L' or 'l' then A is lower triangular /// /// @param n Specifies the order of the matrix A. n>=0 /// @param alpha Real scalar. /// @param x Pointer to complex vector x. /// @param incx Increment of the vector x. x!=0 /// @param A Pointer to complex Hermitian n-by-n matrix A. If uplo = 'U' or 'u' then only the upper /// triangular part of A is referenced and the lower part is not referenced. If uplo = 'L' or 'l' then /// only the lower triangular part of A is referenced and the upper part is not referenced. /// @param ldA Column length of matrix A. ldA>=n. /// @ingroup BLAS template <typename real_t> int HER(char uplo, int_t n, real_t alpha, complex<real_t> *x, int_t incx, complex<real_t> *A, int_t ldA) { using std::conj; using std::real; using std::toupper; const real_t zero(0.0); complex<real_t> t; int_t i,j,kx,jx,ix; uplo=toupper(uplo); if((uplo!='U')&&(uplo!='L')) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(ldA<n) return -7; else if((n==0)||(alpha==zero)) return 0; if(incx==1) { if(uplo=='U') { for(j=0;j<n;j++) { t=alpha*conj(x[j]); for(i=0;i<j;i++) A[i]+=x[i]*t; A[j]=real(A[j])+real(x[j]*t); A+=ldA; } } else { for(j=0;j<n;j++) { t=alpha*conj(x[j]); A[j]=real(A[j])+real(t*x[j]); for(i=j+1;i<n;i++) A[i]+=x[i]*t; A+=ldA; } } } else { kx=(incx>0)?0:(1-n)*incx; if(uplo=='U') { jx=kx; for(j=0;j<n;j++) { t=alpha*conj(x[jx]); ix=kx; for(i=0;i<j;i++) { A[i]+=x[ix]*t; ix+=incx; } A[j]=real(A[j])+real(x[jx]*t); A+=ldA; jx+=incx; } } else { jx=kx; for(j=0;j<n;j++) { t=alpha*conj(x[jx]); A[j]=real(A[j])+real(t*x[jx]); ix=jx; for(i=j+1;i<n;i++) { ix+=incx; A[i]+=x[ix]*t; } jx+=incx; A+=ldA; } } } return 0; } #ifdef __latl_cblas #include <cblas.h> template <> int HER<float>(char uplo, int_t n, float alpha, complex<float> *x, int_t incx, complex<float> *A, int_t ldA) { uplo=std::toupper(uplo); if((uplo!='U')&&(uplo!='L')) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(ldA<n) return -7; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_cher(CblasColMajor,Uplo,n,alpha,x,incx,A,ldA); return 0; } template <> int HER<double>(char uplo, int_t n, double alpha, complex<double> *x, int_t incx, complex<double> *A, int_t ldA) { uplo=std::toupper(uplo); if((uplo!='U')&&(uplo!='L')) return -1; else if(n<0) return -2; else if(incx==0) return -5; else if(ldA<n) return -7; const CBLAS_UPLO Uplo=(uplo=='U')?CblasUpper:CblasLower; cblas_zher(CblasColMajor,Uplo,n,alpha,x,incx,A,ldA); return 0; } #endif } #endif
{ "alphanum_fraction": 0.4729493892, "avg_line_length": 25.8983050847, "ext": "h", "hexsha": "5ce9e1b2dd42402b66158e74ec511e39e6292a58", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z", "max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z", "max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_forks_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_forks_repo_name": "langou/latl", "max_forks_repo_path": "include/her.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_issues_repo_name": "langou/latl", "max_issues_repo_path": "include/her.h", "max_line_length": 127, "max_stars_count": 6, "max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492", "max_stars_repo_licenses": [ "BSD-3-Clause-Open-MPI" ], "max_stars_repo_name": "langou/latl", "max_stars_repo_path": "include/her.h", "max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z", "num_tokens": 1322, "size": 4584 }
// many-small-dgemms.c: // Mini-app which investigates different ways to perform many small dgemm operations. // Looping over thousands of rocblas calls is slow, so looking into other solutions. // This functionality is very interesting to several applications, including nuccor. // Date: Oct 15th, 2019 // Author: Justin Gage Lietz // Contact: lietzjg@ornl.gov #include <stdio.h> #include <stdlib.h> #include <time.h> #include <cblas.h> /* #include <cublas_v2.h> */ #include <hip/hip_runtime.h> #include <rocblas.h> #include <omp.h> #include <string.h> //for memcpy #include <magma_v2.h> // tolerance as 1.e-15 fails #define TOL 1.e-14 // Pulled from magma test code #define TESTING_CHECK( err ) \ do { \ magma_int_t err_ = (err); \ if ( err_ != 0 ) { \ fprintf( stderr, "Error: %s\nfailed at %s:%d: error %lld: %s\n", \ #err, __FILE__, __LINE__, \ (long long) err_, magma_strerror(err_) ); \ exit(1); \ } \ } while( 0 ) size_t idx(size_t i, size_t j, size_t nrows, size_t ncols){ return j*nrows + i; } size_t cidx(size_t i, size_t j, size_t nrows, size_t ncols){ return i*ncols + j; } void print_c_matrix(double *mat, size_t nrows, size_t ncols){ for(int i = 0; i < nrows; i++){ for(int j = 0; j < ncols; j++){ printf("%f ", mat[ cidx(i,j,nrows,ncols) ]); } printf("\n"); } printf("\n"); } void print_matrix(double *mat, size_t nrows, size_t ncols){ for(int i = 0; i < nrows; i++){ for(int j = 0; j < ncols; j++){ printf("%f ", mat[ idx(i,j,nrows,ncols) ]); } printf("\n"); } printf("\n"); } void print_matrix_array(double *mat_A, size_t *Aoffsets, size_t *nrows, size_t *ncols, size_t nBlocks){ for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ size_t Aoffset = Aoffsets[iBlock]; printf("iBlock: %zu\n",iBlock); print_matrix( &mat_A[Aoffset], nrows[iBlock], ncols[iBlock] ); } } void cblas_wrapper(double *A, double* B, double* C, size_t M_in, size_t N_in, size_t K_in){ int M = M_in; int K = K_in; int N = N_in; int LDA = M; int LDB = K; int LDC = M; double alpha = 1.0; double beta = 0.0; cblas_dgemm(/*CBLAS*/ CblasColMajor, /* TRANS A */ CblasNoTrans, /* TRANS B */ CblasNoTrans, /* M */M, /* N */N, /* K */K, /* alpha */alpha, /* A */A, /* LDA */LDA, /* B */B, /* LDB */LDB, /* BETA */beta, /* C */C, /* LDC */LDC); } void device_dgemm(rocblas_handle handle, double *A, double* B, double* C, size_t M_in, size_t N_in, size_t K_in){ int M = M_in; int K = K_in; int N = N_in; int LDA = M; int LDB = K; int LDC = M; double alpha = 1.0; double beta = 0.0; size_t ABytes = sizeof(double)*M*K; size_t BBytes = sizeof(double)*K*N; size_t CBytes = sizeof(double)*M*N; double *d_A; double *d_B; double *d_C; const rocblas_operation transA = rocblas_operation_none; const rocblas_operation transB = rocblas_operation_none; hipMalloc(&d_A, ABytes); hipMalloc(&d_B, BBytes); hipMalloc(&d_C, CBytes); hipMemcpy(d_A, A, ABytes, hipMemcpyHostToDevice); hipMemcpy(d_B, B, BBytes, hipMemcpyHostToDevice); rocblas_dgemm(/*rocblas handle*/ handle, /* TRANS A */ transA, /* TRANS B */ transB, /* M */M, /* N */N, /* K */K, /* alpha */&alpha, /* A */d_A, /* LDA */LDA, /* B */d_B, /* LDB */LDB, /* BETA */&beta, /* C */d_C, /* LDC */LDC); hipMemcpy(C, d_C, CBytes, hipMemcpyDeviceToHost); hipFree(d_A); hipFree(d_B); hipFree(d_C); } void rocblas_array_dgemm( rocblas_handle handle, const double *A, const double* B, double* C, const size_t *Ms, const size_t *Ns, const size_t *Ks, const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){ const rocblas_operation transA = rocblas_operation_none; const rocblas_operation transB = rocblas_operation_none; double *d_A, *d_B, *d_C; size_t ABytes = Aoffsets[nBlocks]*sizeof(double); size_t BBytes = Boffsets[nBlocks]*sizeof(double); size_t CBytes = Coffsets[nBlocks]*sizeof(double); hipMalloc(&d_A, ABytes); hipMalloc(&d_B, BBytes); hipMalloc(&d_C, CBytes); hipMemcpy(d_A, A, ABytes, hipMemcpyHostToDevice); hipMemcpy(d_B, B, BBytes, hipMemcpyHostToDevice); double start = omp_get_wtime(); for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ size_t Aoffset = Aoffsets[iBlock]; size_t Boffset = Boffsets[iBlock]; size_t Coffset = Coffsets[iBlock]; int M = Ms[iBlock]; int N = Ns[iBlock]; int K = Ks[iBlock]; int LDA = M; int LDB = K; int LDC = M; double alpha = 1.0; double beta = 0.0; /* char transa = 'N'; */ /* char transb = 'N'; */ rocblas_dgemm(/*rocblas handle*/ handle, /* TRANS A */ transA, /* TRANS B */ transB, /* M */ M, /* N */ N, /* K */ K, /* alpha */ &alpha, /* A */ &d_A[Aoffset], /* LDA */ LDA, /* B */ &d_B[Boffset], /* LDB */ LDB, /* BETA */ &beta, /* C */ &d_C[Coffset], /* LDC */ LDC); } double stop = omp_get_wtime(); printf("time of rocblas_dgemm loop: %f\n", stop - start); hipMemcpy(C, d_C, CBytes, hipMemcpyDeviceToHost); hipFree(d_A); hipFree(d_B); hipFree(d_C); } void magma_array_dgemm( const double *A, const double* B, double* C, const size_t *Ms, const size_t *Ns, const size_t *Ks, const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){ magma_trans_t transA = MagmaNoTrans; magma_trans_t transB = MagmaNoTrans; double const* * dA_array; double const* * dB_array; double **dC_array; double alpha; double beta; magma_int_t* d_lddb; magma_int_t* d_ldda; magma_int_t* d_lddc; magma_int_t* d_m; magma_int_t* d_n; magma_int_t* d_k; int* h_m; int* h_n; int* h_k; double **hA_array; double **hB_array; double **hC_array; double *d_A_elems; double *d_B_elems; double *d_C_elems; magma_int_t batchCount; magma_queue_t queue; magma_device_t device; magma_getdevice( &device ); magma_queue_create( device, &queue ); batchCount = nBlocks; // Magma needs larger arrays TESTING_CHECK( magma_malloc((void**)&d_m, (batchCount+1)*sizeof(magma_int_t)) ); TESTING_CHECK( magma_malloc((void**)&d_n, (batchCount+1)*sizeof(magma_int_t)) ); TESTING_CHECK( magma_malloc((void**)&d_k, (batchCount+1)*sizeof(magma_int_t)) ); TESTING_CHECK( magma_malloc((void**)&d_ldda, (batchCount+1)*sizeof(magma_int_t) ) ); TESTING_CHECK( magma_malloc((void**)&d_lddb, (batchCount+1)*sizeof(magma_int_t) ) ); TESTING_CHECK( magma_malloc((void**)&d_lddc, (batchCount+1)*sizeof(magma_int_t) ) ); // Looks like magma_malloc works with regular c int as well. TESTING_CHECK( magma_malloc_cpu((void**)&h_m, (batchCount+1)*sizeof(int) ) ); TESTING_CHECK( magma_malloc_cpu((void**)&h_n, (batchCount+1)*sizeof(int) ) ); TESTING_CHECK( magma_malloc_cpu((void**)&h_k, (batchCount+1)*sizeof(int) ) ); // dA_array is the array of pointers need by dgemm // d_A_elems are the actual mtx elements being pointed to // hA_array is the host side pointers that will get passed to dA_array TESTING_CHECK( magma_malloc( (void**)&dA_array, sizeof(double*)*batchCount ) ); TESTING_CHECK( magma_malloc( (void**)&dB_array, sizeof(double*)*batchCount ) ); TESTING_CHECK( magma_malloc( (void**)&dC_array, sizeof(double*)*batchCount ) ); TESTING_CHECK( magma_malloc( (void**)&d_A_elems, sizeof(double)*Aoffsets[nBlocks] ) ); TESTING_CHECK( magma_malloc( (void**)&d_B_elems, sizeof(double)*Boffsets[nBlocks] ) ); TESTING_CHECK( magma_malloc( (void**)&d_C_elems, sizeof(double)*Coffsets[nBlocks] ) ); TESTING_CHECK( magma_malloc_cpu( (void**)&hA_array, sizeof(double*)*batchCount ) ); TESTING_CHECK( magma_malloc_cpu( (void**)&hB_array, sizeof(double*)*batchCount ) ); TESTING_CHECK( magma_malloc_cpu( (void**)&hC_array, sizeof(double*)*batchCount ) ); // magma needs 32-bit int, while main was using 64 for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ h_m[iBlock] = Ms[iBlock]; h_n[iBlock] = Ns[iBlock]; h_k[iBlock] = Ks[iBlock]; } magma_setvector(batchCount, sizeof(magma_int_t), h_m, 1, d_m, 1, queue); magma_setvector(batchCount, sizeof(magma_int_t), h_n, 1, d_n, 1, queue); magma_setvector(batchCount, sizeof(magma_int_t), h_k, 1, d_k, 1, queue); magma_setvector(batchCount, sizeof(magma_int_t), h_m, 1, d_ldda, 1, queue); magma_setvector(batchCount, sizeof(magma_int_t), h_k, 1, d_lddb, 1, queue); magma_setvector(batchCount, sizeof(magma_int_t), h_m, 1, d_lddc, 1, queue); magma_setvector(Aoffsets[nBlocks], sizeof(double), A, 1, d_A_elems, 1, queue); magma_setvector(Boffsets[nBlocks], sizeof(double), B, 1, d_B_elems, 1, queue); size_t Aoffset; size_t Boffset; size_t Coffset; for(int iBlock = 0; iBlock < nBlocks; iBlock++){ Aoffset = Aoffsets[iBlock]; Boffset = Boffsets[iBlock]; Coffset = Coffsets[iBlock]; hA_array[iBlock] = d_A_elems + Aoffset; hB_array[iBlock] = d_B_elems + Boffset; hC_array[iBlock] = d_C_elems + Coffset; } magma_setvector(batchCount, sizeof(double*), hA_array, 1, dA_array, 1, queue); magma_setvector(batchCount, sizeof(double*), hB_array, 1, dB_array, 1, queue); magma_setvector(batchCount, sizeof(double*), hC_array, 1, dC_array, 1, queue); alpha = 1.0; beta = 0.0; batchCount = nBlocks; double start,stop; start = omp_get_wtime(); magmablas_dgemm_vbatched( transA, /* magma_trans_t */ transB, /* magma_int_t * */ d_m, /* magma_int_t * */ d_n, /* magma_int_t * */ d_k, /* double */ alpha, /* double const *const * */ dA_array, /* magma_int_t * */ d_ldda, /* double const *const * */ dB_array, /* magma_int_t * */ d_lddb, /* double */ beta, /* double ** */ dC_array, /* magma_int_t * */ d_lddc, /* magma_int_t */ batchCount, /* magma_queue_t */ queue); stop = omp_get_wtime(); printf("time of magmablas_dgemm_vbatched: %f\n", stop - start); magma_getvector(Coffsets[nBlocks], sizeof(double), d_C_elems, 1, C, 1, queue); // Clean up magma_queue_destroy( queue ); TESTING_CHECK( magma_free(d_m) ); TESTING_CHECK( magma_free(d_n) ); TESTING_CHECK( magma_free(d_k) ); TESTING_CHECK( magma_free(d_ldda) ); TESTING_CHECK( magma_free(d_lddb) ); TESTING_CHECK( magma_free(d_lddc) ); TESTING_CHECK( magma_free_cpu(h_m) ); TESTING_CHECK( magma_free_cpu(h_n) ); TESTING_CHECK( magma_free_cpu(h_k) ); TESTING_CHECK( magma_free(dA_array) ); TESTING_CHECK( magma_free(dB_array) ); TESTING_CHECK( magma_free(dC_array) ); TESTING_CHECK( magma_free(d_A_elems) ); TESTING_CHECK( magma_free(d_B_elems) ); TESTING_CHECK( magma_free(d_C_elems) ); TESTING_CHECK( magma_free_cpu(hA_array) ); TESTING_CHECK( magma_free_cpu(hB_array) ); TESTING_CHECK( magma_free_cpu(hC_array) ); } void host_matmul(const double *A, const double* B, double* C, const size_t M, const size_t N, const size_t K){ for(size_t i = 0; i < M; i++){ for(size_t j = 0; j < N; j++){ C[ idx(i,j,M,N) ] = 0.0; for(size_t k = 0; k < K; k++){ C[ idx(i,j,M,N) ] += A[ idx(i,k,M,K) ] * B[ idx(k,j,K,N) ]; } } } } void host_array_matmul(const double *A, const double* B, double* C, const size_t *Ms, const size_t *Ns, const size_t *Ks, const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){ for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ size_t Aoffset = Aoffsets[iBlock]; size_t Boffset = Boffsets[iBlock]; size_t Coffset = Coffsets[iBlock]; host_matmul(&A[Aoffset], &B[Boffset], &C[Coffset], Ms[iBlock], Ns[iBlock], Ks[iBlock]); } } void host_array_dgemm(const double *A, const double* B, double* C, const size_t *Ms, const size_t *Ns, const size_t *Ks, const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){ for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ size_t Aoffset = Aoffsets[iBlock]; size_t Boffset = Boffsets[iBlock]; size_t Coffset = Coffsets[iBlock]; int M = Ms[iBlock]; int N = Ns[iBlock]; int K = Ks[iBlock]; int LDA = M; int LDB = K; int LDC = M; double alpha = 1.0; double beta = 0.0; /* char transa = 'N'; */ /* char transb = 'N'; */ cblas_dgemm(/*CBLAS*/ CblasColMajor, /* TRANS A */ CblasNoTrans, /* TRANS B */ CblasNoTrans, /* M */ M, /* N */ N, /* K */ K, /* alpha */ alpha, /* A */ &A[Aoffset], /* LDA */ LDA, /* B */ &B[Boffset], /* LDB */ LDB, /* BETA */ beta, /* C */ &C[Coffset], /* LDC */ LDC); } } void host_transpose(double *mat_in, double *mat_out, size_t nrows_in, size_t ncols_in){ for(size_t i = 0; i < nrows_in; i++){ for(size_t j = 0; j < ncols_in; j++){ mat_out[ idx(j,i,ncols_in,nrows_in) ] = mat_in[ idx(i,j,nrows_in, ncols_in) ]; } } } int check_equal(double *mat_A, double *mat_B, size_t nrows, size_t ncols){ int flag = 1; for(size_t i = 0; i < nrows; i++){ for(size_t j = 0; j < ncols; j++){ if( fabs( mat_A[ idx(i,j,nrows,ncols) ] - mat_B[ idx(i,j,nrows,ncols) ]) > TOL ){ flag = 0; return flag; } } } return flag; } int check_matrix_array_equal(double *mat_A, double *mat_B, size_t *Aoffsets, size_t *Boffsets, size_t *nrows, size_t *ncols, size_t nBlocks){ int flag = 1; for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ size_t Aoffset = Aoffsets[iBlock]; size_t Boffset = Boffsets[iBlock]; flag *= check_equal( &mat_A[Aoffset], &mat_B[Boffset], nrows[iBlock], ncols[iBlock] ); if( !check_equal(&mat_A[Aoffset], &mat_B[Boffset], nrows[iBlock], ncols[iBlock]) ){ printf("error in block: %zu\n"); printf("A\n"); print_matrix( &mat_A[Aoffset], nrows[iBlock], ncols[iBlock] ); printf("B\n"); print_matrix( &mat_B[Aoffset], nrows[iBlock], ncols[iBlock] ); return flag; } } return flag; } void generate_random_array(size_t* array, size_t nBlocks, size_t max_size){ size_t rando; for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ rando = rand()%max_size + 1; array[iBlock] = rando; } } void load_random_matrix(double* mat_in, size_t nrows, size_t ncols){ double rando; for(size_t i = 0; i < nrows; i++){ for(size_t j = 0; j < ncols; j++){ rando= (double) rand()/RAND_MAX*2.0 - 1.0; mat_in[ idx(i,j,nrows,ncols) ] = rando; } } } int main(){ // Start magma TESTING_CHECK( magma_init() ); magma_print_environment(); // magma seems to break at 2^16, but 2^15 blocks is fine size_t nBlocks = 1<<15; size_t max_block_size = 10; // Small test for debugging // size_t nBlocks = 3; // size_t max_block_size = 4; size_t *Ms_array; size_t *Ns_array; size_t *Ks_array; size_t *Aoffsets; size_t *Boffsets; size_t *Coffsets; Ms_array = (size_t*)malloc(sizeof(size_t)*nBlocks); Ns_array = (size_t*)malloc(sizeof(size_t)*nBlocks); Ks_array = (size_t*)malloc(sizeof(size_t)*nBlocks); Aoffsets = (size_t*)malloc(sizeof(size_t)*(nBlocks+1)); Boffsets = (size_t*)malloc(sizeof(size_t)*(nBlocks+1)); Coffsets = (size_t*)malloc(sizeof(size_t)*(nBlocks+1)); /* srand( time(NULL) ); */ // Reproducible seed srand( 100 ); generate_random_array(Ms_array,nBlocks,max_block_size); generate_random_array(Ns_array,nBlocks,max_block_size); generate_random_array(Ks_array,nBlocks,max_block_size); Aoffsets[0] = 0; Boffsets[0] = 0; Coffsets[0] = 0; // Offset array elements indicate starting location of each block // Final array element indicates where the next block WOULD start // This is needed to count the total number of elements for(size_t iBlock = 1; iBlock < nBlocks + 1; iBlock++){ Aoffsets[iBlock] = Aoffsets[iBlock-1] + Ms_array[iBlock-1] * Ks_array[iBlock-1]; Boffsets[iBlock] = Boffsets[iBlock-1] + Ks_array[iBlock-1] * Ns_array[iBlock-1]; Coffsets[iBlock] = Coffsets[iBlock-1] + Ms_array[iBlock-1] * Ns_array[iBlock-1]; } size_t ABytes = Aoffsets[nBlocks]*sizeof(double); size_t BBytes = Boffsets[nBlocks]*sizeof(double); size_t CBytes = Coffsets[nBlocks]*sizeof(double); double *h_A; double *h_B; double *h_C; double *h_C_host; double *h_C_device; double *h_C_magma; h_A = (double*)malloc(ABytes); h_B = (double*)malloc(BBytes); h_C = (double*)malloc(CBytes); h_C_host = (double*)malloc(CBytes); h_C_device = (double*)malloc(CBytes); h_C_magma = (double*)malloc(CBytes); for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){ size_t Aoffset = Aoffsets[iBlock]; size_t Boffset = Boffsets[iBlock]; load_random_matrix(&h_A[Aoffset], Ms_array[iBlock], Ks_array[iBlock]); load_random_matrix(&h_B[Boffset], Ks_array[iBlock], Ns_array[iBlock]); } double start,stop; int check; ////////////////////////////////////////////////////////////////////// // Tests on host ////////////////////////////////////////////////////////////////////// start = omp_get_wtime(); host_array_matmul(h_A, h_B, h_C, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks); stop = omp_get_wtime(); printf("naive loop time: %f\n", stop - start); start = omp_get_wtime(); host_array_dgemm(h_A, h_B, h_C_host, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks); stop = omp_get_wtime(); printf("host blas time: %f\n", stop - start); check = check_matrix_array_equal(h_C_host, h_C, Coffsets, Coffsets, Ms_array, Ns_array, nBlocks); if( check == 0 ){ printf("check host dgemm failed: %d\n",check); } ////////////////////////////////////////////////////////////////////// // Run tests on device ////////////////////////////////////////////////////////////////////// rocblas_handle handle; rocblas_create_handle(&handle); start = omp_get_wtime(); rocblas_array_dgemm(handle, h_A, h_B, h_C_device, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks); stop = omp_get_wtime(); printf("rocblas wrapper time: %f\n", stop - start); check = check_matrix_array_equal(h_C_device, h_C, Coffsets, Coffsets, Ms_array, Ns_array, nBlocks); if( check == 0 ){ printf("check device dgemm failed: %d\n",check); } start = omp_get_wtime(); magma_array_dgemm(h_A, h_B, h_C_magma, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks); stop = omp_get_wtime(); printf("magma blas wrapper time: %f\n", stop - start); check = check_matrix_array_equal(h_C_magma, h_C, Coffsets, Coffsets, Ms_array, Ns_array, nBlocks); if( check == 0 ){ printf("magma dgemm failed: %d\n",check); } // Clean up rocblas_destroy_handle(handle); free(h_A); free(h_B); free(h_C); free(h_C_host); free(h_C_device); free(h_C_magma); magma_finalize(); return 0; }
{ "alphanum_fraction": 0.6144670051, "avg_line_length": 30.78125, "ext": "c", "hexsha": "2c227ba2eee44a06b39fd004b08b2d6b3d99ac06", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-22T01:26:09.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-01T23:33:57.000Z", "max_forks_repo_head_hexsha": "e794ed4120a2f28f8d9650f8501397a451eb88c3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "justinlietz/small_dgemms", "max_forks_repo_path": "amd/many-small-dgemms-amd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "e794ed4120a2f28f8d9650f8501397a451eb88c3", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "justinlietz/small_dgemms", "max_issues_repo_path": "amd/many-small-dgemms-amd.c", "max_line_length": 141, "max_stars_count": null, "max_stars_repo_head_hexsha": "e794ed4120a2f28f8d9650f8501397a451eb88c3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "justinlietz/small_dgemms", "max_stars_repo_path": "amd/many-small-dgemms-amd.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6071, "size": 19700 }
/*** * Copyright 2019 The Katla Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef KATLA_CORE_H #define KATLA_CORE_H #include "outcome/outcome.hpp" namespace outcome = OUTCOME_V2_NAMESPACE; #include "fmt/format.h" #include <gsl/span> #include <cstdio> #include <cstdlib> #include <string_view> #ifdef _MSC_VER #ifdef KATLA_CORE_INDLL # define KATLA_CORE_DECLSPEC __declspec(dllexport) #else # define KATLA_CORE_DECLSPEC __declspec(dllimport) #endif #else #define KATLA_CORE_DECLSPEC #endif namespace katla { template<class T, std::size_t Extent> using span = gsl::span<T, Extent>; /**** * Declare format and print here for convenience. Current implementation uses the Fmt lib, * the idea is to use std c++ format later. Which is the reason for the indirection. */ template <typename S, typename... Args> inline std::string format(const S& format_str, Args&&... args) { return fmt::format(format_str, args...); } template <typename S, typename... Args> inline void print(std::FILE* f, const S& format_str, Args&&... args) { fmt::print(f, format_str, args...); } template <typename S, typename... Args> inline void printInfo(const S& message, Args&&... args) { print(stdout, fmt::format("{}\n", message), args...); fflush(stdout); } template <typename S, typename... Args> inline void printError(const S& message, Args&&... args) { print(stderr, fmt::format("{}\n", message), args...); fflush(stderr); } template <typename S, typename... Args> inline void fatal(const S& message, Args&&... args) { print(stderr, fmt::format("{}\n", message), args...); fflush(stderr); std::abort(); } } #endif // KATLA_CORE_H
{ "alphanum_fraction": 0.6628056628, "avg_line_length": 28.7777777778, "ext": "h", "hexsha": "a6063c02be5477959cf5041afbbc428011c3d5db", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z", "max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "plok/katla", "max_forks_repo_path": "core/core.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "plok/katla", "max_issues_repo_path": "core/core.h", "max_line_length": 94, "max_stars_count": null, "max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "plok/katla", "max_stars_repo_path": "core/core.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 572, "size": 2331 }
static char help[] = "Newton's method for a three-variable system.\n" "The system is from fitting logistic population model\n" "P(t) = N / (1 + A exp(-Nbt)) to 3 points (t,P) from census data in\n" "D. Zill, 11th ed., exercise 4 in section 3.2. The points are\n" "(1790,3.929), (1850,23.192), (1910,91.972); populations in millions.\n"; /* example: $ make census $ ./census -snes_fd -snes_monitor 0 SNES Function norm 2.233793904584e+01 ... 17 SNES Function norm 6.521724317021e-07 18 SNES Function norm 4.358557709045e-09 Vec Object: 1 MPI processes type: seq 197.274 49.2096 0.000158863 */ #include <petsc.h> extern PetscErrorCode FormFunction(SNES, Vec, Vec, void*); int main(int argc,char **argv) { PetscErrorCode ierr; SNES snes; // nonlinear solver context Vec x, r; // solution, residual vectors double *ax; PetscInitialize(&argc,&argv,NULL,help); ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr); ierr = VecSetSizes(x,PETSC_DECIDE,3); CHKERRQ(ierr); ierr = VecSetFromOptions(x); CHKERRQ(ierr); ierr = VecSetUp(x); CHKERRQ(ierr); ierr = VecGetArray(x,&ax);CHKERRQ(ierr); // ax = [N, A, b]; see equations in FormFunction() below // these initial values are based on *guessing* N=300 // as the limiting population, then computing A, then b ax[0] = 300.0; ax[1] = 75.0; ax[2] = 1.0e-4; ierr = VecRestoreArray(x,&ax);CHKERRQ(ierr); ierr = VecAssemblyBegin(x);CHKERRQ(ierr); ierr = VecAssemblyEnd(x);CHKERRQ(ierr); ierr = VecDuplicate(x,&r); CHKERRQ(ierr); ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr); ierr = SNESSetFunction(snes,r,FormFunction,NULL); CHKERRQ(ierr); ierr = SNESSetFromOptions(snes); CHKERRQ(ierr); ierr = SNESSolve(snes,NULL,x); CHKERRQ(ierr); ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr); VecDestroy(&x); VecDestroy(&r); SNESDestroy(&snes); return PetscFinalize(); } PetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) { PetscErrorCode ierr; const double *ax; double *aF; ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr); ierr = VecGetArray(F,&aF);CHKERRQ(ierr); // ax = [N, A, b] // 3.929 (1 + A) - N = 0 // 23.192 (1 + A exp(-60*N*b)) - N = 0 // 91.972 (1 + A exp(-120*N*b)) - N = 0 aF[0] = 3.929 * (1.0 + ax[1]) - ax[0]; aF[1] = 23.192 * (1.0 + ax[1] * PetscExpReal(-60.0*ax[0]*ax[2])) - ax[0]; aF[2] = 91.972 * (1.0 + ax[1] * PetscExpReal(-120.0*ax[0]*ax[2])) - ax[0]; ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr); ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr); return 0; }
{ "alphanum_fraction": 0.6294492319, "avg_line_length": 33.7848101266, "ext": "c", "hexsha": "9f1d01a1dccc638701844594d66682e12a2eae47", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mapengfei-nwpu/p4pdes", "max_forks_repo_path": "c/ch4/solns/census.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mapengfei-nwpu/p4pdes", "max_issues_repo_path": "c/ch4/solns/census.c", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mapengfei-nwpu/p4pdes", "max_stars_repo_path": "c/ch4/solns/census.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 900, "size": 2669 }
/* multimin/simplex.c * * Copyright (C) 2007 Brian Gough * Copyright (C) 2002 Tuomo Keskitalo, Ivo Alxneit * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* - Originally written by Tuomo Keskitalo <tuomo.keskitalo@iki.fi> - Corrections to nmsimplex_iterate and other functions by Ivo Alxneit <ivo.alxneit@psi.ch> - Additional help by Brian Gough <bjg@network-theory.co.uk> */ /* The Simplex method of Nelder and Mead, also known as the polytope search alogorithm. Ref: Nelder, J.A., Mead, R., Computer Journal 7 (1965) pp. 308-313. This implementation uses n+1 corner points in the simplex. */ #include <config.h> #include <stdlib.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_multimin.h> typedef struct { gsl_matrix *x1; /* simplex corner points */ gsl_vector *y1; /* function value at corner points */ gsl_vector *ws1; /* workspace 1 for algorithm */ gsl_vector *ws2; /* workspace 2 for algorithm */ } nmsimplex_state_t; static double nmsimplex_move_corner (const double coeff, const nmsimplex_state_t * state, size_t corner, gsl_vector * xc, const gsl_multimin_function * f) { /* moves a simplex corner scaled by coeff (negative value represents mirroring by the middle point of the "other" corner points) and gives new corner in xc and function value at xc as a return value */ gsl_matrix *x1 = state->x1; size_t i, j; double newval, mp; for (j = 0; j < x1->size2; j++) { mp = 0.0; for (i = 0; i < x1->size1; i++) { if (i != corner) { mp += (gsl_matrix_get (x1, i, j)); } } mp /= (double) (x1->size1 - 1); newval = mp - coeff * (mp - gsl_matrix_get (x1, corner, j)); gsl_vector_set (xc, j, newval); } newval = GSL_MULTIMIN_FN_EVAL (f, xc); return newval; } static int nmsimplex_contract_by_best (nmsimplex_state_t * state, size_t best, gsl_vector * xc, gsl_multimin_function * f) { /* Function contracts the simplex in respect to best valued corner. That is, all corners besides the best corner are moved. */ /* the xc vector is simply work space here */ gsl_matrix *x1 = state->x1; gsl_vector *y1 = state->y1; size_t i, j; double newval; int status = GSL_SUCCESS; for (i = 0; i < x1->size1; i++) { if (i != best) { for (j = 0; j < x1->size2; j++) { newval = 0.5 * (gsl_matrix_get (x1, i, j) + gsl_matrix_get (x1, best, j)); gsl_matrix_set (x1, i, j, newval); } /* evaluate function in the new point */ gsl_matrix_get_row (xc, x1, i); newval = GSL_MULTIMIN_FN_EVAL (f, xc); gsl_vector_set (y1, i, newval); /* notify caller that we found at least one bad function value. we finish the contraction (and do not abort) to allow the user to handle the situation */ if(!gsl_finite(newval)) { status = GSL_EBADFUNC; } } } return status; } static int nmsimplex_calc_center (const nmsimplex_state_t * state, gsl_vector * mp) { /* calculates the center of the simplex to mp */ gsl_matrix *x1 = state->x1; size_t i, j; double val; for (j = 0; j < x1->size2; j++) { val = 0.0; for (i = 0; i < x1->size1; i++) { val += gsl_matrix_get (x1, i, j); } val /= x1->size1; gsl_vector_set (mp, j, val); } return GSL_SUCCESS; } static double nmsimplex_size (nmsimplex_state_t * state) { /* calculates simplex size as average sum of length of vectors from simplex center to corner points: ( sum ( || y - y_middlepoint || ) ) / n */ gsl_vector *s = state->ws1; gsl_vector *mp = state->ws2; gsl_matrix *x1 = state->x1; size_t i; double ss = 0.0; /* Calculate middle point */ nmsimplex_calc_center (state, mp); for (i = 0; i < x1->size1; i++) { gsl_matrix_get_row (s, x1, i); gsl_blas_daxpy (-1.0, mp, s); ss += gsl_blas_dnrm2 (s); } return ss / (double) (x1->size1); } static int nmsimplex_alloc (void *vstate, size_t n) { nmsimplex_state_t *state = (nmsimplex_state_t *) vstate; if (n == 0) { GSL_ERROR("invalid number of parameters specified", GSL_EINVAL); } state->x1 = gsl_matrix_alloc (n + 1, n); if (state->x1 == NULL) { GSL_ERROR ("failed to allocate space for x1", GSL_ENOMEM); } state->y1 = gsl_vector_alloc (n + 1); if (state->y1 == NULL) { gsl_matrix_free(state->x1); GSL_ERROR ("failed to allocate space for y", GSL_ENOMEM); } state->ws1 = gsl_vector_alloc (n); if (state->ws1 == NULL) { gsl_matrix_free(state->x1); gsl_vector_free(state->y1); GSL_ERROR ("failed to allocate space for ws1", GSL_ENOMEM); } state->ws2 = gsl_vector_alloc (n); if (state->ws2 == NULL) { gsl_matrix_free(state->x1); gsl_vector_free(state->y1); gsl_vector_free(state->ws1); GSL_ERROR ("failed to allocate space for ws2", GSL_ENOMEM); } return GSL_SUCCESS; } static int nmsimplex_set (void *vstate, gsl_multimin_function * f, const gsl_vector * x, double *size, const gsl_vector * step_size) { int status; size_t i; double val; nmsimplex_state_t *state = (nmsimplex_state_t *) vstate; gsl_vector *xtemp = state->ws1; if (xtemp->size != x->size) { GSL_ERROR("incompatible size of x", GSL_EINVAL); } if (xtemp->size != step_size->size) { GSL_ERROR("incompatible size of step_size", GSL_EINVAL); } /* first point is the original x0 */ val = GSL_MULTIMIN_FN_EVAL (f, x); if (!gsl_finite(val)) { GSL_ERROR("non-finite function value encountered", GSL_EBADFUNC); } gsl_matrix_set_row (state->x1, 0, x); gsl_vector_set (state->y1, 0, val); /* following points are initialized to x0 + step_size */ for (i = 0; i < x->size; i++) { status = gsl_vector_memcpy (xtemp, x); if (status != 0) { GSL_ERROR ("vector memcopy failed", GSL_EFAILED); } val = gsl_vector_get (xtemp, i) + gsl_vector_get (step_size, i); gsl_vector_set (xtemp, i, val); val = GSL_MULTIMIN_FN_EVAL (f, xtemp); if (!gsl_finite(val)) { GSL_ERROR("non-finite function value encountered", GSL_EBADFUNC); } gsl_matrix_set_row (state->x1, i + 1, xtemp); gsl_vector_set (state->y1, i + 1, val); } /* Initialize simplex size */ *size = nmsimplex_size (state); return GSL_SUCCESS; } static void nmsimplex_free (void *vstate) { nmsimplex_state_t *state = (nmsimplex_state_t *) vstate; gsl_matrix_free (state->x1); gsl_vector_free (state->y1); gsl_vector_free (state->ws1); gsl_vector_free (state->ws2); } static int nmsimplex_iterate (void *vstate, gsl_multimin_function * f, gsl_vector * x, double *size, double *fval) { /* Simplex iteration tries to minimize function f value */ /* Includes corrections from Ivo Alxneit <ivo.alxneit@psi.ch> */ nmsimplex_state_t *state = (nmsimplex_state_t *) vstate; /* xc and xc2 vectors store tried corner point coordinates */ gsl_vector *xc = state->ws1; gsl_vector *xc2 = state->ws2; gsl_vector *y1 = state->y1; gsl_matrix *x1 = state->x1; size_t n = y1->size; size_t i; size_t hi, s_hi, lo; double dhi, ds_hi, dlo; int status; double val, val2; if (xc->size != x->size) { GSL_ERROR("incompatible size of x", GSL_EINVAL); } /* get index of highest, second highest and lowest point */ dhi = dlo = gsl_vector_get (y1, 0); hi = 0; lo = 0; ds_hi = gsl_vector_get(y1, 1); s_hi = 1; for (i = 1; i < n; i++) { val = (gsl_vector_get (y1, i)); if (val < dlo) { dlo = val; lo = i; } else if (val > dhi) { ds_hi = dhi; s_hi = hi; dhi = val; hi = i; } else if (val > ds_hi) { ds_hi = val; s_hi = i; } } /* reflect the highest value */ val = nmsimplex_move_corner (-1.0, state, hi, xc, f); if (gsl_finite(val) && val < gsl_vector_get (y1, lo)) { /* reflected point becomes lowest point, try expansion */ val2 = nmsimplex_move_corner (-2.0, state, hi, xc2, f); if (gsl_finite(val2) && val2 < gsl_vector_get (y1, lo)) { gsl_matrix_set_row (x1, hi, xc2); gsl_vector_set (y1, hi, val2); } else { gsl_matrix_set_row (x1, hi, xc); gsl_vector_set (y1, hi, val); } } /* reflection does not improve things enough or we got a non-finite (illegal) function value */ else if (!gsl_finite(val) || val > gsl_vector_get (y1, s_hi)) { if (gsl_finite(val) && val <= gsl_vector_get (y1, hi)) { /* if trial point is better than highest point, replace highest point */ gsl_matrix_set_row (x1, hi, xc); gsl_vector_set (y1, hi, val); } /* try one dimensional contraction */ val2 = nmsimplex_move_corner (0.5, state, hi, xc2, f); if (gsl_finite(val2) && val2 <= gsl_vector_get (y1, hi)) { gsl_matrix_set_row (state->x1, hi, xc2); gsl_vector_set (y1, hi, val2); } else { /* contract the whole simplex in respect to the best point */ status = nmsimplex_contract_by_best (state, lo, xc, f); if (status != GSL_SUCCESS) { GSL_ERROR ("nmsimplex_contract_by_best failed", GSL_EFAILED); } } } else { /* trial point is better than second highest point. Replace highest point by it */ gsl_matrix_set_row (x1, hi, xc); gsl_vector_set (y1, hi, val); } /* return lowest point of simplex as x */ lo = gsl_vector_min_index (y1); gsl_matrix_get_row (x, x1, lo); *fval = gsl_vector_get (y1, lo); /* Update simplex size */ *size = nmsimplex_size (state); return GSL_SUCCESS; } static const gsl_multimin_fminimizer_type nmsimplex_type = { "nmsimplex", /* name */ sizeof (nmsimplex_state_t), &nmsimplex_alloc, &nmsimplex_set, &nmsimplex_iterate, &nmsimplex_free }; const gsl_multimin_fminimizer_type * gsl_multimin_fminimizer_nmsimplex = &nmsimplex_type;
{ "alphanum_fraction": 0.5971178499, "avg_line_length": 24.1688034188, "ext": "c", "hexsha": "0d05b1b6a9b37147eb851abd2e1092d8dc3da649", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multimin/simplex.c", "max_issues_count": 6, "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multimin/simplex.c", "max_line_length": 81, "max_stars_count": 14, "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_path": "gsl-2.6/multimin/simplex.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 3319, "size": 11311 }
// Copyright The Authors 2018. // Distributed under the 3-Clause BSD License. // (See accompanying file LICENSE or copy at // https://opensource.org/licenses/BSD-3-Clause) #pragma once #include <cstdint> // for std::uint8_t #include <gsl/gsl> // for gsl::span<std::uint8_t> #include <vector> // for std::vector<std::uint8_t> namespace blocxxi { namespace p2p { namespace kademlia { /// Represents an output buffer to which headers and message bodies can be /// serialized. Whatever type is used, it needs to be able to expand as needed. using Buffer = std::vector<std::uint8_t>; /// Represents a read-only view over the input buffer used to deserialize /// headers and message bodies. using BufferReader = gsl::span<std::uint8_t>; } // namespace kademlia } // namespace p2p } // namespace blocxxi
{ "alphanum_fraction": 0.7115151515, "avg_line_length": 30.5555555556, "ext": "h", "hexsha": "217e4f6cf6dcb02882a1a3d0eaf9802f5852d858", "lang": "C", "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z", "max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z", "max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "canhld94/blocxxi", "max_forks_repo_path": "p2p/include/p2p/kademlia/buffer.h", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "canhld94/blocxxi", "max_issues_repo_path": "p2p/include/p2p/kademlia/buffer.h", "max_line_length": 79, "max_stars_count": 24, "max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "canhld94/blocxxi", "max_stars_repo_path": "p2p/include/p2p/kademlia/buffer.h", "max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z", "max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z", "num_tokens": 211, "size": 825 }
#include <stdio.h> #include <gsl/gsl_const_mksa.h> int main (void) { double c = GSL_CONST_MKS_SPEED_OF_LIGHT; double au = GSL_CONST_MKS_ASTRONOMICAL_UNIT; double min = GSL_CONST_MKS_MINUTE; double r_earth = 1.00 * au; double r_mars = 1.52 * au; double tmin, tmax; tmin = (r_mars - r_earth)/c; tmax = (r_mars + r_earth)/c; printf("light travel time from Earth to Mars:\n"); printf("minimum = %.1f minutes\n", tmin/min); printf("maximum = %.1f minutes\n", tmax/min); }
{ "alphanum_fraction": 0.6720321932, "avg_line_length": 20.7083333333, "ext": "c", "hexsha": "5c302e9662456efa3df2dddb6959a5eb6257d431", "lang": "C", "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z", "max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/const/demo.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/const/demo.c", "max_line_length": 52, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/const/demo.c", "max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z", "num_tokens": 172, "size": 497 }
/* matrix/gsl_matrix_ushort.h * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSL_MATRIX_USHORT_H__ #define __GSL_MATRIX_USHORT_H__ #if !defined( GSL_FUN ) # if !defined( GSL_DLL ) # define GSL_FUN extern # elif defined( BUILD_GSL_DLL ) # define GSL_FUN extern __declspec(dllexport) # else # define GSL_FUN extern __declspec(dllimport) # endif #endif #include <stdlib.h> #include <gsl/gsl_types.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_inline.h> #include <gsl/gsl_check_range.h> #include <gsl/gsl_vector_ushort.h> #undef __BEGIN_DECLS #undef __END_DECLS #ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } #else # define __BEGIN_DECLS /* empty */ # define __END_DECLS /* empty */ #endif __BEGIN_DECLS typedef struct { size_t size1; size_t size2; size_t tda; unsigned short * data; gsl_block_ushort * block; int owner; } gsl_matrix_ushort; typedef struct { gsl_matrix_ushort matrix; } _gsl_matrix_ushort_view; typedef _gsl_matrix_ushort_view gsl_matrix_ushort_view; typedef struct { gsl_matrix_ushort matrix; } _gsl_matrix_ushort_const_view; typedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view; /* Allocation */ GSL_FUN gsl_matrix_ushort * gsl_matrix_ushort_alloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_ushort * gsl_matrix_ushort_calloc (const size_t n1, const size_t n2); GSL_FUN gsl_matrix_ushort * gsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b, const size_t offset, const size_t n1, const size_t n2, const size_t d2); GSL_FUN gsl_matrix_ushort * gsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m, const size_t k1, const size_t k2, const size_t n1, const size_t n2); GSL_FUN gsl_vector_ushort * gsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m, const size_t i); GSL_FUN gsl_vector_ushort * gsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m, const size_t j); GSL_FUN void gsl_matrix_ushort_free (gsl_matrix_ushort * m); /* Views */ GSL_FUN _gsl_matrix_ushort_view gsl_matrix_ushort_submatrix (gsl_matrix_ushort * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_diagonal (gsl_matrix_ushort * m); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_subrow (gsl_matrix_ushort * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_ushort_view gsl_matrix_ushort_subcolumn (gsl_matrix_ushort * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_ushort_view gsl_matrix_ushort_view_array (unsigned short * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_ushort_view gsl_matrix_ushort_view_array_with_tda (unsigned short * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_ushort_view gsl_matrix_ushort_view_vector (gsl_vector_ushort * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_ushort_view gsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m, const size_t i, const size_t j, const size_t n1, const size_t n2); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_row (const gsl_matrix_ushort * m, const size_t i); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_column (const gsl_matrix_ushort * m, const size_t j); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m, const size_t k); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m, const size_t k); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_subrow (const gsl_matrix_ushort * m, const size_t i, const size_t offset, const size_t n); GSL_FUN _gsl_vector_ushort_const_view gsl_matrix_ushort_const_subcolumn (const gsl_matrix_ushort * m, const size_t j, const size_t offset, const size_t n); GSL_FUN _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_array (const unsigned short * base, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base, const size_t n1, const size_t n2, const size_t tda); GSL_FUN _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v, const size_t n1, const size_t n2); GSL_FUN _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v, const size_t n1, const size_t n2, const size_t tda); /* Operations */ GSL_FUN void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m); GSL_FUN void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m); GSL_FUN void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x); GSL_FUN int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ; GSL_FUN int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ; GSL_FUN int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m); GSL_FUN int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format); GSL_FUN int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src); GSL_FUN int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, gsl_matrix_ushort * m2); GSL_FUN int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_FUN int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m); GSL_FUN int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src); GSL_FUN unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m); GSL_FUN unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m); GSL_FUN void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out); GSL_FUN void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax); GSL_FUN void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin); GSL_FUN void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax); GSL_FUN int gsl_matrix_ushort_equal (const gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_FUN int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m); GSL_FUN int gsl_matrix_ushort_ispos (const gsl_matrix_ushort * m); GSL_FUN int gsl_matrix_ushort_isneg (const gsl_matrix_ushort * m); GSL_FUN int gsl_matrix_ushort_isnonneg (const gsl_matrix_ushort * m); GSL_FUN int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_FUN int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_FUN int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_FUN int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b); GSL_FUN int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x); GSL_FUN int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x); GSL_FUN int gsl_matrix_ushort_add_diagonal (gsl_matrix_ushort * a, const double x); /***********************************************************************/ /* The functions below are obsolete */ /***********************************************************************/ GSL_FUN int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i); GSL_FUN int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j); GSL_FUN int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v); GSL_FUN int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v); /***********************************************************************/ /* inline functions if you are using GCC */ GSL_FUN INLINE_DECL unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x); GSL_FUN INLINE_DECL unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j); GSL_FUN INLINE_DECL const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j); #ifdef HAVE_INLINE INLINE_FUN unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ; } else if (j >= m->size2) { GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ; } } #endif return m->data[i * m->tda + j] ; } INLINE_FUN void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ; } } #endif m->data[i * m->tda + j] = x ; } INLINE_FUN unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (unsigned short *) (m->data + (i * m->tda + j)) ; } INLINE_FUN const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j) { #if GSL_RANGE_CHECK if (GSL_RANGE_COND(1)) { if (i >= m->size1) { GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ; } else if (j >= m->size2) { GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ; } } #endif return (const unsigned short *) (m->data + (i * m->tda + j)) ; } #endif __END_DECLS #endif /* __GSL_MATRIX_USHORT_H__ */
{ "alphanum_fraction": 0.6728784617, "avg_line_length": 37.3102493075, "ext": "h", "hexsha": "300e23b46ece49af649092839db4731d9ec32b09", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_forks_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_ushort.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_issues_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_ushort.h", "max_line_length": 134, "max_stars_count": null, "max_stars_repo_head_hexsha": "7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mharding01/augmented-neuromuscular-RT-running", "max_stars_repo_path": "mbsysCopy/win64_include_lib/include/gsl/gsl_matrix_ushort.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3417, "size": 13469 }
#pragma once #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES3/gl3.h> #include <GLES3/gl3ext.h> #include <GLES3/gl3platform.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include <gsl/gsl> namespace android::OpenGLHelpers { constexpr GLint GetTextureUnit(GLenum texture) { return texture - GL_TEXTURE0; } GLuint CreateShaderProgram(const char* vertShaderSource, const char* fragShaderSource); namespace GLTransactions { inline auto MakeCurrent(EGLDisplay display, EGLSurface drawSurface, EGLSurface readSurface, EGLContext context) { EGLDisplay previousDisplay{ eglGetDisplay(EGL_DEFAULT_DISPLAY) }; EGLSurface previousDrawSurface{ eglGetCurrentSurface(EGL_DRAW) }; EGLSurface previousReadSurface{ eglGetCurrentSurface(EGL_READ) }; EGLContext previousContext{ eglGetCurrentContext() }; eglMakeCurrent(display, drawSurface, readSurface, context); return gsl::finally([previousDisplay, previousDrawSurface, previousReadSurface, previousContext]() { eglMakeCurrent(previousDisplay, previousDrawSurface, previousReadSurface, previousContext); }); } } }
{ "alphanum_fraction": 0.7235636969, "avg_line_length": 36.3939393939, "ext": "h", "hexsha": "d97af33bace18bf7df463d0a8a0f92b4b22f05bf", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "fc7b2add9da4ef8e79ad86e087457685bdb2417f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "EricBeetsOfficial-Opuscope/BabylonNative", "max_forks_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "fc7b2add9da4ef8e79ad86e087457685bdb2417f", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "EricBeetsOfficial-Opuscope/BabylonNative", "max_issues_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_line_length": 208, "max_stars_count": null, "max_stars_repo_head_hexsha": "fc7b2add9da4ef8e79ad86e087457685bdb2417f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "EricBeetsOfficial-Opuscope/BabylonNative", "max_stars_repo_path": "Dependencies/AndroidExtensions/Include/AndroidExtensions/OpenGLHelpers.h", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 277, "size": 1201 }
/* linalg/svd.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2007 Gerard Jungman, Brian Gough * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_blas.h> #include <gsl/gsl_linalg.h> #include "givens.c" #include "svdstep.c" /* Factorise a general M x N matrix A into, * * A = U D V^T * * where U is a column-orthogonal M x N matrix (U^T U = I), * D is a diagonal N x N matrix, * and V is an N x N orthogonal matrix (V^T V = V V^T = I) * * U is stored in the original matrix A, which has the same size * * V is stored as a separate matrix (not V^T). You must take the * transpose to form the product above. * * The diagonal matrix D is stored in the vector S, D_ii = S_i */ int gsl_linalg_SV_decomp (gsl_matrix * A, gsl_matrix * V, gsl_vector * S, gsl_vector * work) { size_t a, b, i, j, iter; const size_t M = A->size1; const size_t N = A->size2; const size_t K = GSL_MIN (M, N); if (M < N) { GSL_ERROR ("svd of MxN matrix, M<N, is not implemented", GSL_EUNIMPL); } else if (V->size1 != N) { GSL_ERROR ("square matrix V must match second dimension of matrix A", GSL_EBADLEN); } else if (V->size1 != V->size2) { GSL_ERROR ("matrix V must be square", GSL_ENOTSQR); } else if (S->size != N) { GSL_ERROR ("length of vector S must match second dimension of matrix A", GSL_EBADLEN); } else if (work->size != N) { GSL_ERROR ("length of workspace must match second dimension of matrix A", GSL_EBADLEN); } /* Handle the case of N = 1 (SVD of a column vector) */ if (N == 1) { gsl_vector_view column = gsl_matrix_column (A, 0); double norm = gsl_blas_dnrm2 (&column.vector); gsl_vector_set (S, 0, norm); gsl_matrix_set (V, 0, 0, 1.0); if (norm != 0.0) { gsl_blas_dscal (1.0/norm, &column.vector); } return GSL_SUCCESS; } { gsl_vector_view f = gsl_vector_subvector (work, 0, K - 1); /* bidiagonalize matrix A, unpack A into U S V */ gsl_linalg_bidiag_decomp (A, S, &f.vector); gsl_linalg_bidiag_unpack2 (A, S, &f.vector, V); /* apply reduction steps to B=(S,Sd) */ chop_small_elements (S, &f.vector); /* Progressively reduce the matrix until it is diagonal */ b = N - 1; iter = 0; while (b > 0) { double fbm1 = gsl_vector_get (&f.vector, b - 1); if (fbm1 == 0.0 || gsl_isnan (fbm1)) { b--; continue; } /* Find the largest unreduced block (a,b) starting from b and working backwards */ a = b - 1; while (a > 0) { double fam1 = gsl_vector_get (&f.vector, a - 1); if (fam1 == 0.0 || gsl_isnan (fam1)) { break; } a--; } iter++; if (iter > 100 * N) { GSL_ERROR("SVD decomposition failed to converge", GSL_EMAXITER); } { const size_t n_block = b - a + 1; gsl_vector_view S_block = gsl_vector_subvector (S, a, n_block); gsl_vector_view f_block = gsl_vector_subvector (&f.vector, a, n_block - 1); gsl_matrix_view U_block = gsl_matrix_submatrix (A, 0, a, A->size1, n_block); gsl_matrix_view V_block = gsl_matrix_submatrix (V, 0, a, V->size1, n_block); qrstep (&S_block.vector, &f_block.vector, &U_block.matrix, &V_block.matrix); /* remove any small off-diagonal elements */ chop_small_elements (&S_block.vector, &f_block.vector); } } } /* Make singular values positive by reflections if necessary */ for (j = 0; j < K; j++) { double Sj = gsl_vector_get (S, j); if (Sj < 0.0) { for (i = 0; i < N; i++) { double Vij = gsl_matrix_get (V, i, j); gsl_matrix_set (V, i, j, -Vij); } gsl_vector_set (S, j, -Sj); } } /* Sort singular values into decreasing order */ for (i = 0; i < K; i++) { double S_max = gsl_vector_get (S, i); size_t i_max = i; for (j = i + 1; j < K; j++) { double Sj = gsl_vector_get (S, j); if (Sj > S_max) { S_max = Sj; i_max = j; } } if (i_max != i) { /* swap eigenvalues */ gsl_vector_swap_elements (S, i, i_max); /* swap eigenvectors */ gsl_matrix_swap_columns (A, i, i_max); gsl_matrix_swap_columns (V, i, i_max); } } return GSL_SUCCESS; } /* Modified algorithm which is better for M>>N */ int gsl_linalg_SV_decomp_mod (gsl_matrix * A, gsl_matrix * X, gsl_matrix * V, gsl_vector * S, gsl_vector * work) { size_t i, j; const size_t M = A->size1; const size_t N = A->size2; if (M < N) { GSL_ERROR ("svd of MxN matrix, M<N, is not implemented", GSL_EUNIMPL); } else if (V->size1 != N) { GSL_ERROR ("square matrix V must match second dimension of matrix A", GSL_EBADLEN); } else if (V->size1 != V->size2) { GSL_ERROR ("matrix V must be square", GSL_ENOTSQR); } else if (X->size1 != N) { GSL_ERROR ("square matrix X must match second dimension of matrix A", GSL_EBADLEN); } else if (X->size1 != X->size2) { GSL_ERROR ("matrix X must be square", GSL_ENOTSQR); } else if (S->size != N) { GSL_ERROR ("length of vector S must match second dimension of matrix A", GSL_EBADLEN); } else if (work->size != N) { GSL_ERROR ("length of workspace must match second dimension of matrix A", GSL_EBADLEN); } if (N == 1) { gsl_vector_view column = gsl_matrix_column (A, 0); double norm = gsl_blas_dnrm2 (&column.vector); gsl_vector_set (S, 0, norm); gsl_matrix_set (V, 0, 0, 1.0); if (norm != 0.0) { gsl_blas_dscal (1.0/norm, &column.vector); } return GSL_SUCCESS; } /* Convert A into an upper triangular matrix R */ for (i = 0; i < N; i++) { gsl_vector_view c = gsl_matrix_column (A, i); gsl_vector_view v = gsl_vector_subvector (&c.vector, i, M - i); double tau_i = gsl_linalg_householder_transform (&v.vector); /* Apply the transformation to the remaining columns */ if (i + 1 < N) { gsl_matrix_view m = gsl_matrix_submatrix (A, i, i + 1, M - i, N - (i + 1)); gsl_linalg_householder_hm (tau_i, &v.vector, &m.matrix); } gsl_vector_set (S, i, tau_i); } /* Copy the upper triangular part of A into X */ for (i = 0; i < N; i++) { for (j = 0; j < i; j++) { gsl_matrix_set (X, i, j, 0.0); } { double Aii = gsl_matrix_get (A, i, i); gsl_matrix_set (X, i, i, Aii); } for (j = i + 1; j < N; j++) { double Aij = gsl_matrix_get (A, i, j); gsl_matrix_set (X, i, j, Aij); } } /* Convert A into an orthogonal matrix L */ for (j = N; j-- > 0;) { /* Householder column transformation to accumulate L */ double tj = gsl_vector_get (S, j); gsl_matrix_view m = gsl_matrix_submatrix (A, j, j, M - j, N - j); gsl_linalg_householder_hm1 (tj, &m.matrix); } /* unpack R into X V S */ gsl_linalg_SV_decomp (X, V, S, work); /* Multiply L by X, to obtain U = L X, stored in U */ { gsl_vector_view sum = gsl_vector_subvector (work, 0, N); for (i = 0; i < M; i++) { gsl_vector_view L_i = gsl_matrix_row (A, i); gsl_vector_set_zero (&sum.vector); for (j = 0; j < N; j++) { double Lij = gsl_vector_get (&L_i.vector, j); gsl_vector_view X_j = gsl_matrix_row (X, j); gsl_blas_daxpy (Lij, &X_j.vector, &sum.vector); } gsl_vector_memcpy (&L_i.vector, &sum.vector); } } return GSL_SUCCESS; } /* Solves the system A x = b using the SVD factorization * * A = U S V^T * * to obtain x. For M x N systems it finds the solution in the least * squares sense. */ int gsl_linalg_SV_solve (const gsl_matrix * U, const gsl_matrix * V, const gsl_vector * S, const gsl_vector * b, gsl_vector * x) { if (U->size1 != b->size) { GSL_ERROR ("first dimension of matrix U must size of vector b", GSL_EBADLEN); } else if (U->size2 != S->size) { GSL_ERROR ("length of vector S must match second dimension of matrix U", GSL_EBADLEN); } else if (V->size1 != V->size2) { GSL_ERROR ("matrix V must be square", GSL_ENOTSQR); } else if (S->size != V->size1) { GSL_ERROR ("length of vector S must match size of matrix V", GSL_EBADLEN); } else if (V->size2 != x->size) { GSL_ERROR ("size of matrix V must match size of vector x", GSL_EBADLEN); } else { const size_t N = U->size2; size_t i; gsl_vector *w = gsl_vector_calloc (N); gsl_blas_dgemv (CblasTrans, 1.0, U, b, 0.0, w); for (i = 0; i < N; i++) { double wi = gsl_vector_get (w, i); double alpha = gsl_vector_get (S, i); if (alpha != 0) alpha = 1.0 / alpha; gsl_vector_set (w, i, alpha * wi); } gsl_blas_dgemv (CblasNoTrans, 1.0, V, w, 0.0, x); gsl_vector_free (w); return GSL_SUCCESS; } } /* This is a the jacobi version */ /* Author: G. Jungman */ /* * Algorithm due to J.C. Nash, Compact Numerical Methods for * Computers (New York: Wiley and Sons, 1979), chapter 3. * See also Algorithm 4.1 in * James Demmel, Kresimir Veselic, "Jacobi's Method is more * accurate than QR", Lapack Working Note 15 (LAWN15), October 1989. * Available from netlib. * * Based on code by Arthur Kosowsky, Rutgers University * kosowsky@physics.rutgers.edu * * Another relevant paper is, P.P.M. De Rijk, "A One-Sided Jacobi * Algorithm for computing the singular value decomposition on a * vector computer", SIAM Journal of Scientific and Statistical * Computing, Vol 10, No 2, pp 359-371, March 1989. * */ int gsl_linalg_SV_decomp_jacobi (gsl_matrix * A, gsl_matrix * Q, gsl_vector * S) { if (A->size1 < A->size2) { /* FIXME: only implemented M>=N case so far */ GSL_ERROR ("svd of MxN matrix, M<N, is not implemented", GSL_EUNIMPL); } else if (Q->size1 != A->size2) { GSL_ERROR ("square matrix Q must match second dimension of matrix A", GSL_EBADLEN); } else if (Q->size1 != Q->size2) { GSL_ERROR ("matrix Q must be square", GSL_ENOTSQR); } else if (S->size != A->size2) { GSL_ERROR ("length of vector S must match second dimension of matrix A", GSL_EBADLEN); } else { const size_t M = A->size1; const size_t N = A->size2; size_t i, j, k; /* Initialize the rotation counter and the sweep counter. */ int count = 1; int sweep = 0; int sweepmax = 5*N; double tolerance = 10 * M * GSL_DBL_EPSILON; /* Always do at least 12 sweeps. */ sweepmax = GSL_MAX (sweepmax, 12); /* Set Q to the identity matrix. */ gsl_matrix_set_identity (Q); /* Store the column error estimates in S, for use during the orthogonalization */ for (j = 0; j < N; j++) { gsl_vector_view cj = gsl_matrix_column (A, j); double sj = gsl_blas_dnrm2 (&cj.vector); gsl_vector_set(S, j, GSL_DBL_EPSILON * sj); } /* Orthogonalize A by plane rotations. */ while (count > 0 && sweep <= sweepmax) { /* Initialize rotation counter. */ count = N * (N - 1) / 2; for (j = 0; j < N - 1; j++) { for (k = j + 1; k < N; k++) { double a = 0.0; double b = 0.0; double p = 0.0; double q = 0.0; double cosine, sine; double v; double abserr_a, abserr_b; int sorted, orthog, noisya, noisyb; gsl_vector_view cj = gsl_matrix_column (A, j); gsl_vector_view ck = gsl_matrix_column (A, k); gsl_blas_ddot (&cj.vector, &ck.vector, &p); p *= 2.0 ; /* equation 9a: p = 2 x.y */ a = gsl_blas_dnrm2 (&cj.vector); b = gsl_blas_dnrm2 (&ck.vector); q = a * a - b * b; v = hypot(p, q); /* test for columns j,k orthogonal, or dominant errors */ abserr_a = gsl_vector_get(S,j); abserr_b = gsl_vector_get(S,k); sorted = (GSL_COERCE_DBL(a) >= GSL_COERCE_DBL(b)); orthog = (fabs (p) <= tolerance * GSL_COERCE_DBL(a * b)); noisya = (a < abserr_a); noisyb = (b < abserr_b); if (sorted && (orthog || noisya || noisyb)) { count--; continue; } /* calculate rotation angles */ if (v == 0 || !sorted) { cosine = 0.0; sine = 1.0; } else { cosine = sqrt((v + q) / (2.0 * v)); sine = p / (2.0 * v * cosine); } /* apply rotation to A */ for (i = 0; i < M; i++) { const double Aik = gsl_matrix_get (A, i, k); const double Aij = gsl_matrix_get (A, i, j); gsl_matrix_set (A, i, j, Aij * cosine + Aik * sine); gsl_matrix_set (A, i, k, -Aij * sine + Aik * cosine); } gsl_vector_set(S, j, fabs(cosine) * abserr_a + fabs(sine) * abserr_b); gsl_vector_set(S, k, fabs(sine) * abserr_a + fabs(cosine) * abserr_b); /* apply rotation to Q */ for (i = 0; i < N; i++) { const double Qij = gsl_matrix_get (Q, i, j); const double Qik = gsl_matrix_get (Q, i, k); gsl_matrix_set (Q, i, j, Qij * cosine + Qik * sine); gsl_matrix_set (Q, i, k, -Qij * sine + Qik * cosine); } } } /* Sweep completed. */ sweep++; } /* * Orthogonalization complete. Compute singular values. */ { double prev_norm = -1.0; for (j = 0; j < N; j++) { gsl_vector_view column = gsl_matrix_column (A, j); double norm = gsl_blas_dnrm2 (&column.vector); /* Determine if singular value is zero, according to the criteria used in the main loop above (i.e. comparison with norm of previous column). */ if (norm == 0.0 || prev_norm == 0.0 || (j > 0 && norm <= tolerance * prev_norm)) { gsl_vector_set (S, j, 0.0); /* singular */ gsl_vector_set_zero (&column.vector); /* annihilate column */ prev_norm = 0.0; } else { gsl_vector_set (S, j, norm); /* non-singular */ gsl_vector_scale (&column.vector, 1.0 / norm); /* normalize column */ prev_norm = norm; } } } if (count > 0) { /* reached sweep limit */ GSL_ERROR ("Jacobi iterations did not reach desired tolerance", GSL_ETOL); } return GSL_SUCCESS; } }
{ "alphanum_fraction": 0.5090480841, "avg_line_length": 27.6301587302, "ext": "c", "hexsha": "32033d860ef7f3c9f699693b40eb43a9cb8a08bb", "lang": "C", "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "skair39/structured", "max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/svd.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "skair39/structured", "max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/svd.c", "max_line_length": 88, "max_stars_count": 14, "max_stars_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "mattjr/structured", "max_stars_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/svd.c", "max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z", "num_tokens": 4753, "size": 17407 }
#include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv.h> #include <math.h> #ifndef CRANESUB char *fn1="crane1io.dat"; char *fn2="crane2io.dat"; FILE *fp; #endif//#ifndef CRANESUB typedef struct{ double g;//gravity double M;//mass of the car double m;//mass of the load double r;//length of the rope double C;//damping coefficient double F;//input force double T;//tension to the rope double x,x0;//x position of the load double y,y0;//y position of the load double X;//X position of the car double a;//angle (theta) double dx,dx0; double dy,dy0; double dX,dX0; double dr; double da,da0; double ddx; double ddy; double ddX; double ddr; double dda; double dXmax; double ddXmax; double Fmax;//Force double h; int nh; double _h; int _dim; double *_y; double *_y_err; double *_dydt_in; double *_dydt_out; const gsl_odeiv_step_type *_T; gsl_odeiv_step *_s; gsl_odeiv_system _sys; double _t; // int *initialize; int (*cranefunc)(); double (*plant)(); //int (*p) (int num); /* 関数ポインタpを宣言 */ } CRANE; #define dim_crane 4 //double ddXn;//for check int crane1func (double t, const double y[], double f[], void *params) { CRANE *c = (CRANE *)params; //y[0]=crane->p, y[1]=crane->dp, y[2]=crane->X, y[3]=crane->dX f[0] = y[1]; f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; // f[1] = (-2*c->dr -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; f[2] = y[3]; f[3] = c->ddX; // if(fabs(t-(int)t)<1e6) fprintf(stderr,"check t=%g f=%g,%g,%g,%g\n ",t,f[0],f[1],f[2],f[3]); // if(fabs(t-(int)(t+0.5))<1e8) fprintf(stderr,"check t=%g y=%g,%g,%g,%g\n ",t,y[0],y[1],y[2],y[3]); // if(ddXn>0){ // fprintf(stderr,"t=%g check?? ddXn=%g=?=%g\n",t,ddXn,c->ddX); // } // double dd=fabs(t-(int)(t+0.5)); if(t>5 && dd<1e-12){ // fprintf(stderr,"check t=%g c->ddX=%g, t=%g, it=%d.dd=%g\n ",t,c->ddX,t,(int)(t+0.5),dd); // } return GSL_SUCCESS; } //////////////// //#define square(x) ((x)*(x)) double square(double x){return((x)*(x));} //double plant(double uu) double plant1(double uu,CRANE *crane) { // fprintf(stderr,"check uu=%g, ",uu); if(uu>crane->ddXmax) uu=crane->ddXmax; else if(uu<-crane->ddXmax) uu=-crane->ddXmax; // fprintf(stderr,"->%g, \n",uu); int n; for(n=0;n<crane->nh;n++){ crane->ddX=uu;//crane->ddX=(uu<crane->ddXmax)?uu:crane->ddXmax; // if(ddXn>0){ // fprintf(stderr,"ddXn=%g=?=%g\n",ddXn,crane->ddX); // } if(crane->dX>=crane->dXmax && crane->ddX>0) crane->ddX=0; else if(crane->dX<=-crane->dXmax && crane->ddX<0) crane->ddX=0; int status = gsl_odeiv_step_apply (crane->_s, crane->_t, crane->_h, crane->_y, crane->_y_err, crane->_dydt_in, crane->_dydt_out, &crane->_sys); if (status != GSL_SUCCESS) {fprintf(stderr,"### failure of plant calc.\n"); break;} int i;for(i=0;i<dim_crane;i++) crane->_dydt_in[i]=crane->_dydt_out[i]; crane->_t+=crane->_h; crane->a =crane->_y[0]; crane->da =crane->_y[1]; crane->X =crane->_y[2]; crane->dX =crane->_y[3]; crane->x =crane->X+crane->r * sin(crane->a); //output y crane->y =crane->r*cos(crane->a); crane->dx=(crane->x-crane->x0)/crane->_h; crane->dy=(crane->y-crane->y0)/crane->_h; crane->ddx=(crane->dx-crane->dx0)/crane->_h; crane->ddy=(crane->dy-crane->dy0)/crane->_h; crane->T=crane->m*sqrt(square(crane->ddx)+square(crane->ddy-crane->g)); crane->F=crane->M*crane->ddX-crane->T*sin(crane->a); crane->dda=(crane->da-crane->da0)/crane->_h; crane->x0=crane->x; crane->y0=crane->y; crane->dx0=crane->dx; crane->dy0=crane->dy; crane->da0=crane->da; } #ifndef CRANESUB fprintf(fp,"%.7e %.7e %.7e", crane->_t,crane->_y[0],crane->_y[1]);//crane->a,crane->da fprintf(fp," %.7e %.7e %.7e" ,crane->X,crane->dX,crane->ddX); fprintf(fp," %.7e %.7e %.7e" ,crane->x,crane->dx,crane->ddx); fprintf(fp," %.7e %.7e %.7e" ,crane->y,crane->dy,crane->ddy); fprintf(fp," %.7e %.7e" ,crane->T,crane->F); fprintf(fp,"\n"); #endif //#ifndef CRANESUB return(crane->x);//crane->x in [0,AP_y=10?] ==> rt in [0,1] } int initialize1(CRANE *crane) { crane->cranefunc=crane1func; crane->plant=plant1; crane->g=9.8; crane->M=100; crane->m=20;//10;//20 crane->r=5;//5; crane->C=1;//5; crane->dr=crane->ddr=0; crane->x0=0; crane->y0=crane->r; crane->dx0=crane->dy0=crane->da0=0; crane->dXmax=1.;//??ddXmax=(dXmax-dX)/dt;//?? crane->ddXmax=0.2;//??ddXmax=(dXmax-dX)/dt;//?? crane->Fmax=30.0;//check// crane->Fmax=30;//check #ifdef CRANESUB crane->h=AP_tS; crane->m=_crane_m; crane->r=_crane_r; crane->dXmax=_crane_dXmax; if(_AP_umax>0) AP_u_max=crane->ddXmax=_AP_umax; else AP_u_max=crane->ddXmax; AP_u_min=-AP_u_max; // starttime=0; // totaltime=50; rr=AP_r=_AP_r;//10 rr_kyoyou=_rr_kyoyou; // p=(double *)malloc(buffsize*sizeof(double)); C_MODE=11; // iteration=_iteration; #else crane->h=0.01; #endif crane->nh=10; crane->_h=crane->h/crane->nh;//0.001 crane->_dim=4; if(crane->_y==NULL){ crane->_y=(double*)malloc(crane->_dim*sizeof(double)); crane->_y_err=(double*)malloc(crane->_dim*sizeof(double)); crane->_dydt_in=(double*)malloc(crane->_dim*sizeof(double)); crane->_dydt_out=(double*)malloc(crane->_dim*sizeof(double)); } crane->_T= gsl_odeiv_step_rk4; crane->_s= gsl_odeiv_step_alloc (crane->_T, crane->_dim); crane->_sys= (gsl_odeiv_system){crane1func, NULL, crane->_dim, crane}; // crane->_sys= (gsl_odeiv_system){crane1func, NULL, crane->_dim, &crane}; // crane->_sys= (gsl_odeiv_system){crane->cranefunc, NULL, crane->_dim, &crane}; //initialize variables crane->_t=crane->_y[0]=crane->_y[1]=crane->_y[2]=crane->_y[3]=0; int i;for(i=0;i<crane->_dim;i++) crane->_dydt_in[i]=0; GSL_ODEIV_FN_EVAL(&(crane->_sys), crane->_t, crane->_y, crane->_dydt_in); // crane->a =crane->_y[0]; // crane->da =crane->_y[1]; // crane->X =crane->_y[2]; // crane->dX =crane->_y[3]; // crane->x =crane->X+crane->r * sin(crane->a); //output y // crane->y =crane->r*cos(crane->a); // crane->dXmax=1.;//??ddXmax=(dXmax-dX)/dt;//?? // crane->ddXmax=0.2;//??ddXmax=(dXmax-dX)/dt;//?? return(0); }//endof initialize1 #ifndef CRANESUB int main1(int argc,char **argv) { //////////////////////////////////////////////////// /// method 1 /// /// input ddX /// /// output a,x,y,F /// //////////////////////////////////////////////////// // double h = 0.001;//,hh=0.1; h = 0.0001;//,hh=0.1; double t0=5; //stationary double t1=5.0+t0;//accelerate(speed up) double t2=2.0+t1;//free run double t3=5.0+t2;//decelerate(slow down) double t4=20+t3; //free run CRANE crane[1]; // int (*initialize)(); // if(1==1){ // initialize=initialize1; // } // (*initialize)(crane); crane->_y=NULL; initialize1(crane); int M=(t4/crane->h)+1; // ddX=(double*)malloc(sizeof(double)*M); double *ddX=(double*)malloc(sizeof(double)*M); // double *F =(double*)malloc(sizeof(double)*M); double Vmax=1;//dX/dt=1[m/s] int n; double t; //////////////////////////////////////////////////// /// set ddX /// //////////////////////////////////////////////////// int n0 =t0/crane->h+0.5, n4=t4/crane->h+0.5; for(t=0;t<t4;t+=crane->h){ n=t/crane->h; if(t<=t0) ddX[n]=0; //zero else if(t<=t1) ddX[n]=Vmax/(t1-t0); //accelerate else if(t<=t2) ddX[n]=0; //free move else if(t<=t3) ddX[n]=-Vmax/(t3-t2);//decelerate else ddX[n]=0; //free move } //////////////////////////////////////////////////// /// Solve by the Runge Kutta Method of GSL /// //////////////////////////////////////////////////// // char *fn="crane1io.dat"; fp=fopen(fn1,"w"); fprintf(fp,"#%.7e %d %d %.7e %.7e %.7e %.7e #h,n0,n4,M,n,r\n",crane->h,n0,n4,crane->M,crane->m,crane->r,crane->C); // double dx0=0,dy0=0,da0=0; // for(n=0;n<n4;){ for(t=0;t<t4;t+=crane->h){ n=t/crane->h; // ddXn=ddX[n];if(n>500 && n<510){ // fprintf(stderr,"check n=%d,t=%g ddX=%g\n",n,t,ddX[n]); // } // (*(crane->plant))(ddX[n],crane); plant1(ddX[n],crane); } fclose(fp); fprintf(stdout,"Results are stored in '%s'.\n",fn1); gsl_odeiv_step_free (crane->_s); return 0; }//endof main1 #endif//endof #ifndef CRANESUB ///////////////////////// int crane2func (double t, const double y[], double f[], void *params) { CRANE *c = (CRANE *)params; //y[0]=crane->p, y[1]=crane->da, y[2]=crane->X, y[3]=crane->dX f[0] = y[1]; f[1] = (-(2*c->dr+c->C)*y[1] -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; // f[1] = (-2*c->dr -c->ddX*cos(y[0]) -c->g*sin(y[0]))/c->r; f[2] = y[3]; // f[3] = c->ddX; f[3] = (c->F+c->T*sin(y[0]))/c->M; return GSL_SUCCESS; }//endof crane2func double plant2(double uu,CRANE *crane) { // crane->F=uu; if(uu>crane->Fmax) uu=crane->Fmax; else if(uu<-crane->Fmax) uu=-crane->Fmax; int n; for(n=0;n<crane->nh;n++){ crane->F=uu;// if(crane->dX>=crane->dXmax && crane->F>0) crane->F=0; else if(crane->dX<=-crane->dXmax && crane->F<0) crane->F=0; int status = gsl_odeiv_step_apply (crane->_s, crane->_t, crane->_h, crane->_y, crane->_y_err, crane->_dydt_in, crane->_dydt_out, &crane->_sys); if (status != GSL_SUCCESS) break; int i;for(i=0;i<dim_crane;i++) crane->_dydt_in[i]=crane->_dydt_out[i]; crane->_t+=crane->_h; crane->a =crane->_y[0]; crane->da =crane->_y[1]; crane->X =crane->_y[2]; crane->dX =crane->_y[3]; crane->x =crane->X+crane->r * sin(crane->a); crane->y =crane->r*cos(crane->a); crane->dx=(crane->x-crane->x0)/crane->_h; crane->dy=(crane->y-crane->y0)/crane->_h; crane->ddx=(crane->dx-crane->dx0)/crane->_h; crane->ddy=(crane->dy-crane->dy0)/crane->_h; crane->T=crane->m*sqrt(square(crane->ddx)+square(crane->ddy-crane->g)); crane->ddX=(crane->dX-crane->dX0)/crane->_h; // crane->F=crane->M*crane->ddX-crane->T*sin(crane->a); crane->dda=(crane->da-crane->da0)/crane->_h; /* crane->dda=(-2*crane->dr*crane->da-crane->g*sin(crane->a)-ddX[n]*cos(crane->a))/crane->r; */ crane->x0=crane->x; crane->y0=crane->y; crane->dx0=crane->dx; crane->dy0=crane->dy; crane->da0=crane->da; crane->dX0=crane->dX; } #ifndef CRANESUB fprintf(fp,"%.7e %.7e %.7e", crane->_t,crane->_y[0],crane->_y[1]);//crane->a,crane->da fprintf(fp," %.7e %.7e %.7e" ,crane->X,crane->dX,crane->ddX); fprintf(fp," %.7e %.7e %.7e" ,crane->x,crane->dx,crane->ddx); fprintf(fp," %.7e %.7e %.7e" ,crane->y,crane->dy,crane->ddy); fprintf(fp," %.7e %.7e" ,crane->T,crane->F); fprintf(fp,"\n"); #endif return(crane->x); // return(crane->X); }//endof plant2 int initialize2(CRANE *crane) { crane->cranefunc=crane2func; crane->plant=plant2; crane->Fmax=20.0;//check// crane->Fmax=30;//check // crane->dXmax=1.0; crane->dXmax=1.0; crane->ddXmax=0.2; crane->g=9.8; crane->M=100; crane->m=20;//10;//10;//20 crane->r=5;//5; crane->C=1;//5; crane->dr=crane->ddr=0; crane->x0=0; crane->y0=crane->r; crane->dX0=crane->dx0=crane->dy0=crane->da0=0; #ifdef CRANESUB // crane->Fmax=_crane_Fmax;//check// crane->Fmax=30;//check crane->m=_crane_m; crane->r=_crane_r; crane->h=AP_tS; crane->dXmax=_crane_dXmax; if(_AP_umax>0) AP_u_max=crane->Fmax=_AP_umax; else AP_u_max=crane->Fmax; AP_u_min=-AP_u_max; // starttime=0; // totaltime=100;// totaltime=40; // totaltime=50;// totaltime=40; // int kmax=totaltime/AP_tS; // _rr=(double*)malloc(kmax*sizeof(double)); rr=AP_r=_AP_r;//10 // int k;for(k=0;k<kmax;k++) _rr[k]=AP_r;//10; rr_kyoyou=_rr_kyoyou; // p=(double *)malloc(buffsize*sizeof(double)); C_MODE=11; // iteration=_iteration; // fprintf(stdout,"?????????iteration=%d\n",_iteration); #else crane->h=0.01; #endif crane->nh=10; crane->F=crane->a=crane->da=crane->dda=0; crane->T=crane->m*crane->g; crane->_h=crane->h/crane->nh;//0.001 crane->_dim=4; {// if(crane->_y==NULL){ crane->_y=(double*)malloc(crane->_dim*sizeof(double)); crane->_y_err=(double*)malloc(crane->_dim*sizeof(double)); crane->_dydt_in=(double*)malloc(crane->_dim*sizeof(double)); crane->_dydt_out=(double*)malloc(crane->_dim*sizeof(double)); } crane->_T= gsl_odeiv_step_rk4; crane->_s= gsl_odeiv_step_alloc (crane->_T, crane->_dim); crane->_sys= (gsl_odeiv_system){crane->cranefunc, NULL, crane->_dim, crane}; // crane->_sys= (gsl_odeiv_system){crane->cranefunc, NULL, crane->_dim, &crane}; crane->_t=crane->_y[0]=crane->_y[1]=crane->_y[2]=crane->_y[3]=0; int i;for(i=0;i<crane->_dim;i++) crane->_dydt_in[i]=0; GSL_ODEIV_FN_EVAL(&(crane->_sys), crane->_t, crane->_y, crane->_dydt_in); return(0); } #ifndef CRANESUB int main2(int argc, char** argv) { // CRANE crane; CRANE crane[1]; crane->g=9.8; crane->M=100; crane->m=20; crane->r=5; crane->dr=crane->ddr=0; //////////////////////////////////////////////////// /// method 2 /// /// input F /// /// output p,x,y,X,... /// //////////////////////////////////////////////////// double h;//,hh=0.1; //result for different h /*gnuplot set style data lines;n=1; n=n+1;plot "crane1io.dat" using 1:n, "crane2io.dat" using 1:n;print "n=",n #strange at n=9(ddx),12(ddy),13(T) */ //////////////////////////////////////////////////// /// read F /// //////////////////////////////////////////////////// // char *fn1="crane1io.dat"; FILE *fp1=fopen(fn1,"r"); int n4; #define buffsize 512 char buff[buffsize]; int n0; if(fgets(buff,buffsize,fp1)!=NULL) sscanf(buff,"#%lf%d%d%lf%lf%lf%lf",&h,&n0,&n4,&crane->M,&crane->m,&crane->r,&crane->C); crane->h=h; double t4=n4*h; double *F =(double*)malloc(sizeof(double)*(n4+1)); // int M=n4+1;double *F =(double*)malloc(sizeof(double)*M); // double *ddX=(double*)malloc(sizeof(double)*M); int n; double t; // double dx0=0,dy0=0,dX0=0,da0=0; // double x0=0,y0=crane->r; if(fgets(buff,buffsize,fp1)!=NULL); //?? fgets(buff,buffsize,fp1); for(n=0;n<n4;n++){// double _x1,_x2,_x3,_x4,_x5,_x6,_x7,_x8,_x9,_x10,_x11,_x12,_x13,_x14; if(fgets(buff,buffsize,fp1)!=NULL) // fgets(buff,buffsize,fp1); sscanf(buff,"%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf", &_x1,&_x2,&_x3,&_x4,&_x5,&_x6,&_x7,&_x8,&_x9,&_x10,&_x11,&_x12,&_x13,&_x14); F[n]=_x14; } //////////////////////////////////////////////////// /// Solve by the Runge Kutta Method of GSL /// //////////////////////////////////////////////////// crane->_y=NULL; initialize2(crane); fp=fopen(fn2,"w"); for(t=0;t<t4;t+=crane->h){ n=t/crane->h; plant2(F[n],crane); // (*(crane->plant))(F[n],crane); } fclose(fp); fprintf(stdout,"Results are stored in '%s'.\n",fn2); gsl_odeiv_step_free (crane->_s); return 0; }//main2 #endif //#ifndef CRANESUB #ifndef CRANESUB int main(int argc,char **argv) { if(argc<2){ fprintf(stderr,"Usage:%s [1|2]\n",argv[0]); return(1); } if(argv[1][0]!='2') main1(argc,argv); else main2(argc,argv); return(0); } #endif //#ifndef CRANESUB
{ "alphanum_fraction": 0.5547534644, "avg_line_length": 32.5945378151, "ext": "c", "hexsha": "45e470f3d848d9f2e5b0fb974e293ee1a0b15abe", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z", "max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_forks_repo_licenses": [ "CECILL-B" ], "max_forks_repo_name": "Kurogi-Lab/CAN2", "max_forks_repo_path": "1021/mspc/crane.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CECILL-B" ], "max_issues_repo_name": "Kurogi-Lab/CAN2", "max_issues_repo_path": "1021/mspc/crane.c", "max_line_length": 116, "max_stars_count": null, "max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136", "max_stars_repo_licenses": [ "CECILL-B" ], "max_stars_repo_name": "Kurogi-Lab/CAN2", "max_stars_repo_path": "1021/mspc/crane.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6047, "size": 15515 }
/* copied from http://www.gnu.org/software/gsl/manual/html_node/Basis-Splines.html */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <gsl/gsl_bspline.h> #include <gsl/gsl_multifit.h> #include <gsl/gsl_sf_erf.h> void geterf_(double *xanderfx) { xanderfx[1] = gsl_sf_erf(xanderfx[0]); } //spline locations held fixed in Mpc^-1; CMB basically fixed P(k) in these units void dopksmoothbspline_(double *kvals, double *lnpklinear, double *lnpksmooth, int *npts) { double kmaxsuppress = 0.01*0.7; size_t n, ncoeffs, nbreak; gsl_bspline_workspace *bw; gsl_vector *B; gsl_vector *c, *w, *x, *y; gsl_matrix *X, *cov; gsl_multifit_linear_workspace *mw; double deltak,lastk; int i,j,countkeep; nbreak = 9; gsl_vector *mybreaks = gsl_vector_alloc(nbreak); gsl_vector_set(mybreaks,0,(0.001*0.7)); gsl_vector_set(mybreaks,1,(0.025*0.7)); gsl_vector_set(mybreaks,2,(0.075*0.7)); gsl_vector_set(mybreaks,3,(0.125*0.7)); gsl_vector_set(mybreaks,4,(0.175*0.7)); gsl_vector_set(mybreaks,5,(0.225*0.7)); gsl_vector_set(mybreaks,6,(0.275*0.7)); gsl_vector_set(mybreaks,7,(0.325*0.7)); gsl_vector_set(mybreaks,8,(0.375*0.7)); countkeep = 0; for(i=0;i<(*npts);i++) { if((kvals[i]) >= gsl_vector_get(mybreaks,0) && (kvals[i]) <= gsl_vector_get(mybreaks,nbreak-1)) { countkeep += 1; } } n = countkeep; ncoeffs = nbreak + 2; /* allocate a cubic bspline workspace (k = 4) */ bw = gsl_bspline_alloc(4, nbreak); B = gsl_vector_alloc(ncoeffs); x = gsl_vector_alloc(n); y = gsl_vector_alloc(n); X = gsl_matrix_alloc(n, ncoeffs); c = gsl_vector_alloc(ncoeffs); w = gsl_vector_alloc(n); cov = gsl_matrix_alloc(ncoeffs, ncoeffs); mw = gsl_multifit_linear_alloc(n, ncoeffs); i=0; for(j=0;j<(*npts);j++) { if((kvals[j]) >= gsl_vector_get(mybreaks,0) && (kvals[j]) <= gsl_vector_get(mybreaks,nbreak-1)) { gsl_vector_set(x,i,(kvals[j])); gsl_vector_set(y,i,exp(lnpklinear[j])*pow(kvals[j],1.5)); if(j>0) { deltak = kvals[j] - kvals[j-1]; } else { deltak = kvals[0]; if(kvals[1] - kvals[0] < deltak) { deltak = kvals[1]-kvals[0]; } } gsl_vector_set(w,i,deltak); i+=1; } } gsl_bspline_knots(mybreaks,bw); for(i=0;i<n;i++) { double xi = gsl_vector_get(x,i); gsl_bspline_eval(xi,B,bw); for(j=0;j<ncoeffs;j++) { double Bj = gsl_vector_get(B,j); gsl_matrix_set(X,i,j,Bj); } } //do fit double yi,yierr,chisq; gsl_multifit_wlinear(X,w,y,c,cov,&chisq,mw); i = 0; for(j=0;j<(*npts);j++) { if((kvals[j]) >= gsl_vector_get(mybreaks,0) && (kvals[j]) <= gsl_vector_get(mybreaks,nbreak-1)) { gsl_bspline_eval(gsl_vector_get(x,i),B,bw); gsl_multifit_linear_est(B,c,cov,&yi,&yierr); lnpksmooth[j] = log(yi*pow(kvals[j],-1.5)); i += 1; } else { lnpksmooth[j] = lnpklinear[j]; } //spline is wacky at small k -- suppress difference at k < 0.01 if(kvals[j] < kmaxsuppress) { lnpksmooth[j] = lnpklinear[j]; } } assert(i==n); gsl_bspline_free(bw); gsl_vector_free(B); gsl_vector_free(x); gsl_vector_free(y); gsl_vector_free(mybreaks); gsl_matrix_free(X); gsl_vector_free(c); gsl_vector_free(w); gsl_matrix_free(cov); gsl_multifit_linear_free(mw); } /* FILE *open_file_read(char *filename) { FILE *ifp; if(!(ifp=fopen(filename,"r"))) { fprintf(stderr,"Can't open %s\n",filename); return NULL; } else { return ifp; } } int get_file_length(FILE *ifp, int *headercount, int *linecount) { int i; char line[256]; *headercount = 0; *linecount = 0; while(fgets(line,256,ifp)) { if(!feof(ifp)) { (*linecount)++; } else { break; } if(strstr(line,"#")) { (*headercount)++; } } (void) rewind(ifp); } int main() { double *lnpksmooth, *lnpklinear, *kvals; FILE *ifp; int headercount, linecount,i,j; double kval,pnw,plin; ifp = open_file_read("/Users/breid/cosmomcmnu/test1.cut"); get_file_length(ifp,&headercount,&linecount); lnpksmooth = (double *) malloc(sizeof(double)*linecount); lnpklinear = (double *) malloc(sizeof(double)*linecount); kvals = (double *) malloc(sizeof(double)*linecount); for(i=0;i<linecount;i++) { fscanf(ifp,"%lf %lf %lf\n",&kval,&pnw,&plin); lnpklinear[i] = plin; kvals[i] = kval*0.701; //kvals[i] = kval; } dopksmoothbspline_(kvals,lnpklinear,lnpksmooth,&linecount); for(i=0;i<linecount;i++) { printf("%f %f %f\n",kvals[i],lnpklinear[i],lnpksmooth[i]); } return 0; } */
{ "alphanum_fraction": 0.6481687014, "avg_line_length": 25.0277777778, "ext": "c", "hexsha": "66ebec0529766415d7f06c19a212b8fceb839f18", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3c1d029b74034b92cb2974de15e4c18637a5277e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sjoudaki/CosmoJBD", "max_forks_repo_path": "source/bsplinepk.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "3c1d029b74034b92cb2974de15e4c18637a5277e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sjoudaki/CosmoJBD", "max_issues_repo_path": "source/bsplinepk.c", "max_line_length": 99, "max_stars_count": 1, "max_stars_repo_head_hexsha": "3c1d029b74034b92cb2974de15e4c18637a5277e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sjoudaki/CosmoJBD", "max_stars_repo_path": "source/bsplinepk.c", "max_stars_repo_stars_event_max_datetime": "2020-06-04T15:29:37.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-04T15:29:37.000Z", "num_tokens": 1653, "size": 4505 }
/* NAME: calc_splitnmerge PURPOSE: calculates the split and merge hierarchy after an proj_EM convergence CALLING SEQUENCE: calc_splitnmerge(struct datapoint * data,int N, struct gaussian * gaussians, int K, gsl_matrix * qij, int * snmhierarchy){ INPUT: data - the data N - number of data points gaussians - model gaussians K - number of gaussians qij - matrix of log(posterior likelihoods) bs - bs from previous EM estimate OUTPUT: snmhierarchy - the hierarchy, first row has the highest prioriry, goes down from there REVISION HISTORY: 2008-09-21 - Written Bovy */ #include <stdio.h> #include <math.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_blas.h> #include <proj_gauss_mixtures.h> void calc_splitnmerge(struct datapoint * data,int N, struct gaussian * gaussians, int K, gsl_matrix * qij, int * snmhierarchy){ gsl_matrix * tempqij = gsl_matrix_alloc(N,K); gsl_matrix_memcpy(tempqij,qij); gsl_matrix * Jmerge = gsl_matrix_alloc(K,K); gsl_matrix_set_all(Jmerge,-1.); int kk1, kk2, kk, ii,maxsnm= K*(K-1)*(K-2)/2; int d = (gaussians->VV)->size1;//dim of mm double temp1,temp2,temp; for (kk1 = 0; kk1 != K; ++kk1) for (kk2 = kk1+1; kk2 != K; ++kk2){ temp = 0.; for (ii=0; ii != N; ++ii){ //make them all exps temp1 = exp(gsl_matrix_get(qij,ii,kk1)); temp2 = exp(gsl_matrix_get(qij,ii,kk2)); temp += temp1*temp2; } gsl_matrix_set(Jmerge,kk1,kk2,temp); } //Then calculate Jsplit gsl_vector * Jsplit = gsl_vector_alloc(K); gsl_vector * Jsplit_temp = gsl_vector_alloc(K); gsl_vector_set_all(Jsplit,-1.); //if there is missing data, fill in the missing data struct missingdatapoint{ gsl_vector *ww; }; struct missingdatapoint * missingdata; missingdata = (struct missingdatapoint *) malloc(N * sizeof (struct missingdatapoint) ); for (ii=0; ii != N; ++ii){ missingdata->ww = gsl_vector_alloc(d); ++missingdata; } missingdata -= N; gsl_matrix * tempRR,* tempVV; gsl_vector * tempSS,* tempwork; gsl_vector * expectedww = gsl_vector_alloc(d); //gsl_vector_view tempUcol; double lambda; int di,signum; for (ii=0; ii != N; ++ii){ //First check whether there is any missing data if ((data->ww)->size == d){ gsl_vector_memcpy(missingdata->ww,data->ww); ++missingdata; ++data; continue; } /*AS IT STANDS THE MISSING DATA PART IS *NOT* IMPLEMENTED CORRECTLY: A CORRECT IMPLEMENTATION NEEDS THE NULL SPACE OF THE PROJECTION MATRIX WHICH CAN BE FOUND FROM THE FULL SINGULAR VALUE DECOMPOSITIIN, UNFORTUNATELY GSL DOES NOT COMPUTE THE FULL SVD, BUT ONLY THE THIN SVD. LAPACK MIGHT DO, BUT MIGHT NOT BE INSTALLED (?) AND THIS MIGHT BE HARD TO IMPLEMENT. INDICATED BELOW ARE THE SECTION THAT WOULD HAVE TO BE FIXED TO MAKE THIS WORK */ //calculate expectation, for this we need to calculate the bbijs (EXACTLY THE SAME AS IN PROJ_EM, SHOULD WRITE GENERAL FUNCTION TO DO THIS) gsl_vector_set_zero(expectedww); for (kk = 0; kk != K; ++kk){ //prepare... di = (data->SS)->size1; p = gsl_permutation_alloc (di); wminusRm = gsl_vector_alloc (di); gsl_vector_memcpy(wminusRm,data->ww); TinvwminusRm = gsl_vector_alloc (di); Tij = gsl_matrix_alloc(di,di); gsl_matrix_memcpy(Tij,data->SS); Tij_inv = gsl_matrix_alloc(di,di); VRT = gsl_matrix_alloc(d,di); VRTTinv = gsl_matrix_alloc(d,di); Rtrans = gsl_matrix_alloc(d,di); //Calculate Tij gsl_matrix_transpose_memcpy(Rtrans,data->RR); gsl_blas_dsymm(CblasLeft,CblasUpper,1.0,gaussians->VV,Rtrans,0.0,VRT);//Only the upper right part of VV is calculated gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,data->RR,VRT,1.0,Tij);//This is Tij //Calculate LU decomp of Tij and Tij inverse gsl_linalg_LU_decomp(Tij,p,&signum); gsl_linalg_LU_invert(Tij,p,Tij_inv); //Calculate Tijinv*(w-Rm) gsl_blas_dgemv(CblasNoTrans,-1.0,data->RR,gaussians->mm,1.0,wminusRm); gsl_blas_dsymv(CblasUpper,1.0,Tij_inv,wminusRm,0.0,TinvwminusRm); //Now calculate bij and Bij gsl_vector_memcpy(bs->bbij,gaussians->mm); gsl_blas_dgemv(CblasNoTrans,1.0,VRT,TinvwminusRm,1.0,bs->bbij); //..and add the result to expectedww gsl_vector_scale(bs->bbij,exp(gsl_matrix_get(qij,ii,kk))); gsl_vector_add(expectedww,bs->bbij); //Clean up gsl_permutation_free (p); gsl_vector_free(wminusRm); gsl_vector_free(TinvwminusRm); gsl_matrix_free(Tij); gsl_matrix_free(Tij_inv); gsl_matrix_free(VRT); gsl_matrix_free(VRTTinv); gsl_matrix_free(Rtrans); ++gaussians; } gaussians -= K; //if missing, fill in the missing data tempRR = gsl_matrix_alloc((data->RR)->size2,(data->RR)->size1);//will hold the transpose of RR //tempVV = gsl_matrix_alloc((data->RR)->size1,(data->RR)->size1); //tempSS = gsl_vector_alloc((data->RR)->size1); //tempwork = gsl_vector_alloc((data->RR)->size1); gsl_matrix_transpose_memcpy(tempRR,data->RR); gsl_blas_dgemv(CblasNoTrans,1.,tempRR,data->ww,0.,missingdata->ww); //gsl_linalg_SV_decomp(tempRR,tempVV,tempSS,tempwork); //compute the missing data THIS PART IS NOT IMPLEMENTED CORRECTLY //for (kk = 0; kk != d-(data->ww)->size; ++kk){ //tempUcol = gsl_matrix_column(tempRR,d-1-kk); //gsl_blas_ddot(&(tempUcol.vector),expectedww,&lambda); //gsl_vector_scale(&(tempUcol.vector),lambda); //gsl_vector_add(missingdata->ww,&(tempUcol.vector)); //} ++missingdata; ++data; //free gsl_matrix_free(tempRR); //gsl_matrix_free(tempVV); //gsl_vector_free(tempSS); //gsl_vector_free(tempwork); } data -= N; missingdata -= N; //then for every gaussian, calculate the KL divergence between the local data density and the l-th gaussian double tempsplit; p = gsl_permutation_alloc (d); tempVV= gsl_matrix_alloc(d,d); tempRR= gsl_matrix_alloc(d,d); tempSS= gsl_vector_alloc(d); tempwork= gsl_vector_alloc(d); for (kk = 0; kk != K; ++kk){ //calculate qil/ql factors normalize_row(tempqij,kk,false,true,0.); //calculate inverse of V and det(V) gsl_matrix_memcpy(tempVV,gaussians->VV); gsl_linalg_LU_decomp(tempVV,p,&signum); gsl_linalg_LU_invert(tempVV,p,tempRR);//tempRR now has the inverse of VV tempsplit = d * halflogtwopi + 0.5 * gsl_linalg_LU_lndet(tempVV); for (ii=0; ii != N; ++ii){ if (exp(gsl_matrix_get(tempqij,ii,kk)) == 0.){ ++missingdata; continue; } tempsplit += gsl_matrix_get(tempqij,ii,kk) * exp(gsl_matrix_get(tempqij,ii,kk)); gsl_vector_memcpy(tempSS,gaussians->mm); gsl_vector_scale(tempSS,-1.); gsl_vector_add(tempSS,missingdata->ww); gsl_blas_dgemv(CblasNoTrans,1.0,tempRR,tempSS,0.,tempwork); gsl_blas_ddot(tempSS,tempwork,&lambda); tempsplit += 0.5 * exp(gsl_matrix_get(tempqij,ii,kk)) * lambda; ++missingdata; } gsl_vector_set(Jsplit,kk,tempsplit); //printf("Jsplit for gaussian %i = %f\n",kk,tempsplit); missingdata -= N; ++gaussians; } gaussians -= K; //free gsl_permutation_free(p); gsl_matrix_free(tempRR); gsl_matrix_free(tempVV); gsl_vector_free(tempSS); gsl_vector_free(tempwork); //and put everything in the hierarchy size_t maxj, maxk, maxl; for (kk1 = 0; kk1 != maxsnm; kk1 += (K-2)){ gsl_matrix_max_index(Jmerge,&maxj,&maxk); gsl_vector_memcpy(Jsplit_temp,Jsplit); gsl_vector_set(Jsplit_temp,maxj,-1.); gsl_vector_set(Jsplit_temp,maxk,-1.); for (kk2=0; kk2 != K-2; ++kk2){ maxl = gsl_vector_max_index(Jsplit_temp); gsl_vector_set(Jsplit_temp,maxl,-1.); *(snmhierarchy++)= maxj; *(snmhierarchy++)= maxk; *(snmhierarchy++)= maxl; //printf("j = %i, k = %i, l = %i\n",(int)maxj,(int)maxk,(int)maxl); } //then set it to zero and find the next gsl_matrix_set(Jmerge,maxj,maxk,-1.); } snmhierarchy -= 3*maxsnm; //clean up gsl_matrix_free(Jmerge); gsl_vector_free(Jsplit); gsl_vector_free(Jsplit_temp); return ; }
{ "alphanum_fraction": 0.6641395909, "avg_line_length": 35.3617021277, "ext": "c", "hexsha": "645bcb5889c458081422ba8a18c9d2fc8150c305", "lang": "C", "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z", "max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z", "max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_forks_repo_path": "src/calc_splitnmerge.c", "max_issues_count": 24, "max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_issues_repo_path": "src/calc_splitnmerge.c", "max_line_length": 143, "max_stars_count": 73, "max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution", "max_stars_repo_path": "src/calc_splitnmerge.c", "max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z", "max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z", "num_tokens": 2532, "size": 8310 }
/* -*- linux-c -*- */ /* fewbody_ks.c Copyright (C) 2002-2004 John M. Fregeau This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <math.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_odeiv.h> #include "fewbody.h" /* the dot product of two K-S vectors */ double fb_ks_dot(double x[4], double y[4]) { return(x[0] * y[0] + x[1] * y[1] + x[2] * y[2] + x[3] * y[3]); } /* the modulus of a K-S vector */ double fb_ks_mod(double x[4]) { return(sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2] + x[3] * x[3])); } /* calculate Q given q */ void fb_calc_Q(double q[4], double Q[4]) { double u[4]; u[0] = sqrt(0.5 * (fb_mod(q) + fabs(q[0]))); u[1] = 0.5 * q[1] / u[0]; u[2] = 0.5 * q[2] / u[0]; u[3] = 0.0; if (q[0] > 0.0) { Q[0] = u[0]; Q[1] = u[1]; Q[2] = u[2]; Q[3] = u[3]; } else { Q[0] = u[1]; Q[1] = u[0]; Q[2] = u[3]; Q[3] = u[2]; } } /* calculate the K-S matrix */ void fb_calc_ksmat(double Q[4], double Qmat[4][4]) { Qmat[0][0] = Q[0]; Qmat[0][1] = -Q[1]; Qmat[0][2] = -Q[2]; Qmat[0][3] = Q[3]; Qmat[1][0] = Q[1]; Qmat[1][1] = Q[0]; Qmat[1][2] = -Q[3]; Qmat[1][3] = -Q[2]; Qmat[2][0] = Q[2]; Qmat[2][1] = Q[3]; Qmat[2][2] = Q[0]; Qmat[2][3] = Q[1]; Qmat[3][0] = Q[3]; Qmat[3][1] = -Q[2]; Qmat[3][2] = Q[1]; Qmat[3][3] = -Q[0]; } /* calculate the a matrix */ void fb_calc_amat(double **a, int nstar, int kstar) { int i, j, k; /* first zero out the matrix */ for (i=0; i<nstar; i++) { for (k=0; k<kstar; k++) { a[i][k] = 0.0; } } /* then set the non-zero components */ k = -1; for (i=0; i<nstar-1; i++) { for (j=i+1; j<nstar; j++) { k++; a[i][k] = 1.0; a[j][k] = -1.0; } } } /* calculate the T matrix */ void fb_calc_Tmat(double **a, double *m, double **T, int nstar, int kstar) { int u, v, e; for (u=0; u<kstar; u++) { for (v=0; v<kstar; v++) { T[u][v] = 0.0; for (e=0; e<nstar; e++) { T[u][v] += a[e][u] * a[e][v] / m[e]; } T[u][v] *= 0.5; } } } /* the derivatives function for the GSL ODE integrator */ int fb_ks_func(double s, const double *y, double *f, void *params) { int k, l, m, kstar; double *M, **amat, **Tmat, Einit; double **Q, **P, **p, **A, **TP, **TQ, **UQ, *d; double Qmat[4][4], Pmat[4][4], Astar[4], T, U, val, L, H, G, GT, GU; /* set parameters */ kstar = (*(fb_ks_params_t *) params).kstar; M = (*(fb_ks_params_t *) params).M; amat = (*(fb_ks_params_t *) params).amat; Tmat = (*(fb_ks_params_t *) params).Tmat; Einit = (*(fb_ks_params_t *) params).Einit; /* allocate memory */ Q = fb_malloc_matrix(kstar, 4); P = fb_malloc_matrix(kstar, 4); p = fb_malloc_matrix(kstar, 4); A = fb_malloc_matrix(kstar, 4); TP = fb_malloc_matrix(kstar, 4); TQ = fb_malloc_matrix(kstar, 4); UQ = fb_malloc_matrix(kstar, 4); d = fb_malloc_vector(kstar); /* set Q_k, P_k, and p_k */ for (k=0; k<kstar; k++) { /* read Q_k and P_k directly from y[] */ for (l=0; l<4; l++) { Q[k][l] = y[k*8+1+l]; P[k][l] = y[k*8+4+1+l]; } /* calculate the KS matrix from Q_k */ fb_calc_ksmat(Q[k], Qmat); /* and then calculate p_k */ for (l=0; l<4; l++) { p[k][l] = 0.0; for (m=0; m<4; m++) { p[k][l] += Qmat[l][m] * P[k][m]; } p[k][l] /= 2.0 * fb_ks_dot(Q[k], Q[k]); } } /* set intermediate variables */ T = 0.0; U = 0.0; for (k=0; k<kstar; k++) { /* first calculate the K-S matrix for this value of k */ fb_calc_ksmat(Q[k], Qmat); /* calculate A_k */ for (m=0; m<4; m++) { A[k][m] = 0.0; for (l=0; l<kstar; l++) { A[k][m] += Tmat[k][l] * p[l][m]; } } /* then d_k */ d[k] = fb_ks_dot(A[k], p[k]); /* increment the sums for T and U */ T += d[k]; U += M[k] / fb_ks_dot(Q[k], Q[k]); /* then calculate the first partial derivative of T with respect to P_k */ for (m=0; m<4; m++) { TP[k][m] = 0.0; for (l=0; l<4; l++) { TP[k][m] += Qmat[l][m] * A[k][l]; } TP[k][m] /= fb_ks_dot(Q[k], Q[k]); } /* A^*_k */ Astar[0] = A[k][0]; Astar[1] = A[k][1]; Astar[2] = A[k][2]; Astar[3] = -A[k][3]; /* calculate the K-S matrix for P_k */ fb_calc_ksmat(P[k], Pmat); /* then calculate the first partial derivatives of T and U */ for (l=0; l<4; l++) { val = 0.0; for (m=0; m<4; m++) { val += Pmat[m][l] * Astar[m]; } TQ[k][l] = (val - 4.0 * d[k] * Q[k][l]) / fb_ks_dot(Q[k], Q[k]); UQ[k][l] = -2.0 * M[k] * Q[k][l] / fb_sqr(fb_ks_dot(Q[k], Q[k])); } } /* set the Lagrangian, Hamiltonian, and the initial energy */ L = T + U; H = T - U; G = (H - Einit) / L; GT = (1.0 - G) / L; GU = -(1.0 + G) / L; /* set derivatives */ f[0] = 1.0 / L; for (k=0; k<kstar; k++) { for (l=0; l<4; l++) { f[k*8+1+l] = GT * TP[k][l]; f[k*8+4+1+l] = -GT * TQ[k][l] - GU * UQ[k][l]; } } /* free memory */ fb_free_matrix(Q); fb_free_matrix(P); fb_free_matrix(p); fb_free_matrix(A); fb_free_matrix(TP); fb_free_matrix(TQ); fb_free_matrix(UQ); fb_free_vector(d); /* all done */ return(GSL_SUCCESS); } /* function to calculate the Einit parameter for the integrator */ /* the code here is a verbatim copy from the first part of fb_ks_func */ double fb_ks_Einit(const double *y, fb_ks_params_t params) { int k, l, m; double **Q, **P, **p, **A, *d; double Qmat[4][4], T, U; /* allocate memory */ Q = fb_malloc_matrix(params.kstar, 4); P = fb_malloc_matrix(params.kstar, 4); p = fb_malloc_matrix(params.kstar, 4); A = fb_malloc_matrix(params.kstar, 4); d = fb_malloc_vector(params.kstar); /* set Q_k, P_k, and p_k */ for (k=0; k<params.kstar; k++) { /* read Q_k and P_k directly from y[] */ for (l=0; l<4; l++) { Q[k][l] = y[k*8+1+l]; P[k][l] = y[k*8+4+1+l]; } /* calculate the KS matrix from Q_k */ fb_calc_ksmat(Q[k], Qmat); /* and then calculate p_k */ for (l=0; l<4; l++) { p[k][l] = 0.0; for (m=0; m<4; m++) { p[k][l] += Qmat[l][m] * P[k][m]; } p[k][l] /= 2.0 * fb_ks_dot(Q[k], Q[k]); } } /* set intermediate variables */ T = 0.0; U = 0.0; for (k=0; k<params.kstar; k++) { /* first calculate the K-S matrix for this value of k */ fb_calc_ksmat(Q[k], Qmat); /* calculate A_k */ for (m=0; m<4; m++) { A[k][m] = 0.0; for (l=0; l<params.kstar; l++) { A[k][m] += params.Tmat[k][l] * p[l][m]; } } /* then d_k */ d[k] = fb_ks_dot(A[k], p[k]); /* increment the sums for T and U */ T += d[k]; U += params.M[k] / fb_ks_dot(Q[k], Q[k]); } /* free memory */ fb_free_matrix(Q); fb_free_matrix(P); fb_free_matrix(p); fb_free_matrix(A); fb_free_vector(d); return(T-U); } /* function to convert from Euclidean coordinates to K-S coordinates */ void fb_euclidean_to_ks(fb_obj_t **star, double *y, int nstar, int kstar) { int i, j, k, l, m; double **q, **p, Q[4], P[4], Qmat[4][4]; q = fb_malloc_matrix(kstar, 4); p = fb_malloc_matrix(kstar, 4); /* then calculate q_k and p_k */ k = -1; for (i=0; i<nstar-1; i++) { for (j=i+1; j<nstar; j++) { k++; for (l=0; l<3; l++) { q[k][l] = star[i]->x[l] - star[j]->x[l]; p[k][l] = (star[i]->m * star[i]->v[l] - star[j]->m * star[j]->v[l])/((double) nstar); } q[k][3] = 0.0; p[k][3] = 0.0; } } /* and then Q_k and P_k */ for (k=0; k<kstar; k++) { /* calculate Q_k */ fb_calc_Q(q[k], Q); /* then P_k */ fb_calc_ksmat(Q, Qmat); for (l=0; l<4; l++) { P[l] = 0.0; for (m=0; m<4; m++) { P[l] += Qmat[m][l] * p[k][m]; } P[l] *= 2.0; /* then set y_i */ y[8*k+l+1] = Q[l]; y[8*k+l+4+1] = P[l]; } } fb_free_matrix(q); fb_free_matrix(p); } /* function to convert from K-S coordinates to Euclidean coordinates */ void fb_ks_to_euclidean(double *y, fb_obj_t **star, int nstar, int kstar) { int i, j, k, l; double *m, mtot, **Q, **P, **q, **p, Qmat[4][4]; /* allocate memory */ m = fb_malloc_vector(nstar); Q = fb_malloc_matrix(kstar, 4); P = fb_malloc_matrix(kstar, 4); q = fb_malloc_matrix(kstar, 4); p = fb_malloc_matrix(kstar, 4); /* set the masses */ mtot = 0.0; for (i=0; i<nstar; i++) { m[i] = star[i]->m; mtot += m[i]; } /* set Q_k, P_k, and p_k */ for (k=0; k<kstar; k++) { /* read Q_k and P_k directly from y[] */ for (l=0; l<4; l++) { Q[k][l] = y[k*8+1+l]; P[k][l] = y[k*8+4+1+l]; } /* calculate the KS matrix from Q_k */ fb_calc_ksmat(Q[k], Qmat); /* and then calculate q_k and p_k */ for (l=0; l<4; l++) { q[k][l] = 0.0; p[k][l] = 0.0; for (j=0; j<4; j++) { q[k][l] += Qmat[l][j] * Q[k][j]; p[k][l] += Qmat[l][j] * P[k][j]; } p[k][l] /= 2.0 * fb_ks_dot(Q[k], Q[k]); } } /* set r_i and v_i */ for (i=0; i<nstar; i++) { for (k=0; k<3; k++) { star[i]->x[k] = 0.0; star[i]->v[k] = 0.0; } for (j=i+1; j<nstar; j++) { for (k=0; k<3; k++) { star[i]->x[k] += m[j] * q[FB_KS_K(i, j, nstar)][k]; star[i]->v[k] += p[FB_KS_K(i, j, nstar)][k]; } } for (j=0; j<i; j++) { for (k=0; k<3; k++) { star[i]->x[k] += - m[j] * q[FB_KS_K(j, i, nstar)][k]; star[i]->v[k] += - p[FB_KS_K(j, i, nstar)][k]; } } for (k=0; k<3; k++) { star[i]->x[k] /= mtot; star[i]->v[k] /= m[i]; } } /* free memory */ fb_free_vector(m); fb_free_matrix(Q); fb_free_matrix(P); fb_free_matrix(q); fb_free_matrix(p); }
{ "alphanum_fraction": 0.5248618785, "avg_line_length": 22.2706935123, "ext": "c", "hexsha": "e7966c3b9a59d0ece0a95983ff3cbe852c717080", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_forks_repo_licenses": [ "PSF-2.0" ], "max_forks_repo_name": "gnodvi/cosmos", "max_forks_repo_path": "ext/fewbod/fewbody-0.26/fewbody_ks.c", "max_issues_count": 1, "max_issues_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_issues_repo_issues_event_max_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-13T20:35:46.000Z", "max_issues_repo_licenses": [ "PSF-2.0" ], "max_issues_repo_name": "gnodvi/cosmos", "max_issues_repo_path": "ext/fewbod/fewbody-0.26/fewbody_ks.c", "max_line_length": 89, "max_stars_count": null, "max_stars_repo_head_hexsha": "3612456fc2042519f96a49e4d4cc6d3c1f41de7c", "max_stars_repo_licenses": [ "PSF-2.0" ], "max_stars_repo_name": "gnodvi/cosmos", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_ks.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4133, "size": 9955 }
/* * iaf_cond_alpha_mc.h * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * NEST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with NEST. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef IAF_COND_ALPHA_MC_H #define IAF_COND_ALPHA_MC_H // Generated includes: #include "config.h" #ifdef HAVE_GSL // C++ includes: #include <vector> // C includes: #include <gsl/gsl_errno.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_odeiv.h> // Includes from nestkernel: #include "archiving_node.h" #include "connection.h" #include "event.h" #include "nest_types.h" #include "recordables_map.h" #include "ring_buffer.h" #include "universal_data_logger.h" // Includes from sli: #include "dictdatum.h" #include "name.h" /* BeginDocumentation Name: iaf_cond_alpha_mc - PROTOTYPE Multi-compartment conductance-based leaky integrate-and-fire neuron model. Description: THIS MODEL IS A PROTOTYPE FOR ILLUSTRATION PURPOSES. IT IS NOT YET FULLY TESTED. USE AT YOUR OWN PERIL! iaf_cond_alpha_mc is an implementation of a multi-compartment spiking neuron using IAF dynamics with conductance-based synapses. It serves mainly to illustrate the implementation of multicompartment models in NEST. The model has three compartments: soma, proximal and distal dendrite, labeled as s, p, and d, respectively. Compartments are connected through passive conductances as follows C_m.s d/dt V_m.s = ... - g_sp ( V_m.s - V_m.p ) C_m.p d/dt V_m.p = ... - g_sp ( V_m.p - V_m.s ) - g_pd ( V_m.p - V_m.d ) C_m.d d/dt V_m.d = ... - g_pd ( V_m.d - V_m.p ) A spike is fired when the somatic membrane potential exceeds threshold, V_m.s >= V_th. After a spike, somatic membrane potential is clamped to a reset potential, V_m.s == V_reset, for the refractory period. Dendritic membrane potentials are not manipulated after a spike. There is one excitatory and one inhibitory conductance-based synapse onto each compartment, with alpha-function time course. The alpha function is normalised such that an event of weight 1.0 results in a peak current of 1 nS at t = tau_syn. Each compartment can also receive current input from a current generator, and an external (rheobase) current can be set for each compartment. Synapses, including those for injection external currents, are addressed through the receptor types given in the receptor_types entry of the state dictionary. Note that in contrast to the single-compartment iaf_cond_alpha model, all synaptic weights must be positive numbers! Parameters: The following parameters can be set in the status dictionary. Parameters for each compartment are collected in a sub-dictionary; these sub-dictionaries are called "soma", "proximal", and "distal", respectively. In the list below, these parameters are marked with an asterisk. V_m* double - Membrane potential in mV E_L* double - Leak reversal potential in mV. C_m* double - Capacity of the membrane in pF E_ex* double - Excitatory reversal potential in mV. E_in* double - Inhibitory reversal potential in mV. g_L* double - Leak conductance in nS; tau_syn_ex* double - Rise time of the excitatory synaptic alpha function in ms. tau_syn_in* double - Rise time of the inhibitory synaptic alpha function in ms. I_e* double - Constant input current in pA. g_sp double - Conductance connecting soma and proximal dendrite, in nS. g_pd double - Conductance connecting proximal and distal dendrite, in nS. t_ref double - Duration of refractory period in ms. V_th double - Spike threshold in mV. V_reset double - Reset potential of the membrane in mV. Example: See examples/nest/mc_neuron.py. Remark: This is a prototype for illustration which has undergone only limited testing. Details of the implementation and user-interface will likely change. USE AT YOUR OWN PERIL! Sends: SpikeEvent Receives: SpikeEvent, CurrentEvent, DataLoggingRequest References: Meffin, H., Burkitt, A. N., & Grayden, D. B. (2004). An analytical model for the large, fluctuating synaptic conductance state typical of neocortical neurons in vivo. J. Comput. Neurosci., 16, 159-175. Bernander, O ., Douglas, R. J., Martin, K. A. C., & Koch, C. (1991). Synaptic background activity influences spatiotemporal integration in single pyramidal cells. Proc. Natl. Acad. Sci. USA, 88(24), 11569-11573. Author: Plesser SeeAlso: iaf_cond_alpha */ namespace nest { /** * Function computing right-hand side of ODE for GSL solver. * @note Must be declared here so we can befriend it in class. * @note Must have C-linkage for passing to GSL. * @note No point in declaring it inline, since it is called * through a function pointer. */ extern "C" int iaf_cond_alpha_mc_dynamics( double, const double*, double*, void* ); /** * @note All parameters that occur for both compartments * and dendrite are stored as C arrays, with index 0 being soma. */ class iaf_cond_alpha_mc : public Archiving_Node { // Boilerplate function declarations -------------------------------- public: iaf_cond_alpha_mc(); iaf_cond_alpha_mc( const iaf_cond_alpha_mc& ); ~iaf_cond_alpha_mc(); /** * Import sets of overloaded virtual functions. * @see Technical Issues / Virtual Functions: Overriding, Overloading, and * Hiding */ using Node::handle; using Node::handles_test_event; port send_test_event( Node&, rport, synindex, bool ); void handle( SpikeEvent& ); void handle( CurrentEvent& ); void handle( DataLoggingRequest& ); port handles_test_event( SpikeEvent&, rport ); port handles_test_event( CurrentEvent&, rport ); port handles_test_event( DataLoggingRequest&, rport ); void get_status( DictionaryDatum& ) const; void set_status( const DictionaryDatum& ); private: void init_state_( const Node& proto ); void init_buffers_(); void calibrate(); void update( Time const&, const long, const long ); // Enumerations and constants specifying structure and properties ---- //! Compartments, NCOMP is number enum Compartments_ { SOMA = 0, PROX, DIST, NCOMP }; /** * Minimal spike receptor type. * @note Start with 1 so we can forbid port 0 to avoid accidental * creation of connections with no receptor type set. */ static const port MIN_SPIKE_RECEPTOR = 1; /** * Spike receptors. */ enum SpikeSynapseTypes { SOMA_EXC = MIN_SPIKE_RECEPTOR, SOMA_INH, PROX_EXC, PROX_INH, DIST_EXC, DIST_INH, SUP_SPIKE_RECEPTOR }; static const size_t NUM_SPIKE_RECEPTORS = SUP_SPIKE_RECEPTOR - MIN_SPIKE_RECEPTOR; /** * Minimal current receptor type. * @note Start with SUP_SPIKE_RECEPTOR to avoid any overlap and * accidental mix-ups. */ static const port MIN_CURR_RECEPTOR = SUP_SPIKE_RECEPTOR; /** * Current receptors. */ enum CurrentSynapseTypes { I_SOMA = MIN_CURR_RECEPTOR, I_PROX, I_DIST, SUP_CURR_RECEPTOR }; static const size_t NUM_CURR_RECEPTORS = SUP_CURR_RECEPTOR - MIN_CURR_RECEPTOR; // Friends -------------------------------------------------------- friend int iaf_cond_alpha_mc_dynamics( double, const double*, double*, void* ); friend class RecordablesMap< iaf_cond_alpha_mc >; friend class UniversalDataLogger< iaf_cond_alpha_mc >; // Parameters ------------------------------------------------------ /** * Independent parameters of the model. * These parameters must be passed to the iteration function that * is passed to the GSL ODE solvers. Since the iteration function * is a C++ function with C linkage, the parameters can be stored * in a C++ struct with member functions, as long as we just pass * it by void* from C++ to C++ function. The struct must be public, * though, since the iteration function is a function with C-linkage, * whence it cannot be a member function of iaf_cond_alpha_mc. * @note One could achieve proper encapsulation by an extra level * of indirection: Define the iteration function as a member * function, plus an additional wrapper function with C linkage. * Then pass a struct containing a pointer to the node and a * pointer-to-member-function to the iteration function as void* * to the wrapper function. The wrapper function can then invoke * the iteration function on the node (Stroustrup, p 418). But * this appears to involved, and the extra indirections cost. */ struct Parameters_ { double V_th; //!< Threshold Potential in mV double V_reset; //!< Reset Potential in mV double t_ref; //!< Refractory period in ms double g_conn[ NCOMP - 1 ]; //!< Conductances connecting compartments, //!< in nS double g_L[ NCOMP ]; //!< Leak Conductance in nS double C_m[ NCOMP ]; //!< Membrane Capacitance in pF double E_ex[ NCOMP ]; //!< Excitatory reversal Potential in mV double E_in[ NCOMP ]; //!< Inhibitory reversal Potential in mV double E_L[ NCOMP ]; //!< Leak reversal Potential (aka resting potential) //!< in mV double tau_synE[ NCOMP ]; //!< Synaptic Time Constant Excitatory Synapse //!< in ms double tau_synI[ NCOMP ]; //!< Synaptic Time Constant for Inhibitory //!< Synapse in ms double I_e[ NCOMP ]; //!< Constant Current in pA Parameters_(); //!< Sets default parameter values Parameters_( const Parameters_& ); //!< needed to copy C-arrays Parameters_& operator=( const Parameters_& ); //!< needed to copy C-arrays void get( DictionaryDatum& ) const; //!< Store current values in dictionary void set( const DictionaryDatum& ); //!< Set values from dicitonary }; // State variables ------------------------------------------------------ /** * State variables of the model. * @note Copy constructor and assignment operator required because * of C-style array. */ public: struct State_ { /** * Elements of state vector. * For the multicompartmental case here, these are offset values. * The state variables are stored in contiguous blocks for each * compartment, beginning with the soma. */ enum StateVecElems_ { V_M = 0, DG_EXC, G_EXC, DG_INH, G_INH, STATE_VEC_COMPS }; //! total size of state vector static const size_t STATE_VEC_SIZE = STATE_VEC_COMPS * NCOMP; //! neuron state, must be C-array for GSL solver double y_[ STATE_VEC_SIZE ]; int r_; //!< number of refractory steps remaining State_( const Parameters_& ); //!< Default initialization State_( const State_& ); State_& operator=( const State_& ); void get( DictionaryDatum& ) const; void set( const DictionaryDatum&, const Parameters_& ); /** * Compute linear index into state array from compartment and element. * @param comp compartment index * @param elem elemet index * @note compartment argument is not of type Compartments_, since looping * over enumerations does not work. */ static size_t idx( size_t comp, StateVecElems_ elem ) { return comp * STATE_VEC_COMPS + elem; } }; private: // Internal buffers -------------------------------------------------------- /** * Buffers of the model. */ struct Buffers_ { Buffers_( iaf_cond_alpha_mc& ); //!<Sets buffer pointers to 0 //! Sets buffer pointers to 0 Buffers_( const Buffers_&, iaf_cond_alpha_mc& ); //! Logger for all analog data UniversalDataLogger< iaf_cond_alpha_mc > logger_; /** buffers and sums up incoming spikes/currents * @note Using STL vectors here to ensure initialization. */ std::vector< RingBuffer > spikes_; std::vector< RingBuffer > currents_; /** GSL ODE stuff */ gsl_odeiv_step* s_; //!< stepping function gsl_odeiv_control* c_; //!< adaptive stepsize control function gsl_odeiv_evolve* e_; //!< evolution function gsl_odeiv_system sys_; //!< struct describing system // IntergrationStep_ should be reset with the neuron on ResetNetwork, // but remain unchanged during calibration. Since it is initialized with // step_, and the resolution cannot change after nodes have been created, // it is safe to place both here. double step_; //!< step size in ms double IntegrationStep_; //!< current integration time step, updated by GSL /** * Input currents injected by CurrentEvent. * This variable is used to transport the current applied into the * _dynamics function computing the derivative of the state vector. * It must be a part of Buffers_, since it is initialized once before * the first simulation, but not modified before later Simulate calls. */ double I_stim_[ NCOMP ]; //!< External Stimulus in pA }; // Internal variables --------------------------------------------- /** * Internal variables of the model. */ struct Variables_ { /** initial value to normalise excitatory synaptic conductance */ double PSConInit_E_[ NCOMP ]; /** initial value to normalise inhibitory synaptic conductance */ double PSConInit_I_[ NCOMP ]; int RefractoryCounts_; }; // Access functions for UniversalDataLogger ------------------------------- /** * Read out state vector elements, used by UniversalDataLogger * First template argument is component "name", second compartment "name". */ template < State_::StateVecElems_ elem, Compartments_ comp > double get_y_elem_() const { return S_.y_[ S_.idx( comp, elem ) ]; } //! Read out number of refractory steps, used by UniversalDataLogger double get_r_() const { return Time::get_resolution().get_ms() * S_.r_; } // Data members ---------------------------------------------------- Parameters_ P_; State_ S_; Variables_ V_; Buffers_ B_; //! Table of compartment names static std::vector< Name > comp_names_; //! Dictionary of receptor types, leads to seg fault on exit, see #328 // static DictionaryDatum receptor_dict_; //! Mapping of recordables names to access functions static RecordablesMap< iaf_cond_alpha_mc > recordablesMap_; }; inline port iaf_cond_alpha_mc::send_test_event( Node& target, rport receptor_type, synindex, bool ) { SpikeEvent e; e.set_sender( *this ); return target.handles_test_event( e, receptor_type ); } inline port iaf_cond_alpha_mc::handles_test_event( SpikeEvent&, rport receptor_type ) { if ( receptor_type < MIN_SPIKE_RECEPTOR || receptor_type >= SUP_SPIKE_RECEPTOR ) { if ( receptor_type < 0 || receptor_type >= SUP_CURR_RECEPTOR ) { throw UnknownReceptorType( receptor_type, get_name() ); } else { throw IncompatibleReceptorType( receptor_type, get_name(), "SpikeEvent" ); } } return receptor_type - MIN_SPIKE_RECEPTOR; } inline port iaf_cond_alpha_mc::handles_test_event( CurrentEvent&, rport receptor_type ) { if ( receptor_type < MIN_CURR_RECEPTOR || receptor_type >= SUP_CURR_RECEPTOR ) { if ( receptor_type >= 0 && receptor_type < MIN_CURR_RECEPTOR ) { throw IncompatibleReceptorType( receptor_type, get_name(), "CurrentEvent" ); } else { throw UnknownReceptorType( receptor_type, get_name() ); } } return receptor_type - MIN_CURR_RECEPTOR; } inline port iaf_cond_alpha_mc::handles_test_event( DataLoggingRequest& dlr, rport receptor_type ) { if ( receptor_type != 0 ) { if ( receptor_type < 0 || receptor_type >= SUP_CURR_RECEPTOR ) { throw UnknownReceptorType( receptor_type, get_name() ); } else { throw IncompatibleReceptorType( receptor_type, get_name(), "DataLoggingRequest" ); } } return B_.logger_.connect_logging_device( dlr, recordablesMap_ ); } inline void iaf_cond_alpha_mc::get_status( DictionaryDatum& d ) const { P_.get( d ); S_.get( d ); Archiving_Node::get_status( d ); ( *d )[ names::recordables ] = recordablesMap_.get_list(); /** * @todo dictionary construction should be done only once for * static member in default c'tor, but this leads to * a seg fault on exit, see #328 */ DictionaryDatum receptor_dict_ = new Dictionary(); ( *receptor_dict_ )[ names::soma_exc ] = SOMA_EXC; ( *receptor_dict_ )[ names::soma_inh ] = SOMA_INH; ( *receptor_dict_ )[ names::soma_curr ] = I_SOMA; ( *receptor_dict_ )[ names::proximal_exc ] = PROX_EXC; ( *receptor_dict_ )[ names::proximal_inh ] = PROX_INH; ( *receptor_dict_ )[ names::proximal_curr ] = I_PROX; ( *receptor_dict_ )[ names::distal_exc ] = DIST_EXC; ( *receptor_dict_ )[ names::distal_inh ] = DIST_INH; ( *receptor_dict_ )[ names::distal_curr ] = I_DIST; ( *d )[ names::receptor_types ] = receptor_dict_; } inline void iaf_cond_alpha_mc::set_status( const DictionaryDatum& d ) { Parameters_ ptmp = P_; // temporary copy in case of errors ptmp.set( d ); // throws if BadProperty State_ stmp = S_; // temporary copy in case of errors stmp.set( d, ptmp ); // throws if BadProperty // We now know that (ptmp, stmp) are consistent. We do not // write them back to (P_, S_) before we are also sure that // the properties to be set in the parent class are internally // consistent. Archiving_Node::set_status( d ); // if we get here, temporaries contain consistent set of properties P_ = ptmp; S_ = stmp; } } // namespace #endif // HAVE_GSL #endif // IAF_COND_ALPHA_MC_H
{ "alphanum_fraction": 0.6764256897, "avg_line_length": 31.5154639175, "ext": "h", "hexsha": "0a2199c257fe19953a8af1a1d3e64fa398f382ff", "lang": "C", "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-03-25T09:32:56.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-09T06:45:59.000Z", "max_forks_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_forks_repo_path": "NEST-14.0-FPGA/models/iaf_cond_alpha_mc.h", "max_issues_count": 2, "max_issues_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_issues_repo_issues_event_max_datetime": "2021-09-08T02:33:46.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-23T05:34:21.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "zlchai/SNN-simulator-on-PYNQcluster", "max_issues_repo_path": "NEST-14.0-FPGA/models/iaf_cond_alpha_mc.h", "max_line_length": 80, "max_stars_count": 45, "max_stars_repo_head_hexsha": "14f86a76edf4e8763b58f84960876e95d4efc43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "OpenHEC/SNN-simulator-on-PYNQcluster", "max_stars_repo_path": "NEST-14.0-FPGA/models/iaf_cond_alpha_mc.h", "max_stars_repo_stars_event_max_datetime": "2022-01-29T12:16:41.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-09T06:45:53.000Z", "num_tokens": 4580, "size": 18342 }
/*! \file fasttransforms.h \brief fasttransforms.h is the main header file for FastTransforms. */ #ifndef FASTTRANSFORMS_H #define FASTTRANSFORMS_H #include <cblas.h> #include <fftw3.h> typedef double ft_complex[2]; #ifdef _OPENMP #include <omp.h> #define FT_GET_THREAD_NUM() omp_get_thread_num() #define FT_GET_NUM_THREADS() omp_get_num_threads() #define FT_GET_MAX_THREADS() omp_get_max_threads() #define FT_SET_NUM_THREADS(x) omp_set_num_threads(x) #else #define FT_GET_THREAD_NUM() 0 #define FT_GET_NUM_THREADS() 1 #define FT_GET_MAX_THREADS() 1 #define FT_SET_NUM_THREADS(x) #endif #define FT_CONCAT(prefix, name, suffix) prefix ## name ## suffix void ft_horner(const int n, const double * c, const int incc, const int m, double * x, double * f); void ft_hornerf(const int n, const float * c, const int incc, const int m, float * x, float * f); void ft_clenshaw(const int n, const double * c, const int incc, const int m, double * x, double * f); void ft_clenshawf(const int n, const float * c, const int incc, const int m, float * x, float * f); void ft_orthogonal_polynomial_clenshaw(const int n, const double * c, const int incc, const double * A, const double * B, const double * C, const int m, double * x, double * phi0, double * f); void ft_orthogonal_polynomial_clenshawf(const int n, const float * c, const int incc, const float * A, const float * B, const float * C, const int m, float * x, float * phi0, float * f); void ft_eigen_eval(const int n, const double * c, const int incc, const double * A, const double * B, const double * C, const int m, double * x, const int sign, double * f); void ft_eigen_evalf(const int n, const float * c, const int incc, const float * A, const float * B, const float * C, const int m, float * x, const int sign, float * f); void ft_eigen_evall(const int n, const long double * c, const int incc, const long double * A, const long double * B, const long double * C, const int m, long double * x, const int sign, long double * f); #if defined(FT_QUADMATH) #include <quadmath.h> typedef __float128 quadruple; void ft_eigen_evalq(const int n, const quadruple * c, const int incc, const quadruple * A, const quadruple * B, const quadruple * C, const int m, quadruple * x, const int sign, quadruple * f); #endif #define FT_SN (1U << 0) #define FT_CN (1U << 1) #define FT_DN (1U << 2) #include "tdc.h" /*! \brief Pre-compute a factorization of the connection coefficients between Legendre and Chebyshev polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Legendre}} P_\ell(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Chebyshev}} T_\ell(x). \f] `normleg` and `normcheb` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_legendre_to_chebyshevf, \ref ft_plan_legendre_to_chebyshevl, and \ref ft_mpfr_plan_legendre_to_chebyshev. */ ft_tb_eigen_FMM * ft_plan_legendre_to_chebyshev(const int normleg, const int normcheb, const int n); /*! \brief Pre-compute a factorization of the connection coefficients between Chebyshev and Legendre polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Chebyshev}} T_\ell(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Legendre}} P_\ell(x). \f] `normcheb` and `normleg` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_chebyshev_to_legendref, \ref ft_plan_chebyshev_to_legendrel, and \ref ft_mpfr_plan_chebyshev_to_legendre. */ ft_tb_eigen_FMM * ft_plan_chebyshev_to_legendre(const int normcheb, const int normleg, const int n); /*! \brief Pre-compute a factorization of the connection coefficients between ultraspherical polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{(1)} C_\ell^{(\lambda)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{(2)} C_\ell^{(\mu)}(x). \f] `norm1` and `norm2` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_ultraspherical_to_ultrasphericalf, \ref ft_plan_ultraspherical_to_ultrasphericall, and \ref ft_mpfr_plan_ultraspherical_to_ultraspherical. */ ft_tb_eigen_FMM * ft_plan_ultraspherical_to_ultraspherical(const int norm1, const int norm2, const int n, const double lambda, const double mu); /*! \brief Pre-compute a factorization of the connection coefficients between Jacobi polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{(1)} P_\ell^{(\alpha,\beta)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{(2)} P_\ell^{(\gamma,\delta)}(x). \f] `norm1` and `norm2` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_jacobi_to_jacobif, \ref ft_plan_jacobi_to_jacobil, and \ref ft_mpfr_plan_jacobi_to_jacobi. */ ft_tb_eigen_FMM * ft_plan_jacobi_to_jacobi(const int norm1, const int norm2, const int n, const double alpha, const double beta, const double gamma, const double delta); /*! \brief Pre-compute a factorization of the connection coefficients between Laguerre polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{(1)} L_\ell^{(\alpha)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{(2)} L_\ell^{(\beta)}(x). \f] `norm1` and `norm2` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_laguerre_to_laguerref, \ref ft_plan_laguerre_to_laguerrel, and \ref ft_mpfr_plan_laguerre_to_laguerre. */ ft_tb_eigen_FMM * ft_plan_laguerre_to_laguerre(const int norm1, const int norm2, const int n, const double alpha, const double beta); /*! \brief Pre-compute a factorization of the connection coefficients between Jacobi and ultraspherical polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Jacobi}} P_\ell^{(\alpha,\beta)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{ultraspherical}} C_\ell^{(\lambda)}(x). \f] `normjac` and `normultra` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_jacobi_to_ultrasphericalf, \ref ft_plan_jacobi_to_ultrasphericall, and \ref ft_mpfr_plan_jacobi_to_ultraspherical. */ ft_tb_eigen_FMM * ft_plan_jacobi_to_ultraspherical(const int normjac, const int normultra, const int n, const double alpha, const double beta, const double lambda); /*! \brief Pre-compute a factorization of the connection coefficients between ultraspherical and Jacobi polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{ultraspherical}} C_\ell^{(\lambda)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Jacobi}} P_\ell^{(\alpha,\beta)}(x). \f] `normultra` and `normjac` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_ultraspherical_to_jacobif, \ref ft_plan_ultraspherical_to_jacobil, and \ref ft_mpfr_plan_ultraspherical_to_jacobi. */ ft_tb_eigen_FMM * ft_plan_ultraspherical_to_jacobi(const int normultra, const int normjac, const int n, const double lambda, const double alpha, const double beta); /*! \brief Pre-compute a factorization of the connection coefficients between Jacobi and Chebyshev polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Jacobi}} P_\ell^{(\alpha,\beta)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Chebyshev}} T_\ell(x). \f] `normjac` and `normcheb` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_jacobi_to_chebyshevf, \ref ft_plan_jacobi_to_chebyshevl, and \ref ft_mpfr_plan_jacobi_to_chebyshev. */ ft_tb_eigen_FMM * ft_plan_jacobi_to_chebyshev(const int normjac, const int normcheb, const int n, const double alpha, const double beta); /*! \brief Pre-compute a factorization of the connection coefficients between Chebyshev and Jacobi polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Chebyshev}} T_\ell(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Jacobi}} P_\ell^{(\alpha,\beta)}(x). \f] `normcheb` and `normjac` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_chebyshev_to_jacobif, \ref ft_plan_chebyshev_to_jacobil, and \ref ft_mpfr_plan_chebyshev_to_jacobi. */ ft_tb_eigen_FMM * ft_plan_chebyshev_to_jacobi(const int normcheb, const int normjac, const int n, const double alpha, const double beta); /*! \brief Pre-compute a factorization of the connection coefficients between ultraspherical and Chebyshev polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{ultraspherical}} C_\ell^{(\lambda)}(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Chebyshev}} T_\ell(x). \f] `normultra` and `normcheb` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_ultraspherical_to_chebyshevf, \ref ft_plan_ultraspherical_to_chebyshevl, and \ref ft_mpfr_plan_ultraspherical_to_chebyshev. */ ft_tb_eigen_FMM * ft_plan_ultraspherical_to_chebyshev(const int normultra, const int normcheb, const int n, const double lambda); /*! \brief Pre-compute a factorization of the connection coefficients between Chebyshev and ultraspherical polynomials in double precision so that ft_bfmv converts between expansions: \f[ \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{Chebyshev}} T_\ell(x) = \sum_{\ell=0}^{n-1} c_\ell^{\mathrm{ultraspherical}} C_\ell^{(\lambda)}(x). \f] `normcheb` and `normultra` govern the normalizations, either standard ( == 0) or orthonormalized ( == 1).\n See also \ref ft_plan_chebyshev_to_ultrasphericalf, \ref ft_plan_chebyshev_to_ultrasphericall, and \ref ft_mpfr_plan_chebyshev_to_ultraspherical. */ ft_tb_eigen_FMM * ft_plan_chebyshev_to_ultraspherical(const int normcheb, const int normultra, const int n, const double lambda); ft_btb_eigen_FMM * ft_plan_associated_jacobi_to_jacobi(const int norm1, const int norm2, const int n, const int c, const double alpha, const double beta, const double gamma, const double delta); ft_btb_eigen_FMM * ft_plan_associated_laguerre_to_laguerre(const int norm1, const int norm2, const int n, const int c, const double alpha, const double beta); ft_btb_eigen_FMM * ft_plan_associated_hermite_to_hermite(const int norm1, const int norm2, const int n, const int c); /// A single precision version of \ref ft_plan_legendre_to_chebyshev. ft_tb_eigen_FMMf * ft_plan_legendre_to_chebyshevf(const int normleg, const int normcheb, const int n); /// A single precision version of \ref ft_plan_chebyshev_to_legendre. ft_tb_eigen_FMMf * ft_plan_chebyshev_to_legendref(const int normcheb, const int normleg, const int n); /// A single precision version of \ref ft_plan_ultraspherical_to_ultraspherical. ft_tb_eigen_FMMf * ft_plan_ultraspherical_to_ultrasphericalf(const int norm1, const int norm2, const int n, const float lambda, const float mu); /// A single precision version of \ref ft_plan_jacobi_to_jacobi. ft_tb_eigen_FMMf * ft_plan_jacobi_to_jacobif(const int norm1, const int norm2, const int n, const float alpha, const float beta, const float gamma, const float delta); /// A single precision version of \ref ft_plan_laguerre_to_laguerre. ft_tb_eigen_FMMf * ft_plan_laguerre_to_laguerref(const int norm1, const int norm2, const int n, const float alpha, const float beta); /// A single precision version of \ref ft_plan_jacobi_to_ultraspherical. ft_tb_eigen_FMMf * ft_plan_jacobi_to_ultrasphericalf(const int normjac, const int normultra, const int n, const float alpha, const float beta, const float lambda); /// A single precision version of \ref ft_plan_ultraspherical_to_jacobi. ft_tb_eigen_FMMf * ft_plan_ultraspherical_to_jacobif(const int normultra, const int normjac, const int n, const float lambda, const float alpha, const float beta); /// A single precision version of \ref ft_plan_jacobi_to_chebyshev. ft_tb_eigen_FMMf * ft_plan_jacobi_to_chebyshevf(const int normjac, const int normcheb, const int n, const float alpha, const float beta); /// A single precision version of \ref ft_plan_chebyshev_to_jacobi. ft_tb_eigen_FMMf * ft_plan_chebyshev_to_jacobif(const int normcheb, const int normjac, const int n, const float alpha, const float beta); /// A single precision version of \ref ft_plan_ultraspherical_to_chebyshev. ft_tb_eigen_FMMf * ft_plan_ultraspherical_to_chebyshevf(const int normultra, const int normcheb, const int n, const float lambda); /// A single precision version of \ref ft_plan_chebyshev_to_ultraspherical. ft_tb_eigen_FMMf * ft_plan_chebyshev_to_ultrasphericalf(const int normcheb, const int normultra, const int n, const float lambda); ft_btb_eigen_FMMf * ft_plan_associated_jacobi_to_jacobif(const int norm1, const int norm2, const int n, const int c, const float alpha, const float beta, const float gamma, const float delta); ft_btb_eigen_FMMf * ft_plan_associated_laguerre_to_laguerref(const int norm1, const int norm2, const int n, const int c, const float alpha, const float beta); ft_btb_eigen_FMMf * ft_plan_associated_hermite_to_hermitef(const int norm1, const int norm2, const int n, const int c); /// A long double precision version of \ref ft_plan_legendre_to_chebyshev. ft_tb_eigen_FMMl * ft_plan_legendre_to_chebyshevl(const int normleg, const int normcheb, const int n); /// A long double precision version of \ref ft_plan_chebyshev_to_legendre. ft_tb_eigen_FMMl * ft_plan_chebyshev_to_legendrel(const int normcheb, const int normleg, const int n); /// A long double precision version of \ref ft_plan_ultraspherical_to_ultraspherical. ft_tb_eigen_FMMl * ft_plan_ultraspherical_to_ultrasphericall(const int norm1, const int norm2, const int n, const long double lambda, const long double mu); /// A long double precision version of \ref ft_plan_jacobi_to_jacobi. ft_tb_eigen_FMMl * ft_plan_jacobi_to_jacobil(const int norm1, const int norm2, const int n, const long double alpha, const long double beta, const long double gamma, const long double delta); /// A long double precision version of \ref ft_plan_laguerre_to_laguerre. ft_tb_eigen_FMMl * ft_plan_laguerre_to_laguerrel(const int norm1, const int norm2, const int n, const long double alpha, const long double beta); /// A long double precision version of \ref ft_plan_jacobi_to_ultraspherical. ft_tb_eigen_FMMl * ft_plan_jacobi_to_ultrasphericall(const int normjac, const int normultra, const int n, const long double alpha, const long double beta, const long double lambda); /// A long double precision version of \ref ft_plan_ultraspherical_to_jacobi. ft_tb_eigen_FMMl * ft_plan_ultraspherical_to_jacobil(const int normultra, const int normjac, const int n, const long double lambda, const long double alpha, const long double beta); /// A long double precision version of \ref ft_plan_jacobi_to_chebyshev. ft_tb_eigen_FMMl * ft_plan_jacobi_to_chebyshevl(const int normjac, const int normcheb, const int n, const long double alpha, const long double beta); /// A long double precision version of \ref ft_plan_chebyshev_to_jacobi. ft_tb_eigen_FMMl * ft_plan_chebyshev_to_jacobil(const int normcheb, const int normjac, const int n, const long double alpha, const long double beta); /// A long double precision version of \ref ft_plan_ultraspherical_to_chebyshev. ft_tb_eigen_FMMl * ft_plan_ultraspherical_to_chebyshevl(const int normultra, const int normcheb, const int n, const long double lambda); /// A long double precision version of \ref ft_plan_chebyshev_to_ultraspherical. ft_tb_eigen_FMMl * ft_plan_chebyshev_to_ultrasphericall(const int normcheb, const int normultra, const int n, const long double lambda); ft_btb_eigen_FMMl * ft_plan_associated_jacobi_to_jacobil(const int norm1, const int norm2, const int n, const int c, const long double alpha, const long double beta, const long double gamma, const long double delta); ft_btb_eigen_FMMl * ft_plan_associated_laguerre_to_laguerrel(const int norm1, const int norm2, const int n, const int c, const long double alpha, const long double beta); ft_btb_eigen_FMMl * ft_plan_associated_hermite_to_hermitel(const int norm1, const int norm2, const int n, const int c); #include <mpfr.h> typedef struct { mpfr_t * data; int n; int b; } ft_mpfr_triangular_banded; void ft_mpfr_destroy_plan(mpfr_t * A, int n); void ft_mpfr_trmv(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * x, mpfr_rnd_t rnd); void ft_mpfr_trsv(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * x, mpfr_rnd_t rnd); void ft_mpfr_trmm(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * B, int LDB, int N, mpfr_rnd_t rnd); void ft_mpfr_trsm(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t * B, int LDB, int N, mpfr_rnd_t rnd); // C -- Julia interoperability. Julia `BigFloat` does not have the same size as `mpfr_t`. // So we give all Julia-owned data its own address, and dereference to retrieve the number. void ft_mpfr_trmv_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** x, mpfr_rnd_t rnd); void ft_mpfr_trsv_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** x, mpfr_rnd_t rnd); void ft_mpfr_trmm_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** B, int LDB, int N, mpfr_rnd_t rnd); void ft_mpfr_trsm_ptr(char TRANS, int n, mpfr_t * A, int LDA, mpfr_t ** B, int LDB, int N, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_legendre_to_chebyshev that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_legendre_to_chebyshev(const int normleg, const int normcheb, const int n, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_chebyshev_to_legendre that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_chebyshev_to_legendre(const int normcheb, const int normleg, const int n, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_ultraspherical_to_ultraspherical that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_ultraspherical_to_ultraspherical(const int norm1, const int norm2, const int n, mpfr_srcptr lambda, mpfr_srcptr mu, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_jacobi_to_jacobi that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_jacobi_to_jacobi(const int norm1, const int norm2, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_srcptr gamma, mpfr_srcptr delta, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_laguerre_to_laguerre that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_laguerre_to_laguerre(const int norm1, const int norm2, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_jacobi_to_ultraspherical that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_jacobi_to_ultraspherical(const int normjac, const int normultra, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_srcptr lambda, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_ultraspherical_to_jacobi that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_ultraspherical_to_jacobi(const int normultra, const int normjac, const int n, mpfr_srcptr lambda, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_jacobi_to_chebyshev that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_jacobi_to_chebyshev(const int normjac, const int normcheb, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_chebyshev_to_jacobi that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_chebyshev_to_jacobi(const int normcheb, const int normjac, const int n, mpfr_srcptr alpha, mpfr_srcptr beta, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_ultraspherical_to_chebyshev that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_ultraspherical_to_chebyshev(const int normultra, const int normcheb, const int n, mpfr_srcptr lambda, mpfr_prec_t prec, mpfr_rnd_t rnd); /// A multi-precision version of \ref ft_plan_chebyshev_to_ultraspherical that returns a dense array of connection coefficients. mpfr_t * ft_mpfr_plan_chebyshev_to_ultraspherical(const int normcheb, const int normultra, const int n, mpfr_srcptr lambda, mpfr_prec_t prec, mpfr_rnd_t rnd); /// Set the number of OpenMP threads. void ft_set_num_threads(const int n); /// Data structure to store sines and cosines of Givens rotations. typedef struct ft_rotation_plan_s ft_rotation_plan; /// Destroy a \ref ft_rotation_plan. void ft_destroy_rotation_plan(ft_rotation_plan * RP); ft_rotation_plan * ft_plan_rotsphere(const int n); /// Convert a single vector of spherical harmonic coefficients in A with stride S from order m2 down to order m1. void ft_kernel_sph_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); /// Convert a single vector of spherical harmonic coefficients in A with stride S from order m1 up to order m2. void ft_kernel_sph_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); ft_rotation_plan * ft_plan_rottriangle(const int n, const double alpha, const double beta, const double gamma); /// Convert a single vector of triangular harmonic coefficients in A with stride S from order m2 down to order m1. void ft_kernel_tri_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); /// Convert a single vector of triangular harmonic coefficients in A with stride S from order m1 up to order m2. void ft_kernel_tri_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); ft_rotation_plan * ft_plan_rotdisk(const int n, const double alpha, const double beta); /// Convert a single vector of disk harmonic coefficients in A with stride S from order m2 down to order m1. void ft_kernel_disk_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); /// Convert a single vector of disk harmonic coefficients in A with stride S from order m1 up to order m2. void ft_kernel_disk_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); ft_rotation_plan * ft_plan_rotrectdisk(const int n, const double beta); /// Convert a single vector of rectangularized disk harmonic coefficients in A with stride S from order m2 down to order m1. void ft_kernel_rectdisk_hi2lo(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); /// Convert a single vector of rectangularized disk harmonic coefficients in A with stride S from order m1 up to order m2. void ft_kernel_rectdisk_lo2hi(const ft_rotation_plan * RP, const int m1, const int m2, double * A, const int S); void ft_kernel_tet_hi2lo(const ft_rotation_plan * RP, const int L, const int m, double * A); void ft_kernel_tet_lo2hi(const ft_rotation_plan * RP, const int L, const int m, double * A); /// Data structure to store sines and cosines of Givens rotations for spin-weighted harmonics. typedef struct ft_spin_rotation_plan_s ft_spin_rotation_plan; /// Destroy a \ref ft_spin_rotation_plan. void ft_destroy_spin_rotation_plan(ft_spin_rotation_plan * SRP); ft_spin_rotation_plan * ft_plan_rotspinsphere(const int n, const int s); /// Convert a single vector of spin-weighted spherical harmonic coefficients in A with stride S from order m down to order m%2. void ft_kernel_spinsph_hi2lo(const ft_spin_rotation_plan * SRP, const int m, ft_complex * A, const int S); /// Convert a single vector of spin-weighted spherical harmonic coefficients in A with stride S from order m%2 up to order m. void ft_kernel_spinsph_lo2hi(const ft_spin_rotation_plan * SRP, const int m, ft_complex * A, const int S); void ft_execute_sph_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_sph_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_sphv_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_sphv_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_tri_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_tri_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_disk_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_disk_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_rectdisk_hi2lo(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_rectdisk_lo2hi(const ft_rotation_plan * RP, double * A, double * B, const int M); void ft_execute_tet_hi2lo(const ft_rotation_plan * RP1, const ft_rotation_plan * RP2, double * A, const int L, const int M); void ft_execute_tet_lo2hi(const ft_rotation_plan * RP1, const ft_rotation_plan * RP2, double * A, const int L, const int M); void ft_execute_spinsph_hi2lo(const ft_spin_rotation_plan * SRP, ft_complex * A, ft_complex * B, const int M); void ft_execute_spinsph_lo2hi(const ft_spin_rotation_plan * SRP, ft_complex * A, ft_complex * B, const int M); /// Data structure to store \ref ft_rotation_plan "ft_rotation_plan"s, arrays to represent 1D orthogonal polynomial transforms and their inverses, and Greek parameters. typedef struct { ft_rotation_plan ** RP; double * B; double ** P; double ** Pinv; double alpha; double beta; double gamma; double delta; int NRP; int NP; } ft_harmonic_plan; /// Destroy a \ref ft_harmonic_plan. void ft_destroy_harmonic_plan(ft_harmonic_plan * P); /// Plan a spherical harmonic transform. ft_harmonic_plan * ft_plan_sph2fourier(const int n); /// Transform a spherical harmonic expansion to a bivariate Fourier series. void ft_execute_sph2fourier(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Transform a bivariate Fourier series to a spherical harmonic expansion. void ft_execute_fourier2sph(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); void ft_execute_sphv2fourier(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); void ft_execute_fourier2sphv(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Plan a triangular harmonic transform. ft_harmonic_plan * ft_plan_tri2cheb(const int n, const double alpha, const double beta, const double gamma); /// Transform a triangular harmonic expansion to a bivariate Chebyshev series. void ft_execute_tri2cheb(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Transform a bivariate Chebyshev series to a triangular harmonic expansion. void ft_execute_cheb2tri(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Plan a disk harmonic transform. ft_harmonic_plan * ft_plan_disk2cxf(const int n, const double alpha, const double beta); /// Transform a disk harmonic expansion to a Chebyshev--Fourier series. void ft_execute_disk2cxf(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Transform a Chebyshev--Fourier series to a disk harmonic expansion. void ft_execute_cxf2disk(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Plan a rectangularized disk harmonic transform. ft_harmonic_plan * ft_plan_rectdisk2cheb(const int n, const double beta); /// Transform a rectangularized disk harmonic expansion to a Chebyshev series. void ft_execute_rectdisk2cheb(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Transform a Chebyshev series to a rectangularized disk harmonic expansion. void ft_execute_cheb2rectdisk(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int M); /// Plan a tetrahedral harmonic transform. ft_harmonic_plan * ft_plan_tet2cheb(const int n, const double alpha, const double beta, const double gamma, const double delta); /// Transform a tetrahedral harmonic expansion to a trivariate Chebyshev series. void ft_execute_tet2cheb(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int L, const int M); /// Transform a trivariate Chebyshev series to a tetrahedral harmonic expansion. void ft_execute_cheb2tet(const char TRANS, const ft_harmonic_plan * P, double * A, const int N, const int L, const int M); /// Data structure to store a \ref ft_spin_rotation_plan, and various arrays to represent 1D orthogonal polynomial transforms. typedef struct { ft_spin_rotation_plan * SRP; ft_complex * B; ft_complex * P1; ft_complex * P2; ft_complex * P1inv; ft_complex * P2inv; int s; } ft_spin_harmonic_plan; /// Destroy a \ref ft_spin_harmonic_plan. void ft_destroy_spin_harmonic_plan(ft_spin_harmonic_plan * P); /// Plan a spin-weighted spherical harmonic transform. ft_spin_harmonic_plan * ft_plan_spinsph2fourier(const int n, const int s); /// Transform a spin-weighted spherical harmonic expansion to a bivariate Fourier series. void ft_execute_spinsph2fourier(const char TRANS, const ft_spin_harmonic_plan * P, ft_complex * A, const int N, const int M); /// Transform a bivariate Fourier series to a spin-weighted spherical harmonic expansion. void ft_execute_fourier2spinsph(const char TRANS, const ft_spin_harmonic_plan * P, ft_complex * A, const int N, const int M); int ft_fftw_init_threads(void); void ft_fftw_plan_with_nthreads(const int n); typedef struct { fftw_plan plantheta1; fftw_plan plantheta2; fftw_plan plantheta3; fftw_plan plantheta4; fftw_plan planphi; double * Y; } ft_sphere_fftw_plan; /// Destroy a \ref ft_sphere_fftw_plan. void ft_destroy_sphere_fftw_plan(ft_sphere_fftw_plan * P); ft_sphere_fftw_plan * ft_plan_sph_with_kind(const int N, const int M, const fftw_r2r_kind kind[3][1]); /// Plan FFTW synthesis on the sphere. ft_sphere_fftw_plan * ft_plan_sph_synthesis(const int N, const int M); /// Plan FFTW analysis on the sphere. ft_sphere_fftw_plan * ft_plan_sph_analysis(const int N, const int M); ft_sphere_fftw_plan * ft_plan_sphv_synthesis(const int N, const int M); ft_sphere_fftw_plan * ft_plan_sphv_analysis(const int N, const int M); /// Execute FFTW synthesis on the sphere. void ft_execute_sph_synthesis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M); /// Execute FFTW analysis on the sphere. void ft_execute_sph_analysis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M); void ft_execute_sphv_synthesis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M); void ft_execute_sphv_analysis(const char TRANS, const ft_sphere_fftw_plan * P, double * X, const int N, const int M); typedef struct { fftw_plan planxy; } ft_triangle_fftw_plan; /// Destroy a \ref ft_triangle_fftw_plan. void ft_destroy_triangle_fftw_plan(ft_triangle_fftw_plan * P); ft_triangle_fftw_plan * ft_plan_tri_with_kind(const int N, const int M, const fftw_r2r_kind kind0, const fftw_r2r_kind kind1); /// Plan FFTW synthesis on the triangle. ft_triangle_fftw_plan * ft_plan_tri_synthesis(const int N, const int M); /// Plan FFTW analysis on the triangle. ft_triangle_fftw_plan * ft_plan_tri_analysis(const int N, const int M); /// Execute FFTW synthesis on the triangle. void ft_execute_tri_synthesis(const char TRANS, const ft_triangle_fftw_plan * P, double * X, const int N, const int M); /// Execute FFTW analysis on the triangle. void ft_execute_tri_analysis(const char TRANS, const ft_triangle_fftw_plan * P, double * X, const int N, const int M); typedef struct { fftw_plan planxyz; } ft_tetrahedron_fftw_plan; void ft_destroy_tetrahedron_fftw_plan(ft_tetrahedron_fftw_plan * P); ft_tetrahedron_fftw_plan * ft_plan_tet_with_kind(const int N, const int L, const int M, const fftw_r2r_kind kind0, const fftw_r2r_kind kind1, const fftw_r2r_kind kind2); ft_tetrahedron_fftw_plan * ft_plan_tet_synthesis(const int N, const int L, const int M); ft_tetrahedron_fftw_plan * ft_plan_tet_analysis(const int N, const int L, const int M); void ft_execute_tet_synthesis(const char TRANS, const ft_tetrahedron_fftw_plan * P, double * X, const int N, const int L, const int M); void ft_execute_tet_analysis(const char TRANS, const ft_tetrahedron_fftw_plan * P, double * X, const int N, const int L, const int M); typedef struct { fftw_plan planr1; fftw_plan planr2; fftw_plan planr3; fftw_plan planr4; fftw_plan plantheta; double * Y; } ft_disk_fftw_plan; /// Destroy a \ref ft_disk_fftw_plan. void ft_destroy_disk_fftw_plan(ft_disk_fftw_plan * P); ft_disk_fftw_plan * ft_plan_disk_with_kind(const int N, const int M, const fftw_r2r_kind kind[3][1]); /// Plan FFTW synthesis on the disk. ft_disk_fftw_plan * ft_plan_disk_synthesis(const int N, const int M); /// Plan FFTW analysis on the disk. ft_disk_fftw_plan * ft_plan_disk_analysis(const int N, const int M); /// Execute FFTW synthesis on the disk. void ft_execute_disk_synthesis(const char TRANS, const ft_disk_fftw_plan * P, double * X, const int N, const int M); /// Execute FFTW analysis on the disk. void ft_execute_disk_analysis(const char TRANS, const ft_disk_fftw_plan * P, double * X, const int N, const int M); typedef struct { fftw_plan planx1; fftw_plan planx2; fftw_plan plany; } ft_rectdisk_fftw_plan; /// Destroy a \ref ft_rectdisk_fftw_plan. void ft_destroy_rectdisk_fftw_plan(ft_rectdisk_fftw_plan * P); ft_rectdisk_fftw_plan * ft_plan_rectdisk_with_kind(const int N, const int M, const fftw_r2r_kind kind[3][1]); /// Plan FFTW synthesis on the rectangularized disk. ft_rectdisk_fftw_plan * ft_plan_rectdisk_synthesis(const int N, const int M); /// Plan FFTW analysis on the rectangularized disk. ft_rectdisk_fftw_plan * ft_plan_rectdisk_analysis(const int N, const int M); /// Execute FFTW synthesis on the rectangularized disk. void ft_execute_rectdisk_synthesis(const char TRANS, const ft_rectdisk_fftw_plan * P, double * X, const int N, const int M); /// Execute FFTW analysis on the rectangularized disk. void ft_execute_rectdisk_analysis(const char TRANS, const ft_rectdisk_fftw_plan * P, double * X, const int N, const int M); typedef struct { fftw_plan plantheta1; fftw_plan plantheta2; fftw_plan plantheta3; fftw_plan plantheta4; fftw_plan planphi; double * Y; int S; } ft_spinsphere_fftw_plan; /// Destroy a \ref ft_spinsphere_fftw_plan. void ft_destroy_spinsphere_fftw_plan(ft_spinsphere_fftw_plan * P); int ft_get_spin_spinsphere_fftw_plan(const ft_spinsphere_fftw_plan * P); ft_spinsphere_fftw_plan * ft_plan_spinsph_with_kind(const int N, const int M, const int S, const fftw_r2r_kind kind[2][1], const int sign); /// Plan FFTW synthesis on the sphere with spin. ft_spinsphere_fftw_plan * ft_plan_spinsph_synthesis(const int N, const int M, const int S); /// Plan FFTW analysis on the sphere with spin. ft_spinsphere_fftw_plan * ft_plan_spinsph_analysis(const int N, const int M, const int S); /// Execute FFTW synthesis on the sphere with spin. void ft_execute_spinsph_synthesis(const char TRANS, const ft_spinsphere_fftw_plan * P, ft_complex * X, const int N, const int M); /// Execute FFTW analysis on the sphere with spin. void ft_execute_spinsph_analysis(const char TRANS, const ft_spinsphere_fftw_plan * P, ft_complex * X, const int N, const int M); typedef struct { ft_banded ** B; ft_triangular_banded ** T; int n; } ft_gradient_plan; void ft_destroy_gradient_plan(ft_gradient_plan * P); ft_gradient_plan * ft_plan_sph_gradient(const int n); void ft_execute_sph_gradient(ft_gradient_plan * P, double * U, double * Ut, double * Up, const int N, const int M); void ft_execute_sph_curl(ft_gradient_plan * P, double * U, double * Ut, double * Up, const int N, const int M); typedef struct { ft_triangular_banded ** T; ft_banded_qr ** F; double * X; int n; } ft_helmholtzhodge_plan; void ft_destroy_helmholtzhodge_plan(ft_helmholtzhodge_plan * P); ft_helmholtzhodge_plan * ft_plan_sph_helmholtzhodge(const int n); void ft_execute_sph_helmholtzhodge(ft_helmholtzhodge_plan * P, double * U1, double * U2, double * V1, double * V2, const int N, const int M); /*! \brief A static struct to store an orthogonal matrix \f$Q \in \mathbb{R}^{3\times3}\f$, such that \f$Q^\top Q = I\f$. \f$Q\f$ has column-major storage. */ typedef struct { double Q[9]; } ft_orthogonal_transformation; /*! \brief Every orthogonal matrix \f$Q \in \mathbb{R}^{3\times3}\f$ can be decomposed as a product of \f$ZYZ\f$ Euler angles and, if necessary, a reflection \f$R\f$ about the \f$xy\f$-plane. \f[ Q = ZYZR, \f] where the \f$z\f$-axis rotations are: \f[ Z = \begin{pmatrix} c & -s & 0\\ s & c & 0\\ 0 & 0 & 1\end{pmatrix}, \f] the \f$y\f$-axis rotation is: \f[ Y = \begin{pmatrix} c & 0 & -s\\ 0 & 1 & 0\\ s & 0 & c\end{pmatrix}, \f] and the potential reflection is: \f[ R = \begin{pmatrix} 1 & 0 & 0\\ 0 & 1 & 0\\ 0 & 0 & \pm 1\end{pmatrix}. \f] The reflection is stored as an integer `sign` corresponding to the bottom right entry. */ typedef struct { double s[3]; double c[3]; int sign; } ft_ZYZR; /*! \brief A static struct to store a reflection about the plane \f$w\cdot x = 0\f$ in \f$\mathbb{R}^3\f$. */ typedef struct { double w[3]; } ft_reflection; ft_ZYZR ft_create_ZYZR(ft_orthogonal_transformation Q); void ft_apply_ZYZR(ft_ZYZR Q, ft_orthogonal_transformation * U); void ft_apply_reflection(ft_reflection Q, ft_orthogonal_transformation * U); void ft_execute_sph_polar_rotation(double * A, const int N, const int M, double s, double c); void ft_execute_sph_polar_reflection(double * A, const int N, const int M); typedef struct { ft_symmetric_tridiagonal_symmetric_eigen * F11; ft_symmetric_tridiagonal_symmetric_eigen * F21; ft_symmetric_tridiagonal_symmetric_eigen * F12; ft_symmetric_tridiagonal_symmetric_eigen * F22; int l; } ft_partial_sph_isometry_plan; typedef struct { ft_partial_sph_isometry_plan ** F; int n; } ft_sph_isometry_plan; void ft_destroy_partial_sph_isometry_plan(ft_partial_sph_isometry_plan * F); void ft_destroy_sph_isometry_plan(ft_sph_isometry_plan * F); ft_partial_sph_isometry_plan * ft_plan_partial_sph_isometry(const int l); ft_sph_isometry_plan * ft_plan_sph_isometry(const int n); void ft_execute_sph_yz_axis_exchange(ft_sph_isometry_plan * J, double * A, const int N, const int M); void ft_execute_sph_isometry(ft_sph_isometry_plan * J, ft_ZYZR Q, double * A, const int N, const int M); void ft_execute_sph_rotation(ft_sph_isometry_plan * J, const double alpha, const double beta, const double gamma, double * A, const int N, const int M); void ft_execute_sph_reflection(ft_sph_isometry_plan * J, ft_reflection W, double * A, const int N, const int M); void ft_execute_sph_orthogonal_transformation(ft_sph_isometry_plan * J, ft_orthogonal_transformation Q, double * A, const int N, const int M); #endif // FASTTRANSFORMS_H
{ "alphanum_fraction": 0.7723035615, "avg_line_length": 60.7353846154, "ext": "h", "hexsha": "cf0d6e148be9135f4fa9ec497c817ed98677570d", "lang": "C", "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2022-01-28T21:29:14.000Z", "max_forks_repo_forks_event_min_datetime": "2018-06-11T15:21:32.000Z", "max_forks_repo_head_hexsha": "4f0beb32d3447a04fdf6e236c550ab0f4ef6f73a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MikaelSlevinsky/FastTransforms", "max_forks_repo_path": "src/fasttransforms.h", "max_issues_count": 51, "max_issues_repo_head_hexsha": "4f0beb32d3447a04fdf6e236c550ab0f4ef6f73a", "max_issues_repo_issues_event_max_datetime": "2021-09-09T15:53:04.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-28T15:01:52.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MikaelSlevinsky/FastTransforms", "max_issues_repo_path": "src/fasttransforms.h", "max_line_length": 216, "max_stars_count": 36, "max_stars_repo_head_hexsha": "4f0beb32d3447a04fdf6e236c550ab0f4ef6f73a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MikaelSlevinsky/FastTransforms", "max_stars_repo_path": "src/fasttransforms.h", "max_stars_repo_stars_event_max_datetime": "2022-01-01T00:27:31.000Z", "max_stars_repo_stars_event_min_datetime": "2018-05-05T04:01:23.000Z", "num_tokens": 11338, "size": 39478 }
/* ** False disovery rate (FDR) ** ** G.Lohmann, Jan 2017 */ #include <viaio/VImage.h> #include <viaio/Vlib.h> #include <viaio/mu.h> #include <viaio/option.h> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_histogram.h> #include <gsl/gsl_cdf.h> #include <gsl/gsl_math.h> /* get array of FDR values */ double *GetFdr(gsl_histogram *nullhist,gsl_histogram *realhist) { size_t i=0; size_t nbins = gsl_histogram_bins (nullhist); /* cumulative distribution functions (CDF) */ gsl_histogram_pdf *cdfz = gsl_histogram_pdf_alloc(nbins); gsl_histogram_pdf *cdf0 = gsl_histogram_pdf_alloc(nbins); gsl_histogram_pdf_init (cdfz,realhist); gsl_histogram_pdf_init (cdf0,nullhist); /* fdr array */ double *fdr = (double *)VCalloc(nbins,sizeof(double)); for (i=0; i<nbins; i++) { double Fz = cdfz->sum[i]; double F0 = cdf0->sum[i]; double xFdr = 1.0; if (Fz < 1.0) xFdr = (1.0-F0)/(1.0-Fz); if (xFdr > 1.0) xFdr = 1.0; if (xFdr < 0.0) xFdr = 0.0; fdr[i] = xFdr; } /* enforce monotonicity */ fdr[0] = 1.0; for (i=1; i<nbins; i++) { if (fdr[i] > fdr[i-1]) fdr[i] = fdr[i-1]; } return fdr; } /* thresholding */ void ApplyFdrThreshold(VImage dest,double alpha) { double u=0,beta=1.0-alpha; size_t i,n=0; VFloat *pp = VImageData(dest); for (i=0; i<VImageNPixels(dest); i++) { u = (*pp); if (u < beta) *pp = 0; else n++; pp++; } fprintf(stderr," Number of voxels at Fdr < %.4f: %lu\n",alpha,n); } /* estimage false discovery rates */ void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double alpha) { size_t j; double u=0,tiny=0.002; double hmin = gsl_histogram_min (realhist); double hmax = gsl_histogram_max (realhist); /* compute Fdr */ double *Fdr = GetFdr(nullhist,realhist); /* apply FDR */ VFillImage(dest,VAllBands,0); int b,r,c; for (b=0; b<VImageNBands(dest); b++) { for (r=0; r<VImageNRows(dest); r++) { for (c=0; c<VImageNColumns(dest); c++) { u = VGetPixel(src,b,r,c); if (u > hmax) u = hmax-tiny; if (u < hmin) u = hmin+tiny; if (fabs(u) > 0) { if (gsl_histogram_find (realhist,(double)u,&j) == GSL_SUCCESS) { VPixel(dest,b,r,c,VFloat) = 1.0 - Fdr[j]; } } } } } /* apply threshold if needed */ if (alpha < 0.99) ApplyFdrThreshold(dest,alpha); return; }
{ "alphanum_fraction": 0.6259572753, "avg_line_length": 22.5545454545, "ext": "c", "hexsha": "e833b46491f89ec772a1302af52bf7eac56a5fa6", "lang": "C", "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z", "max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z", "max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "zrajna/lipsia", "max_forks_repo_path": "src/stats/utils/FDR.c", "max_issues_count": 7, "max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "zrajna/lipsia", "max_issues_repo_path": "src/stats/utils/FDR.c", "max_line_length": 93, "max_stars_count": 17, "max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "zrajna/lipsia", "max_stars_repo_path": "src/stats/utils/FDR.c", "max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z", "num_tokens": 873, "size": 2481 }
// Copyright (c) 2013 Vasili Baranau // Distributed under the MIT software license // See the accompanying file License.txt or http://opensource.org/licenses/MIT #ifndef Generation_PackingGenerators_Headers_BaseConjugateGradientStep_h #define Generation_PackingGenerators_Headers_BaseConjugateGradientStep_h #ifdef GSL_AVAILABLE #include <gsl/gsl_multimin.h> #include "BasePackingStep.h" namespace PackingServices { class IPairPotential; } namespace PackingServices { class IEnergyService; } namespace PackingGenerators { // Implements a base conjugate gradient optimization step class BaseConjugateGradientStep : public BasePackingStep { protected: PackingServices::IEnergyService* energyService; PackingServices::IPairPotential* pairPotential; std::vector<Core::SpatialVector> particleForces; // Minimization parameters gsl_multimin_function_fdf functionToMinimize; gsl_vector* coordinates; gsl_multimin_fdfminimizer* minimizer; const gsl_multimin_fdfminimizer_type* algorithmType; static const Core::FLOAT_TYPE potentialNormalizer; static const Core::FLOAT_TYPE initialStep; static const Core::FLOAT_TYPE gradientOrthogonalityTolerance; public: void SetParticles(Model::Packing* particles); void SetContext(const Model::ModellingContext& context); ~BaseConjugateGradientStep(); // Methods for integration with GSL conjugate gradient void UpdateParticleCoordinates(const gsl_vector& x); virtual Core::FLOAT_TYPE GetPotentialEnergy(); virtual void FillParticleForces(std::vector<Core::SpatialVector>* particleForces); void FillEnergyGradient(gsl_vector* g); void ResetGeneration(); protected: BaseConjugateGradientStep(PackingServices::GeometryService* geometryService, PackingServices::INeighborProvider* neighborProvider, PackingServices::MathService* mathService, PackingServices::IPairPotential* pairPotential, PackingServices::IEnergyService* energyService); void InitializeMinimization(); virtual void ResetOuterDiameterRatio() = 0; private: void InitializeMinimizationAlgorithm(); void FreeGenerationData(); void FillCoordinates(const Model::Packing& particles, gsl_vector* coordinates); }; double GetPotentialEnergyGlobal(const gsl_vector* x, void * params); void FillEnergyGradientGlobal(const gsl_vector* x, void* params, gsl_vector* g); void FillEnergyAndGradientGlobal(const gsl_vector* x, void* params, double* f, gsl_vector* g); } #endif // GSL #endif /* Generation_PackingGenerators_Headers_BaseConjugateGradientStep_h */
{ "alphanum_fraction": 0.7391147895, "avg_line_length": 33.8902439024, "ext": "h", "hexsha": "e03b6f2fdb7e8e10faec9a0d16f9dd887f9c37de", "lang": "C", "max_forks_count": 36, "max_forks_repo_forks_event_max_datetime": "2022-03-18T12:51:03.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-14T02:43:16.000Z", "max_forks_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MINATILO/packing-generation", "max_forks_repo_path": "PackingGeneration/Generation/PackingGenerators/Headers/BaseConjugateGradientStep.h", "max_issues_count": 31, "max_issues_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_issues_repo_issues_event_max_datetime": "2022-03-02T10:31:50.000Z", "max_issues_repo_issues_event_min_datetime": "2015-07-20T17:57:08.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MINATILO/packing-generation", "max_issues_repo_path": "PackingGeneration/Generation/PackingGenerators/Headers/BaseConjugateGradientStep.h", "max_line_length": 98, "max_stars_count": 79, "max_stars_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MINATILO/packing-generation", "max_stars_repo_path": "PackingGeneration/Generation/PackingGenerators/Headers/BaseConjugateGradientStep.h", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:56.000Z", "max_stars_repo_stars_event_min_datetime": "2015-08-23T12:05:30.000Z", "num_tokens": 577, "size": 2779 }
/** * author: Jochen K"upper * created: Jan 2002 * file: pygsl/src/statistics/longmodule.c * $Id: shortmodule.c,v 1.7 2004/03/24 08:40:45 schnizer Exp $ * * " */ #include <Python.h> #include <pygsl/error_helpers.h> #include <pygsl/block_helpers.h> #include <gsl/gsl_statistics.h> /* include real functions for different data-types */ #define STATMOD_APPEND_PY_TYPE(X) X ## Int #define STATMOD_APPEND_PYC_TYPE(X) X ## SHORT #define STATMOD_FUNC_EXT(X, Y) X ## _short ## Y #define STATMOD_PY_AS_C PyInt_AsLong #define STATMOD_C_TYPE short int #include "functions.c" /* initialization */ PyGSL_STATISTICS_INIT(short, "short") /* * Local Variables: * mode: c * c-file-style: "Stroustrup" * End: */
{ "alphanum_fraction": 0.7033426184, "avg_line_length": 17.95, "ext": "c", "hexsha": "7b61f83a2b6fa4ca06881d14397179fb83bc01ea", "lang": "C", "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/shortmodule.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/shortmodule.c", "max_line_length": 62, "max_stars_count": null, "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/shortmodule.c", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 210, "size": 718 }
/* hka chi-square stat estimation based on original Hudson, Kreitman, Aguade 1987 implementation. The parameters of the model are calculated by solving the system of equations numerically. A. D. Kern 6/2005 */ #include "stdio.h" #include "stdlib.h" #include "math.h" #include "string.h" #include "hka.h" #include "ctype.h" #include <gsl/gsl_vector.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_multiroots.h> /* currently the maximum number of loci is at 10^7, and the maximum locus name is 80 characters long */ struct hkaData data[MAXLOCI]; int locusNumber = 0; int lineageNumber = 1; int main(int argc, char *argv[]){ int i = 0; gsl_vector *chiSquares, *expectedPolyA, *expectedD, *devs; gsl_vector *params; //0-locusNumber-1 = 4Nu's, locusNumber = tHat, locusNumber + 1 = fHat double x; getData(argc, argv); if(lineageNumber > 1){ params = gsl_vector_alloc(locusNumber + 2); } else{ params = gsl_vector_alloc(locusNumber + 1); } //solve the system of equations solveSystem(params); //calculate chiSquare Stats chiSquares =gsl_vector_alloc(locusNumber); expectedPolyA = gsl_vector_alloc(locusNumber); expectedD = gsl_vector_alloc(locusNumber); devs = gsl_vector_alloc(locusNumber); x = calculateHKA(params, chiSquares, expectedPolyA, expectedD); //print some stuff if(lineageNumber > 1){ printf("chiSquared = %f\nt_hat = %f\nf_hat = %f\n",x, gsl_vector_get(params,locusNumber), gsl_vector_get(params,locusNumber + 1)); } else{ printf("chiSquared = %f\nt_hat = %f\nf_hat = 1.0\n",x, gsl_vector_get(params,locusNumber)); } for(i = 0; i < locusNumber; i++){ printf("locus %s \ttheta:\t %f\texpSA:\t %f\tobsSA:\t %f\texpD:\t %f\tobsD:\t %f\t chiSquared:\t%f\n",data[i].name, gsl_vector_get(params,i),gsl_vector_get(expectedPolyA,i), data[i].sa, gsl_vector_get(expectedD,i), data[i].d, gsl_vector_get(chiSquares,i)); } gsl_vector_free(params); return(0); } void usage(){ printf("usage:\nhka infile\n"); exit(1); } /* parses the data file and reads in options (currently no options boss) */ void getData(int argc, char *argv[]){ FILE *infile; int l, na, nb, sa, sb, args, flag, i,lineCount; double d; char string[81]; //here's the character length limit char *sArray[30], line[500]; if (argc < 2){ usage(); } else{ infile = fopen(argv[1],"r"); if (infile == NULL){ fprintf(stderr,"Error opening infile!!!\n"); exit(1); } flag = 0; args = 2; while(args < argc){ switch(argv[args][1]){ case 'm' : //missing data mode flag = 1; } args++; } if (flag){ //missing data mode expect- na, d,lArray, sArray while(fgets(line, 100, infile)){ lineCount = chopByWhite(line,sArray,30); // data[locusNumber].name = (char) sArray[0]; data[locusNumber].na = atoi(sArray[1]); data[locusNumber].d = (double) atof(sArray[2]); for(i = 0; i < data[locusNumber].na - 2; i++){ data[locusNumber].lArray[i] = atoi(sArray[i+3]); data[locusNumber].sArray[i] = atoi(sArray[i+data[locusNumber].na - 1 + 3]); } printf("%d\n",data[locusNumber].sArray[2]); } } else{ /* collect hka data from infile- expect length, na, nb, sa, sb, d */ while(fscanf(infile, "%80s %d %d %d %d %d %lf", string, &l, &na, &nb, &sa, &sb, &d) != EOF){ strcpy(data[locusNumber].name, string); data[locusNumber].length = l; data[locusNumber].na = na; data[locusNumber].nb = nb; if (nb > 1){ lineageNumber = 2; } data[locusNumber].sa = (double) sa; data[locusNumber].sb = (double) sb; data[locusNumber].d = (double) d; data[locusNumber].lArray[0] = 666; locusNumber++; } } fclose(infile); } } /* harmSum returns the denominator portion of Watterson's estimator */ double harmSum(int n){ int i; double sum = 0.0; for(i = 1; i < n; i++){ sum += 1.0 / i; } return(sum); } /* harmSumSquare is for calculating the variance of Watterson's estimator */ double harmSumSquare(int n){ int i; double sum = 0.0; for(i = 1; i < n; i++){ sum += 1.0 / ( i * i); } return(sum); } /*setFunction- this sets up the multiroot function for solving */ int setHKAFunction(const gsl_vector *x, void *p, gsl_vector *f){ double sumS, trueS, sumD, trueD, yi, trueYi; double sumSb, trueSb; int i; /*set up all the equations. the first are the sum of segSites and sum of divergence respectively */ if (lineageNumber == 1){ sumS = yi = sumD = trueS = trueD = 0.0; for(i = 0; i < locusNumber; i++){ sumS += data[i].length * harmSum(data[i].na) * gsl_vector_get(x,i); sumD += data[i].length * (gsl_vector_get(x,locusNumber) + 1) * gsl_vector_get(x,i); trueS += data[i].sa; trueD += data[i].d; } gsl_vector_set(f,0,fabs(trueS - sumS)); gsl_vector_set(f,1,fabs(trueD - sumD)); //Sa+D eqns for(i = 0; i < locusNumber - 1; i++){ trueYi = data[i].sa + data[i].d; yi = gsl_vector_get(x,i) * \ ((data[i].length * gsl_vector_get(x,locusNumber) + \ data[i].length + (data[i].length * harmSum(data[i].na)))); gsl_vector_set(f,i+2,fabs(trueYi - yi)); } } else{ sumS = sumSb = yi = sumD = trueS = trueSb = trueD = 0.0; for(i = 0; i < locusNumber; i++){ sumS += data[i].length * harmSum(data[i].na) * gsl_vector_get(x,i); sumSb += data[i].length * harmSum(data[i].nb) * gsl_vector_get(x,i) * gsl_vector_get(x, locusNumber + 1); sumD += data[i].length * (gsl_vector_get(x,locusNumber) + ((1.0 + gsl_vector_get(x,locusNumber+1)) / 2.0)) * gsl_vector_get(x,i); trueS += data[i].sa; trueSb += data[i].sb; trueD += data[i].d; } gsl_vector_set(f,0,fabs(trueS - sumS)); gsl_vector_set(f,1,fabs(trueSb - sumSb)); gsl_vector_set(f,2,fabs(trueD - sumD)); //Sa+Sb+D eqns for(i = 0; i < locusNumber - 1; i++){ trueYi = data[i].sa + data[i].sb + data[i].d; yi = (data[i].length * (gsl_vector_get(x,locusNumber) + ((1.0 + gsl_vector_get(x,locusNumber+1)) / 2.0)) * gsl_vector_get(x,i)) \ + ( data[i].length * harmSum(data[i].na) * gsl_vector_get(x,i)) + \ (data[i].length * harmSum(data[i].nb) * gsl_vector_get(x,i) * gsl_vector_get(x, locusNumber + 1)); gsl_vector_set(f,i+3,fabs(trueYi - yi)); } } return GSL_SUCCESS; } int solveSystem(gsl_vector *params){ const gsl_multiroot_fsolver_type *T; gsl_multiroot_fsolver *s; gsl_vector *x; int status; size_t iter = 0; void *point=NULL; size_t n; if (lineageNumber == 1){ n = locusNumber + 1; x = gsl_vector_alloc(locusNumber + 1); } else{ n = locusNumber + 2; x = gsl_vector_alloc(locusNumber + 2); } gsl_multiroot_function f = {&setHKAFunction, n, point}; gsl_vector_set_all(x, 1); T = gsl_multiroot_fsolver_hybrids; s = gsl_multiroot_fsolver_alloc(T, n); gsl_multiroot_fsolver_set(s, &f, x); do{ iter++; status = gsl_multiroot_fsolver_iterate(s); if(status){ break; } status = gsl_multiroot_test_residual(s->f, 1e-7); } while (status == GSL_CONTINUE && iter < 100); gsl_vector_memcpy(params, s->x); gsl_vector_free(x); gsl_multiroot_fsolver_free (s); return 0; } /* calculateHKA- this is the main beast that calculates estimates of t_hat, f(the ratio of popn sizes), and theta's for each locus. it returns the chi-square statistic, and takes pointers to the other relavent quantities (t_hat, etc.). */ double calculateHKA(gsl_vector *params,gsl_vector *chiSquares, gsl_vector *expectedPolyA, gsl_vector *expectedD){ double chiSquared, chiSquared_i; double expSA, expSB, varSA, varSB, expD, varD; double hsA, hsB; double devA, devB, devD,fHat; int i; if(lineageNumber > 1){ fHat = gsl_vector_get(params,locusNumber+1); } else{ fHat = 1.0; } chiSquared = 0.0; for(i=0; i < locusNumber; i++){ hsA = harmSum(data[i].na); hsB = harmSum(data[i].nb); //calculate expectations and variances at the ith locus expSA = gsl_vector_get(params,i) * data[i].length * hsA; varSA = expSA + ((gsl_vector_get(params,i) * data[i].length) * (gsl_vector_get(params,i) * data[i].length) * harmSumSquare(data[i].na)); expSB = gsl_vector_get(params,i) * fHat * data[i].length * hsB; varSB = expSB + ((gsl_vector_get(params,i) * fHat * data[i].length) * (gsl_vector_get(params,i) * fHat * data[i].length) * harmSumSquare(data[i].nb)); // equals zero if no poly data from speciesB expD = (gsl_vector_get(params,i) * data[i].length) * (gsl_vector_get(params,locusNumber) + (0.5 * (1.0 + fHat))); varD = expD + (((gsl_vector_get(params,i) * data[i].length) * 0.5 * (1.0 + fHat)) * ((gsl_vector_get(params,i) * data[i].length) * 0.5 * (1.0 + fHat))); //calculate deviations for species_a_theta, species_b_theta, and divergence. // then add to chi-square stat devA = ((data[i].sa - expSA) * (data[i].sa - expSA)) / varSA; devB = ((data[i].sb - expSB) * (data[i].sb - expSB)) / varSB; //careful here will not be number if no poly data for speciesB devD = ((data[i].d - expD) * (data[i].d - expD)) / varD; //is deviation for species B finite? if (isnan(devB)){ chiSquared_i = devA + devD; } else{ chiSquared_i = devA + devB + devD; } chiSquared += chiSquared_i; gsl_vector_set(chiSquares,i,chiSquared_i); gsl_vector_set(expectedPolyA, i, expSA); gsl_vector_set(expectedD, i, expD); } return(chiSquared); } /* took this out of Jim Kent's tree */ int chopByWhite(char *in, char *outArray[], int outSize) /* Like chopString, but specialized for white space separators. */ { int recordCount = 0; char c; for (;;) { if (outArray != NULL && recordCount >= outSize) break; /* Skip initial separators. */ while (isspace(*in)) ++in; if (*in == 0) break; /* Store start of word and look for end of word. */ if (outArray != NULL) outArray[recordCount] = in; recordCount += 1; for (;;) { if ((c = *in) == 0) break; if (isspace(c)) break; ++in; } if (*in == 0) break; /* Tag end of word with zero. */ if (outArray != NULL) *in = 0; /* And skip over the zero. */ in += 1; } return recordCount; }
{ "alphanum_fraction": 0.6133790085, "avg_line_length": 30.638483965, "ext": "c", "hexsha": "287d019038e5ad5447b7cead421bb7e372991a6d", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kern-lab/hka", "max_forks_repo_path": "hka.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kern-lab/hka", "max_issues_repo_path": "hka.c", "max_line_length": 264, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a5aab11242ceffcc84a1701a3a397b1e57634f89", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kern-lab/hka", "max_stars_repo_path": "hka.c", "max_stars_repo_stars_event_max_datetime": "2018-10-06T02:12:05.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-06T02:12:05.000Z", "num_tokens": 3320, "size": 10509 }
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <math.h> #include <stdint.h> #include <gbpLib.h> #include <gbpSort.h> #include <gbpRNG.h> #include <gbpMCMC.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_fit.h> #include <gsl/gsl_interp.h> void analyze_MCMC(MCMC_info *MCMC) { char filename_output_dir[SID_MAX_FILENAME_LENGTH]; char filename_chain_dir[SID_MAX_FILENAME_LENGTH]; char filename_results_dir[SID_MAX_FILENAME_LENGTH]; char filename_plots_dir[SID_MAX_FILENAME_LENGTH]; char filename_run[SID_MAX_FILENAME_LENGTH]; char filename_chain[SID_MAX_FILENAME_LENGTH]; char filename_chain_config[SID_MAX_FILENAME_LENGTH]; char filename_stats[SID_MAX_FILENAME_LENGTH]; char filename_coverage[SID_MAX_FILENAME_LENGTH]; char filename_chain_covariance[SID_MAX_FILENAME_LENGTH]; char filename_covariance[SID_MAX_FILENAME_LENGTH]; char filename_histograms[SID_MAX_FILENAME_LENGTH]; char filename_results[SID_MAX_FILENAME_LENGTH]; char filename_stop[SID_MAX_FILENAME_LENGTH]; char column_txt[SID_MAX_FILENAME_LENGTH]; char problem_name_test[MCMC_NAME_SIZE]; char P_name_test[MCMC_NAME_SIZE]; char name_test[MCMC_NAME_SIZE]; char array_name_test[MCMC_NAME_SIZE]; char array_name_temp[MCMC_NAME_SIZE]; int n_avg_test; int flag_autocor_on_test; int flag_no_map_write; int n_P_test; int n_DS_test; int n_arrays_test; int n_M_test; double P_init_test; double M_target_test; double dM_target_test; int i_P, j_P, k_P; int i_M, j_M; int ii_P, jj_P; int i_avg; int i_C; int i_DS, n_DS; int i_iteration, j_iteration; int flag_continue; char flag_success; int flag_stop = GBP_FALSE; int i_coverage; int j_coverage; int i_proposal; int bin_x; int bin_y; int n_avg; int n_avg_burn; int n_avg_integrate; int n_P, n_C; int n_gals; size_t n_success, n_fail; size_t n_success_all, n_fail_all; double * x_P; double ** x_M; double * M_target; double * dM_target; double * V; double ** C; double * P_min; double * P_max; double * P_new; double * P_last; double * P_avg; double * dP_avg; double ** M_best; double ** M_best_parameters; double ** M_peak_parameters; double * ln_likelihood_DS_peak; double * ln_likelihood_DS_best; size_t n_residual; double * residual; double ** M_min; double ** M_max; double ** M_new; double ** M_lo_68; double ** M_hi_68; double ** M_lo_95; double ** M_hi_95; size_t *** M_histogram; double ** M_last; double ** M_avg; double ** dM_avg; size_t ** P_histogram; size_t ** coverage_true; size_t ** coverage_false; size_t ** coverage_keep; double ** mean_L_histogram; double ** max_L_histogram; uint64_t * temp_out; double ** max_L_surface; double ** mean_L_surface; double L_x, L_y, L_z; int n_x, n_y, n_z; int n_C_x; double ln_likelihood_new; double ln_likelihood_last; double ln_likelihood_best; double ln_likelihood_peak; FILE * fp_run; FILE * fp_chain; FILE * fp_chain_config; FILE * fp_stats; FILE * fp_coverage; FILE * fp_chain_covariance; FILE * fp_covariance; FILE * fp_histograms; FILE * fp_results; FILE * fp_stop; int seed = 182743; int i_report; int i_iteration_start; int i_iteration_next_report; int n_accepted; int n_active; int n_iterations; int n_iterations_burn; int n_iterations_integrate; int n_iterations_phase; int n_thin; int n_thin_burn; int n_thin_integrate; int i_thin; double temperature; int flag_autocor_on; int n_coverage; int coverage_size; int i_phase; int i_array; int * n_M; int flag_initialized; int n_used; gsl_matrix * m; gsl_vector * b; double RN; MCMC_DS_info *current_DS; MCMC_DS_info *next_DS; double *** M_arrays; double *** P_arrays; int * n_P_arrays; int * n_M_arrays; double constant; size_t * histogram_index; size_t * coverage_keep_index; size_t P_best_index; size_t M_best_index; double accumulator; size_t P_lo_68_index; size_t P_hi_68_index; size_t P_lo_95_index; size_t P_hi_95_index; size_t M_lo_68_index; size_t M_hi_68_index; size_t M_lo_95_index; size_t M_hi_95_index; double * P_lo_68; double * P_hi_68; double * P_lo_95; double * P_hi_95; double * P_contour_68; double * P_contour_95; double * P_best; double * P_peak; int my_chain; int flag_init; int i_column; int dummy_t; double * P_i_bar_accum; double * P_ij_bar_accum; double * P_i_bar; double * P_ij_bar; double * V_compute; int n_covariance; int i_covariance; int j_covariance; int n_iterations_file_total; int n_iterations_file_burn; int flag_restart = GBP_FALSE; int size_temp1; int size_temp2[2]; int flag_minimize_IO; size_t i_iteration_buffer; size_t i_P_buffer; size_t i_M_buffer; SID_log("Performing MCMC analysis...", SID_LOG_OPEN | SID_LOG_TIMER); SID_log("Initializing...", SID_LOG_OPEN); // Initialize dataset arrays init_MCMC_arrays(MCMC); // Initialize some constants etc. n_P = MCMC->n_P; n_DS = MCMC->n_DS; n_avg = MCMC->n_avg; my_chain = MCMC->my_chain; n_iterations = MCMC->n_iterations; n_iterations_burn = MCMC->n_iterations_burn; n_iterations_integrate = n_iterations - n_iterations_burn; n_thin = MCMC->n_thin; coverage_size = MCMC->coverage_size; flag_autocor_on = MCMC->flag_autocor_on; flag_no_map_write = MCMC->flag_no_map_write; flag_minimize_IO = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO); // Initialize arrays used for computing the covariance matrix P_i_bar_accum = (double *)SID_malloc(sizeof(double) * n_P); P_ij_bar_accum = (double *)SID_malloc(sizeof(double) * n_P * n_P); P_i_bar = (double *)SID_malloc(sizeof(double) * n_P); P_ij_bar = (double *)SID_malloc(sizeof(double) * n_P * n_P); V_compute = (double *)SID_malloc(sizeof(double) * n_P * n_P); for(i_P = 0, k_P = 0; i_P < n_P; i_P++) { P_i_bar_accum[i_P] = 0.; P_i_bar[i_P] = 0.; for(j_P = 0; j_P < n_P; j_P++, k_P++) { P_ij_bar_accum[k_P] = 0.; P_ij_bar[k_P] = 0.; if(i_P == j_P) V_compute[k_P] = 1.; else V_compute[k_P] = 0.; } } // Initialize chain arrays etc n_M = MCMC->n_M; M_new = MCMC->M_new; M_last = MCMC->M_last; n_M_arrays = (int *)SID_malloc(sizeof(int) * n_DS); M_arrays = (double ***)SID_malloc(sizeof(double **) * n_DS); current_DS = MCMC->DS; i_DS = 0; while(current_DS != NULL) { next_DS = current_DS->next; n_M[i_DS] = current_DS->n_M; n_M_arrays[i_DS] = current_DS->n_arrays; M_arrays[i_DS] = current_DS->array; current_DS = next_DS; i_DS++; } P_new = MCMC->P_new; P_last = MCMC->P_last; // Set default directories sprintf(filename_output_dir, "%s/", MCMC->filename_output_dir); sprintf(filename_chain_dir, "%s/chains/", filename_output_dir); sprintf(filename_results_dir, "%s/results/", filename_output_dir); sprintf(filename_plots_dir, "%s/plots/", filename_output_dir); // Set default filenames sprintf(filename_run, "%s/run.dat", filename_output_dir); sprintf(filename_chain, "%s/chain_trace_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_chain_config, "%s/chain_config_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_chain_covariance, "%s/chain_covariance_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_stats, "%s/chain_stats_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_coverage, "%s/coverage.dat", filename_results_dir); sprintf(filename_histograms, "%s/histograms.dat", filename_results_dir); sprintf(filename_covariance, "%s/covariance.dat", filename_results_dir); sprintf(filename_stop, "%s/stop", filename_output_dir); // Initialize coverage arrays for(i_P = 0, n_coverage = 0; i_P < n_P; i_P++) { for(j_P = i_P + 1; j_P < n_P; j_P++) n_coverage++; } P_min = MCMC->P_min; P_max = MCMC->P_max; P_avg = MCMC->P_avg; dP_avg = MCMC->dP_avg; P_best = MCMC->P_best; P_peak = MCMC->P_peak; P_lo_68 = MCMC->P_lo_68; P_hi_68 = MCMC->P_hi_68; P_lo_95 = MCMC->P_lo_95; P_hi_95 = MCMC->P_hi_95; P_contour_68 = (double *)SID_malloc(sizeof(double) * n_coverage); P_contour_95 = (double *)SID_malloc(sizeof(double) * n_coverage); P_histogram = (size_t **)SID_malloc(sizeof(size_t *) * n_P); mean_L_histogram = (double **)SID_malloc(sizeof(double *) * n_P); max_L_histogram = (double **)SID_malloc(sizeof(double *) * n_P); for(i_P = 0; i_P < n_P; i_P++) { P_histogram[i_P] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size); mean_L_histogram[i_P] = (double *)SID_malloc(sizeof(double) * coverage_size); max_L_histogram[i_P] = (double *)SID_malloc(sizeof(double) * coverage_size); P_min[i_P] = DBL_MAX; P_max[i_P] = -DBL_MAX; P_avg[i_P] = 0.; dP_avg[i_P] = 0.; for(j_P = 0; j_P < coverage_size; j_P++) { P_histogram[i_P][j_P] = 0; mean_L_histogram[i_P][j_P] = 0.; max_L_histogram[i_P][j_P] = -1e10; } } M_best = (double **)SID_malloc(sizeof(double *) * n_DS); M_best_parameters = (double **)SID_malloc(sizeof(double *) * n_DS); M_peak_parameters = (double **)SID_malloc(sizeof(double *) * n_DS); M_min = (double **)SID_malloc(sizeof(double *) * n_DS); M_max = (double **)SID_malloc(sizeof(double *) * n_DS); M_lo_68 = (double **)SID_malloc(sizeof(double *) * n_DS); M_hi_68 = (double **)SID_malloc(sizeof(double *) * n_DS); M_lo_95 = (double **)SID_malloc(sizeof(double *) * n_DS); M_hi_95 = (double **)SID_malloc(sizeof(double *) * n_DS); M_avg = (double **)SID_malloc(sizeof(double *) * n_DS); dM_avg = (double **)SID_malloc(sizeof(double *) * n_DS); M_histogram = (size_t ***)SID_malloc(sizeof(size_t **) * n_DS); current_DS = MCMC->DS; for(i_DS = 0, n_residual = 0; i_DS < n_DS; i_DS++) { next_DS = current_DS->next; if(current_DS->M_best == NULL) current_DS->M_best = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_best_parameters == NULL) current_DS->M_best_parameters = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_peak_parameters == NULL) current_DS->M_peak_parameters = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_min == NULL) current_DS->M_min = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_max == NULL) current_DS->M_max = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_lo_68 == NULL) current_DS->M_lo_68 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_hi_68 == NULL) current_DS->M_hi_68 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_lo_95 == NULL) current_DS->M_lo_95 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_hi_95 == NULL) current_DS->M_hi_95 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->M_avg == NULL) current_DS->M_avg = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); if(current_DS->dM_avg == NULL) current_DS->dM_avg = (double *)SID_malloc(sizeof(double) * n_M[i_DS]); M_best[i_DS] = current_DS->M_best; M_best_parameters[i_DS] = current_DS->M_best_parameters; M_peak_parameters[i_DS] = current_DS->M_peak_parameters; M_min[i_DS] = current_DS->M_min; M_max[i_DS] = current_DS->M_max; M_lo_68[i_DS] = current_DS->M_lo_68; M_hi_68[i_DS] = current_DS->M_hi_68; M_lo_95[i_DS] = current_DS->M_lo_95; M_hi_95[i_DS] = current_DS->M_hi_95; M_avg[i_DS] = current_DS->M_avg; dM_avg[i_DS] = current_DS->dM_avg; M_histogram[i_DS] = (size_t **)SID_malloc(sizeof(size_t *) * n_M[i_DS]); for(i_M = 0; i_M < n_M[i_DS]; i_M++) { M_histogram[i_DS][i_M] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size); M_avg[i_DS][i_M] = 0.; dM_avg[i_DS][i_M] = 0.; M_min[i_DS][i_M] = DBL_MAX; M_max[i_DS][i_M] = -DBL_MAX; for(j_M = 0; j_M < coverage_size; j_M++) M_histogram[i_DS][i_M][j_M] = 0; } n_residual = GBP_MAX(n_residual, (size_t)n_M[i_DS]); current_DS = next_DS; } if(next_DS != NULL) SID_exit_error("Invalid dataset count in analyze_MCMC().", SID_ERROR_LOGIC); residual = (double *)SID_malloc(sizeof(double) * n_residual); coverage_true = (size_t **)SID_malloc(sizeof(size_t *) * n_coverage); coverage_false = (size_t **)SID_malloc(sizeof(size_t *) * n_coverage); coverage_keep = (size_t **)SID_malloc(sizeof(size_t *) * n_coverage); max_L_surface = (double **)SID_malloc(sizeof(double *) * n_coverage); mean_L_surface = (double **)SID_malloc(sizeof(double *) * n_coverage); for(i_coverage = 0; i_coverage < n_coverage; i_coverage++) { coverage_true[i_coverage] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size * coverage_size); coverage_false[i_coverage] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size * coverage_size); coverage_keep[i_coverage] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size * coverage_size); max_L_surface[i_coverage] = (double *)SID_malloc(sizeof(double) * coverage_size * coverage_size); mean_L_surface[i_coverage] = (double *)SID_malloc(sizeof(double) * coverage_size * coverage_size); for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++) { coverage_true[i_coverage][j_coverage] = 0; coverage_false[i_coverage][j_coverage] = 0; coverage_keep[i_coverage][j_coverage] = 0; max_L_surface[i_coverage][j_coverage] = -1e10; mean_L_surface[i_coverage][j_coverage] = 0.; } } temp_out = (uint64_t *)SID_malloc(sizeof(uint64_t) * coverage_size * coverage_size); SID_log("Done.", SID_LOG_CLOSE); // Process the chain(s) SID_log("Process chain file(s)...", SID_LOG_OPEN); if(flag_no_map_write) SID_log("Mapping results are *not* available.", SID_LOG_COMMENT); else SID_log("Mapping results are available.", SID_LOG_COMMENT); // Count the number of runs we will analyze int n_runs; int i_run; if(flag_minimize_IO || !SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_ANALYZE_ALL_RUNS)) n_runs = 1; else { int flag_continue = GBP_TRUE; while(flag_continue) { // Set chain filename if(n_runs == 0) sprintf(filename_output_dir, "%s/", MCMC->filename_output_root); else sprintf(filename_output_dir, "%s.%d/", MCMC->filename_output_root, n_runs); sprintf(filename_chain_dir, "%s/chains/", filename_output_dir); sprintf(filename_chain, "%s/chain_trace_%06d.dat", filename_chain_dir, my_chain); if((fp_chain = fopen(filename_chain, "r")) != NULL) { n_runs++; fclose(fp_chain); } else flag_continue = GBP_FALSE; } SID_log("Analyzing %d chain(s).", SID_LOG_COMMENT, n_runs); } if(my_chain == SID.My_rank) { // Loop over all the chains for(i_run = 0, n_used = 0; i_run < n_runs; i_run++) { if(!flag_minimize_IO) { // Set chain filename (use default if we are not analyzing all runs) if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_ANALYZE_ALL_RUNS)) { if(i_run == 0) sprintf(filename_output_dir, "%s/", MCMC->filename_output_root); else sprintf(filename_output_dir, "%s.%d/", MCMC->filename_output_root, i_run); sprintf(filename_chain_dir, "%s/chains/", filename_output_dir); sprintf(filename_chain, "%s/chain_trace_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_chain_config, "%s/chain_config_%06d.dat", filename_chain_dir, my_chain); } // Read number of iterations if((fp_chain = fopen(filename_chain_config, "rb")) == NULL) SID_exit_error("Could not open chain configuration file {%s}.", SID_ERROR_IO_OPEN, filename_chain_config); SID_fread_verify(&n_iterations, sizeof(int), 1, fp_chain); SID_fread_verify(&n_iterations_burn, sizeof(int), 1, fp_chain); fclose(fp_chain); // Open chain file if((fp_chain = fopen(filename_chain, "rb")) == NULL) SID_exit_error("Could not open chain file {%s}.", SID_ERROR_IO_OPEN, filename_chain); } i_iteration_buffer = 0; i_P_buffer = 0; i_M_buffer = 0; ln_likelihood_peak = -1e20; for(i_iteration = 0, flag_init = GBP_TRUE; i_iteration < n_iterations; i_iteration++) { for(i_avg = 0; i_avg < n_avg; i_avg++) { switch(flag_minimize_IO) { case GBP_TRUE: flag_success = MCMC->flag_success_buffer[i_iteration_buffer]; ln_likelihood_new = MCMC->ln_likelihood_new_buffer[i_iteration_buffer]; i_iteration_buffer++; memcpy(P_new, &(MCMC->P_new_buffer[i_P_buffer]), (size_t)n_P * sizeof(double)); i_P_buffer += n_P; if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { memcpy(M_new[i_DS], &(MCMC->M_new_buffer[i_M_buffer]), (size_t)n_M[i_DS] * sizeof(double)); i_M_buffer += n_M[i_DS]; } } break; default: SID_fread_verify(&flag_success, sizeof(char), 1, fp_chain); SID_fread_verify(&ln_likelihood_new, sizeof(double), 1, fp_chain); SID_fread_verify(P_new, sizeof(double), n_P, fp_chain); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) SID_fread_verify(M_new[i_DS], sizeof(double), n_M[i_DS], fp_chain); } break; } if(i_iteration >= n_iterations_burn) { if(flag_init || flag_success) { memcpy(P_last, P_new, (size_t)n_P * sizeof(double)); ln_likelihood_last = ln_likelihood_new; if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) memcpy(M_last[i_DS], M_new[i_DS], (size_t)n_M[i_DS] * sizeof(double)); } flag_init = GBP_FALSE; } n_used++; // Compute covariance matrix for(i_P = 0, k_P = 0; i_P < n_P; i_P++) { P_i_bar_accum[i_P] += P_last[i_P]; for(j_P = 0; j_P < n_P; j_P++, k_P++) P_ij_bar_accum[k_P] += P_last[i_P] * P_last[j_P]; } // Compute parameter extrema and averages for(i_P = 0; i_P < n_P; i_P++) { if(P_last[i_P] < P_min[i_P]) P_min[i_P] = P_last[i_P]; if(P_last[i_P] > P_max[i_P]) P_max[i_P] = P_last[i_P]; P_avg[i_P] += P_last[i_P]; } // Store parameters with highest likelihood if(ln_likelihood_last > ln_likelihood_peak) { memcpy(P_peak, P_last, (size_t)n_P * sizeof(double)); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) memcpy(M_peak_parameters[i_DS], M_last[i_DS], (size_t)n_M[i_DS] * sizeof(double)); } ln_likelihood_peak = ln_likelihood_last; } // Compute mapping-space extrema and averages if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) { if(M_last[i_DS][i_M] < M_min[i_DS][i_M]) M_min[i_DS][i_M] = M_last[i_DS][i_M]; if(M_last[i_DS][i_M] > M_max[i_DS][i_M]) M_max[i_DS][i_M] = M_last[i_DS][i_M]; M_avg[i_DS][i_M] += M_last[i_DS][i_M]; } } } } } } if(!flag_minimize_IO) fclose(fp_chain); } // Finish averages for(i_P = 0; i_P < n_P; i_P++) { P_avg[i_P] /= (double)n_used; } if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) M_avg[i_DS][i_M] /= (double)n_used; } } for(i_run = 0; i_run < n_runs; i_run++) { if(!flag_minimize_IO) { // Set chain filename (use default if we are not analyzing all runs) if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_ANALYZE_ALL_RUNS)) { if(i_run == 0) sprintf(filename_output_dir, "%s/", MCMC->filename_output_root); else sprintf(filename_output_dir, "%s.%d/", MCMC->filename_output_root, i_run); sprintf(filename_chain_dir, "%s/chains/", filename_output_dir); sprintf(filename_chain, "%s/chain_trace_%06d.dat", filename_chain_dir, my_chain); sprintf(filename_chain_config, "%s/chain_config_%06d.dat", filename_chain_dir, my_chain); } // Read number of iterations if((fp_chain = fopen(filename_chain_config, "rb")) == NULL) SID_exit_error("Could not open chain configuration file {%s}.", SID_ERROR_IO_OPEN, filename_chain); SID_fread_verify(&n_iterations, sizeof(int), 1, fp_chain); SID_fread_verify(&n_iterations_burn, sizeof(int), 1, fp_chain); fclose(fp_chain); // Open chain file if((fp_chain = fopen(filename_chain, "rb")) == NULL) SID_exit_error("Could not open chain file {%s}.", SID_ERROR_IO_OPEN, filename_chain); } i_iteration_buffer = 0; i_P_buffer = 0; i_M_buffer = 0; for(i_iteration = 0, flag_init = GBP_TRUE; i_iteration < n_iterations; i_iteration++) { for(i_avg = 0; i_avg < n_avg; i_avg++) { switch(flag_minimize_IO) { case GBP_TRUE: flag_success = MCMC->flag_success_buffer[i_iteration_buffer]; ln_likelihood_new = MCMC->ln_likelihood_new_buffer[i_iteration_buffer]; i_iteration_buffer++; memcpy(P_new, &(MCMC->P_new_buffer[i_P_buffer]), (size_t)n_P * sizeof(double)); i_P_buffer += n_P; if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { memcpy(M_new[i_DS], &(MCMC->M_new_buffer[i_M_buffer]), (size_t)n_M[i_DS] * sizeof(double)); i_M_buffer += n_M[i_DS]; } } break; default: SID_fread_verify(&flag_success, sizeof(char), 1, fp_chain); SID_fread_verify(&ln_likelihood_new, sizeof(double), 1, fp_chain); SID_fread_verify(P_new, sizeof(double), n_P, fp_chain); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) SID_fread_verify(M_new[i_DS], sizeof(double), n_M[i_DS], fp_chain); } break; } if(i_iteration >= n_iterations_burn) { if(flag_init || flag_success) { memcpy(P_last, P_new, (size_t)n_P * sizeof(double)); ln_likelihood_last = ln_likelihood_new; for(i_DS = 0; i_DS < n_DS; i_DS++) memcpy(M_last[i_DS], M_new[i_DS], (size_t)n_M[i_DS] * sizeof(double)); flag_init = GBP_FALSE; } // Build coverage maps if(flag_success) { for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) { bin_x = (int)((double)(coverage_size) * (P_last[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P])); for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) { bin_y = (int)((double)(coverage_size) * (P_last[j_P] - P_min[j_P]) / (P_max[j_P] - P_min[j_P])); if(bin_x >= 0 && bin_x < coverage_size && bin_y >= 0 && bin_y < coverage_size) coverage_true[i_coverage][bin_x * coverage_size + bin_y]++; } } } else { for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) { bin_x = (int)((double)(coverage_size) * (P_new[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P])); for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) { bin_y = (int)((double)(coverage_size) * (P_new[j_P] - P_min[j_P]) / (P_max[j_P] - P_min[j_P])); if(bin_x >= 0 && bin_x < coverage_size && bin_y >= 0 && bin_y < coverage_size) coverage_false[i_coverage][bin_x * coverage_size + bin_y]++; } } } for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) { bin_x = (int)((double)(coverage_size) * (P_last[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P])); for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) { bin_y = (int)((double)(coverage_size) * (P_last[j_P] - P_min[j_P]) / (P_max[j_P] - P_min[j_P])); if(bin_x >= 0 && bin_x < coverage_size && bin_y >= 0 && bin_y < coverage_size) { coverage_keep[i_coverage][bin_x * coverage_size + bin_y]++; max_L_surface[i_coverage][bin_x * coverage_size + bin_y] = GBP_MAX(max_L_surface[i_coverage][bin_x * coverage_size + bin_y], ln_likelihood_last); mean_L_surface[i_coverage][bin_x * coverage_size + bin_y] += ln_likelihood_last; } } } // Build histograms for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) { bin_x = (int)((double)(coverage_size) * (P_last[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P])); if(bin_x >= 0 && bin_x < coverage_size) { P_histogram[i_P][bin_x]++; mean_L_histogram[i_P][bin_x] += ln_likelihood_last; max_L_histogram[i_P][bin_x] = GBP_MAX(max_L_histogram[i_P][bin_x], ln_likelihood_last); } } for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) { bin_x = (int)((double)(coverage_size) * (M_last[i_DS][i_M] - M_min[i_DS][i_M]) / (M_max[i_DS][i_M] - M_min[i_DS][i_M])); if(bin_x >= 0 && bin_x < coverage_size) M_histogram[i_DS][i_M][bin_x]++; } } // Compute parameter standard deviations for(i_P = 0; i_P < n_P; i_P++) { dP_avg[i_P] += pow(P_last[i_P] - P_avg[i_P], 2.); } if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) dM_avg[i_DS][i_M] += pow(M_last[i_DS][i_M] - M_avg[i_DS][i_M], 2.); } } } } } // i_iteration if(!flag_minimize_IO) fclose(fp_chain); } SID_log("Number of used propositions: %d", SID_LOG_COMMENT, n_used); // Finish mean likelihood histograms & surfaces for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) { for(j_coverage = 0; j_coverage < coverage_size; j_coverage++) mean_L_histogram[i_P][j_coverage] /= (double)P_histogram[i_P][j_coverage]; for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) { for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++) mean_L_surface[i_coverage][j_coverage] /= (double)coverage_keep[i_coverage][j_coverage]; } } // Finish standard deviations for(i_P = 0; i_P < n_P; i_P++) dP_avg[i_P] = sqrt(dP_avg[i_P] / (double)n_used); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) dM_avg[i_DS][i_M] = sqrt(dM_avg[i_DS][i_M] / (double)n_used); } } // Finish covariance matrix for(i_P = 0; i_P < n_P; i_P++) P_i_bar[i_P] = P_i_bar_accum[i_P] / (double)n_used; for(i_P = 0, k_P = 0; i_P < n_P; i_P++) { for(j_P = 0; j_P < n_P; j_P++, k_P++) { P_ij_bar[k_P] = P_ij_bar_accum[k_P] / (double)n_used; V_compute[k_P] = P_ij_bar[k_P] - P_i_bar[i_P] * P_i_bar[j_P]; } } // Write covariance matrix if(SID.I_am_Master) { if((fp_covariance = fopen(filename_covariance, "wb")) == NULL) SID_exit_error("Could not open {%s} for writing.", SID_ERROR_IO_OPEN, filename_covariance); fwrite(&n_P, sizeof(int), 1, fp_covariance); fwrite(V_compute, sizeof(double), n_P * n_P, fp_covariance); fclose(fp_covariance); } // Compute mapped dataset confidence intervals from histograms SID_log("Compute confidence intervals...", SID_LOG_OPEN); if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) { merge_sort(M_histogram[i_DS][i_M], (size_t)coverage_size, &histogram_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); accumulator = M_histogram[i_DS][i_M][histogram_index[coverage_size - 1]]; M_best_index = histogram_index[coverage_size - 1]; M_lo_68_index = histogram_index[coverage_size - 1]; M_hi_68_index = histogram_index[coverage_size - 1]; for(j_P = coverage_size - 2; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.68; j_P--) { if(histogram_index[j_P] < M_lo_68_index) M_lo_68_index = histogram_index[j_P]; if(histogram_index[j_P] > M_hi_68_index) M_hi_68_index = histogram_index[j_P]; accumulator += M_histogram[i_DS][i_M][histogram_index[j_P]]; } M_lo_95_index = M_lo_68_index; M_hi_95_index = M_hi_68_index; for(; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.95; j_P--) { if(histogram_index[j_P] < M_lo_95_index) M_lo_95_index = histogram_index[j_P]; if(histogram_index[j_P] > M_hi_95_index) M_hi_95_index = histogram_index[j_P]; accumulator += M_histogram[i_DS][i_M][histogram_index[j_P]]; } M_best[i_DS][i_M] = M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_best_index) + 0.5) / (double)coverage_size; M_lo_68[i_DS][i_M] = M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_lo_68_index) + 0.5) / (double)coverage_size; M_hi_68[i_DS][i_M] = M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_hi_68_index) + 0.5) / (double)coverage_size; M_lo_95[i_DS][i_M] = M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_lo_95_index) + 0.5) / (double)coverage_size; M_hi_95[i_DS][i_M] = M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_hi_95_index) + 0.5) / (double)coverage_size; SID_free(SID_FARG histogram_index); } } } // Compute parameter confidence intervals from histograms for(i_P = 0; i_P < n_P; i_P++) { merge_sort(P_histogram[i_P], (size_t)coverage_size, &histogram_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); accumulator = P_histogram[i_P][histogram_index[coverage_size - 1]]; P_best_index = histogram_index[coverage_size - 1]; P_lo_68_index = histogram_index[coverage_size - 1]; P_hi_68_index = histogram_index[coverage_size - 1]; for(j_P = 1, k_P = 0; j_P < coverage_size; j_P++) if(max_L_histogram[i_P][j_P] > max_L_histogram[i_P][k_P]) k_P = j_P; for(j_P = coverage_size - 2; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.68; j_P--) { if(histogram_index[j_P] < P_lo_68_index) P_lo_68_index = histogram_index[j_P]; if(histogram_index[j_P] > P_hi_68_index) P_hi_68_index = histogram_index[j_P]; accumulator += P_histogram[i_P][histogram_index[j_P]]; } P_lo_95_index = P_lo_68_index; P_hi_95_index = P_hi_68_index; for(; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.95; j_P--) { if(histogram_index[j_P] < P_lo_95_index) P_lo_95_index = histogram_index[j_P]; if(histogram_index[j_P] > P_hi_95_index) P_hi_95_index = histogram_index[j_P]; accumulator += P_histogram[i_P][histogram_index[j_P]]; } P_best[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_best_index) + 0.5) / (double)coverage_size; P_lo_68[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_lo_68_index) + 0.5) / (double)coverage_size; P_hi_68[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_hi_68_index) + 0.5) / (double)coverage_size; P_lo_95[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_lo_95_index) + 0.5) / (double)coverage_size; P_hi_95[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_hi_95_index) + 0.5) / (double)coverage_size; SID_free(SID_FARG histogram_index); } // Compute parameter confidence contours from coverage maps for(i_coverage = 0; i_coverage < n_coverage; i_coverage++) { merge_sort( coverage_keep[i_coverage], (size_t)(coverage_size * coverage_size), &coverage_keep_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE); accumulator = coverage_keep[i_coverage][coverage_keep_index[coverage_size * coverage_size - 1]]; P_contour_68[i_coverage] = coverage_keep[i_coverage][coverage_keep_index[coverage_size * coverage_size - 1]]; for(j_P = (coverage_size * coverage_size) - 2; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.68; j_P--) { P_contour_68[i_coverage] = coverage_keep[i_coverage][coverage_keep_index[j_P]]; accumulator += coverage_keep[i_coverage][coverage_keep_index[j_P]]; } P_contour_95[i_coverage] = P_contour_68[i_coverage]; for(; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.95; j_P--) { P_contour_95[i_coverage] = coverage_keep[i_coverage][coverage_keep_index[j_P]]; accumulator += coverage_keep[i_coverage][coverage_keep_index[j_P]]; } SID_free(SID_FARG coverage_keep_index); } SID_log("Done.", SID_LOG_CLOSE); // Write coverage maps SID_log("Writing coverage maps...", SID_LOG_OPEN); fp_coverage = fopen(filename_coverage, "wb"); fwrite(&n_coverage, sizeof(int), 1, fp_coverage); fwrite(&coverage_size, sizeof(int), 1, fp_coverage); fwrite(P_min, sizeof(double), n_P, fp_coverage); fwrite(P_max, sizeof(double), n_P, fp_coverage); for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) { for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) { fwrite(&P_contour_68[i_coverage], sizeof(double), 1, fp_coverage); fwrite(&P_contour_95[i_coverage], sizeof(double), 1, fp_coverage); // We need to covert to uint64_t so that allresults_MCMC.py works on 32-bit systems for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++) temp_out[j_coverage] = coverage_true[i_coverage][j_coverage]; fwrite(temp_out, sizeof(uint64_t), coverage_size * coverage_size, fp_coverage); for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++) temp_out[j_coverage] = coverage_false[i_coverage][j_coverage]; fwrite(temp_out, sizeof(uint64_t), coverage_size * coverage_size, fp_coverage); for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++) temp_out[j_coverage] = coverage_keep[i_coverage][j_coverage]; fwrite(temp_out, sizeof(uint64_t), coverage_size * coverage_size, fp_coverage); fwrite(max_L_surface[i_coverage], sizeof(double), coverage_size * coverage_size, fp_coverage); fwrite(mean_L_surface[i_coverage], sizeof(double), coverage_size * coverage_size, fp_coverage); } } fclose(fp_coverage); SID_log("Done.", SID_LOG_CLOSE); // Write histograms SID_log("Writing histograms...", SID_LOG_OPEN); fp_histograms = fopen(filename_histograms, "wb"); for(i_P = 0; i_P < n_P; i_P++) { fwrite(&P_best[i_P], sizeof(double), 1, fp_histograms); fwrite(&P_lo_68[i_P], sizeof(double), 1, fp_histograms); fwrite(&P_hi_68[i_P], sizeof(double), 1, fp_histograms); fwrite(&P_lo_95[i_P], sizeof(double), 1, fp_histograms); fwrite(&P_hi_95[i_P], sizeof(double), 1, fp_histograms); fwrite(&P_peak[i_P], sizeof(double), 1, fp_histograms); // We need to covert to uint64_t so that allresults_MCMC.py works on 32-bit systems for(j_coverage = 0; j_coverage < coverage_size; j_coverage++) temp_out[j_coverage] = P_histogram[i_P][j_coverage]; fwrite(temp_out, sizeof(uint64_t), coverage_size, fp_histograms); fwrite(mean_L_histogram[i_P], sizeof(double), coverage_size, fp_histograms); fwrite(max_L_histogram[i_P], sizeof(double), coverage_size, fp_histograms); } if(!flag_no_map_write) { for(i_DS = 0; i_DS < n_DS; i_DS++) { for(i_M = 0; i_M < n_M[i_DS]; i_M++) { fwrite(&M_best[i_DS][i_M], sizeof(double), 1, fp_histograms); fwrite(&M_lo_68[i_DS][i_M], sizeof(double), 1, fp_histograms); fwrite(&M_hi_68[i_DS][i_M], sizeof(double), 1, fp_histograms); fwrite(&M_lo_95[i_DS][i_M], sizeof(double), 1, fp_histograms); fwrite(&M_hi_95[i_DS][i_M], sizeof(double), 1, fp_histograms); // We need to covert to uint64_t so that allresults_MCMC.py works on 32-bit systems for(j_coverage = 0; j_coverage < coverage_size; j_coverage++) temp_out[j_coverage] = M_histogram[i_DS][i_M][j_coverage]; fwrite(temp_out, sizeof(uint64_t), coverage_size, fp_histograms); } } } fclose(fp_histograms); SID_log("Done.", SID_LOG_CLOSE); } SID_log("Done.", SID_LOG_CLOSE); // Compute best fit models and their likelihoods if(MCMC->map_P_to_M != NULL) { SID_Bcast(P_best, n_P, SID_DOUBLE, my_chain, MCMC->comm); MCMC->map_P_to_M(P_best, MCMC, M_best_parameters); MCMC->compute_MCMC_ln_likelihood( MCMC, M_best_parameters, P_best, MCMC->ln_likelihood_DS_best, MCMC->n_DoF_DS_best, &(MCMC->ln_likelihood_best), &(MCMC->n_DoF_best)); SID_Bcast(P_peak, n_P, SID_DOUBLE, my_chain, MCMC->comm); MCMC->map_P_to_M(P_peak, MCMC, M_peak_parameters); MCMC->compute_MCMC_ln_likelihood( MCMC, M_peak_parameters, P_peak, MCMC->ln_likelihood_DS_peak, MCMC->n_DoF_DS_peak, &(MCMC->ln_likelihood_peak), &(MCMC->n_DoF_peak)); } if(my_chain == SID.My_rank) { // Write fit results SID_log("Writing final statistics...", SID_LOG_OPEN); sprintf(filename_results, "%s/fit_for_parameters.dat", filename_results_dir); fp_results = fopen(filename_results, "w"); fprintf(fp_results, "# MCMC parameter fit results to %s\n", MCMC->problem_name); if(MCMC->map_P_to_M != NULL) { fprintf(fp_results, "# ln(likelihood)+constant=%le w/ %d DoF (marginalized PDF)\n", MCMC->ln_likelihood_best, MCMC->n_DoF_best); fprintf(fp_results, "# ln(likelihood)+constant=%le w/ %d DoF (maximum likelihood)\n", MCMC->ln_likelihood_peak, MCMC->n_DoF_peak); } fprintf(fp_results, "# n_samples_used=%d\n", n_used); fprintf(fp_results, "# n_parameters =%d\n", n_P); fprintf(fp_results, "# n_data_sets =%d\n", n_DS); fprintf(fp_results, "# used data sets:\n"); current_DS = MCMC->DS; while(current_DS != NULL) { next_DS = current_DS->next; fprintf(fp_results, "# %s\n", current_DS->name); current_DS = next_DS; i_DS++; } sprintf(column_txt, "Column:"); i_column = 1; fprintf(fp_results, "# %s (%02d) Parameter name\n", column_txt, i_column++); sprintf(column_txt, " "); for(i_array = 0; i_array < MCMC->n_arrays; i_array++) fprintf(fp_results, "# %s (%02d) %s\n", column_txt, i_column++, MCMC->array_name[i_array]); fprintf(fp_results, "# %s (%02d) Initial value\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Average\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Standard deviation\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Maximum likelihood value\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Lower limit (68%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Upper limit (68%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Lower limit (95%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Upper limit (95%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Best fit value\n", column_txt, i_column++); for(i_P = 0; i_P < n_P; i_P++) { strcpy(array_name_temp, MCMC->P_names[i_P]); search_and_replace(array_name_temp, " ", "~"); fprintf(fp_results, MCMC->P_name_format, array_name_temp); for(i_array = 0; i_array < MCMC->n_arrays; i_array++) fprintf(fp_results, " %13.6le", MCMC->array[i_array][i_P]); fprintf(fp_results, " %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le\n", MCMC->P_init[i_P], P_avg[i_P], dP_avg[i_P], P_best[i_P], P_lo_68[i_P], P_hi_68[i_P], P_lo_95[i_P], P_hi_95[i_P], P_peak[i_P]); } fclose(fp_results); // Write the fits for each dataset i_DS = 0; current_DS = MCMC->DS; while(current_DS != NULL) { next_DS = current_DS->next; M_target = current_DS->M_target; dM_target = current_DS->dM_target; if(current_DS->n_D <= 1) { if(n_DS > 1) sprintf(filename_results, "%s/fit_for_dataset_%05d.dat", filename_results_dir, i_DS); else sprintf(filename_results, "%s/fit_for_dataset.dat", filename_results_dir); fp_results = fopen(filename_results, "w"); fprintf(fp_results, "# MCMC data set fit results for %s\n", current_DS->name); fprintf(fp_results, "# n_samples_used=%d\n", n_used); fprintf(fp_results, "# dataset size =%d\n", n_M[i_DS]); if(MCMC->map_P_to_M != NULL) { fprintf(fp_results, "# ln(likelihood)+constant=%le w/ %d DoF (marginalized PDF)\n", MCMC->ln_likelihood_DS_best[i_DS], MCMC->n_DoF_DS_best[i_DS]); fprintf(fp_results, "# ln(likelihood)+constant=%le w/ %d DoF (maximum likelihood)\n", MCMC->ln_likelihood_DS_peak[i_DS], MCMC->n_DoF_DS_peak[i_DS]); } sprintf(column_txt, "Column:"); for(i_array = 0, i_column = 1; i_array < MCMC->n_arrays; i_array++) { fprintf(fp_results, "# %s (%02d) %s\n", column_txt, i_column++, current_DS->array_name[i_array]); sprintf(column_txt, " "); } sprintf(column_txt, " "); fprintf(fp_results, "# %s (%02d) Dataset\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Dataset uncertainty\n", column_txt, i_column++); if(!flag_no_map_write) { fprintf(fp_results, "# %s (%02d) Average\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Standard deviation\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Marginalized likelihood value\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Lower limit (68%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Upper limit (68%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Lower limit (95%% confidence)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Upper limit (95%% confidence)\n", column_txt, i_column++); } if(MCMC->map_P_to_M != NULL) { fprintf(fp_results, "# %s (%02d) Model (Marginalized likelihood parameters)\n", column_txt, i_column++); fprintf(fp_results, "# %s (%02d) Model (Maximum likelihood parameters)\n", column_txt, i_column++); } for(i_P = 0; i_P < n_M[i_DS]; i_P++) { for(i_array = 0; i_array < n_M_arrays[i_DS]; i_array++) fprintf(fp_results, "%13.6le ", M_arrays[i_DS][i_array][i_P]); fprintf(fp_results, "%13.6le %13.6le", M_target[i_P], dM_target[i_P]); if(!flag_no_map_write) fprintf(fp_results, " %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le", M_avg[i_DS][i_P], dM_avg[i_DS][i_P], M_best[i_DS][i_P], M_lo_68[i_DS][i_P], M_hi_68[i_DS][i_P], M_lo_95[i_DS][i_P], M_hi_95[i_DS][i_P]); if(MCMC->map_P_to_M != NULL) fprintf(fp_results, " %13.6le %13.6le", M_best_parameters[i_DS][i_P], M_peak_parameters[i_DS][i_P]); fprintf(fp_results, "\n"); } fclose(fp_results); } else { if(n_DS > 1) sprintf(filename_results, "%s/fit_for_dataset_%05d.fits", filename_results_dir, i_DS); else sprintf(filename_results, "%s/fit_for_dataset.fits", filename_results_dir); #if USE_CFITSIO write_image_FITS(M_target, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "DATASET"); append_image_FITS(dM_target, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "UNCERTAINTY"); if(!flag_no_map_write) { append_image_FITS(M_best[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MAP_MAXL"); append_image_FITS(M_lo_68[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MAP_68PC_LO"); append_image_FITS(M_hi_68[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MAP_68PC_HI"); append_image_FITS(M_lo_95[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MAP_95PC_LO"); append_image_FITS(M_hi_95[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MAP_95PC_HI"); } if(MCMC->map_P_to_M != NULL) { // Write the fit from the maximum likelihood of the marginalized pdf append_image_FITS(M_best_parameters[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MODEL_MAXL"); for(i_P = 0; i_P < n_M[i_DS]; i_P++) residual[i_P] = M_target[i_P] - M_best_parameters[i_DS][i_P]; append_image_FITS(residual, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "RESIDUAL_MAXL"); // Write the best fit append_image_FITS(M_peak_parameters[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "MODEL_BEST"); for(i_P = 0; i_P < n_M[i_DS]; i_P++) residual[i_P] = M_target[i_P] - M_peak_parameters[i_DS][i_P]; append_image_FITS(residual, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, "RESIDUAL_BEST"); } #else SID_exit_error("2D analysis can only be written if you compile with USE_CFITSIO=1", SID_ERROR_LOGIC); #endif } current_DS = next_DS; i_DS++; } SID_log("Done.", SID_LOG_CLOSE); } // if this is my chain // Clean-up SID_log("Cleaning-up...", SID_LOG_OPEN); SID_free(SID_FARG P_i_bar_accum); SID_free(SID_FARG P_ij_bar_accum); SID_free(SID_FARG P_i_bar); SID_free(SID_FARG P_ij_bar); SID_free(SID_FARG V_compute); for(i_DS = 0; i_DS < n_DS; i_DS++) { for(j_M = 0; j_M < n_M[i_DS]; j_M++) SID_free(SID_FARG M_histogram[i_DS][j_M]); SID_free(SID_FARG M_histogram[i_DS]); } SID_free(SID_FARG M_avg); SID_free(SID_FARG dM_avg); SID_free(SID_FARG M_best); SID_free(SID_FARG residual); SID_free(SID_FARG M_best_parameters); SID_free(SID_FARG M_peak_parameters); SID_free(SID_FARG M_min); SID_free(SID_FARG M_max); SID_free(SID_FARG M_lo_68); SID_free(SID_FARG M_hi_68); SID_free(SID_FARG M_lo_95); SID_free(SID_FARG M_hi_95); SID_free(SID_FARG M_histogram); SID_free(SID_FARG P_contour_68); SID_free(SID_FARG P_contour_95); for(i_P = 0; i_P < n_P; i_P++) { SID_free(SID_FARG P_histogram[i_P]); SID_free(SID_FARG mean_L_histogram[i_P]); SID_free(SID_FARG max_L_histogram[i_P]); } SID_free(SID_FARG P_histogram); SID_free(SID_FARG n_M_arrays); SID_free(SID_FARG M_arrays); SID_free(SID_FARG M_avg); SID_free(SID_FARG dM_avg); for(i_P = 0; i_P < n_coverage; i_P++) { SID_free(SID_FARG coverage_true[i_P]); SID_free(SID_FARG coverage_false[i_P]); SID_free(SID_FARG coverage_keep[i_P]); SID_free(SID_FARG max_L_surface[i_P]); SID_free(SID_FARG mean_L_surface[i_P]); } SID_free(SID_FARG coverage_true); SID_free(SID_FARG coverage_false); SID_free(SID_FARG coverage_keep); SID_free(SID_FARG max_L_surface); SID_free(SID_FARG mean_L_surface); SID_free(SID_FARG temp_out); SID_log("Done.", SID_LOG_CLOSE); SID_log("Done.", SID_LOG_CLOSE); }
{ "alphanum_fraction": 0.5346089012, "avg_line_length": 51.9810298103, "ext": "c", "hexsha": "3cdf38caf8da04584422b4fe1710743b7424adf9", "lang": "C", "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z", "max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gbpoole/gbpCode", "max_forks_repo_path": "src/gbpMath/gbpMCMC/analyze_MCMC.c", "max_issues_count": 2, "max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z", "max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gbpoole/gbpCode", "max_issues_repo_path": "src/gbpMath/gbpMCMC/analyze_MCMC.c", "max_line_length": 149, "max_stars_count": 1, "max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gbpoole/gbpCode", "max_stars_repo_path": "src/gbpMath/gbpMCMC/analyze_MCMC.c", "max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z", "num_tokens": 14236, "size": 57543 }
/* * BSD 3-Clause License * * Copyright (c) 2021, Shahriar Rezghi <shahriar25.ss@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <complex> #define lapack_complex_float std::complex<float> #define lapack_complex_double std::complex<double> #include <blasw/config.h> #ifdef BLASW_CBLAS_MKL #include <mkl_cblas.h> #else #include <cblas.h> #endif #ifdef BLASW_LAPACKE_FOUND #ifdef BLASW_LAPACKE_MKL #include <mkl_lapacke.h> #else #include <lapacke.h> #endif #endif #include <cstdlib> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <type_traits> #define CHECK(expr) \ if (!static_cast<bool>(expr)) throw std::runtime_error(std::string("Expression \"") + #expr + "\" has failed!"); namespace Blasw { using Size = int; using Index = CBLAS_INDEX; enum class Major { Row = CblasRowMajor, Col = CblasColMajor, }; enum class State { None = CblasNoTrans, Trans = CblasTrans, ConjTrans = CblasConjTrans, }; enum class Triangular { Upper = CblasUpper, Lower = CblasLower, }; enum class Diagonal { Unit = CblasUnit, NonUnit = CblasNonUnit, }; template <typename T> struct From { using Type = T; }; template <typename T> struct From<std::complex<T>> { using Type = T; }; template <typename T> struct To { using Type = std::complex<T>; }; template <typename T> struct To<std::complex<T>> { using Type = std::complex<T>; }; namespace Impl { inline CBLAS_ORDER blcvt(Major major) { return CBLAS_ORDER(major); } inline CBLAS_TRANSPOSE blcvt(State state) { return CBLAS_TRANSPOSE(state); } inline CBLAS_UPLO blcvt(Triangular tri) { return CBLAS_UPLO(tri); } inline CBLAS_DIAG blcvt(Diagonal diag) { return CBLAS_DIAG(diag); } } // namespace Impl //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #define STATE(name) \ name<T> &trans() \ { \ state = State::Trans; \ return *this; \ } \ name<T> &adjoint() \ { \ state = State::ConjTrans; \ return *this; \ } template <typename T> struct Vector { T *data; Size size, stride; Vector() {} Vector(T *data, Size size, Size stride) : data(data), size(size) { this->stride = (stride == 0 ? 1 : stride); } }; template <typename T> Vector<T> vec(T *data, Size size, Size stride = 0) { return Vector<T>(data, size, stride); } template <typename T> struct General { using Type = T; T *data; Size rows, cols, stride; Major major; State state; STATE(General); General() : data(nullptr), rows(0), cols(0), stride(0), major{Major::Row}, state(State::None) {} General(T *data, Size rows, Size cols, Size stride, Major major, State state) : data(data), rows(rows), cols(cols), major{major}, state(state) { this->stride = (stride == 0 ? (major == Major::Row ? cols : rows) : stride); } bool _trans() const { return state == State::Trans || state == State::ConjTrans; } Size _rows() const { return _trans() ? cols : rows; } Size _cols() const { return _trans() ? rows : cols; } }; #define GENERAL(name, major) \ template <typename T> \ General<T> name(T *data, Size rows, Size cols, Size stride = 0) \ { \ return General<T>(data, rows, cols, stride, Major::major, State::None); \ } GENERAL(rmat, Row) GENERAL(cmat, Col); template <typename T> struct BGeneral { using Type = T; T *data; Size rows, cols, stride; Major major; State state; Size sub, super; STATE(BGeneral); BGeneral() : data(nullptr), rows(0), cols(0), stride(0), major{Major::Row}, state(State::None), sub(0), super(0) {} BGeneral(T *data, Size rows, Size cols, Size stride, Major major, State state, Size sub, Size super) : data(data), rows(rows), cols(cols), major{major}, state(state), sub(sub), super(super) { this->stride = (stride == 0 ? (major == Major::Row ? cols : rows) : stride); } bool _trans() const { return state == State::Trans || state == State::ConjTrans; } Size _rows() const { return _trans() ? cols : rows; } Size _cols() const { return _trans() ? rows : cols; } }; #define BGENERAL(name, major, str) \ template <typename T> \ BGeneral<T> name(T *data, Size rows, Size cols, Size sub, Size super, Size stride = 0) \ { \ return BGeneral<T>(data, rows, cols, stride, Major::major, State::None, sub, super); \ } BGENERAL(rbmat, Row, cols) BGENERAL(cbmat, Col, rows); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template <typename T> struct Triangle { using Type = T; T *data; Size size, stride; Major major; State state; Triangular tri; Diagonal diag; STATE(Triangle); Triangle() : data(nullptr), size(0), stride(0), major{Major::Row}, state(State::None), tri(Triangular::Upper), diag(Diagonal::NonUnit) { } Triangle(T *data, Size size, Size stride, Major major, State state, Triangular tri, Diagonal diag) : data(data), size(size), major{major}, state(state), tri(tri), diag(diag) { this->stride = (stride == 0 ? size : stride); } Triangle<T> &unit() { diag = Diagonal::Unit; return *this; } }; #define TRIANGLE(name, major, tri) \ template <typename T> \ Triangle<T> name(T *data, Size size, Size stride = 0) \ { \ return Triangle<T>(data, size, stride, Major::major, State::None, Triangular::tri); \ } TRIANGLE(rupper, Row, Upper) TRIANGLE(cupper, Col, Upper); TRIANGLE(rlower, Row, Lower) TRIANGLE(clower, Col, Lower); template <typename T> struct BTriangle { using Type = T; T *data; Size size, stride; Major major; State state; Triangular tri; Diagonal diag; Size super; STATE(BTriangle); BTriangle() : data(nullptr), size(0), stride(0), major{Major::Row}, state(State::None), tri(Triangular::Upper), diag(Diagonal::NonUnit), super(0) { } BTriangle(T *data, Size size, Size stride, Major major, State state, Triangular tri, Diagonal diag, Size super) : data(data), size(size), major{major}, state(state), tri(tri), diag(diag), super(super) { this->stride = (stride == 0 ? size : stride); } BTriangle<T> &unit() { diag = Diagonal::Unit; return *this; } }; #define BTRIANGLE(name, major, tri) \ template <typename T> \ BTriangle<T> name(T *data, Size size, Size super, Size stride = 0) \ { \ return BTriangle<T>(data, size, stride, Major::major, State::None, Triangular::tri, super); \ } BTRIANGLE(rbupper, Row, Upper) BTRIANGLE(cbupper, Col, Upper); BTRIANGLE(rblower, Row, Lower) BTRIANGLE(cblower, Col, Lower); template <typename T> struct PTriangle { using Type = T; T *data; Size size; Major major; State state; Triangular tri; Diagonal diag; STATE(PTriangle); PTriangle() : data(nullptr), size(0), major{Major::Row}, state(State::None), tri(Triangular::Upper), diag(Diagonal::NonUnit) { } PTriangle(T *data, Size size, Major major, State state, Triangular tri, Diagonal diag) : data(data), size(size), major{major}, state(state), tri(tri), diag(diag) { } PTriangle<T> &unit() { diag = Diagonal::Unit; return *this; } }; #define PTRIANGLE(name, major, tri) \ template <typename T> \ PTriangle<T> name(T *data, Size size) \ { \ return PTriangle<T>(data, size, Major::major, State::None, Triangular::tri); \ } PTRIANGLE(rpupper, Row, Upper) PTRIANGLE(cpupper, Col, Upper); PTRIANGLE(rplower, Row, Lower) PTRIANGLE(cplower, Col, Lower); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template <typename T> struct Symmetric { using Type = T; T *data; Size size, stride; Major major; Triangular tri; Symmetric() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper) {} Symmetric(T *data, Size size, Size stride, Major major, Triangular tri) : data(data), size(size), major{major}, tri(tri) { this->stride = (stride == 0 ? size : stride); } }; #define SYMMETRIC(name, major, tri) \ template <typename T> \ Symmetric<T> name(T *data, Size size, Size stride = 0) \ { \ return Symmetric<T>(data, size, stride, Major::major, Triangular::tri); \ } SYMMETRIC(rusym, Row, Upper) SYMMETRIC(cusym, Col, Upper); SYMMETRIC(rlsym, Row, Lower) SYMMETRIC(clsym, Col, Lower); template <typename T> struct BSymmetric { using Type = T; T *data; Size size, stride; Major major; Triangular tri; Size super; BSymmetric() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper), super(0) {} BSymmetric(T *data, Size size, Size stride, Major major, Triangular tri, Size super) : data(data), size(size), major{major}, tri(tri), super(super) { this->stride = (stride == 0 ? size : stride); } }; #define BSYMMETRIC(name, major, tri) \ template <typename T> \ BSymmetric<T> name(T *data, Size size, Size super, Size stride = 0) \ { \ return BSymmetric<T>(data, size, stride, Major::major, Triangular::tri, super); \ } BSYMMETRIC(rbusym, Row, Upper) BSYMMETRIC(cbusym, Col, Upper); BSYMMETRIC(rblsym, Row, Lower) BSYMMETRIC(cblsym, Col, Lower); template <typename T> struct PSymmetric { using Type = T; T *data; Size size; Major major; Triangular tri; PSymmetric() : data(nullptr), size(0), major{Major::Row}, tri(Triangular::Upper) {} PSymmetric(T *data, Size size, Major major, Triangular tri) : data(data), size(size), major{major}, tri(tri) {} }; #define PSYMMETRIC(name, major, tri) \ template <typename T> \ PSymmetric<T> name(T *data, Size size) \ { \ return PSymmetric<T>(data, size, Major::major, Triangular::tri); \ } PSYMMETRIC(rpusym, Row, Upper) PSYMMETRIC(cpusym, Col, Upper); PSYMMETRIC(rplsym, Row, Lower) PSYMMETRIC(cplsym, Col, Lower); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template <typename T> struct Hermitian { using Type = T; T *data; Size size, stride; Major major; Triangular tri; Hermitian() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper) {} Hermitian(T *data, Size size, Size stride, Major major, Triangular tri) : data(data), major{major}, size(size), tri(tri) { this->stride = (stride == 0 ? size : stride); } }; #define HERMITIAN(name, major, tri) \ template <typename T> \ Hermitian<T> name(T *data, Size size, Size stride = 0) \ { \ return Hermitian<T>(data, size, stride, Major::major, Triangular::tri); \ } HERMITIAN(ruherm, Row, Upper) HERMITIAN(cuherm, Col, Upper); HERMITIAN(rlherm, Row, Lower) HERMITIAN(clherm, Col, Lower); template <typename T> struct BHermitian { using Type = T; T *data; Size size, stride; Major major; Triangular tri; Size super; BHermitian() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper), super(0) {} BHermitian(T *data, Size size, Size stride, Major major, Triangular tri, Size super) : data(data), size(size), major{major}, tri(tri), super(super) { this->stride = (stride == 0 ? size : stride); } }; #define BHERMITIAN(name, major, tri) \ template <typename T> \ BHermitian<T> name(T *data, Size size, Size super, Size stride = 0) \ { \ return BHermitian<T>(data, size, stride, Major::major, Triangular::tri, super); \ } BHERMITIAN(rbuherm, Row, Upper) BHERMITIAN(cbuherm, Col, Upper); BHERMITIAN(rblherm, Row, Lower) BHERMITIAN(cblherm, Col, Lower); template <typename T> struct PHermitian { using Type = T; T *data; Size size; Major major; Triangular tri; PHermitian() : data(nullptr), size(0), major{Major::Row}, tri(Triangular::Upper) {} PHermitian(T *data, Size size, Major major, Triangular tri) : data(data), size(size), major{major}, tri(tri) {} }; #define PHERMITIAN(name, major, tri) \ template <typename T> \ PHermitian<T> name(T *data, Size size) \ { \ return PHermitian<T>(data, size, Major::major, Triangular::tri); \ } PHERMITIAN(rpusym, Row, Upper) PHERMITIAN(cpusym, Col, Upper); PHERMITIAN(rplsym, Row, Lower) PHERMITIAN(cplsym, Col, Lower); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// template <typename T> struct Posdef { using Type = T; T *data; Size size, stride; Major major; Triangular tri; Posdef() : data(nullptr), size(0), stride(0), major{Major::Row}, tri(Triangular::Upper) {} Posdef(T *data, Size size, Size stride, Major major, Triangular tri) : data(data), size(size), major{major}, tri(tri) { this->stride = (stride == 0 ? size : stride); } }; #define POSDEF(name, major, tri) \ template <typename T> \ Posdef<T> name(T *data, Size size, Size stride = 0) \ { \ return Posdef<T>(data, size, stride, Major::major, Triangular::tri); \ } POSDEF(rupod, Row, Upper) POSDEF(cupod, Col, Upper); POSDEF(rlpod, Row, Lower) POSDEF(clpod, Col, Lower); //////////////////////////////////////////////////////////////////////////////// /// BLAS LEVEL 1 /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #define REPEAT0(func, name1, name2) \ func(cblas_##name1, float, ); \ func(cblas_##name2, double, ); #define REPEAT1(func, name1, name2) \ func(cblas_##name1, std::complex<float>, (void *)&); \ func(cblas_##name2, std::complex<double>, (void *)&); #define REPEAT(func, name1, name2, name3, name4) \ REPEAT0(func, name1, name2) \ REPEAT1(func, name3, name4) #define ROTG(F, T, R) \ inline void givens(T &a, T &b, T &c, T &s) { F(&a, &b, &c, &s); } #define ROTMG(F, T, R) \ inline void givens(T &d1, T &d2, T &b1, T &b2, T P[5]) { F(&d1, &d2, &b1, b2, P); } REPEAT0(ROTG, srotg, drotg) REPEAT0(ROTMG, srotmg, drotmg) #define ROT(F, T, R) \ inline void rotate(Vector<T> X, Vector<T> Y, From<T>::Type c, From<T>::Type s) \ { \ CHECK(X.size == Y.size); \ return F(X.size, X.data, X.stride, Y.data, Y.stride, c, s); \ } REPEAT0(ROT, srot, drot) #define ROTM(F, T, R) \ inline void rotate(Vector<T> X, Vector<T> Y, From<T>::Type P[5]) \ { \ CHECK(X.size == Y.size); \ return F(X.size, X.data, X.stride, Y.data, Y.stride, P); \ } REPEAT0(ROTM, srotm, drotm) #define SWAP(F, T, R) \ inline void swap(Vector<T> X, Vector<T> Y) \ { \ CHECK(X.size == Y.size); \ return F(X.size, X.data, X.stride, Y.data, Y.stride); \ } REPEAT(SWAP, sswap, dswap, cswap, zswap) #define SCAL(F, T, R) \ inline void scale(Vector<T> X, T alpha) { return F(X.size, R alpha, X.data, X.stride); } REPEAT(SCAL, sscal, dscal, cscal, zscal) #define SSCAL(F, T, R) \ inline void scale(Vector<T> X, From<T>::Type alpha) { return F(X.size, alpha, X.data, X.stride); } REPEAT1(SSCAL, csscal, zdscal) #define COPY(F, T, R) \ inline void copy(Vector<T> X, Vector<T> Y) \ { \ CHECK(X.size == Y.size); \ return F(X.size, X.data, X.stride, Y.data, Y.stride); \ } REPEAT(COPY, scopy, dcopy, ccopy, zcopy) #define AXPY(F, T, R) \ inline void axpy(Vector<T> X, Vector<T> Y, T alpha) \ { \ CHECK(X.size == Y.size); \ return F(X.size, R alpha, X.data, X.stride, Y.data, Y.stride); \ } REPEAT(AXPY, saxpy, daxpy, caxpy, zaxpy) #define DOT(F, T, R) \ inline T dot(Vector<T> X, Vector<T> Y) \ { \ CHECK(X.size == Y.size); \ return F(X.size, X.data, X.stride, Y.data, Y.stride); \ } REPEAT0(DOT, sdot, ddot) #define DOTU(F, T, R) \ inline T dot(Vector<T> X, Vector<T> Y, bool conj = true) \ { \ CHECK(X.size == Y.size); \ T result; \ if (conj) \ F##c_sub(X.size, X.data, X.stride, Y.data, Y.stride, R result); \ else \ F##u_sub(X.size, X.data, X.stride, Y.data, Y.stride, R result); \ return result; \ } REPEAT1(DOTU, cdot, zdot) inline float exdot(Vector<float> X, Vector<float> Y, float beta) { CHECK(X.size == Y.size); return cblas_sdsdot(X.size, beta, X.data, X.stride, Y.data, Y.stride); } inline float exdot(Vector<float> X, Vector<float> Y) { CHECK(X.size == Y.size); return cblas_dsdot(X.size, X.data, X.stride, Y.data, Y.stride); } #define NRM2(F, T, R) \ inline From<T>::Type norm2(Vector<T> X) { return F(X.size, X.data, X.stride); } REPEAT(NRM2, snrm2, dnrm2, scnrm2, dznrm2) #define ASUM(F, T, R) \ inline From<T>::Type asum(Vector<T> X) { return F(X.size, X.data, X.stride); } REPEAT(ASUM, sasum, dasum, scasum, dzasum) #define IAMAX(F, T, R) \ inline Index iamax(Vector<T> X) { return F(X.size, X.data, X.stride); } REPEAT(IAMAX, isamax, idamax, icamax, izamax) //////////////////////////////////////////////////////////////////////////////// /// BLAS LEVEL 2 /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #define GEMV(F, T, R) \ inline void dot(General<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A._cols() == X.size) CHECK(A._rows() == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.state), A.rows, A.cols, R alpha, A.data, A.stride, X.data, X.stride, \ R beta, Y.data, Y.stride); \ } REPEAT(GEMV, sgemv, dgemv, cgemv, zgemv) #define GBMV(F, T, R) \ inline void dot(BGeneral<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A._cols() == X.size) CHECK(A._rows() == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.state), A.rows, A.cols, A.sub, A.super, R alpha, A.data, A.stride, \ X.data, X.stride, R beta, Y.data, Y.stride); \ } REPEAT(GBMV, sgbmv, dgbmv, cgbmv, zgbmv) #define SYMV(F, T, R) \ inline void dot(Symmetric<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A.size == X.size) CHECK(A.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, A.stride, X.data, X.stride, R beta, \ Y.data, Y.stride); \ } #define HEMV(F, T, R) \ inline void dot(Hermitian<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A.size == X.size) CHECK(A.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, A.stride, X.data, X.stride, R beta, \ Y.data, Y.stride); \ } REPEAT0(SYMV, ssymv, dsymv) REPEAT1(HEMV, chemv, zhemv) #define SBMV(F, T, R) \ inline void dot(BSymmetric<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A.size == X.size) CHECK(A.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, A.super, R alpha, A.data, A.stride, X.data, X.stride, \ R beta, Y.data, Y.stride); \ } #define HBMV(F, T, R) \ inline void dot(BHermitian<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A.size == X.size) CHECK(A.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, A.super, R alpha, A.data, A.stride, X.data, X.stride, \ R beta, Y.data, Y.stride); \ } REPEAT0(SBMV, ssbmv, dsbmv) REPEAT1(HBMV, chbmv, zhbmv) #define SPMV(F, T, R) \ inline void dot(PSymmetric<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A.size == X.size) CHECK(A.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, X.data, X.stride, R beta, Y.data, \ Y.stride); \ } #define HPMV(F, T, R) \ inline void dot(PHermitian<T> A, Vector<T> X, Vector<T> Y, T alpha, T beta) \ { \ CHECK(A.size == X.size) CHECK(A.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, A.data, X.data, X.stride, R beta, Y.data, \ Y.stride); \ } REPEAT0(SPMV, sspmv, dspmv) REPEAT1(HPMV, chpmv, zhpmv) #define TRMV(F, T, R) \ inline void dot(Triangle<T> A, Vector<T> X) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, \ A.stride, X.data, X.stride); \ } REPEAT(TRMV, strmv, dtrmv, ctrmv, ztrmv) #define TBMV(F, T, R) \ inline void dot(BTriangle<T> A, Vector<T> X) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.super, \ A.data, A.stride, X.data, X.stride); \ } REPEAT(TBMV, stbmv, dtbmv, ctbmv, ztbmv) #define TPMV(F, T, R) \ inline void dot(PTriangle<T> A, Vector<T> X) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, X.data, \ X.stride); \ } REPEAT(TPMV, stpmv, dtpmv, ctpmv, ztpmv) #define TRSV(F, T, R) \ inline void solve(Triangle<T> A, Vector<T> X) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, \ A.stride, X.data, X.stride); \ } REPEAT(TRSV, strsv, dtrsv, ctrsv, ztrsv) #define TBSV(F, T, R) \ inline void solve(BTriangle<T> A, Vector<T> X) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.super, \ A.data, A.stride, X.data, X.stride); \ } REPEAT(TBSV, stbsv, dtbsv, ctbsv, ztbsv) #define TPSV(F, T, R) \ inline void solve(PTriangle<T> A, Vector<T> X) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), A.size, A.data, X.data, \ X.stride); \ } REPEAT(TPSV, stpsv, dtpsv, ctpsv, ztpsv) #define GER(F, T, R) \ inline void update(Vector<T> X, Vector<T> Y, General<T> A, T alpha) \ { \ CHECK(X.size == A.rows) CHECK(Y.size == A.cols) CHECK(A.state == State::None); \ F(Impl::blcvt(A.major), X.size, Y.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, A.stride); \ } REPEAT0(GER, sger, dger) #define GERU(F, T, R) \ inline void update(Vector<T> X, Vector<T> Y, General<T> A, T alpha, bool conj = true) \ { \ CHECK(X.size == A.rows) CHECK(Y.size == A.cols) CHECK(A.state == State::None); \ if (conj) \ F##c(Impl::blcvt(A.major), X.size, Y.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, A.stride); \ else \ F##u(Impl::blcvt(A.major), X.size, Y.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, A.stride); \ } REPEAT1(GERU, cger, zger) #define SYR(F, T, R) \ inline void update(Vector<T> X, Symmetric<T> A, T alpha) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, A.data, A.stride); \ } #define HER(F, T, R) \ inline void update(Vector<T> X, Hermitian<T> A, From<T>::Type alpha) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, alpha, X.data, X.stride, A.data, A.stride); \ } REPEAT0(SYR, ssyr, dsyr) REPEAT1(HER, cher, zher) #define SPR(F, T, R) \ inline void update(Vector<T> X, PSymmetric<T> A, T alpha) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, A.data); \ } #define HPR(F, T, R) \ inline void update(Vector<T> X, PHermitian<T> A, From<T>::Type alpha) \ { \ CHECK(A.size == X.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, alpha, X.data, X.stride, A.data); \ } REPEAT0(SPR, sspr, dspr) REPEAT1(HPR, chpr, zhpr) #define SYR2(F, T, R) \ inline void update(Vector<T> X, Vector<T> Y, Symmetric<T> A, T alpha) \ { \ CHECK(A.size == X.size) CHECK(X.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, \ A.stride); \ } #define HER2(F, T, R) \ inline void update(Vector<T> X, Vector<T> Y, Hermitian<T> A, T alpha) \ { \ CHECK(A.size == X.size) CHECK(X.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data, \ A.stride); \ } REPEAT0(SYR2, ssyr2, dsyr2) REPEAT1(HER2, cher2, zher2) #define SPR2(F, T, R) \ inline void update(Vector<T> X, Vector<T> Y, PSymmetric<T> A, T alpha) \ { \ CHECK(A.size == X.size) CHECK(X.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data); \ } #define HPR2(F, T, R) \ inline void update(Vector<T> X, Vector<T> Y, PHermitian<T> A, T alpha) \ { \ CHECK(A.size == X.size) CHECK(X.size == Y.size); \ F(Impl::blcvt(A.major), Impl::blcvt(A.tri), A.size, R alpha, X.data, X.stride, Y.data, Y.stride, A.data); \ } REPEAT0(SPR2, sspr2, dspr2) REPEAT1(HPR2, chpr2, zhpr2) //////////////////////////////////////////////////////////////////////////////// /// BLAS LEVEL 3 /////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #define GEMM(F, T, R) \ inline void dot(General<T> A, General<T> B, General<T> C, T alpha, T beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major) CHECK(C.state == State::None); \ CHECK(A._cols() == B._rows()) CHECK(A._rows() == C.rows) CHECK(B._cols() == C.cols); \ F(Impl::blcvt(A.major), Impl::blcvt(A.state), Impl::blcvt(B.state), C.rows, C.cols, A._cols(), R alpha, \ A.data, A.stride, B.data, B.stride, R beta, C.data, C.stride); \ } REPEAT(GEMM, sgemm, dgemm, cgemm, zgemm) #define SYMM(F, T, R) \ inline void dot(Symmetric<T> A, General<T> B, General<T> C, T alpha, T beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major); \ CHECK(B.state == State::None) CHECK(C.state == State::None); \ CHECK(A.size == B.rows) CHECK(A.size == C.rows) CHECK(B.cols == C.cols); \ F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data, \ B.stride, R beta, C.data, C.stride); \ } \ inline void dot(General<T> B, Symmetric<T> A, General<T> C, T alpha, T beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major); \ CHECK(B.state == State::None) CHECK(C.state == State::None); \ CHECK(A.size == B.cols) CHECK(A.size == C.cols) CHECK(B.rows == C.rows); \ F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data, \ B.stride, R beta, C.data, C.stride); \ } REPEAT(SYMM, ssymm, dsymm, csymm, zsymm) #define HEMM(F, T, R) \ inline void dot(Hermitian<T> A, General<T> B, General<T> C, T alpha, T beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major); \ CHECK(B.state == State::None) CHECK(C.state == State::None); \ CHECK(A.size == B.rows) CHECK(A.size == C.rows) CHECK(B.cols == C.cols); \ F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data, \ B.stride, R beta, C.data, C.stride); \ } \ inline void dot(General<T> B, Hermitian<T> A, General<T> C, T alpha, T beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major); \ CHECK(B.state == State::None) CHECK(C.state == State::None); \ CHECK(A.size == B.cols) CHECK(A.size == C.cols) CHECK(B.rows == C.rows); \ F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), C.rows, C.cols, R alpha, A.data, A.stride, B.data, \ B.stride, R beta, C.data, C.stride); \ } REPEAT1(HEMM, chemm, zhemm) #define TRMM(F, T, R) \ inline void dot(Triangle<T> A, General<T> B, T alpha) \ { \ CHECK(A.major == B.major) CHECK(A.size == B.rows) CHECK(B.state == State::None); \ F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows, \ B.cols, R alpha, A.data, A.stride, B.data, B.stride); \ } \ inline void dot(General<T> B, Triangle<T> A, T alpha) \ { \ CHECK(A.major == B.major) CHECK(A.size == B.cols) CHECK(B.state == State::None); \ F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows, \ B.cols, R alpha, A.data, A.stride, B.data, B.stride); \ } REPEAT(TRMM, strmm, dtrmm, ctrmm, ztrmm) #define TRSM(F, T, R) \ inline void solve(Triangle<T> A, General<T> B, T alpha) \ { \ CHECK(A.major == B.major) CHECK(A.size == B.rows) CHECK(B.state == State::None); \ F(Impl::blcvt(A.major), CblasLeft, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows, \ B.cols, R alpha, A.data, A.stride, B.data, B.stride); \ } \ inline void solve(General<T> B, Triangle<T> A, T alpha) \ { \ CHECK(A.major == B.major) CHECK(A.size == B.cols) CHECK(B.state == State::None); \ F(Impl::blcvt(A.major), CblasRight, Impl::blcvt(A.tri), Impl::blcvt(A.state), Impl::blcvt(A.diag), B.rows, \ B.cols, R alpha, A.data, A.stride, B.data, B.stride); \ } REPEAT(TRSM, strsm, dtrsm, ctrsm, ztrsm) #define SYRK(F, T, R) \ inline void update(General<T> A, Symmetric<T> C, T alpha, T beta) \ { \ CHECK(A.major == C.major) CHECK(A._rows() == C.size); \ F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), A._cols(), R alpha, A.data, \ A.stride, R beta, C.data, C.stride); \ } REPEAT(SYRK, ssyrk, dsyrk, csyrk, zsyrk) #define HERK(F, T, R) \ inline void update(General<T> A, Hermitian<T> C, From<T>::Type alpha, From<T>::Type beta) \ { \ CHECK(A.major == C.major) CHECK(A._rows() == C.size); \ F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), A._cols(), alpha, A.data, \ A.stride, beta, C.data, C.stride); \ } REPEAT1(HERK, cherk, zherk) #define SYR2K(F, T, R) \ inline void update(General<T> A, General<T> B, Symmetric<T> C, T alpha, T beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major) CHECK(A.state == B.state); \ CHECK(A._rows() == C.size) CHECK(A._rows() == B._rows()) CHECK(A._cols() == B._cols()); \ F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), B._cols(), R alpha, A.data, \ A.stride, B.data, B.stride, R beta, C.data, C.stride); \ } REPEAT(SYR2K, ssyr2k, dsyr2k, csyr2k, zsyr2k) #define HER2K(F, T, R) \ inline void update(General<T> A, General<T> B, Hermitian<T> C, T alpha, From<T>::Type beta) \ { \ CHECK(A.major == B.major) CHECK(A.major == C.major) CHECK(A.state == B.state); \ CHECK(A._rows() == C.size) CHECK(A._rows() == B._rows()) CHECK(A._cols() == B._cols()); \ F(Impl::blcvt(A.major), Impl::blcvt(C.tri), Impl::blcvt(A.state), A._rows(), B._cols(), R alpha, A.data, \ A.stride, B.data, B.stride, beta, C.data, C.stride); \ } REPEAT1(HER2K, cher2k, zher2k) //////////////////////////////////////////////////////////////////////////////// /// LAPACK ///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// #ifdef BLASW_LAPACKE_FOUND #undef REPEAT0 #undef REPEAT1 #undef REPEAT #define REPEAT0(func, name1, name2) \ func(LAPACKE_##name1, float, ); \ func(LAPACKE_##name2, double, ); #define REPEAT1(func, name1, name2) \ func(LAPACKE_##name1, std::complex<float>, (void *)&); \ func(LAPACKE_##name2, std::complex<double>, (void *)&); #define REPEAT(func, name1, name2, name3, name4) \ REPEAT0(func, name1, name2) \ REPEAT1(func, name3, name4) namespace Impl { inline int lpcvt(Major major) { return major == Major::Row ? LAPACK_ROW_MAJOR : LAPACK_ROW_MAJOR; } inline char lpcvt(State state) { if (state == State::None) return 'N'; else if (state == State::Trans) return 'T'; else if (state == State::ConjTrans) return 'C'; else return '\0'; } inline char lpcvt(Triangular tri) { return tri == Triangular::Upper ? 'U' : 'L'; } template <typename T> std::unique_ptr<T> alloc(Size size) { #ifdef _WIN32 auto P = malloc(size * sizeof(T)); #else auto P = aligned_alloc(64, size * sizeof(T)); #endif return std::unique_ptr<T>((T *)P); } } // namespace Impl #define GETRI(F, T, R) \ inline bool inverse(General<T> A) \ { \ CHECK(A.rows == A.cols) CHECK(A.state == State::None); \ auto P = Impl::alloc<int>(A.rows); \ if (F##getrf(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, P.get()) != 0) return false; \ return F##getri(Impl::lpcvt(A.major), A.rows, A.data, A.stride, P.get()) == 0; \ } REPEAT(GETRI, s, d, c, z) #define SYTRI(F, T, R) \ inline bool inverse(Symmetric<T> A) \ { \ auto P = Impl::alloc<int>(A.size); \ if (F##sytrf(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.get()) != 0) return false; \ return F##sytri(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.get()) == 0; \ } REPEAT(SYTRI, s, d, c, z) #define GEDTR(F, T, R) \ inline T determinant(General<T> A) \ { \ CHECK(A.rows == A.cols) CHECK(A.state == State::None); \ auto _P = Impl::alloc<int>(A.rows); \ if (F##getrf(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, _P.get()) != 0) return 0; \ \ T det = 1; \ auto P = _P.get(); \ for (Size i = 0; i < A.rows; ++i) det *= A.data[i * A.stride + i] * T(P[i] == i ? 1 : -1); \ return det; \ } REPEAT(GEDTR, s, d, c, z) #define SYDTR(F, T, R) \ inline T determinant(Symmetric<T> A) \ { \ auto _P = Impl::alloc<int>(A.size); \ if (F##sytrf(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, _P.get()) != 0) return 0; \ \ T det = 1; \ auto P = _P.get(); \ for (Size i = 0; i < A.size; ++i) det *= A.data[i * A.stride + i] * T(P[i] == i ? 1 : -1); \ return det; \ } REPEAT(SYDTR, s, d, c, z) #define HEDTR(F, T, R) \ inline T determinant(Hermitian<T> A) \ { \ auto _P = Impl::alloc<int>(A.size); \ if (F##hetrf(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, _P.get()) != 0) return 0; \ \ T det = 1; \ auto P = _P.get(); \ for (Size i = 0; i < A.size; ++i) det *= A.data[i * A.stride + i] * T(P[i] == i ? 1 : -1); \ return det; \ } REPEAT1(HEDTR, c, z) #define GETRF(F, T, R) \ inline bool lufact(General<T> A, Vector<int> P) \ { \ CHECK(A.state == State::None) CHECK(std::min(A.rows, A.cols) == P.size) CHECK(P.stride == 1); \ return F(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, P.data) == 0; \ } REPEAT(GETRF, sgetrf, dgetrf, cgetrf, zgetrf) #define SYTRF(F, T, R) \ inline bool lufact(Symmetric<T> A, Vector<int> P) \ { \ CHECK(A.size == P.size) CHECK(P.stride == 1); \ return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.data) == 0; \ } REPEAT(SYTRF, ssytrf, dsytrf, csytrf, zsytrf) #define HETRF(F, T, R) \ inline bool lufact(Hermitian<T> A, Vector<int> P) \ { \ CHECK(A.size == P.size) CHECK(P.stride == 1); \ return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride, P.data) == 0; \ } REPEAT1(HETRF, chetrf, zhetrf) #define POTRF(F, T, R) \ inline bool cholesky(Posdef<T> A) \ { \ return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, A.data, A.stride) == 0; \ } REPEAT(POTRF, spotrf, dpotrf, cpotrf, zpotrf) #define GEQRF(F, TYPE, R) \ inline bool qrfact(General<TYPE> A, Vector<TYPE> T) \ { \ CHECK(A.state == State::None) CHECK(std::min(A.rows, A.cols) == T.size) CHECK(T.stride == 1); \ return F(Impl::lpcvt(A.major), A.rows, A.cols, A.data, A.stride, T.data) == 0; \ } REPEAT(GEQRF, sgeqrf, dgeqrf, cgeqrf, zgeqrf) #define GEEV(F, T, REF) \ inline bool eigen(General<T> A, Vector<std::complex<T>> E, General<T> L, General<T> R) \ { \ CHECK(A.major == L.major) CHECK(A.major == R.major); \ CHECK(A.state == State::None) CHECK(L.state == State::None) CHECK(R.state == State::None); \ CHECK(A.rows == A.cols) CHECK(L.rows == L.cols) CHECK(R.rows == R.cols); \ CHECK(A.rows == E.size) CHECK(E.stride == 1); \ \ if (L.data == nullptr) L.stride = A.rows; \ if (R.data == nullptr) R.stride = A.rows; \ auto _WR = Impl::alloc<T>(A.rows), _WI = Impl::alloc<T>(A.rows); \ if (F(Impl::lpcvt(A.major), L.data == nullptr ? 'N' : 'V', R.data == nullptr ? 'N' : 'V', A.rows, A.data, \ A.stride, _WR.get(), _WI.get(), L.data, L.stride, R.data, R.stride) != 0) \ return false; \ \ auto WR = _WR.get(), WI = _WI.get(); \ for (Size i = 0; i < A.rows; ++i) E.data[i].real(WR[i]), E.data[i].imag(WI[i]); \ return true; \ } #define GEEVC(F, T, REF) \ inline bool eigen(General<T> A, Vector<T> E, General<T> L, General<T> R) \ { \ CHECK(A.major == L.major) CHECK(A.major == R.major); \ CHECK(A.state == State::None) CHECK(L.state == State::None) CHECK(R.state == State::None); \ CHECK(A.rows == A.cols) CHECK(L.rows == L.cols) CHECK(R.rows == R.cols); \ CHECK(A.rows == E.size) CHECK(E.stride == 1); \ \ if (L.data == nullptr) L.stride = A.rows; \ if (R.data == nullptr) R.stride = A.rows; \ return F(Impl::lpcvt(A.major), L.data == nullptr ? 'N' : 'V', R.data == nullptr ? 'N' : 'V', A.rows, A.data, \ A.stride, E.data, L.data, L.stride, R.data, R.stride) == 0; \ } REPEAT0(GEEV, sgeev, dgeev) REPEAT1(GEEVC, cgeev, zgeev) #define SYEV(F, T, R) \ inline bool eigen(Symmetric<T> A, Vector<T> E, bool vectors, bool divcon) \ { \ CHECK(A.size == E.size) CHECK(E.stride == 1); \ auto V = vectors ? 'V' : 'N'; \ \ if (divcon) \ return F##d(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0; \ else \ return F(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0; \ } #define HEEV(F, T, R) \ inline bool eigen(Hermitian<T> A, Vector<From<T>::Type> E, bool vectors, bool divcon) \ { \ CHECK(A.size == E.size) CHECK(E.stride == 1); \ auto V = vectors ? 'V' : 'N'; \ \ if (divcon) \ return F##d(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0; \ else \ return F(Impl::lpcvt(A.major), V, Impl::lpcvt(A.tri), A.size, A.data, A.stride, E.data) == 0; \ } REPEAT0(SYEV, ssyev, dsyev) REPEAT1(HEEV, cheev, zheev) #define GEES(F, T, R) \ inline bool schur(General<T> A, Vector<std::complex<T>> E, General<T> V) \ { \ CHECK(A.major == V.major) CHECK(A.state == State::None) CHECK(V.state == State::None); \ CHECK(A.rows == A.cols) CHECK(A.rows == E.size) CHECK(E.stride == 1) CHECK(V.rows == V.cols); \ \ int sdim = 0; \ if (V.data == nullptr) V.stride = A.rows; \ auto _WR = Impl::alloc<T>(A.rows), _WI = Impl::alloc<T>(A.rows); \ if (F(Impl::lpcvt(A.major), V.data == nullptr ? 'N' : 'V', 'N', nullptr, A.rows, A.data, A.stride, &sdim, \ _WR.get(), _WI.get(), V.data, V.stride) != 0) \ return false; \ \ auto WR = _WR.get(), WI = _WI.get(); \ for (Size i = 0; i < A.rows; ++i) E.data[i].real(WR[i]), E.data[i].imag(WI[i]); \ return true; \ } #define GEESC(F, T, R) \ inline bool schur(General<T> A, Vector<T> E, General<T> V) \ { \ CHECK(A.major == V.major) CHECK(A.state == State::None) CHECK(V.state == State::None); \ CHECK(A.rows == A.cols) CHECK(A.rows == E.size) CHECK(E.stride == 1) CHECK(V.rows == V.cols); \ \ int sdim = 0; \ if (V.data == nullptr) V.stride = A.rows; \ return F(Impl::lpcvt(A.major), V.data == nullptr ? 'N' : 'V', 'N', nullptr, A.rows, A.data, A.stride, &sdim, \ E.data, V.data, V.stride) == 0; \ } REPEAT0(GEES, sgees, dgees) REPEAT1(GEESC, cgees, zgees) #define GESV(F, T, R) \ inline bool solve(General<T> A, General<T> B) \ { \ CHECK(A.major == B.major) CHECK(A.state == State::None) CHECK(B.state == State::None); \ CHECK(A.rows == A.cols) CHECK(A.rows == B.rows); \ auto P = Impl::alloc<int>(A.rows); \ return F(Impl::lpcvt(A.major), A.rows, B.cols, A.data, A.stride, P.get(), B.data, B.stride) == 0; \ } REPEAT(GESV, sgesv, dgesv, cgesv, zgesv) #define SYSV(F, T, R) \ inline bool solve(Symmetric<T> A, General<T> B) \ { \ CHECK(A.major == B.major) CHECK(B.state == State::None) CHECK(A.size == B.rows); \ auto P = Impl::alloc<int>(A.size); \ return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, B.cols, A.data, A.stride, P.get(), B.data, \ B.stride) == 0; \ } REPEAT(SYSV, ssysv, dsysv, csysv, zsysv) #define HESV(F, T, R) \ inline bool solve(Hermitian<T> A, General<T> B) \ { \ CHECK(A.major == B.major) CHECK(B.state == State::None) CHECK(A.size == B.rows); \ auto P = Impl::alloc<int>(A.size); \ return F(Impl::lpcvt(A.major), Impl::lpcvt(A.tri), A.size, B.cols, A.data, A.stride, P.get(), B.data, \ B.stride) == 0; \ } REPEAT1(HESV, chesv, zhesv) #define GELS(F, T, R) \ inline bool lsquares(General<T> A, General<T> B) \ { \ CHECK(A.major == B.major) CHECK(B.state == State::None) CHECK(A._rows() == B.rows); \ return F(Impl::lpcvt(A.major), Impl::lpcvt(A.state), A._rows(), A._cols(), B.cols, A.data, A.stride, B.data, \ B.stride) == 0; \ } REPEAT(GELS, sgels, dgels, cgels, zgels) #define GESVD(F, T, R) \ inline bool svd(General<T> A, Vector<From<T>::Type> S, General<T> U, General<T> VT) \ { \ CHECK(A.major == U.major) CHECK(A.major == VT.major); \ CHECK(A.state == State::None) CHECK(U.state == State::None) CHECK(VT.state == State::None); \ CHECK(std::min(A.rows, A.cols) == S.size) CHECK(S.stride == 1); \ \ if (U.data != nullptr) CHECK(A.rows == U.rows) CHECK(U.rows == U.cols); \ if (VT.data != nullptr) CHECK(A.cols == VT.rows) CHECK(VT.rows == VT.cols); \ \ if (U.data == nullptr) U.stride = A.rows; \ if (VT.data == nullptr) VT.stride = A.cols; \ auto SB = Impl::alloc<From<T>::Type>(std::min(A.rows, A.cols)); \ return F(Impl::lpcvt(A.major), U.data == nullptr ? 'N' : 'A', VT.data == nullptr ? 'N' : 'A', A.rows, A.cols, \ A.data, A.stride, S.data, U.data, U.stride, VT.data, VT.stride, SB.get()) == 0; \ } REPEAT(GESVD, sgesvd, dgesvd, cgesvd, zgesvd) #define GERK(F, T, R) \ inline Size rank(General<T> A, From<T>::Type epsilon) \ { \ CHECK(A.state == State::None); \ auto SB = Impl::alloc<From<T>::Type>(std::min(A.rows, A.cols)); \ auto _S = Impl::alloc<From<T>::Type>(std::min(A.rows, A.cols)); \ if (F(Impl::lpcvt(A.major), 'N', 'N', A.rows, A.cols, A.data, A.stride, _S.get(), nullptr, \ std::max(A.rows, A.cols), nullptr, std::max(A.rows, A.cols), SB.get()) != 0) \ return 0; \ \ Size rank = 0; \ auto S = _S.get(); \ for (Size i = 0; i < std::min(A.rows, A.cols); ++i) \ if (std::abs(S[i]) >= std::abs(epsilon)) ++rank; \ return rank; \ } REPEAT(GERK, sgesvd, dgesvd, cgesvd, zgesvd) #undef GETRI #undef SYTRI #undef GEDTR #undef SYDTR #undef HEDTR #undef GETRF #undef SYTRF #undef HETRF #undef POTRF #undef GEQRF #undef GEEV #undef GEEVC #undef SYEV #undef HEEV #undef GEES #undef GEESC #undef GESV #undef SYSV #undef HESV #undef GELS #undef GESVD #undef GERK #endif } // namespace Blasw #undef CHECK #undef REPEAT0 #undef REPEAT1 #undef REPEAT #undef STATE #undef GENERAL #undef BGENERAL #undef TRIANGLE #undef BTRIANGLE #undef PTRIANGLE #undef SYMMETRIC #undef BSYMMETRIC #undef PSYMMETRIC #undef HERMITIAN #undef BHERMITIAN #undef PHERMITIAN #undef POSDEF #undef ROTG #undef ROTMG #undef ROT #undef ROTM #undef SWAP #undef SCAL #undef SSCAL #undef COPY #undef AXPY #undef DOT #undef DOTU #undef NRM2 #undef ASUM #undef IAMAX #undef GEMV #undef GBMV #undef SYMV #undef HEMV #undef SBMV #undef HBMV #undef SPMV #undef HPMV #undef TRMV #undef TBMV #undef TPMV #undef TRSV #undef TBSV #undef TPSV #undef GER #undef GERU #undef SYR #undef HER #undef SPR #undef HPR #undef SYR2 #undef HER2 #undef SPR2 #undef HPR2 #undef GEMM #undef SYMM #undef HEMM #undef TRMM #undef TRSM #undef SYRK #undef HERK #undef SYR2K #undef HER2K
{ "alphanum_fraction": 0.3453592313, "avg_line_length": 53.0676691729, "ext": "h", "hexsha": "e1e5027c51786dded286ceff030f471f7a545c3e", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "4295cfe1a2712dbe87fd251bfbb49ca22f13fe98", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "Mathific/Blasw", "max_forks_repo_path": "src/blasw/blasw.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "4295cfe1a2712dbe87fd251bfbb49ca22f13fe98", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "Mathific/Blasw", "max_issues_repo_path": "src/blasw/blasw.h", "max_line_length": 120, "max_stars_count": 1, "max_stars_repo_head_hexsha": "4295cfe1a2712dbe87fd251bfbb49ca22f13fe98", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "Mathific/Blasw", "max_stars_repo_path": "src/blasw/blasw.h", "max_stars_repo_stars_event_max_datetime": "2021-03-09T17:22:50.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-09T17:22:50.000Z", "num_tokens": 15410, "size": 77638 }
#ifndef TRIANGLES_H_XWPDRVKT #define TRIANGLES_H_XWPDRVKT #include <cmath> #include <gsl/gsl> #include <iostream> #include <limits> #include <sens_loc/math/constants.h> #include <type_traits> namespace sens_loc::math { /// This function calculates the bearing angle between two neighbouring range /// measurements. /// \param b reference depth and > 0 /// \param c prior depth and > 0 /// \param cos_alpha == std::cos(alpha) of the angle between two measurements /// \returns bearing angle in radians /// \pre b and c and positive values /// \pre \f$0 < \cos \alpha < 1\f$ /// \post \f$0 < result < \pi\f$ /// /// The bearing angle is angle between the ray to 'b' and the connecting line /// from 'c' to 'b'. /// It is bigger 0° and smaller 180° due to triangle constraints. template <typename Real> inline Real bearing_angle(const Real b, const Real c, const Real cos_alpha) noexcept { static_assert(std::is_arithmetic_v<Real>); Expects(b > 0.); Expects(c > 0.); // => alpha is smaller 90° Expects(cos_alpha > 0.); // => alpha is bigger 0° Expects(cos_alpha < 1.); // NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers) const Real delta = Real(10.) * std::numeric_limits<Real>::epsilon(); const Real nom = b - c * cos_alpha; const Real den = [&]() { const Real d = std::sqrt(b * b + c * c - Real(2.) * b * c * cos_alpha); return d == Real(0.) ? d + delta : d; }(); Ensures(den != 0.); // Note: Because of inaccuracy of floating point operations it is possible // to get abs(ratio) == 1. This is not an error in the implementation // but rather an numerical artifact. To not hit the post-conditions // it is ok to subtract a tiny epsilon. const Real ratio = std::clamp(nom / den, Real(-1.) + delta, Real(1.) - delta); Ensures(ratio > -1.); Ensures(ratio < +1.); const Real result = std::acos(ratio); Ensures(result > 0.); Ensures(result < math::pi<Real>); return result; } /// This function implements the bearing angle with formula from Lin, which is /// incorrect. /// This implementation is here to verify the difference in the results /// and testing covers that as well. template <typename Real = float> inline Real reference_lin_bearing_angle(const Real b, const Real c, const Real cos_alpha) noexcept { static_assert(std::is_arithmetic_v<Real>); Expects(b > 0.); Expects(c > 0.); // => alpha is smaller 90° Expects(cos_alpha > 0.); // => alpha is bigger 0° Expects(cos_alpha < 1.); const Real nom = (b - c * cos_alpha); const Real denom = (b * b + c * c - 2. * b * c * cos_alpha); const Real ratio = nom / denom; Ensures(ratio > -1.); Ensures(ratio < +1.); const Real result = std::acos(ratio); Ensures(result > 0.); Ensures(result < math::pi<Real>); return result; } } // namespace sens_loc::math #endif /* end of include guard: TRIANGLES_H_XWPDRVKT */
{ "alphanum_fraction": 0.6260242543, "avg_line_length": 29.9117647059, "ext": "h", "hexsha": "2353d4826fd72718ed0f410db1ff9c1d30651589", "lang": "C", "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "JonasToth/depth-conversions", "max_forks_repo_path": "src/include/sens_loc/math/triangles.h", "max_issues_count": null, "max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "JonasToth/depth-conversions", "max_issues_repo_path": "src/include/sens_loc/math/triangles.h", "max_line_length": 79, "max_stars_count": 2, "max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "JonasToth/depth-conversions", "max_stars_repo_path": "src/include/sens_loc/math/triangles.h", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z", "num_tokens": 820, "size": 3051 }